diff --git a/.agents/skills/which-tier/SKILL.md b/.agents/skills/which-tier/SKILL.md index d259159b08..e1794a4c53 100644 --- a/.agents/skills/which-tier/SKILL.md +++ b/.agents/skills/which-tier/SKILL.md @@ -100,9 +100,11 @@ cargo can see a python file). everybody quotes is `cargo test --lib` alone, and that part is itself tens of seconds now (the per-crate test binaries, `UNIT_SUITE` in the Makefile, run side by side through `tools/cargo-test-parallel.py`; `make test-crate C=` runs just the one you touched); end to end the gate runs in MINUTES warm. The bulk of it is `python3 tests/test_harness.py`, which shells out to -`ci/check-deps.sh` (11 s a run) once or more per self-test to prove each structure gate still -catches a planted violation — 661 s of a 1100 s run, measured 2026-10-01 on a cold lane at load -~5, before those self-tests moved to private tree copies and a thread pool (175 s after). The lab selftest's **~7 s is mostly two DELIBERATE rate-limit waits** — so +`ci/check-deps.sh` to prove each structure gate still catches a planted violation: each DepGates +self-test runs only the rule or rules it plants for (`--only `), and only the whole-script +tests, with the one shared run over the real tree, run every rule. That was 661 s of a 1100 s run, +measured 2026-10-01 on a cold lane at load ~5, before those self-tests moved to private tree +copies and a thread pool (175 s after). The lab selftest's **~7 s is mostly two DELIBERATE rate-limit waits** — so a ten-second-plus pause there is the target working, not a hang. (That step also SSDP-probes the LAN to report whether a UPnP gateway is present; still no television, still no lock.) Do not write a new number here: measure it if you need one — this file has already carried a diff --git a/.github/actions/host-rust/action.yml b/.github/actions/host-rust/action.yml index b40f21db6e..02caeadb0f 100644 --- a/.github/actions/host-rust/action.yml +++ b/.github/actions/host-rust/action.yml @@ -42,8 +42,39 @@ runs: # is byte-for-byte the one `make check` ran against, and the ARM cross-build's. uses: ./.github/actions/rust-toolchain + - name: Build the host crates with line tables only + # Nothing in CI attaches a debugger to a host test binary, and a panic backtrace needs only the + # line table. The default `dev`/`test` profile writes full DWARF for every crate, dependencies + # included, which is most of what rustc's codegen, the linker and the cache archive carry for + # the 18 test binaries. This is the per-user cargo config, so it reaches the bare `cargo` + # lines and every `make` target of the host jobs alike. A dependency built with the old + # profile is a different unit to cargo, and rust-cache's key does not see this file (it hashes + # the manifests, the lockfile, the toolchain files and the workspace's `.cargo/config.toml`, + # not the home one), so the cache step below carries its own `prefix-key`: without it the + # full-DWARF cache restores as an exact hit, every dependency is rebuilt, and the post step + # finds the cache up to date and saves nothing. It is NOT the manifest: a developer's checkout + # keeps full DWARF (docs/agent-reference.md, the lane policy), and the profiles the ARM binary + # is built with do not inherit `dev`, so the shipped library is untouched. + shell: bash + run: | + mkdir -p "$HOME/.cargo" + cat >> "$HOME/.cargo/config.toml" <<'EOF' + [profile.dev] + debug = "line-tables-only" + [profile.dev.package."*"] + debug = false + EOF + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 # The cache key already carries the calling job's id, so the three Rust jobs each keep their # own `target/` instead of racing to save one. + # + # The `prefix-key` names the profile the cached `target/` was built with: the line-tables + # config above is not an input to rust-cache's key, so the profile has to be in the prefix. + # Change that config and bump the number here, or the old entry restores as an exact hit. The + # entry is built cold once per lockfile or toolchain change, like any other key of this cache. + # The host jobs' old `v0-rust-` entries are never read again; GitHub drops an entry that + # nothing has restored for seven days. with: + prefix-key: v1-rust-linetables workspaces: rust-modules diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 878b2e6e27..29b7aa07cf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -454,7 +454,7 @@ jobs: name: host harness tests needs: changes if: needs.changes.outputs.gated == 'true' - runs-on: ubuntu-24.04 + runs-on: ubuntu-latest # FinNative: 15, not 10. Its larger tree takes check-deps' plants 8-10 min on a runner. timeout-minutes: 15 steps: diff --git a/Makefile b/Makefile index 7052306b14..294981ee4b 100644 --- a/Makefile +++ b/Makefile @@ -1692,6 +1692,18 @@ check-cargo-lint: lint # ci/test_test_crate.py pins the two equal. UNIT_RUN = python3 ../tools/cargo-test-parallel.py UNIT_SUITE = plxnative-modules plx_base plx_machine plx_platform plx_gfx plx_net plx_ui plx_plex plx_telemetry plx_data plx_session plx_media plx_playback_contract plx_play_uri plx_play_feed plx_media_codecs plx_appkit plx_screens +# The `hostsim` pass runs only the crates that DECLARE a `hostsim` feature (HOSTSIM_SUITE, a subset of +# UNIT_SUITE in the same order; ci/test_test_crate.py pins both the subset and the recipe). The seven that +# do not (plx_net, plx_ui, plx_appkit, plx_screens, plx_media_codecs, plx_play_uri, plx_playback_contract) +# have no `feature = "hostsim"` in their source and the same test names in both passes (14 crates did in +# CI run 43528579834; the three that differ are `plxnative-modules`, `plx_media` and `plx_play_feed`, +# all kept). Their own test set is therefore identical in the two passes. The old second run did link +# their test binaries against hostsim-built `plx_base`, `plx_gfx`, `plx_platform`, `plx_media` and +# `plx_play_feed` (steerable `ENV_STEERABLE` paths, larger glyph-cache sizes, `ffi_host` present), but +# none of their tests observes those dependency-side differences; the guard does not check that, it +# checks that the crate declares no `hostsim` feature and has no `feature = "hostsim"` in its src, and +# fails when one gains either, which is the moment it must join the list. +HOSTSIM_SUITE = plxnative-modules plx_base plx_machine plx_platform plx_gfx plx_plex plx_telemetry plx_data plx_session plx_media plx_play_feed # The default-feature unit suite and everything that drives cargo through ci/ self-tests. check-cargo-unit-default: @@ -1743,7 +1755,7 @@ check-cargo-unit-default: # The `hostsim` unit suite (the host feed seam exists only there). check-cargo-unit-hostsim: - @# The SAME suite as `check-cargo-unit-default`'s `cargo test --lib`, again under `hostsim`, which is + @# The crates of HOSTSIM_SUITE (the ones that declare `hostsim`) again under `hostsim`, which is @# not a duplicate run: the host feed seam (`play-feed/src/ffi_host.rs`) only exists in that configuration, @# so every test that drives an AU through `sf_feed` is COMPILED OUT of the default pass and cannot fail it. The prime-livelock @# regression is one of those, and it guards the 94-second freeze of 2026-08-29 — a defect that @@ -1754,7 +1766,7 @@ check-cargo-unit-hostsim: cd rust-modules && PATH="$$HOME/.cargo/bin:$$PATH" PLXNATIVE_RUNTIME_DIR="$$d" \ $(TELEMETRY_ENV) \ $(HOST_ENV) \ - $(UNIT_RUN) -- cargo +$(RUST_TOOLCHAIN) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_platform -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens --features hostsim + $(UNIT_RUN) -- cargo +$(RUST_TOOLCHAIN) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_platform -p plx_gfx -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_play_feed --features hostsim # OPT-IN incremental inner loop: the default-feature unit suite (the same `cargo test --lib` as # `check-cargo-unit-default`, same throwaway runtime root and telemetry env) with diff --git a/PRIVACY.md b/PRIVACY.md index 8d5cd1e1d3..e00e5922f4 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -201,10 +201,19 @@ or `development`), the time of the panic (read and bounded as above), the same k webOS and hardware compatibility details (including the `probe` fact and the firmware `build`) that the fault fallback report carries, and the Crash report ID below. It carries none of the library details above. -A main-thread freeze (the app not responding for five seconds or more while it is open on screen) is reported like a crash, under the same choice: code addresses and register values, one of three duration ranges (5 to 10 s, 10 to 30 s, 30 s or more) or "unrecovered", and the details above, without stopping the app. +A main-thread freeze (the app not responding for five seconds or more while it is open on screen) is reported like a crash, under the same choice: code addresses and register values, one of three duration ranges (5 to 10 s, 10 to 30 s, 30 s or more) or "unrecovered", the step of the app's own frame loop the app was in when it stopped responding (`freeze.leg`: one fixed word from a list of eleven naming a phase of the loop, never anything about what was on screen or playing: `event-ingest`, `results`, `dev-scenarios`, `playback-pump`, `land-results`, `navcommit`, `dispatcher-frame`, `update`, `prepare-window`, `present-and-swap` or `frame-report`), and the details above, without stopping the app. When another part of the television's software ends PlxNative by calling `exit()` (for example the system closing it), the app records the call and reports it like a crash, under the same choice: the exit status (a number), which thread made the call (its number, whether it was the main thread, and its own name, a technical label set by PlxNative or a library), the library the call came from (its file name, never the folder, with its build identifier, load address and size, as for a crash report above) and the code address of the call, the time of the call to the second, and the details above. +A report built from the crash log (a fault, a Rust panic, a freeze or an `exit()` call, as above) is +sent the next time the app starts, which after an update is a newer build than the one that left +the record. When the record names a different build of PlxNative than the one sending it, the report's +`release` (the app version it is filed under) is left out rather than filed under the newer +version, and it carries two tags instead: `crash.uploaded_by`, the app version that sent it, and +`crash.build_id`, the build identifier of the build that crashed. Both are an app version and a +binary build identifier, which these reports already carried; nothing new is collected. A report from the same +build as the one sending it, or one whose build cannot be compared, carries `release` and neither tag. + Every crash and error report carries a **Crash report ID**: a random identifier created on this television when you turn crash reports on, sent as the report's `user.id`. It exists so that repeated crashes under one Crash report ID are counted once rather than once each — Sentry's @@ -287,11 +296,21 @@ after the app returned to the foreground) / `preview` (the trailer that plays qu detail page, which the viewer did not press Play for); and `attempt_ordinal`, which open of this playback it was, `1` to `9` and then `9+`, counting the first open, every retry and every handoff. The count starts again at `1` with each new Play and is kept only in memory. Both appear as a tag -and in the playback context. A trailer preview that fails is reported with the same fields and no -more: it is marked `preview`, it counts as the first open, it names direct play as the attempted -delivery (the only route a preview ever opens), and its `started` and `attempt_started` fields -say whether the trailer actually showed a picture before it failed. Sentry files it in an issue of -its own, apart from playback failures. +and in the playback context. A trailer preview that fails is reported with the same fields and one +more, below: it is marked `preview`, it counts as the first open, it names direct play as the +attempted delivery (the only route a preview ever opens), and its `started` and `attempt_started` +fields say whether the trailer actually showed a picture before it failed. Sentry files it in an +issue of its own, apart from playback failures. + +A trailer preview that the app refuses to open, because a preview only ever plays an unmodified +direct play (the failure kind `preview_not_direct`), also names which condition refused it, as one +closed tag, `preview_refusal`: `no_part` (the item has no media file to play), `not_direct` (a direct +play was not available, so the route would have been a transcode or a remux, whatever the reason: +the server's answer, the connection's or the quality setting's rules, or a track the television +cannot play as it is) or `adaptive` (a direct play was available, but Auto quality chose a +bandwidth-adapted stream instead). The first condition that fails in that order is the one named. +No other failure carries it, and it appears as a tag only, not in the playback context. It is one +of those three words and nothing the server said. The report also names `backend` — `unknown` / `feed` / `uri` — and `terminal_stage` — `unknown` / `planning` / `open` / `decode` / `presentation` / `release`. These describe only the diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index 9b4e21978a..f2c88b77c7 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -314,7 +314,7 @@ stated; election does not alter your rights under the other arms. | Package | Version(s) | Declared licence | Copyright | |---|---|---|---| -| The Rust standard library (`core`, `alloc`, `std`, `panic_unwind`, `unwind`, and the `rustc-std-workspace-*` shims) | rustc 1.99.1 (58cf8f9c3 2026-10-13) | MIT OR Apache-2.0 | The Rust Project Developers | +| The Rust standard library (`core`, `alloc`, `std`, `panic_unwind`, `unwind`, and the `rustc-std-workspace-*` shims) | rustc 1.100.0 (0ef1bc386 2026-11-09) | MIT OR Apache-2.0 | The Rust Project Developers | | — its in-tree backtrace support (`library/backtrace`) | 0.3.76 | MIT OR Apache-2.0 | 2014 Alex Crichton | | — its in-tree mpmc channels (`library/std/src/sync/mpmc`) | in-tree | MIT OR Apache-2.0 | 2019 The Crossbeam Project Developers | | addr2line | 0.27.1 | Apache-2.0 OR MIT | The `addr2line` authors | @@ -329,7 +329,7 @@ stated; election does not alter your rights under the other arms. | crc | 3.4.0 | MIT OR Apache-2.0 | 2017 crc-rs Developers | | crc-catalog | 2.5.0 | MIT OR Apache-2.0 | Akhil Velagapudi | | crc32fast | 1.5.0 | MIT OR Apache-2.0 | 2018 Sam Rijs, Alex Crichton and contributors | -| ed25519-compact | 2.6.0 | MIT | 2020-2026 Frank Denis | +| ed25519-compact | 2.6.1 | MIT | 2020-2026 Frank Denis | | either | 1.18.0 | MIT OR Apache-2.0 | Copyright (c) 2015 (the upstream notice names no holder) | | encoding_rs | 0.8.44 | (Apache-2.0 OR MIT) AND BSD-3-Clause | Mozilla Foundation. Its encoding tables derive from the WHATWG Encoding Standard, whose data files are BSD-3-Clause (`licenses/WHATWG-BSD-3-Clause.txt`) | | equivalent | 1.0.3 | Apache-2.0 OR MIT | 2016–2023 The equivalent authors | @@ -381,7 +381,7 @@ stated; election does not alter your rights under the other arms. | tap | 1.0.1 | Copyright (c) 2017 Elliot Linder | | wyz | 0.5.1 | Copyright (c) 2018 myrrlyn (Alexander Payne) | | zmij | 1.0.21 | David Tolnay (a Rust port of Victor Zverovich's C++ `zmij`) | -| rust-lang/libm — compiled *inside* `compiler_builtins` and exposed as intrinsics on this target | as vendored in rustc 1.99.1 | (c) 2018 Jorge Aparicio; musl libc (c) 2005-2020 Rich Felker, et al.; CORE-MATH; and the fdlibm-derived notice: (c) 1993, 2004 Sun Microsystems; (c) 2003-2011 David Schultz; (c) 2003-2009 Steven G. Kargl; (c) 2003-2009 Bruce D. Evans; (c) 2008 Stephen L. Moshier; (c) 2017-2018 Arm Limited | +| rust-lang/libm — compiled *inside* `compiler_builtins` and exposed as intrinsics on this target | as vendored in rustc 1.100.0 | (c) 2018 Jorge Aparicio; musl libc (c) 2005-2020 Rich Felker, et al.; CORE-MATH; and the fdlibm-derived notice: (c) 1993, 2004 Sun Microsystems; (c) 2003-2011 David Schultz; (c) 2003-2009 Steven G. Kargl; (c) 2003-2009 Bruce D. Evans; (c) 2008 Stephen L. Moshier; (c) 2017-2018 Arm Limited | diff --git a/ci/check-deps.sh b/ci/check-deps.sh index e249d40688..e0b4389980 100755 --- a/ci/check-deps.sh +++ b/ci/check-deps.sh @@ -155,6 +155,88 @@ fails=0 fail() { echo "::error::check-deps: $*"; fails=$((fails+1)); } ok() { echo " ok — $*"; } +# ---- selecting rules --------------------------------------------------------------------------- +# `ci/check-deps.sh` with no argument runs EVERY rule: that is what `make check`, CI and +# ci/check-python-steps.txt run, and nothing but an argument changes it (an environment variable left +# exported in a shell would quietly shrink the gate; an argument cannot be inherited). The gate +# self-tests of tests/test_harness.py prove each rule still catches a planted violation, and each +# used to run the whole script for that, ~25 s of CPU a run and ~70 runs. So: +# ci/check-deps.sh --only blocking,workers run just those rules, the code the full run runs for +# them: their verdict lines, a summary, exit 0 or 1 +# ci/check-deps.sh --list-rules the rule names (RULES below), one a line, no rule run +# A name that is no rule, an empty list, a second --only or any other argument exits 2 before any +# rule runs, so a misspelt selector is an error and never "ran nothing (or less than asked), green". A rule's NAME is what its verdict +# line starts with (`ok — ` / `check-deps: : ...`); `allowlist-counts` is the one rule that +# prints nothing when green. +# +# A rule is a block `if want ; then ... fi # ` (or `want && gate ...`) whose body +# is left at the margin, not indented, so the diff and blame of the rules stay what they were. Inside +# a block, use only what the block itself computes, a shared definition (a function, a constant, a +# pattern) outside every block, or one of the three PRELUDES below, which are computed only when a +# rule that reads them is selected (`any_wanted`; a rule that reads one is named in its list). Under +# `set -u` an unset prelude read inside `$( ... )` kills just that subshell and the rule reads +# green, so a rule that reads a prelude it was not named for is loud, not quiet: `is_wholly_test` +# exits 2 and the others print `unbound variable` on stderr (tests/test_harness.py fails on both). +# RULES must name the `want` calls in order; every run ends by checking that, whatever it selected. +RULES=(browse-owner viewstate-owner person-owner search-owner hubs-owner metadata-owner libm ticks wall + fpflags present effect mutators mutators-visibility nav ui-owner-legacy ui-owner-files owned-damage + owned-wake cards layer sessionwrite uistorage legacypage sibling textmeasure dt ladder hittest frame + sink route fnlen testmod threads blocking workers globals forks fxlanes tmppath paging allowlist-counts) +deps_usage() { + echo "check-deps: $*" >&2 + echo "usage: ci/check-deps.sh [--only RULE[,RULE...] | --list-rules]" >&2 + exit 2 +} +known_rule() { + local r + for r in "${RULES[@]}"; do [ "$r" = "$1" ] && return 0; done + return 1 +} +only="" # ",rule,rule," once --only was given, else empty: every rule +have_only=0 +only_arg="" +while [ $# -gt 0 ]; do + case "$1" in + --list-rules) printf '%s\n' "${RULES[@]}"; exit 0 ;; + --only|--only=*) + # one way to say it: a second --only would overwrite the first and run a smaller set, green + [ "$have_only" -eq 0 ] || deps_usage "--only is given once; join the rules with commas (--only a,b)" + have_only=1 + if [ "$1" = "--only" ]; then + [ $# -ge 2 ] || deps_usage "--only needs a rule list" + only_arg="$2"; shift 2 + else + only_arg="${1#--only=}"; shift + fi ;; + *) deps_usage "unknown argument '$1'" ;; + esac +done +if [ "$have_only" -eq 1 ]; then + [ -n "$only_arg" ] || deps_usage "--only needs at least one rule" + case "$only_arg" in ,*|*,|*,,*) deps_usage "--only '$only_arg' has an empty rule name" ;; esac + IFS=, read -r -a only_names <<< "$only_arg" + for only_rule in "${only_names[@]}"; do + known_rule "$only_rule" || deps_usage "--only names '$only_rule', which is no rule (--list-rules says which are)" + done + only=",$only_arg," +fi +rules_seen="" +# want : is this rule selected? The guard of every rule, always in the main shell. +want() { + known_rule "$1" || { echo "check-deps: internal: want '$1' names no rule of RULES" >&2; exit 2; } + rules_seen="$rules_seen $1" + case "$only" in "") return 0 ;; *",$1,"*) return 0 ;; esac + return 1 +} +# any_wanted ...: is no selector given, or is one of these rules selected? Gates a prelude. +any_wanted() { + local r + for r in "$@"; do known_rule "$r" || { echo "check-deps: internal: any_wanted '$r' names no rule" >&2; exit 2; }; done + [ -z "$only" ] && return 0 + for r in "$@"; do case "$only" in *",$r,"*) return 0 ;; esac; done + return 1 +} + # grep_code : matching lines, minus comment-only lines, as `path:line:text`. grep_code() { local pat="$1"; shift @@ -172,7 +254,10 @@ grep_code() { # filters that list with its real pattern. The verdict and the output are unchanged, but the # prefix alternation must stay a NECESSARY part of every owner pattern, never a loose sample. OWNER_PREFIX='(crate|plx_data)::(browse|viewstate|person|search|pms|metadata)::|stores::(browse|viewstate|person|search|hubs|metadata)::' +# PRELUDE 1 of 3 (see "selecting rules"): computed only when one of the six owner rules is selected. +if any_wanted browse-owner viewstate-owner person-owner search-owner hubs-owner metadata-owner; then OWNER_LINES="$(grep -HrnE --include='*.rs' "$OWNER_PREFIX" "$SRC" "$SRC_DATA" "$SRC_APPKIT" "$SRC_SCREENS" 2>/dev/null || true)" +fi grep_code_owner() { printf '%s\n' "$OWNER_LINES" | grep -E -- "$1" | grep -vE '^[^:]+:[0-9]+:[[:space:]]*//' || true } @@ -272,12 +357,19 @@ wholly_test_files() { # question once per candidate file or line with `echo "$wholly_test" | grep -qxF`, which is two # processes an answer. WHOLLY_TEST_INDEX="" +WHOLLY_TEST_READY=0 wholly_test_index_init() { WHOLLY_TEST_INDEX=" $1 " + WHOLLY_TEST_READY=1 } is_wholly_test() { + # a rule asking before the prelude ran would read an empty index, i.e. "no file is a test file" + [ "$WHOLLY_TEST_READY" -eq 1 ] || { + echo "check-deps: internal: is_wholly_test before the wholly_test prelude (name the rule in its any_wanted list)" >&2 + exit 2 + } case "$WHOLLY_TEST_INDEX" in *" $1 @@ -299,8 +391,13 @@ gate() { } echo "== check-deps ==" +# PRELUDE 2 of 3: the test-module classification, 17 `rust_test_modules.py` runs (~3.7 s of CPU), +# computed only when a rule that reads `$wholly_test` / `is_wholly_test` (directly, or through +# `ledger_scan`) is selected. A run with no selector computes it first, as it always did. +if any_wanted libm mutators cards sink threads blocking workers globals forks fxlanes paging; then wholly_test="$(wholly_test_files)" || { fail "Rust test-module classification failed"; exit 1; } wholly_test_index_init "$wholly_test" +fi # browse-owner: Browse has one physical owner per `Stores`; the migration allowlist ended at zero # and is deliberately gone. Reject both the old storage/selector machinery and every free @@ -472,6 +569,7 @@ owner_declarations() { ' "$file" || echo "$file:0:browse declaration scanner failed" done } +if want browse-owner; then browse_owner_matches=$({ owner_declarations "$browse_facades" 'ACTIVE|LEGACY_ADAPTER|BOOTSTRAP_AVAILABLE' \ 'BrowseState|BrowseAdapter|BrowseStore' "$SRC_DATA/browse/mod.rs" @@ -489,12 +587,14 @@ else echo "$browse_owner_matches" | sed 's/^/ /' fail "browse-owner: retired Browse compatibility surface returned" fi +fi # browse-owner # viewstate-owner: ViewState's physical state, Arc transport and notice live on ViewStateStore. # Zero tolerance, no allowlist: a free facade or storage/transport static can only select process # state, which would silently reconnect separate Bridges and let a retired worker cross reset. viewstate_facades='apply|run|run_with_browse|run_with_owners|pump|pump_with_owners|is_busy|take_landed_views|take_landed|request|request_with_browse|request_with_owners|reset|hold_inflight_for_test|owe_hubs_refresh_for_test|seed_ownership_fixture_for_test|ownership_fixture_for_test|late_completion_for_test|seed_post_reset_flight_for_test' viewstate_selectors='ACTIVE|OWNER|QUEUE|SENT|RETRY_CD|WANT_HUBS|LANDED|MAIL|VIEWSTATE|VIEW_STATE|LEGACY_ADAPTER' +if want viewstate-owner; then viewstate_owner_matches=$({ owner_declarations "$viewstate_facades" "$viewstate_selectors" \ 'ViewStateState|ViewStateAdapter|ViewStateStore|Req|Completion|Done' \ @@ -507,6 +607,7 @@ else echo "$viewstate_owner_matches" | sed 's/^/ /' fail "viewstate-owner: retired ViewState compatibility surface returned" fi +fi # viewstate-owner # person-owner: Person's model/generation/retry/dev seed live in PersonState, its indexed fetch # claims/mailboxes live in the rotated Arc, and both belong to one PersonStore per @@ -514,6 +615,7 @@ fi # owners and lets an unaddressed reset, pump or optimistic edit cross the Bridge boundary. person_facades='current|loading|run|pump|apply|install_for_test|install_source_for_test|install_credits_for_test' person_selectors='ACTIVE|OWNER|CURRENT|GEN|RETRY_CD|FETCH|MAIL|PERSON|PERSON_STATE|LEGACY_ADAPTER|HELD' +if want person-owner; then person_owner_matches=$({ owner_declarations "$person_facades" "$person_selectors" \ 'PersonState|PersonAdapter|PersonStore|Person|Fetch|Mail|Landing' \ @@ -526,6 +628,7 @@ else echo "$person_owner_matches" | sed 's/^/ /' fail "person-owner: retired Person compatibility surface returned" fi +fi # person-owner # search-owner: Search's query/generation/shelf model lives in SearchState, its per-source fetch # claims/mailboxes live in the rotated Arc, and both belong to one SearchStore per @@ -540,6 +643,7 @@ fi # rotates the adapter — only a bare, parameterless global `reset()` would be the retired shape. search_facades='apply|snapshot|snapshot_with_directory|run_with_directory|pump_with_directory|query|state|query_gen|publish_shelves_for_test|settling|debounce_elapsed_for_test' search_selectors='ACTIVE|OWNER|QUERY|GEN|STATE|SHELVES|SRC|ARMED|FAV_GEN|IN_FLIGHT|MAIL|SLOT|SEARCH|SEARCH_STATE|LEGACY_ADAPTER' +if want search-owner; then search_owner_matches=$({ owner_declarations "$search_facades" "$search_selectors" \ 'SearchState|SearchAdapter|SearchStore|Fetch|Projection|Shelf' \ @@ -552,6 +656,7 @@ else echo "$search_owner_matches" | sed 's/^/ /' fail "search-owner: retired Search compatibility surface returned" fi +fi # search-owner # hubs-owner: Home's hub catalog model (`PmsState`) and its rotated worker mailbox/minter # (`Arc`) belong to one `HubsStore` per Bridge (`app/bridge.rs`'s `hubs_run`/ @@ -566,6 +671,7 @@ fi # `state`/`adapter` in, exactly like search's own `reset(state, adapter)`. hubs_facades='apply|apply_with_directory|controlled|controlled_with_directory' hubs_selectors='RESULTS|NEXT_REQUEST|HUB_GEN|CATALOG_GEN|LAST_SECTIONS_GEN|ACTIVE|OWNER|LEGACY_ADAPTER' +if want hubs-owner; then hubs_owner_matches=$({ owner_declarations "$hubs_facades" "$hubs_selectors" \ 'PmsState|PmsAdapter|HubsStore|Landing|Src|SourceBuild' \ @@ -578,6 +684,7 @@ else echo "$hubs_owner_matches" | sed 's/^/ /' fail "hubs-owner: retired Hubs compatibility surface returned" fi +fi # hubs-owner # metadata-owner: Detail's item/season/playing model (`MetadataState`) and its worker adapter # (`Arc`, D3's `record::Tracker` included) belong to one `MetadataStore` per @@ -591,6 +698,7 @@ fi # hubs' and search's own owned stores. metadata_facades='apply' metadata_selectors='DETAIL_LANDING|SEASON_LANDING|ALT_LANDING|NOW|CURRENT|TRACKER|NOTICES' +if want metadata-owner; then metadata_owner_matches=$({ owner_declarations "$metadata_facades" "$metadata_selectors" \ 'MetadataState|MetadataAdapter|MetadataStore|Tracker' \ @@ -603,11 +711,13 @@ else echo "$metadata_owner_matches" | sed 's/^/ /' fail "metadata-owner: retired Metadata compatibility surface returned" fi +fi # metadata-owner # libm: the method-call spelling, OUTSIDE machine/src/motion.rs (which owns the integrators and their # table test); `.log(&…`/`.log("…` is a logger, not a logarithm. # Wholly-test files (see `wholly_test_files`) are skipped like inline `#[cfg(test)]` blocks: a # test's reference colour maths is not logical state. +if want libm; then libm_lines=$(grep_code '\.(exp|ln|log|powf|powi|cbrt|sin|cos|tan|atan2|hypot|mul_add|sin_cos)\(' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_PLATFORM" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" \ | grep -vE '\.log\((&|")' | grep -v "^$SRC_MACHINE/motion.rs:") libm_bad=0 @@ -618,19 +728,28 @@ while IFS= read -r line; do if ! allowed libm "$p"; then echo " $line"; libm_bad=$((libm_bad+1)); fi done <<< "$libm_lines" if [ "$libm_bad" -eq 0 ]; then ok "libm"; else fail "libm: $libm_bad line(s) outside ci/allow/libm.txt"; fi +fi # libm -gate ticks 'SDL_GetTicks\(' "$SRC" "$SRC_BASE" "$SRC_PLATFORM" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" +want ticks && gate ticks 'SDL_GetTicks\(' "$SRC" "$SRC_BASE" "$SRC_PLATFORM" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" # Every data/session module is logic unless its exact reviewed IO/instrument file is in ports.ini. +if want wall; then if python3 ci/check-ports.py; then ok "wall"; else fail "wall: outside exact ci/ports.ini files"; fi +fi # wall +if want fpflags; then if grep -rnE 'fp-contract|fast-math|\+fma' rust-modules/Cargo.toml rust-modules/build.rs rust-modules/net/Cargo.toml rust-modules/plex/Cargo.toml rust-modules/telemetry/Cargo.toml rust-modules/data/Cargo.toml rust-modules/session/Cargo.toml rust-modules/media/Cargo.toml rust-modules/appkit/Cargo.toml rust-modules/screens/Cargo.toml rust-modules/platform/Cargo.toml rust-modules/platform/build.rs rust-modules/gfx/Cargo.toml rust-modules/gfx/build.rs rust-modules/ui/Cargo.toml rust-modules/ui/build.rs rust-modules/appkit/build.rs rust-modules/screens/build.rs rust-modules/storage/Cargo.toml rust-modules/storage/build.rs rust-modules/.cargo Makefile 2>/dev/null | grep -v '^[[:space:]]*#'; then fail "fpflags: a floating-point contraction flag is set (spec §4.2 assumes none)" else ok "fpflags"; fi +fi # fpflags +if want present; then n=$(grep -cE '^static [A-Z_]+: Atomic' "$SRC_MACHINE/present.rs"); d=$(grep -c 'pub fn wake_from_worker' "$SRC_MACHINE/present.rs") if [ "$n" -eq 1 ] && [ "$d" -eq 1 ]; then ok "present: one worker door"; else fail "present: $n atomic statics, $d doors (one of each)"; fi +fi # present +if want effect; then if [ -n "$(grep_code '\bEffect::' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_PLATFORM" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS")" ]; then fail "effect: \`Effect::\` is spelled (use Fx:: / AppFx::)"; else ok "effect"; fi +fi # effect # mutators: production lines of ui/, screens/ and app/ (everything before the file's first # `#[cfg(test)]` + `mod` pair, which is where every screen keeps its tests) — PLUS, since D3, every @@ -663,6 +782,7 @@ MUTATORS='\b(browse|pms|metadata|search|person|viewstate)::(set_cur|note_library # production lines of ui/detail.rs go unscanned. `stores::::apply(` lines are the new # spelling and are excluded by name; a SCREEN's own `crate::ui::person::open(` is not a store # call and is masked before the match. +if want mutators; then mut_bad=0 while IFS= read -r f; do if is_wholly_test "$f"; then continue; fi @@ -678,6 +798,7 @@ while IFS= read -r f; do # that can produce a hit. done < <(grep -rlE --include='*.rs' "$MUTATORS" "$SRC_UI" "$SRC_MACHINE" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC/app" "$SRC_MEDIA/route" "$SRC_MEDIA/player" "$SRC/dev" 2>/dev/null | sort) if [ "$mut_bad" -eq 0 ]; then ok "mutators"; else fail "mutators: $mut_bad line(s) call a store mutator directly (use the owner's run/step method, e.g. Bridge::_run)"; fi +fi # mutators # mutators-visibility (D3): the call-site rule above can only ever prove "nobody currently calls # this directly" — it says nothing about whether they COULD. This reads the DECLARATION line of @@ -718,6 +839,7 @@ MUT_FNS_TABLE=( store_seamed() { grep -qE "^${1}::${2}( |$)" ci/allow/store-seams.txt 2>/dev/null } +if want mutators-visibility; then vis_bad=0 for entry in "${MUT_FNS_TABLE[@]}"; do relf="${entry%%|*}" @@ -732,8 +854,47 @@ for entry in "${MUT_FNS_TABLE[@]}"; do done done if [ "$vis_bad" -eq 0 ]; then ok "mutators-visibility"; else fail "mutators-visibility: $vis_bad fn(s) still crate-visible"; fi +fi # mutators-visibility -gate nav '(crate::ui|plx_ui)::nav::' "$SRC_SCREENS" +want nav && gate nav '(crate::ui|plx_ui)::nav::' "$SRC" "$SRC_UI" "$SRC_APPKIT" "$SRC_SCREENS" + +# Completed ownership migration: legacy publications and the old gate cannot return. +if want ui-owner-legacy; then +ui_owner_hits=$(grep_code '(plx_ui|crate::ui)::press::|(plx_machine|crate)::idle::' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_PLATFORM" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS") +if [ -z "$ui_owner_hits" ]; then ok "ui-owner-legacy"; else + printf '%s\n' "$ui_owner_hits" + fail "ui-owner-legacy: retired global readers must not return" +fi +fi # ui-owner-legacy +if want ui-owner-files; then +legacy_owners=0 +for legacy in "$SRC_UI/nav.rs" "$SRC_UI/press.rs" "$SRC_MACHINE/idle.rs"; do + if [ -e "$legacy" ]; then + fail "ui-owner-files: retired module $legacy exists" + legacy_owners=$((legacy_owners+1)) + fi +done +if [ "$legacy_owners" -eq 0 ]; then ok "ui-owner-files"; fi +fi # ui-owner-files + +# Motion collectors may not own generic damage or a second process-global notification adapter. +if want owned-damage; then +owned_damage_hits=$(grep_code 'motion::report::(invalidate|take_damage|select_damage|take_page_damage|OwnScope)' "$SRC" "$SRC_UI" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_DATA" "$SRC_PLEX" "$SRC_MEDIA" "$SRC_PLATFORM") +report_adapter=$(grep_code '\bAtomic[A-Za-z0-9_]*\b|pub fn (invalidate|take_damage|select_damage|take_page_damage|present_dirty|wake)\b' "$SRC_MACHINE/motion/report.rs") +if [ -z "$owned_damage_hits$report_adapter" ]; then ok "owned-damage"; else + printf '%s\n%s\n' "$owned_damage_hits" "$report_adapter" + fail "owned-damage: presentation changes must reach the owned gate, never a global damage adapter" +fi +fi # owned-damage + +# Main-thread render/deferred work must address its owner; only actual IO workers use the atomic door. +if want owned-wake; then +main_wake_hits=$(grep_code 'motion::report::wake|wake_from_worker[[:space:]]*\(' "$SRC_UI" "$SRC/dev" "$SRC/app/run.rs") +if [ -z "$main_wake_hits" ]; then ok "owned-wake"; else + printf '%s\n' "$main_wake_hits" + fail "owned-wake: main-thread work must request PresentEvent::Wake from its owner" +fi +fi # owned-wake # cards: a screen's card shelves and grids come from `plx_ui::cards::{Shelf, Grid}` (the # shared-card-sections plan, layer L1), which own the pop, press, stops, restore and paging a @@ -751,6 +912,7 @@ gate nav '(crate::ui|plx_ui)::nav::' "$SRC_SCREENS" # allowlist (empty) is the screens that still assemble their own, one line per file, and only # SHRINKS. cards_pat='cards::(paint_visible|draw_tile|draw_focused)\b|use [^;]*cards::\{[^}]*\b(paint_visible|draw_tile|draw_focused)\b|\bCardRow\b|\bGridPop\b|\bGridBands\b|press::scale\(\)' +if want cards; then cards_bad=0 while IFS= read -r line; do [ -z "$line" ] && continue @@ -765,6 +927,7 @@ while IFS= read -r line; do echo " $line"; cards_bad=$((cards_bad+1)) done < <(grep_code '\bAvatarRow\b' "$SRC_SCREENS") if [ "$cards_bad" -eq 0 ]; then ok "cards"; else fail "cards: $cards_bad line(s) outside ci/allow/cards.txt (or AvatarRow outside profiles.rs) — draw card sections with plx_ui::cards::Shelf / Grid"; fi +fi # cards # layer: a SCREEN never names the application. §2.1's table says `screens/` may name `ui/`, # `stores/`, `plex/` and `player/` and never `app/`, and until phase 10 that half of the rule was @@ -775,24 +938,28 @@ if [ "$cards_bad" -eq 0 ]; then ok "cards"; else fail "cards: $cards_bad line(s) # and nothing else) is only worth as much as the boundary underneath it. Count is zero, with no # allowlist: a screen that needs something of the loop's asks for it as an effect (`AppFx`, # `LoopReq`) — that is what the bundle in `registry.rs` is. +if want layer; then if [ -n "$(grep_code '(crate|super)::app::' "$SRC_SCREENS")" ]; then grep_code '(crate|super)::app::' "$SRC_SCREENS" | sed 's/^/ /' fail "layer: a screen names the application (§2.1) — ask for it as an AppFx/LoopReq instead" else ok "layer"; fi -gate sessionwrite 'session::load\(' "$SRC_SCREENS" "$SRC_UI" "$SRC_MACHINE" "$SRC_APPKIT" +fi # layer +want sessionwrite && gate sessionwrite 'session::load\(' "$SRC_SCREENS" "$SRC_UI" "$SRC_MACHINE" "$SRC_APPKIT" # uistorage: the LIBRARY (`ui/`) never names the storage layer (§2.1: `ui/` may name only # `crate::{gfx,text,paths,task}`). A ui-owned sweep that needs the app's removal rule takes it as an # injected `fn` (`ui::rec::erase_owned_artifacts`). Zero, no allowlist. The wider table is not a # grep yet: ui/ still names other application modules, mostly from tests and dev instruments. -gate uistorage '(crate|super|plx_platform)::storage::' "$SRC_UI" "$SRC_MACHINE" +want uistorage && gate uistorage '(crate|super|plx_platform)::storage::' "$SRC_UI" "$SRC_MACHINE" # legacypage: the word itself, anywhere under src — a doc that still describes the type is as much # a hit as a declaration, which is the point (nothing compiles the prose either). +if want legacypage; then legacy_hits=$(grep -rn --include='*.rs' 'LegacyPage' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_PLATFORM" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" 2>/dev/null || true) if [ -z "$legacy_hits" ]; then ok "legacypage"; else echo "$legacy_hits" | sed 's/^/ /' fail "legacypage: $(echo "$legacy_hits" | wc -l | tr -d ' ') mention(s) — the type is retired (§15.2)" fi +fi # legacypage # sibling: one screen family per directory; `` is the first path component under screens/. # @@ -802,6 +969,7 @@ fi # gate that forbade it would forbid the structure the spec asks for. It was an allowlist entry # until phase 10 moved the mounter into it; an entry would have had to say "this file names all of # them, permanently", which is a rule and not a migration. +if want sibling; then sib_bad=0 while IFS= read -r f; do [ "$f" = "$SRC_SCREENS/registry.rs" ] && continue @@ -819,6 +987,7 @@ while IFS= read -r f; do done < <(grep -rlE --include='*.rs' 'crate::[a-z_]+' "$SRC_SCREENS" 2>/dev/null | sort) if [ "$sib_bad" -eq 0 ]; then ok "sibling" else fail "sibling: $sib_bad file(s) name a sibling screen (use crate::registry)"; fi +fi # sibling # ============================================================================================ # Phase 12 rules (spec §15.2, D4): the gates the earlier phases' own comments above never wrote, @@ -848,6 +1017,7 @@ else fail "sibling: $sib_bad file(s) name a sibling screen (use crate::registry) # `impl Measure for` added later still only exempts ITS OWN body, and any other raw call anywhere # in the tree fails. tm_seams="$SRC_UI/text_view.rs $SRC_UI/text_buffer.rs $SRC_GFX/text.rs" +if want textmeasure; then tm_bad=0 while IFS= read -r f; do is_seam=0 @@ -865,6 +1035,7 @@ while IFS= read -r f; do # an `impl … Measure for …` block, so a file with no raw call has nothing for it to find. done < <(grep -rlE --include='*.rs' '(crate|plx_gfx)::text::(text_width|elide|cap_h)\(' "$SRC" "$SRC_GFX" "$SRC_UI" "$SRC_APPKIT" "$SRC_SCREENS" 2>/dev/null | sort) if [ "$tm_bad" -eq 0 ]; then ok "textmeasure"; else fail "textmeasure: $tm_bad line(s) outside the Measure seam"; fi +fi # textmeasure # dt (phase 12, D4 — ZERO now, was an allowlist): idle::dt() (deleted from machine/src/idle.rs entirely — # card_row.rs's focused-title marquee, its last caller, now reads the absolute idle::now_ms() @@ -876,11 +1047,13 @@ if [ "$tm_bad" -eq 0 ]; then ok "textmeasure"; else fail "textmeasure: $tm_bad l # class this whole gate exists to catch. motion.rs currently has no hit either; the exclusion is # the documented intent (spec §4.2: the ONLY file licensed to touch a raw per-frame delta), not a # live carve-out. +if want dt; then dt_hits=$(grep_code 'idle::dt\(\)|(\+=|-=)\s*dt\b' "$SRC" "$SRC_MACHINE" "$SRC_PLATFORM" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" | grep -v "^$SRC_MACHINE/motion.rs:") if [ -z "$dt_hits" ]; then ok "dt"; else echo "$dt_hits" | sed 's/^/ /' fail "dt: $(echo "$dt_hits" | wc -l | tr -d ' ') line(s) — see rule comment above" fi +fi # dt # ladder: the old per-screen focus/hit ladder shape, zero across ui/ + screens/ once every Screen # answers FocusSource::Engine/HitSource::Engine (D2). No allowlist: every remaining hit is a @@ -893,13 +1066,13 @@ gate_zero() { fail "$rule: $(echo "$hits" | wc -l | tr -d ' ') line(s) — see rule comment above" fi } -gate_zero ladder 'fn move_focus|fn pointer_focus|fn top_focus|fn zones\b|fn key\(sym|fn focus_is_card|fn focus_is_ctl' "$SRC_UI" "$SRC_MACHINE" "$SRC_APPKIT" "$SRC_SCREENS" +want ladder && gate_zero ladder 'fn move_focus|fn pointer_focus|fn top_focus|fn zones\b|fn key\(sym|fn focus_is_card|fn focus_is_ctl' "$SRC_UI" "$SRC_MACHINE" "$SRC_APPKIT" "$SRC_SCREENS" # hittest: the narrowed raw hit-tester call shape, zero in app/ once the player's HUD registers # its stops through DrawFrame::stop (D2) instead of app/run.rs testing raw coordinates against # player_hud's geometry by hand. Deliberately NOT a blanket `_at(` — that false-positives on # resume_at/memory_at/open_settings_at/write_at, which are unrelated lookups. -gate_zero hittest 'pointer_focus\(|\b(failure_quality|icon|scrub)_hit\(' "$SRC/app" +want hittest && gate_zero hittest 'pointer_focus\(|\b(failure_quality|icon|scrub)_hit\(' "$SRC/app" # frame: the three privileged OS-primitive calls, ZERO-TOLERANCE outside `app/run.rs` (D4) — no # allowlist file, because there is exactly one legitimate home once D1 lands: `app/run.rs` is the @@ -916,6 +1089,7 @@ gate_zero hittest 'pointer_focus\(|\b(failure_quality|icon|scrub)_hit\(' "$SRC/a # actual call typed outside a string still fails this gate. `// `-prefixed comment lines (`app/run.rs` keeps one, describing where a call # used to live) are stripped the same way `grep_code` above does for every other rule. frame_pat='(crate|plx_platform)::tv::window::(pump_bus|opaque_route|clear_opaque_region)\(' +if want frame; then frame_bad=0 while IFS= read -r f; do [ "$f" = "$SRC/app/run.rs" ] && continue @@ -934,6 +1108,7 @@ while IFS= read -r f; do done < <(grep -rlE --include='*.rs' "$frame_pat" "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_PLATFORM" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" 2>/dev/null | sort) if [ "$frame_bad" -eq 0 ]; then ok "frame" else fail "frame: $frame_bad line(s) of a privileged OS-primitive call outside app/run.rs"; fi +fi # frame # sink: the Starfish/ACB verbs (`tv::sink::VideoSink`) are the player's alone (step L15). Only # `player/`, `play-uri/`, the native `webos/` port, and `port.rs` (which installs one) @@ -942,6 +1117,7 @@ else fail "frame: $frame_bad line(s) of a privileged OS-primitive call outside a # ACB plane's boot and hands it on (it was `player/plane_boot.rs`; the composition root is where the # driver set is built). Every other module reaches the television through the narrower `tv` interfaces. Wholly-test files are skipped like inline # `#[cfg(test)]` blocks. Zero, no allowlist. +if want sink; then sink_bad=0 while IFS= read -r line; do [ -z "$line" ] && continue @@ -957,9 +1133,11 @@ while IFS= read -r line; do done < <(grep_code 'tv::sink::(installed|display_installed)|\b(VideoSink|DisplaySink)\b' "$SRC" "$SRC_PLATFORM" "$SRC_UI" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS") if [ "$sink_bad" -eq 0 ]; then ok "sink" else fail "sink: $sink_bad line(s) naming the video sink outside playback execution, port.rs, tv.rs and tv/"; fi +fi # sink # route: `Route::` in app/ = 0, and `enum Route` gone from the whole tree (D1/D4). No allowlist: # the type is meant to be retired, not narrowed. +if want route; then route_app=$(grep_code 'Route::' "$SRC/app") if [ -z "$route_app" ]; then ok "route: Route:: in app/" else fail "route: $(echo "$route_app" | wc -l | tr -d ' ') \`Route::\` use(s) in app/ — the page alphabet is \`AppArg\` (D1)"; fi @@ -969,6 +1147,7 @@ else echo "$route_enum" | sed 's/^/ /' fail "route: enum Route re-declared — the page alphabet is \`AppArg\` (D1)" fi +fi # route # fnlen: app/run.rs::run <= 200 lines, run_application (app/mod.rs, the D4 skeleton) <= 10 and # plex_run (port.rs: install, then hand over) <= 10 — counted by brace @@ -984,6 +1163,7 @@ fn_body_lines() { } ' "$file" } +if want fnlen; then run_len=$(fn_body_lines "$SRC/app/run.rs" 'run') if [ -n "$run_len" ] && [ "$run_len" -le 200 ]; then ok "fnlen: app/run.rs::run ($run_len lines)" else fail "fnlen: app/run.rs::run is ${run_len:-unknown} lines, budget 200 — a phase of the frame belongs in its own function (see run.rs's own doc)"; fi @@ -993,14 +1173,17 @@ else fail "fnlen: run_application (app/mod.rs) is ${runapp_len:-unknown} lines, plexrun_len=$(fn_body_lines "$SRC/port.rs" 'plex_run') if [ -n "$plexrun_len" ] && [ "$plexrun_len" -le 10 ]; then ok "fnlen: plex_run (port.rs) ($plexrun_len lines)" else fail "fnlen: plex_run (port.rs) is ${plexrun_len:-unknown} lines, budget 10"; fi +fi # fnlen # testmod: `#[cfg(test)] mod` count in app/mod.rs = 0 (D4/D8) — every test module named in D8's # table is meant to have moved to its subject's own file by the time this gate is added. +if want testmod; then testmod_n=$(grep -c '^#\[cfg(test)\]$' "$SRC/app/mod.rs" 2>/dev/null || echo 0) # only count ones immediately followed by `mod `, matching the mutators gate's own convention testmod_n=$(awk '/^#\[cfg\(test\)\]$/{p=1;next} p && /^mod /{c++} {p=0} END{print c+0}' "$SRC/app/mod.rs") if [ "$testmod_n" -eq 0 ]; then ok "testmod: app/mod.rs" else fail "testmod: $testmod_n \`#[cfg(test)] mod\` block(s) in app/mod.rs — a test lives beside its subject (D8)"; fi +fi # testmod # threads: `thread::spawn(` outside task.rs, PRODUCTION lines only, EVERY spelling — a # `#[cfg(test)] mod` block is skipped by brace depth, the same convention the `mutators` gate @@ -1019,6 +1202,7 @@ else fail "testmod: $testmod_n \`#[cfg(test)] mod\` block(s) in app/mod.rs — a # `use std::thread::{..spawn..}` lines outside task.rs itself), so this spelling adds nothing # to the count yet — it exists so a FUTURE import cannot go unmatched the way the bare # `thread::spawn(` spelling used to. +if want threads; then threads_bad=0 while IFS= read -r f; do # a wholly-test file is test code exactly like an inline `#[cfg(test)] mod` block, which the @@ -1041,6 +1225,7 @@ done < <(grep -rlE --include='*.rs' '\bspawn\(' "$SRC" "$SRC_BASE" "$SRC_MACHINE threads_declared=$(sed -n 's/^# count: *//p' ci/allow/threads.txt | head -1) if [ "$threads_bad" -eq "${threads_declared:-0}" ]; then ok "threads" else fail "threads: $threads_bad line(s) outside ci/allow/threads.txt (declared count is exactly ${threads_declared:-0}, not a ceiling)"; fi +fi # threads # ---- the ledger rules: blocking, workers, globals, forks, fxlanes ------------------------------- # A LEDGER is an exact multiset of production SITES, one line per site, held under ci/allow and only @@ -1179,6 +1364,7 @@ EOF_STALE # The enclosing fn is the innermost `fn ` whose body holds the call, tracked by # brace depth; a call in a closure belongs to the fn around the closure. The scan is the shared # `ci/ledger.awk` (the ledger machinery above). +if want blocking; then blocking_sites=$( grep -rlE --include='*.rs' 'allow_blocking' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_PLATFORM" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" 2>/dev/null \ | grep -v "^$SRC_BASE/task/blocking.rs\$" | sort \ @@ -1194,6 +1380,7 @@ LG_LEDGERS=ci/allow/blocking.txt LG_COUNT_FILE=ci/allow/blocking.txt \ LG_NOUN='the frame-thread exception ledger' \ LG_TAIL='a new allow_blocking site moves its work to a worker instead; the list only shrinks' \ ledger_check blocking "$blocking_sites" +fi # blocking # ---- the Sans-IO ledgers (docs/sans-io.md): workers, globals, forks, fxlanes ------------------------ # The rule they prepare: logic never performs IO. A MACHINE (a screen, a data/ store, the session @@ -1238,6 +1425,8 @@ globals_pat='client_for|current_server|current_snapshot|keypin::(revision|blocke # candidate: an item under it is skipped whole. forks_pat='cfg.*test|test.*cfg|#!?\[cfg\([^]]*$|cfg!\([^)]*$' forks_plain_re='^[[:space:]]*#\[cfg\((test|any\(test, feature = "test-support"\)|all\((test|any\(test, feature = "test-support"\)), [^()]*\))\)\][[:space:]]*$' +# PRELUDE 3 of 3: computed only when workers, globals or forks is selected. +if any_wanted workers globals forks; then ledger_hits=$( find "$SRC_DATA" "$SRC_SESSION" "$SRC_PLEX" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_SCREENS" "$SRC_UI" "$SRC_APPKIT" "$SRC_MACHINE" "$SRC_PLATFORM/tv/plane.rs" \ -name '*.rs' -type f 2>/dev/null \ @@ -1253,6 +1442,7 @@ ledger_hits=$( !df && $0 ~ f && $0 !~ p { print "F\t" FILENAME; df = 1 } ' ) +fi # ledger_candidates : the files of that rule's scope the prefilter kept ledger_candidates() { printf '%s\n' "$ledger_hits" | awk -F'\t' -v r="$1" '$1 == r { print $2 }' | sort -u @@ -1269,6 +1459,7 @@ ledger_candidates() { # although no machine calls it today, because a machine that did would be starting a worker. A worker # named without a call (`.map(spawn_small)`) is a site too; only a rename (`use ... as`) is refused, # because the renamed calls are invisible. +if want workers; then workers_sites=$( ledger_candidates W \ | LG_MODE=call LG_KEYSPELL=1 LG_USE_OK=1 LG_REF_USE_ONLY=1 \ @@ -1285,6 +1476,7 @@ LG_LEDGERS="$(echo ci/allow/workers/*.txt)" LG_AREA_CHECK=1 \ LG_NOUN='the worker-start ledger' \ LG_TAIL='a machine starts no worker: its work leaves as a typed effect the app runs (docs/sans-io.md); the ledgers only shrink' \ ledger_check workers "$workers_sites" +fi # workers # globals: a production read of a process-global registry in a MACHINE — `client_for(`, `current_server(`, # `current_snapshot(`, `keypin::revision(`, `keypin::blocked_for(`, `session::peek(`, `grant::offers(`, the @@ -1328,6 +1520,7 @@ LG_LEDGERS="$(echo ci/allow/workers/*.txt)" LG_AREA_CHECK=1 \ # a call (`.and_then(client_for)`) reads the registry as surely as a call does, so it is a site too; only a # rename (`use ... as`) is refused, because the renamed calls are invisible. Each getter's own definition is # not a site. +if want globals; then globals_sites=$( { ledger_candidates G printf '%s\n' rust-modules/plex/src/plex/session.rs "$SRC_MEDIA/player/lifecycle.rs"; } \ @@ -1346,6 +1539,7 @@ LG_LEDGERS="$(echo ci/allow/globals/*.txt)" LG_AREA_CHECK=1 \ LG_NOUN='the process-global read ledger' \ LG_TAIL='a machine reads no registry: the value arrives in an event or an argument (docs/sans-io.md); the ledgers only shrink' \ ledger_check globals "$globals_sites" +fi # globals # forks: a production test/production fork across every machine crate (FORK_SCOPE: all of data/, plex/, media/, # session/, screens/, ui/, appkit/ and machine/) — a `#[cfg(..)]` @@ -1360,6 +1554,7 @@ LG_LEDGERS="$(echo ci/allow/globals/*.txt)" LG_AREA_CHECK=1 \ # it) — never a line number. A file can # hold a fork only if it has a cfg line that is not a plain test-only attribute (an item under one is # skipped whole), which is what the candidates are. +if want forks; then forks_sites=$( ledger_candidates F \ | LG_MODE=fork ledger_scan | sort @@ -1371,6 +1566,7 @@ LG_LEDGERS="$(echo ci/allow/forks/*.txt)" LG_AREA_CHECK=1 \ LG_NOUN='the test/production fork ledger' \ LG_TAIL='logic has no cfg(test) fork: the seam is a typed effect tests and replay deliver events through (docs/sans-io.md); the ledgers only shrink' \ ledger_check forks "$forks_sites" +fi # forks # fxlanes: in `Bridge::app_effect` every `AppFx::` arm either pushes `Fx::Deliver(` — the ordered # FIFO, where a result returns as one addressed event in the same drain — or is a ledger line: an arm that @@ -1378,6 +1574,7 @@ LG_LEDGERS="$(echo ci/allow/forks/*.txt)" LG_AREA_CHECK=1 \ # own timing. A NEW variant with a side queue fails; so does a new arm that is not on the FIFO. Keyed # `::AppFx::`, one line for EACH variant on an arm's head (`AppFx::A(r) | AppFx::B(r) => ..` # is two), and `::AppFx::_` for an arm whose head names none (`other => ..`, `_ => ..`). +if want fxlanes; then fxlanes_sites=$( grep -rlE --include='*.rs' 'fn app_effect' "$SRC" 2>/dev/null | sort \ | LG_MODE=arm LG_ARM_FN=app_effect LG_ARM_MATCH='(^|[^A-Za-z0-9_])match[[:space:]]+fx[[:space:]]*\{' LG_ARM_OK='Fx::Deliver\(' \ @@ -1390,6 +1587,7 @@ LG_LEDGERS="$(echo ci/allow/fxlanes/*.txt)" LG_AREA_CHECK=1 \ LG_NOUN='the Bridge::app_effect lane ledger' \ LG_TAIL='an AppFx arm pushes Fx::Deliver(..) onto the one ordered FIFO instead of a side queue (docs/sans-io.md); the ledgers only shrink' \ ledger_check fxlanes "$fxlanes_sites" +fi # fxlanes # tmppath: a literal `/tmp/plxnative-` string outside dev.rs and the log sinks, = 0 (D4). The # earlier version matched only a literal and a filesystem-open VERB co-occurring on the SAME @@ -1415,6 +1613,7 @@ LG_LEDGERS="$(echo ci/allow/fxlanes/*.txt)" LG_AREA_CHECK=1 \ # path through `paths::in_runtime_dir("plxnative-…")`, a bare filename with no `/tmp/` prefix, so # neither one is a `/tmp/plxnative-` literal in the first place and there is no second file to # name here (re-verify this if a log sink is ever given a hardcoded `/tmp/` path). +if want tmppath; then tmp_hits=$(python3 - "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_PLATFORM" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" <<'PY' import os, sys @@ -1506,6 +1705,7 @@ else echo "$tmp_hits" | sed 's/^/ /' fail "tmppath: $(echo "$tmp_hits" | grep -c . ) line(s) of a literal /tmp/plxnative- path outside dev.rs, not comment or log-message text" fi +fi # tmppath # paging: the two Plex paging parameter names are spelled in ONE non-test file, the `paged_path` @@ -1514,6 +1714,7 @@ fi # not counted (they cannot build a request), and test code is: whole test files (the `wholly_test` # classification above) and `#[cfg(test)]` items, found from tokens so a literal inside a string is # never mistaken for a comment. Zero, no allowlist. Scans every crate root, not only plex's. +if want paging; then paging_hits=$(WHOLLY_TEST="$wholly_test" python3 - "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_PLATFORM" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" <<'PY' import os, sys sys.path.insert(0, "ci") @@ -1579,15 +1780,23 @@ else echo "$paging_hits" | sed 's/^/ /' fail "paging: $(echo "$paging_hits" | grep -c . ) production literal(s) spell X-Plex-Container- outside rust-modules/plex/src/plex/paging.rs (use paged_path)" fi +fi # paging # every allowlist's declared count equals its entries — the flat lists, and the per-area ledger files # under ci/allow// (workers, globals, forks, fxlanes) +if want allowlist-counts; then for f in ci/allow/*.txt ci/allow/*/*.txt; do [ -f "$f" ] || continue declared=$(sed -n 's/^# count: *//p' "$f" | head -1) entries=$(grep -cvE '^[[:space:]]*(#|$)' "$f") [ "$declared" = "$entries" ] || fail "$f declares count $declared but has $entries entries" done +fi # allowlist-counts +# RULES and the `want` calls above must name the same rules in the same order, whatever was selected +# (every guard is visited whether or not its rule runs): a rule outside RULES cannot be selected by +# name, and a name without a guard would be "selected" and run nothing. +[ "$rules_seen" = " ${RULES[*]}" ] || fail "RULES and the want guards disagree: RULES is [${RULES[*]}], the guards are [${rules_seen# }]" +if [ -n "$only" ] && [ "$fails" -eq 0 ]; then echo "check-deps: the selected gates are green (--only $only_arg)"; exit 0; fi [ "$fails" -eq 0 ] && { echo "check-deps: all gates green"; exit 0; } echo "check-deps: $fails gate(s) failed"; exit 1 diff --git a/ci/check-ports.py b/ci/check-ports.py index f799bb17b4..f37a9e32de 100644 --- a/ci/check-ports.py +++ b/ci/check-ports.py @@ -51,21 +51,53 @@ def ports(root, ini): result.add(name) return result +# `wall_sites` needs one of these words in the source: `WALL` spells `Instant::`, `SystemTime::` or +# `.elapsed(`, and the alias test needs the token `Instant` or `SystemTime`. A file without any of +# them cannot hold a wall-clock operation, so this rule does not lex or classify it: lexing the +# ~690 files of the scopes (and the wholly-test classification of every scope) was most of this +# gate's 4.6 s of CPU, run once per `ci/check-deps.sh` that selects `wall` (every full run; the +# harness's gate self-tests run only the rule they plant for, so only its whole-script tests and +# its every-rule sweep, which runs `--only wall` too, run it). +# The skip changes what an UNLEXABLE file does here, never what a wall site does: a file with no +# wall word and an unterminated raw string no longer fails THIS rule. `ci/check-list-caps.py` (a step +# of ci/check-python-steps.txt) reports it instead: it runs `rtm.lex` over every production file under +# every `rust-modules/*/src` and `rust-modules/src` (all these scopes), and `rtm.wholly_test_files` over +# each of those roots, and lets the ValueError fail the step. Test-named files (`*_tests.rs`, `tests.rs`, +# a `tests/` directory) and wholly-test files are the ones it does not lex: test code, which rustc rejects +# when it is not Rust. `wholly_test_files(scope)` is computed only for a scope holding a wall site, so an +# unbalanced token group fails this rule only then (ci/test_check_ports.py pins both halves). +NEEDS_WALL_WORD = re.compile(r'Instant|SystemTime|elapsed') + def check(root=ROOT, ini=None): exempt = ports(root, ini or root / 'ci/ports.ini') - tests = set() - for scope in SCOPES: - path = root / scope - if path.is_dir(): tests.update(rtm.wholly_test_files(path)) + scope_paths = [root / scope for scope in SCOPES] + wholly_tests = {} + def is_wholly_test(path): + """`path` is in the union of `wholly_test_files(scope)` over the directory scopes holding it, + each computed on its first use: a scope whose files carry no wall-clock word never is.""" + for scope in scope_paths: + if scope.is_dir() and scope in path.parents: + if scope not in wholly_tests: wholly_tests[scope] = rtm.wholly_test_files(scope) + if path.resolve() in wholly_tests[scope]: return True + return False problems = [] files = set() - for scope in SCOPES: - path = root / scope + for path in scope_paths: files.update(path.rglob('*.rs') if path.is_dir() else ([path] if path.exists() else [])) for path in sorted(files): name = path.relative_to(root).as_posix() - if name in exempt or path.resolve() in tests: continue - if wall_sites(shape.production_tokens(path.read_text(encoding='utf-8'))): + if name in exempt: continue + source = path.read_text(encoding='utf-8') + if not NEEDS_WALL_WORD.search(source): continue + try: has_wall_site = wall_sites(shape.production_tokens(source)) + except ValueError: + # A file with a wall word that cannot be lexed fails this gate, EXCEPT a wholly-test file, + # which this rule never lexed (it skipped those first). Classifying before lexing every + # such file would compute all seven scopes' wholly-test sets (about twice this gate's time); + # classifying only the file that failed to lex costs nothing on a valid tree. + if is_wholly_test(path): continue + raise + if has_wall_site and not is_wholly_test(path): problems.append(f'{name}: wall clock outside ci/ports.ini') return problems diff --git a/ci/check-python-steps.txt b/ci/check-python-steps.txt index e3c1546e67..df2ee1fc7a 100644 --- a/ci/check-python-steps.txt +++ b/ci/check-python-steps.txt @@ -21,11 +21,63 @@ # `ci/test_check_collisions.py` runs these steps side by side to check the first rule; a step that # breaks one of them shows up there rather than as a flake in somebody else's `make check`. # -# ORDER is only the START order: the sixteen slowest steps (measured 2026-10-07) come first, so the -# last one to start is a short one; the run lasts as long as the longest step plus the queue. A new -# step goes at the END; move it up only after measuring (`make check-python-rest` prints each step's -# wall and CPU time and the slowest three). +# ORDER is only the START order: the nine slowest steps of the CI run measured 2026-11-14 (the first +# block below) come first, then the thirteen others of the sixteen slowest measured 2026-10-07 (three of +# those sixteen are among the nine), so the last one to start is a short one; the run lasts as long as +# the longest step plus the queue. A new step goes at the END; move it up only after measuring +# (`make check-python-rest` prints each step's wall and CPU time and the slowest three). +# The nine slowest steps (CI, 2026-11-14: machine-shape 225 s, build-gc 98 s, arm-profile 71 s, check-elf 56 s, +# transition-arguments 47 s, disk-budget 44 s, disk-preflight 44 s, tv-lock 43 s, collisions 40 s) start first: +# test_check_machine_shape.py sat 110th and ended the job at 413 s (it starts ~190 s in, then runs 225 s). + +# The machine-shape gate (ci/machines.ini, docs/sans-io.md): a state machine listed there keeps its state private (a `pub`, +# `pub(crate)` or `pub(super)` field of the listed struct fails, as does a stale entry), so its one writer stays `step` and a new +# way to change it is a new event. It also REPORTS, and never fails on, each machine's `bool` and `Option<..>` field counts: a +# report-only flag ratchet. Pure lexing, no cargo; the self-tests run on synthetic trees in a private temp dir. +python3 ci/test_check_machine_shape.py +# tools/build-gc.sh against disposable repositories, fleet dirs and caches: every OTHER reclaim mode refuses under a held FFmpeg lock, a +# live checkout is spared, `--auto`'s order is the planner's (and its `--worktrees` stage spares a lane inside the idle window, and one holding an ignored file that is not build output), +# `--worktrees` judges a lane against `origin/main` without refreshing its index, and `--evict PLAN` deletes exactly what the plan +# names after re-probing it: it refuses paths that are not derived build trees, skips a tree that turned live, goes on under an +# FFmpeg lock, and never takes a /tmp tree that only looks old. `--evict` runs only inside the fixture's own directories. +python3 ci/test_build_gc.py +# `ARM_PROFILE`: a plain local build compiles the ARM staticlib with the fast `tvdev` profile and +# everything that ships or runs in CI keeps fat-LTO `release`; resolved through print-bench-config. +python3 ci/test_arm_profile.py +python3 ci/test_check_elf.py +python3 ci/test_transition_arguments.py +# tools/disk-budget.py, the disk budget's inventory and planner (docs/disk-budget.md): the ladder's order, stopping at the line, +# refusing only when the whole ladder cannot free the build's estimate plus the reserve, and NEVER planning the current checkout +# below rung 6 (nor, there, the tree being built), a live, tracked, pkg/, vendor/ or non-PlxNative tree; private-byte accounting under hard links; `origin/main` merged detection +# (squash merges, a stale local main, nothing written to the repository); `report` changes nothing; the plan file `build-gc.sh --evict` +# reads (format, order, the stale slot, rung-6 `current`), `settle`, the cargo seed never planned, a /tmp tree aged by ctime so a +# backdated fixture is never a candidate, the probes (`probe`, `tmp-trees`), and that collecting an inventory never rewrites a +# lane's index. Synthetic inventories plus private temp repositories, a stubbed lsof, no real /tmp scan. +python3 ci/test_disk_budget.py +# The disk budget at every build entry: `make disk-preflight` is `tools/disk-budget.py preflight` and an ORDER-ONLY prerequisite of +# every Makefile target that runs cargo. Static: the Makefile is parsed and every target whose recipe runs cargo (directly or through a +# script) must be in `make -s print-disk-entries`, with the prerequisite after the `|`, before the build starts, and the recursive +# `$(MAKE)` lines carrying PLX_DISK_BUDGET_DONE. Dynamic, on a fixture repository with PLX_GC_TEST_FREE_KIB and stubbed lsof/pgrep: +# at comfort nothing starts and the planner is not imported; below the reserve with nothing to evict it refuses with the reason; below +# comfort it evicts idle trees and never the tree being built; the marker and PLX_MIN_FREE_MB=0 are no-ops; the auto lock is +# taken, a live holder is waited on for a bounded time (one --wait-secs deadline for the whole preflight) and no plan is made while it runs (a finished or stale holder is taken over); the inventory cache; a pretend emergency is never planned over real +# trees; the cold store's unpark of an absent parked tree: the cheap no-gos (config removed, volume unmounted) come before any lock wait, the +# lock is held to claim the copy and not across it (two trees restore at once), a claimed or dead-claimed tree, and the free-space rule. `make -n` and `make -s print-*` only, no cargo. +python3 ci/test_disk_preflight.py +# The TV lock's own protocol suite, with NO television: the device half runs under a local sh in a temp dir, and the +# HEADS-UP cases run the real `acquire`/`break` as children with their own lane, lease directory and lock path (one +# line on a new lease, including your own expired one, none on a live renew or a refusal). It also runs the pre-flight's +# verdict table (IDLE / IN USE / UNKNOWN) on fixture replies, cuts a hung probe off at PLX_TV_PREFLIGHT_SECS, and runs +# `with` for real: it refuses to start on IN USE, PLX_TV_IN_USE_OK overrides, and its renewer's whole process tree dies +# with it. That spawns and kills background processes, so it takes about 20 s, not milliseconds. Then the PostToolUse hook +# that turns the HEADS-UP and IN USE lines into reminders: payload shapes, the failure and unrelated cases, malformed +# stdin. Both host-only. +tools/tv-lock.sh selftest +# Nothing that runs at once may collide: two checkouts running the scratch-writing steps (test-compat.py, +# the C unit tests) at once, and a mix of different steps run together as the runner runs this file, +# each against one shared TMPDIR; and no test source binds a fixed port. +python3 ci/test_check_collisions.py # The `check` lock wrapper's own suite: two shared runs at once and a third waiting (naming both # holders), a SIGKILLed holder freeing its slot, PLX_CHECK_SLOTS=1 serializing, exclusive mode for # the benchmarks (blocks and is blocked by shared runs, not starved by a stream of them, two @@ -39,17 +91,6 @@ python3 ci/test_build_bench.py # one record per day (a same-day re-run replaces it), nothing written for a failed benchmark, a red `check` costing only # its own rows, a noisy day marked and kept, nothing identifying in the runner block. Synthetic documents, no cargo. python3 ci/test_build_history.py -# tools/build-gc.sh against disposable repositories, fleet dirs and caches: every OTHER reclaim mode refuses under a held FFmpeg lock, a -# live checkout is spared, `--auto`'s order is the planner's (and its `--worktrees` stage spares a lane inside the idle window, and one holding an ignored file that is not build output), -# `--worktrees` judges a lane against `origin/main` without refreshing its index, and `--evict PLAN` deletes exactly what the plan -# names after re-probing it: it refuses paths that are not derived build trees, skips a tree that turned live, goes on under an -# FFmpeg lock, and never takes a /tmp tree that only looks old. `--evict` runs only inside the fixture's own directories. -python3 ci/test_build_gc.py -python3 ci/test_check_elf.py -# Nothing that runs at once may collide: two checkouts running the scratch-writing steps (test-compat.py, -# the C unit tests) at once, and a mix of different steps run together as the runner runs this file, -# each against one shared TMPDIR; and no test source binds a fixed port. -python3 ci/test_check_collisions.py # `tools/tv-config.sh`, the ONE resolver for the TV address and Wake-on-LAN MAC (this checkout's # .tv-host/.tv-mac, the main checkout's, then ~/.config/plxnative/), and every reader of it # (tv-ssh, wake-tv, the Makefile's TV, tests/run.py, stream-screen.py), against a throwaway repo @@ -213,9 +254,6 @@ python3 tools/test_ci_test_results.py # a pass, every `test result:` line is printed), both against a fake cargo; nothing is compiled. python3 ci/test_test_crate.py python3 ci/test_cargo_test_parallel.py -# `ARM_PROFILE`: a plain local build compiles the ARM staticlib with the fast `tvdev` profile and -# everything that ships or runs in CI keeps fat-LTO `release`; resolved through print-bench-config. -python3 ci/test_arm_profile.py # `HOST_THREADS`: rustc's parallel front end for the local host test builds only; off for CI, RELEASE, # SYMBOLS and every non-debug flavour, and named by no ARM, simulator, clippy or workflow line. python3 ci/test_host_threads.py @@ -308,49 +346,17 @@ python3 ci/gen-third-party-notices.py --check # --skip-if-missing only so a runner without Rust is not red here: CI's host-lint job runs it strict. python3 ci/test_check_vfp.py python3 ci/check-vfp.py --skip-if-missing -# tools/disk-budget.py, the disk budget's inventory and planner (docs/disk-budget.md): the ladder's order, stopping at the line, -# refusing only when the whole ladder cannot free the build's estimate plus the reserve, and NEVER planning the current checkout -# below rung 6 (nor, there, the tree being built), a live, tracked, pkg/, vendor/ or non-PlxNative tree; private-byte accounting under hard links; `origin/main` merged detection -# (squash merges, a stale local main, nothing written to the repository); `report` changes nothing; the plan file `build-gc.sh --evict` -# reads (format, order, the stale slot, rung-6 `current`), `settle`, the cargo seed never planned, a /tmp tree aged by ctime so a -# backdated fixture is never a candidate, the probes (`probe`, `tmp-trees`), and that collecting an inventory never rewrites a -# lane's index. Synthetic inventories plus private temp repositories, a stubbed lsof, no real /tmp scan. -python3 ci/test_disk_budget.py -# The disk budget at every build entry: `make disk-preflight` is `tools/disk-budget.py preflight` and an ORDER-ONLY prerequisite of -# every Makefile target that runs cargo. Static: the Makefile is parsed and every target whose recipe runs cargo (directly or through a -# script) must be in `make -s print-disk-entries`, with the prerequisite after the `|`, before the build starts, and the recursive -# `$(MAKE)` lines carrying PLX_DISK_BUDGET_DONE. Dynamic, on a fixture repository with PLX_GC_TEST_FREE_KIB and stubbed lsof/pgrep: -# at comfort nothing starts and the planner is not imported; below the reserve with nothing to evict it refuses with the reason; below -# comfort it evicts idle trees and never the tree being built; the marker and PLX_MIN_FREE_MB=0 are no-ops; the auto lock is -# taken, a live holder is waited on for a bounded time (one --wait-secs deadline for the whole preflight) and no plan is made while it runs (a finished or stale holder is taken over); the inventory cache; a pretend emergency is never planned over real -# trees; the cold store's unpark of an absent parked tree: the cheap no-gos (config removed, volume unmounted) come before any lock wait, the -# lock is held to claim the copy and not across it (two trees restore at once), a claimed or dead-claimed tree, and the free-space rule. `make -n` and `make -s print-*` only, no cargo. -python3 ci/test_disk_preflight.py # RUST_INPUTS (the Makefile's hand-kept list of directories whose edits rebuild the app library) must search every crate # the app reaches through `path` dependencies: a crate left out is one whose edits `make` never sees, so `make ipk` packages # the previous library and says nothing. Reads manifests only, no cargo; the self-test plants a missing crate in a temp tree. python3 ci/test_check_rust_inputs.py python3 ci/check-rust-inputs.py -# The machine-shape gate (ci/machines.ini, docs/sans-io.md): a state machine listed there keeps its state private (a `pub`, -# `pub(crate)` or `pub(super)` field of the listed struct fails, as does a stale entry), so its one writer stays `step` and a new -# way to change it is a new event. It also REPORTS, and never fails on, each machine's `bool` and `Option<..>` field counts: a -# report-only flag ratchet. Pure lexing, no cargo; the self-tests run on synthetic trees in a private temp dir. -python3 ci/test_check_machine_shape.py python3 ci/test_check_machine_writer.py python3 ci/check-machine-shape.py # tools/pr-land.py (gate / wait / merge / restack) against a fake `gh` on PATH and an injected sleeper: a failed, pending, missing, draft, behind # or head-moved PR never reaches `gh pr merge` (#387), the polling and backoff, the head-oid race, the verify against a temporary # origin, and a planted secret refused before any `gh` call. Real gh JSON as fixtures; temp dirs only, no network, no sleeping on the poll or race timers (one test lets a hung gh hit a 1 s timeout). python3 tools/test_pr_land.py -# The TV lock's own protocol suite, with NO television: the device half runs under a local sh in a temp dir, and the -# HEADS-UP cases run the real `acquire`/`break` as children with their own lane, lease directory and lock path (one -# line on a new lease, including your own expired one, none on a live renew or a refusal). It also runs the pre-flight's -# verdict table (IDLE / IN USE / UNKNOWN) on fixture replies, cuts a hung probe off at PLX_TV_PREFLIGHT_SECS, and runs -# `with` for real: it refuses to start on IN USE, PLX_TV_IN_USE_OK overrides, and its renewer's whole process tree dies -# with it. That spawns and kills background processes, so it takes about 20 s, not milliseconds. Then the PostToolUse hook -# that turns the HEADS-UP and IN USE lines into reminders: payload shapes, the failure and unrelated cases, malformed -# stdin. Both host-only. -tools/tv-lock.sh selftest python3 .claude/hooks/tv-lock-notify-test.py # The custom agents' files (AGENTS.md, "Harness-specific files"): every `.agents/agents/.md` carries a matching frontmatter # `name`, an explicit `model:` (one documented exemption), a description, a RELATIVE `.claude/agents/.md` symlink that resolves @@ -399,7 +405,6 @@ python3 ci/test_step_scope.py python3 ci/test_machine_readonly.py python3 ci/test_readonly_dependencies.py python3 ci/test_readonly_generated.py -python3 ci/test_transition_arguments.py # tools/cold-store.py, the opt-in cold store that parks idle build trees on a second volume: unconfigured it creates no file anywhere; each # reason `available()` can give (no config, no ditto, an unmounted /Volumes root, the same device as the build tree, under min_free_gib, a diff --git a/ci/check-statics.sh b/ci/check-statics.sh index d08dfec75e..23a1bdde60 100755 --- a/ci/check-statics.sh +++ b/ci/check-statics.sh @@ -65,7 +65,7 @@ ok() { echo " ok — $*"; } # path is now a loud gate failure, not a swallowed scan of nothing. GATED_MUT_PATHS=("$UI" "$APPKIT" "$SCREENS" "$DATA/person.rs" "$DATA/metadata.rs" "$DATA/metadata" "$DATA/pms.rs" "$DATA/stores") GATED_WIDE_PATHS=("$DATA/search") -for p in "${GATED_MUT_PATHS[@]}" "${GATED_WIDE_PATHS[@]}" "$MEDIA/route/decision.rs" "$MEDIA/player/engine.rs" "$UI/press.rs"; do +for p in "${GATED_MUT_PATHS[@]}" "${GATED_WIDE_PATHS[@]}" "$MEDIA/route/decision.rs" "$MEDIA/player/engine.rs" "$UI/dispatch/press.rs"; do [ -e "$p" ] || fail "gated path missing: $p — the statics gate would silently scan nothing here" done @@ -75,7 +75,7 @@ matches() { printf '%s\n' "$wide" grep -nE '^\s*static mut SESSION\b' "$MEDIA/route/decision.rs" | sed "s|^|$MEDIA/route/decision.rs:|" grep -nE '^\s*static mut ENGINE\b' "$MEDIA/player/engine.rs" | sed "s|^|$MEDIA/player/engine.rs:|" - grep -nE '^\s*static mut S\b' "$UI/press.rs" | sed "s|^|$UI/press.rs:|" + } | sed -E "s/^([^:]+):[0-9]+:[[:space:]]*(pub(\(crate\))? )?static (mut )?([A-Za-z_][A-Za-z_0-9]*).*/\1 \5/" | sort -u } diff --git a/ci/list-caps.ini b/ci/list-caps.ini index d89d7764eb..cc097a031a 100644 --- a/ci/list-caps.ini +++ b/ci/list-caps.ini @@ -485,9 +485,6 @@ reason = A transcode plan covers the one version and part being played (the play # ---- machine ------------------------------------------------------------ -[machine/src/idle.rs::settled] -class = not-a-list -reason = Clamps a spring-rest threshold (animation). [machine/src/landgate.rs::MAX_DIFFS] class = not-a-list @@ -1414,7 +1411,7 @@ reason = Skeleton entries one frame keeps; a memory bound on a frame that alread class = work reason = Animated bands tracked (focused and closing); independent of catalog size. -[ui/src/press.rs::MAX_HOLD_MS] +[ui/src/dispatch/press.rs::MAX_HOLD_MS] class = not-a-list reason = MAX_HOLD_MS: uI timing, geometry, recorder or frame-budget bound; not a list. diff --git a/ci/module-layers.ini b/ci/module-layers.ini index 47071fc365..1156e95693 100644 --- a/ci/module-layers.ini +++ b/ci/module-layers.ini @@ -43,12 +43,12 @@ members = # EXTRACTED: this layer is the workspace crate `plx_machine` (rust-modules/machine/), the second # split of docs/module-layers.md. Its modules were `ui::machine` ... `ui::motion`; they are now # top-level modules of that crate, which ci/module_graph.py reads as part of the same module tree -# (a path `plx_machine::idle::note` names module `idle`). +# (a path `plx_machine::present::Present` names module `present`). # The deterministic state-machine runtime the stores, auth and screens are written against: # machines and effects, the present gate, the idle/frame wake, the landing schedule, motion. # It lived under ui/ and is not UI. uses = base -members = machine present idle landgate landing job motion +members = machine present landgate landing job motion idle_regression_tests present_contract_tests [platform] # EXTRACTED: this layer is the workspace crate `plx_platform` (rust-modules/platform/), the third diff --git a/ci/proofs/platform-generated-enums.json b/ci/proofs/platform-generated-enums.json index 1b684d371f..39c853242b 100644 --- a/ci/proofs/platform-generated-enums.json +++ b/ci/proofs/platform-generated-enums.json @@ -1,47 +1,41 @@ { - "assumptions": [ - "Offline source-backed unit-enum proof; certificate changes require source review.", - "", - "No Cargo, cached output, generator execution, Copy axiom or type-name exemption.", - "The certificate pins the entire production pipeline and include namespace, not the", - "language list. Its reviewed template emits unit variants in every configuration.", - "Only enum values are certified: LocaleContext/OnceLock and methods are not.", - "Assumes ordinary Cargo/Rust/std/serde execution, no external build/config/compiler", - "overrides, output tampering or unsafe-code/compiler unsoundness attestation." - ], - "configs": { - "../.cargo/config": null, - "../.cargo/config.toml": null, - ".cargo/config": null, - ".cargo/config.toml": "82f061c716740e16cfee63a74d87159e0e0dc253e1092b87c54190c603515b14" - }, - "grammar": { - "Language": { - "catalogue_unit_variants": true, - "suffix": [ - "Pseudo" - ] - }, - "Preference": { - "catalogue_unit_variants": true, - "prefix": [ - "System" - ] - } - }, + "schema": "plx.readonly.generated-unit-enums.v1", + "package": "plx_platform", + "module": "platform/src/i18n/mod.rs", "include": "include!(concat!(env!(\"OUT_DIR\"), \"/languages.rs\"));", - "lock": "b386884c509416c6f2674eabae4d11219248349672dd5fb76f4ff2b086ac313a", - "machine_newtype": "reviewed local newtype macro emits pub struct Name(pub u32); doc attributes only", + "sources": { + "platform/Cargo.toml": "4181b79fa53a7ff6e8b0157f4d1ffe258737896603d267b4802551dee0812472", + "platform/src/lib.rs": "de49b2ad8b017496e851dd647f22aed565fa4753e80b67d43f3368c8d436e60b", + "platform/src/i18n/mod.rs": [ + "40a13d07a43c772b10587e510a69502684abfa1f582ce355b22fd935a8c46f45", + "2c978e3aa3a9215a2e96ebaec9dd5ae3cf3ee85cf1afb43a36b5f42f17ff4d52", + "9ca00f085c87dec8dcb1a356483f1c10a8452b28e3db877ab51d31528b95b503" + ], + "platform/build.rs": "565db6b510ee3a9794c614eaab5ab151703b43311087d1d52adcc845ae6d8f9c", + "platform/build_support/catalog.rs": "ed55b6029a9af5aa5cdf8a7cb70e8fd4fe657c30068ca815f5bef46428e232f9", + "build_support/install_identities.rs": "8039b85c09d27c1f9a80aded1245dd4a0c7b7ac3b633e28cb9b7a0f6d62ed621", + "machine/src/lib.rs": [ + "105afdbb05fb762e6752cef260b6d928b1d828993350aaa71651f96cee0c3188", + "c35d39ae620b5607e7035222ab1023799adaf091d6a4f737a847dd70b26c1b36" + ], + "machine/src/machine.rs": [ + "571415d64a9885248f852b402153feedd4660acbe03606e4796c59659726049f", + "03a6e18f576dcbaff66c3d7405923b155302bfb2996bb373dac115ece055a5bf", + "d08b44dbff241962286eb7e1f85897073ba9f2f712a2ba935837f901635369a8", + "9b1ffb66c7ba2eb9fdffcb4bcbf0a29cda87a003cce69b16c73567c8bc0a65b0" + ] + }, + "text_hashing": "sha256-utf8-bytes-crlf-to-lf-local-root-version-v1", "manifests": { "Cargo.toml": "efc4ecbe83c6751451fa76b8f89793e441db215d07c07aae2fb1394206007e2b", "appkit/Cargo.toml": "1e3a33f392110f269537b12f12879c6bc15309aca304b189d6b0346edf8a1186", "base/Cargo.toml": "ebe0b95553bd44f33f422f7d8e22b75ddeb53c7ee81bbe738f675690694568f7", - "data/Cargo.toml": "dc246544384d3cfe5648b13cfcbd67edff69f027d22a268dd6fdca53bdf1e794", + "data/Cargo.toml": "90a763a8a9e22bda7e95f8ede4dc10ec6e92a62b90bd0fd2e622c617d75ec6c7", "gfx/Cargo.toml": "c8889dd95a481938966c41635f85702695ce9c59956381768e6c56d215d8fc0e", - "jellyfin/Cargo.toml": "8545a9d4603bb26abbb9755a0f7d5b5f65cd389932eed97ce6b0594380a0930a", + "jellyfin/Cargo.toml": "3a2291abbcaf9bb956f709056469766fafd5c76aa1cda95c140d378d68572527", "machine/Cargo.toml": "0bc99e95272916b8d00e1a8dad81440bc4998de12ccd9a00e7853f438c813d03", - "media-codecs/Cargo.toml": "503c8681289314b5c8a63195aad6796cbad93fcb3eedd8d7cba9e8ed0233783f", "media/Cargo.toml": "2b3bb41264db9b9f30869015dfe0dd6656147c432728c9ea9301988c710a4202", + "media-codecs/Cargo.toml": "503c8681289314b5c8a63195aad6796cbad93fcb3eedd8d7cba9e8ed0233783f", "net/Cargo.toml": "bfdb3a08200642eeeafc9762733718c407529f26dce8a7b90665bc77ac928171", "platform/Cargo.toml": "4181b79fa53a7ff6e8b0157f4d1ffe258737896603d267b4802551dee0812472", "play-feed/Cargo.toml": "b85320257da74a1affd81238b8fb6caa7f28960181d5ea0e07704ceef4800515", @@ -54,33 +48,46 @@ "telemetry/Cargo.toml": "19ccd3f933efcda0052c8f0fdd9c9275c566f6d445e77a1049d0c3bd16e71b36", "ui/Cargo.toml": "0957d2057cadbd522ae2ee2446727c9c4022c75fba9cfb2347fd341a10fdacf4" }, - "module": "platform/src/i18n/mod.rs", - "package": "plx_platform", + "configs": { + ".cargo/config": null, + ".cargo/config.toml": "82f061c716740e16cfee63a74d87159e0e0dc253e1092b87c54190c603515b14", + "../.cargo/config": null, + "../.cargo/config.toml": null + }, + "lock": "e4a22856112e6ecb4025e720246bd044d872a915b1dc63bb4f5edf6bb10357fe", + "grammar": { + "Preference": { + "prefix": [ + "System" + ], + "catalogue_unit_variants": true + }, + "Language": { + "catalogue_unit_variants": true, + "suffix": [ + "Pseudo" + ] + } + }, + "machine_newtype": "reviewed local newtype macro emits pub struct Name(pub u32); doc attributes only", "review": [ "build.rs -> catalog::build(locales, OUT_DIR), no cfg-dependent producer", "parse_registry derives variant solely from validated ASCII tag", "discover preserves validated LanguageSpec; compile sorts by row", "languages_rs emits only unit variants; Pseudo cfg_attr only allows dead_code", "string slots use Rust Debug escaping; numeric slots are integers", - "install_identities writes only install_identities.rs, never languages.rs" + "install_identities writes only install_identities.rs, never languages.rs", + "PR1366: PressRead identity/live/active and owned-present sibling/test modules; canonical machine child and doc-only u32 newtype producer unchanged", + "PR1385: Canon byte-feed loops inlined (impl Canon and canon_tests only, FNV-1a byte stream unchanged); newtype macro and its ten u32 invocations unchanged" ], - "schema": "plx.readonly.generated-unit-enums.v1", - "sources": { - "build_support/install_identities.rs": "8039b85c09d27c1f9a80aded1245dd4a0c7b7ac3b633e28cb9b7a0f6d62ed621", - "machine/src/lib.rs": "105afdbb05fb762e6752cef260b6d928b1d828993350aaa71651f96cee0c3188", - "machine/src/machine.rs": [ - "571415d64a9885248f852b402153feedd4660acbe03606e4796c59659726049f", - "03a6e18f576dcbaff66c3d7405923b155302bfb2996bb373dac115ece055a5bf" - ], - "platform/Cargo.toml": "4181b79fa53a7ff6e8b0157f4d1ffe258737896603d267b4802551dee0812472", - "platform/build.rs": "565db6b510ee3a9794c614eaab5ab151703b43311087d1d52adcc845ae6d8f9c", - "platform/build_support/catalog.rs": "ed55b6029a9af5aa5cdf8a7cb70e8fd4fe657c30068ca815f5bef46428e232f9", - "platform/src/i18n/mod.rs": [ - "40a13d07a43c772b10587e510a69502684abfa1f582ce355b22fd935a8c46f45", - "2c978e3aa3a9215a2e96ebaec9dd5ae3cf3ee85cf1afb43a36b5f42f17ff4d52", - "9ca00f085c87dec8dcb1a356483f1c10a8452b28e3db877ab51d31528b95b503" - ], - "platform/src/lib.rs": "de49b2ad8b017496e851dd647f22aed565fa4753e80b67d43f3368c8d436e60b" - }, - "text_hashing": "sha256-utf8-bytes-crlf-to-lf-local-root-version-v1" + "assumptions": [ + "Offline source-backed unit-enum proof; certificate changes require source review.", + "", + "No Cargo, cached output, generator execution, Copy axiom or type-name exemption.", + "The certificate pins the entire production pipeline and include namespace, not the", + "language list. Its reviewed template emits unit variants in every configuration.", + "Only enum values are certified: LocaleContext/OnceLock and methods are not.", + "Assumes ordinary Cargo/Rust/std/serde execution, no external build/config/compiler", + "overrides, output tampering or unsafe-code/compiler unsoundness attestation." + ] } diff --git a/ci/proofs/serde-json-immutable.json b/ci/proofs/serde-json-immutable.json index c4fd0bf9ec..52ae2fbbf8 100644 --- a/ci/proofs/serde-json-immutable.json +++ b/ci/proofs/serde-json-immutable.json @@ -371,14 +371,14 @@ ".cargo/config": null, ".cargo/config.toml": "82f061c716740e16cfee63a74d87159e0e0dc253e1092b87c54190c603515b14" }, - "lock_sha256": "b386884c509416c6f2674eabae4d11219248349672dd5fb76f4ff2b086ac313a", + "lock_sha256": "e4a22856112e6ecb4025e720246bd044d872a915b1dc63bb4f5edf6bb10357fe", "manifests": { "Cargo.toml": "efc4ecbe83c6751451fa76b8f89793e441db215d07c07aae2fb1394206007e2b", "appkit/Cargo.toml": "1e3a33f392110f269537b12f12879c6bc15309aca304b189d6b0346edf8a1186", "base/Cargo.toml": "ebe0b95553bd44f33f422f7d8e22b75ddeb53c7ee81bbe738f675690694568f7", - "data/Cargo.toml": "dc246544384d3cfe5648b13cfcbd67edff69f027d22a268dd6fdca53bdf1e794", + "data/Cargo.toml": "90a763a8a9e22bda7e95f8ede4dc10ec6e92a62b90bd0fd2e622c617d75ec6c7", "gfx/Cargo.toml": "c8889dd95a481938966c41635f85702695ce9c59956381768e6c56d215d8fc0e", - "jellyfin/Cargo.toml": "8545a9d4603bb26abbb9755a0f7d5b5f65cd389932eed97ce6b0594380a0930a", + "jellyfin/Cargo.toml": "3a2291abbcaf9bb956f709056469766fafd5c76aa1cda95c140d378d68572527", "machine/Cargo.toml": "0bc99e95272916b8d00e1a8dad81440bc4998de12ccd9a00e7853f438c813d03", "media-codecs/Cargo.toml": "503c8681289314b5c8a63195aad6796cbad93fcb3eedd8d7cba9e8ed0233783f", "media/Cargo.toml": "2b3bb41264db9b9f30869015dfe0dd6656147c432728c9ea9301988c710a4202", @@ -618,7 +618,7 @@ ], "edition": "2021", "lib": "ui/src/lib.rs", - "lib_sha256": "281909b4dae22109e12cc7eb4bd42a0f46baf53f684a4c1185ccf9dc3c905f44" + "lib_sha256": "b97ad17641a265c8edab4933ba380eef6cb2e52bfc9f68272b6be505088777eb" } }, "text_hashing": "sha256-utf8-bytes-crlf-to-lf-local-root-version-v1" diff --git a/ci/readonly_dependencies.py b/ci/readonly_dependencies.py index 5efc36540e..003aab9bfa 100644 --- a/ci/readonly_dependencies.py +++ b/ci/readonly_dependencies.py @@ -17,7 +17,7 @@ import tarfile CERTIFICATE_PATH = Path(__file__).with_name('proofs') / 'serde-json-immutable.json' -CERTIFICATE_SHA256 = '22a096ca1b1f8e8d1ae70b561b0b6505c8024331edc52663e3ba664f9baa256d' +CERTIFICATE_SHA256 = 'dec1a38d6d2e154a9bdf5f4ea81a05cc2542393baa5310ce3607f8f2a3986418' SCHEMA = 'plx.readonly.locked-json.v1' REGISTRY = 'registry+https://github.com/rust-lang/crates.io-index' SUPPORTED = ['alloc', 'arbitrary_precision', 'default', 'float_roundtrip', 'raw_value', 'std', 'unbounded_depth'] diff --git a/ci/readonly_generated.py b/ci/readonly_generated.py index b89e3e744d..6fbd172546 100644 --- a/ci/readonly_generated.py +++ b/ci/readonly_generated.py @@ -13,7 +13,7 @@ from readonly_dependencies import _local_sha, _sha, _json, _manifest_paths, _configs, _workspace_hashes, WORKSPACE_HASHING CERTIFICATE_PATH = Path(__file__).with_name('proofs') / 'platform-generated-enums.json' -CERTIFICATE_SHA256 = '819c33b28d0967748a4a8bbdef318b1c85a3debda0b9fbd5445043c8388ca722' +CERTIFICATE_SHA256 = '971130a3ee36e696cfd4c3396932192a9c6d10f3f8c0831e59db26d3a56067f3' SOURCES = ['platform/Cargo.toml', 'platform/src/lib.rs', 'platform/src/i18n/mod.rs', 'platform/build.rs', 'platform/build_support/catalog.rs', 'build_support/install_identities.rs', 'machine/src/lib.rs', 'machine/src/machine.rs'] @@ -22,7 +22,11 @@ MACHINE_SOURCES = ['571415d64a9885248f852b402153feedd4660acbe03606e4796c59659726049f', - '03a6e18f576dcbaff66c3d7405923b155302bfb2996bb373dac115ece055a5bf'] + '03a6e18f576dcbaff66c3d7405923b155302bfb2996bb373dac115ece055a5bf', + 'd08b44dbff241962286eb7e1f85897073ba9f2f712a2ba935837f901635369a8', + '9b1ffb66c7ba2eb9fdffcb4bcbf0a29cda87a003cce69b16c73567c8bc0a65b0'] +MACHINE_LIB_SOURCES = ['105afdbb05fb762e6752cef260b6d928b1d828993350aaa71651f96cee0c3188', + 'c35d39ae620b5607e7035222ab1023799adaf091d6a4f737a847dd70b26c1b36'] I18N_SOURCES = ['40a13d07a43c772b10587e510a69502684abfa1f582ce355b22fd935a8c46f45', @@ -32,9 +36,14 @@ def source_hashes(root): sources = {p: _local_sha((root / p).read_bytes()) for p in SOURCES} - # Reviewed checkout variants differ only in NavOp::SelectTabWithChild, not the ID macro. + # Reviewed variants add NavOp::SelectTabWithChild or PressRead identity/live/active, or rewrite + # the Canon byte-feed loops; the complete doc-only newtype producer and its u32 invocations + # are unchanged. if sources['machine/src/machine.rs'] not in MACHINE_SOURCES: raise ValueError('unreviewed machine source') sources['machine/src/machine.rs'] = MACHINE_SOURCES + # Owned-present migration changes sibling/test modules, never the canonical machine child. + if sources['machine/src/lib.rs'] not in MACHINE_LIB_SOURCES: raise ValueError('unreviewed machine namespace') + sources['machine/src/lib.rs'] = MACHINE_LIB_SOURCES # Existing consumer variants differ in clock formatting, not include/enum identity. if sources['platform/src/i18n/mod.rs'] not in I18N_SOURCES: raise ValueError('unreviewed include namespace') sources['platform/src/i18n/mod.rs'] = I18N_SOURCES @@ -56,7 +65,9 @@ def produce_certificate(root): 'discover preserves validated LanguageSpec; compile sorts by row', 'languages_rs emits only unit variants; Pseudo cfg_attr only allows dead_code', 'string slots use Rust Debug escaping; numeric slots are integers', - 'install_identities writes only install_identities.rs, never languages.rs'], + 'install_identities writes only install_identities.rs, never languages.rs', + 'PR1366: PressRead identity/live/active and owned-present sibling/test modules; canonical machine child and doc-only u32 newtype producer unchanged', + 'PR1385: Canon byte-feed loops inlined (impl Canon and canon_tests only, FNV-1a byte stream unchanged); newtype macro and its ten u32 invocations unchanged'], 'assumptions': __doc__.splitlines()} diff --git a/ci/test_check_ports.py b/ci/test_check_ports.py index 0323917733..0d06aa96e0 100644 --- a/ci/test_check_ports.py +++ b/ci/test_check_ports.py @@ -7,6 +7,10 @@ spec = importlib.util.spec_from_file_location('check_ports', Path(__file__).with_name('check-ports.py')) gate = importlib.util.module_from_spec(spec) spec.loader.exec_module(gate) +caps_spec = importlib.util.spec_from_file_location('check_list_caps', Path(__file__).with_name('check-list-caps.py')) +caps = importlib.util.module_from_spec(caps_spec) +caps_spec.loader.exec_module(caps) +UNTERMINATED = 'const S: &str = r#"never closed;\n' class Ports(unittest.TestCase): def fixture(self, name='rust-modules/data/src/job_ports.rs', source='fn run() { Instant::now(); }', ini=None): temp = tempfile.TemporaryDirectory() @@ -38,6 +42,24 @@ def test_spacing_and_noncall_clock_references_are_reads(self): for source in ('fn f() { let now = Instant :: now; }', 'fn f() { i . elapsed ( ); }'): root = self.fixture(ini='', source=source) self.assertTrue(gate.check(root)) + def test_unlexable_file_with_a_wall_word_fails_unless_it_is_wholly_test(self): + root = self.fixture(ini='', source='fn run() { Instant::now(); }\n' + UNTERMINATED) + with self.assertRaisesRegex(ValueError, 'unterminated Rust raw string'): gate.check(root) + root = self.fixture(name='rust-modules/session/src/lib.rs', ini='', source='#[cfg(test)] mod fixture;') + (root / 'rust-modules/session/src/fixture.rs').write_text('fn test() { Instant::now(); }\n' + UNTERMINATED) + self.assertEqual(gate.check(root), []) + def test_unlexable_file_without_a_wall_word_is_left_to_the_list_caps_gate(self): + root = self.fixture(ini='', source='fn run() {}\n' + UNTERMINATED) + self.assertEqual(gate.check(root), []) + with self.assertRaisesRegex(ValueError, 'unterminated Rust raw string'): caps.read_hits(root / 'rust-modules') + def test_unbalanced_token_group_fails_the_wall_rule_only_when_a_wall_site_needs_classifying(self): + root = self.fixture(name='rust-modules/data/src/lib.rs', ini='', source='mod other; fn f() { ( }') + other = root / 'rust-modules/data/src/other.rs' + other.write_text('fn run() {}') + self.assertEqual(gate.check(root), []) + with self.assertRaisesRegex(ValueError, 'unbalanced Rust token group'): caps.read_hits(root / 'rust-modules') + other.write_text('fn run() { Instant::now(); }') + with self.assertRaisesRegex(ValueError, 'unbalanced Rust token group'): gate.check(root) def test_directories_globs_traversal_and_absolute_paths_are_rejected(self): for name in ('rust-modules/data/src', 'rust-modules/data/src/*.rs', '../outside.rs', '/absolute.rs', 'rust-modules/data/src/../x.rs', 'rust-modules/data/src/./x.rs'): diff --git a/ci/test_ci_split.py b/ci/test_ci_split.py index 70ae28dadc..f6e04d180c 100644 --- a/ci/test_ci_split.py +++ b/ci/test_ci_split.py @@ -64,7 +64,7 @@ def rule(target): r"ci/test_no_host_staticlib\.py", r"ci/test_build_not_always_dirty\.py", ], - "check-cargo-unit-hostsim": [r"cargo \+\$\(RUST_TOOLCHAIN\) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_platform -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens --features hostsim"], + "check-cargo-unit-hostsim": [r"cargo \+\$\(RUST_TOOLCHAIN\) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_platform -p plx_gfx -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_play_feed --features hostsim"], } diff --git a/ci/test_gen_notices.py b/ci/test_gen_notices.py index 73c09afc2d..23eef1c1e2 100644 --- a/ci/test_gen_notices.py +++ b/ci/test_gen_notices.py @@ -272,7 +272,7 @@ def setUp(self): self.real = gen.read_std self.addCleanup(setattr, gen, 'read_std', self.real) - def fake(self, std, rustc='rustc 1.100.0 (abc 2026-11-01)', backtrace='0.3.77'): + def fake(self, std, rustc='rustc 1.101.0 (abc 2026-11-01)', backtrace='0.3.77'): gen.read_std = lambda pin: (std, rustc, backtrace, []) def test_the_layout_round_trips_so_a_derive_changes_only_what_moved(self): @@ -283,28 +283,28 @@ def test_the_layout_round_trips_so_a_derive_changes_only_what_moved(self): def test_a_moved_release_rewrites_the_snapshot(self): std = {**self.std, 'libc': ['0.2.999'], 'compiler_builtins': ['0.1.999']} self.fake(std) - out, problems, added = gen.derive_toolchain(self.data, self.text, '1.100.0') + out, problems, added = gen.derive_toolchain(self.data, self.text, '1.101.0') self.assertEqual((problems, added), ([], [])) new = json.loads(out) - self.assertEqual(new['toolchain'], {'pin': '1.100.0', 'rustc': 'rustc 1.100.0 (abc 2026-11-01)', 'backtrace': '0.3.77'}) + self.assertEqual(new['toolchain'], {'pin': '1.101.0', 'rustc': 'rustc 1.101.0 (abc 2026-11-01)', 'backtrace': '0.3.77'}) self.assertEqual(new['std_lock']['libc'], '0.2.999') self.assertEqual(new['groups'], self.data['groups']) self.assertEqual(new['not_shipped'], self.data['not_shipped']) def test_a_crate_new_to_std_needs_a_person_and_nothing_is_rewritten(self): self.fake({**self.std, 'brandnew': ['0.1.0']}) - out, problems, added = gen.derive_toolchain(self.data, self.text, '1.100.0') + out, problems, added = gen.derive_toolchain(self.data, self.text, '1.101.0') self.assertEqual(added, ['brandnew']) self.assertEqual(out, self.text) def test_a_crate_that_left_std_lock_is_dropped_from_std_not_shipped_but_a_linked_one_needs_a_person(self): gone = {k: v for k, v in self.std.items() if k != 'dlmalloc'} self.fake(gone) - out, problems, added = gen.derive_toolchain(self.data, self.text, '1.100.0') + out, problems, added = gen.derive_toolchain(self.data, self.text, '1.101.0') self.assertEqual((problems, added), ([], [])) self.assertNotIn('dlmalloc', json.loads(out)['std_not_shipped']) self.fake({k: v for k, v in self.std.items() if k != 'libc'}) - out, problems, added = gen.derive_toolchain(self.data, self.text, '1.100.0') + out, problems, added = gen.derive_toolchain(self.data, self.text, '1.101.0') self.assertTrue(any('libc' in p for p in problems)) self.assertEqual(out, self.text) @@ -313,8 +313,8 @@ def test_the_stale_pin_is_a_plain_release_or_an_error(self): self.addCleanup(setattr, gen, 'workflow_pins', saved) gen.workflow_pins = lambda: {self.data['toolchain']['pin']} self.assertIsNone(gen.stale_pin(self.data)) - gen.workflow_pins = lambda: {'1.100.0'} - self.assertEqual(gen.stale_pin(self.data), '1.100.0') + gen.workflow_pins = lambda: {'1.101.0'} + self.assertEqual(gen.stale_pin(self.data), '1.101.0') for bad in ('nightly', '1.100', '1.1.1; rm -rf /', '1.2.3-beta'): gen.workflow_pins = lambda bad=bad: {bad} with self.assertRaises(SystemExit): diff --git a/ci/test_readonly_generated.py b/ci/test_readonly_generated.py index 47b6979f9f..aa68d00de5 100644 --- a/ci/test_readonly_generated.py +++ b/ci/test_readonly_generated.py @@ -55,6 +55,27 @@ def test_machine_macro_source_layout(self): module.write_text(original.replace('pub u32', 'pub std::cell::Cell', 1), encoding='utf-8') self.assertFalse(Proof(self.root, gate).inert(module, ['StoreOrd'])) + def test_machine_producer_and_namespace_mutations_fail_closed(self): + module = self.root / 'machine/src/machine.rs' + mutations = [ + ('machine/src/lib.rs', 'pub mod machine;', '#[path="other.rs"] pub mod machine;'), + ('machine/src/machine.rs', 'pub struct $name(pub u32);', 'pub struct $name(pub std::cell::Cell);'), + ('machine/src/machine.rs', '$(#[$m])*', '#[cfg_attr(feature="rogue", payload)] $(#[$m])*'), + ('machine/src/machine.rs', 'StoreOrd\n', 'StoreOrd, Callback\n'), + ('machine/src/machine.rs', 'StoreOrd\n', '#[cfg_attr(feature="rogue", payload)] StoreOrd\n'), + ] + for relative, old, new in mutations: + with self.subTest(path=relative, mutation=new): + path = self.root / relative + original = path.read_text(encoding='utf-8') + self.assertIn(old, original) + path.write_text(original.replace(old, new, 1), encoding='utf-8') + self.assertIsNone(generated.provenance(self.root, module)) + self.assertFalse(Proof(self.root, gate).inert(module, ['StoreOrd'])) + path.write_text(original, encoding='utf-8') + self.assertIsNotNone(generated.provenance(self.root, module)) + self.assertTrue(Proof(self.root, gate).inert(module, ['StoreOrd'])) + def test_additional_language_remains_data_only(self): entries = json.loads(self.catalogue.read_text(encoding='utf-8')) entries.append(dict(tag='sv', native_name='Svenska', region='sv-SE', script='Latn', plurals=['one', 'other'], row=entries[-1]['row'] + 1)) diff --git a/ci/test_test_crate.py b/ci/test_test_crate.py index ad5bd552aa..f083c4ba58 100644 --- a/ci/test_test_crate.py +++ b/ci/test_test_crate.py @@ -200,11 +200,46 @@ def test_the_suite_variable_is_the_recipes_package_list(self): text = (ROOT / "Makefile").read_text() suite = re.search(r"^UNIT_SUITE\s*=\s*(.+)$", text, flags=re.M).group(1).split() flags = " ".join(f"-p {p}" for p in suite) - for target in ("check-cargo-unit-default", "check-cargo-unit-hostsim", "test-fast"): + for target in ("check-cargo-unit-default", "test-fast"): start = text.index(f"\n{target}:") recipe = text[start:start + 6000].split("\n\n")[0] self.assertIn(f"test --lib {flags}", recipe, target) + def test_the_hostsim_pass_is_exactly_the_crates_that_declare_hostsim(self): + """The `hostsim` pass runs HOSTSIM_SUITE, a subset of UNIT_SUITE (`make check`'s first run of + every binary is the default pass). A crate left out has an identical test set in both passes: + no `hostsim` feature in its manifest and no `feature = "hostsim"` in its source. What the guard + does not check is the dependency side: the old pass linked those crates' test binaries + against hostsim-built `plx_base`, `plx_gfx`, `plx_platform`, `plx_media` and `plx_play_feed` + (`ENV_STEERABLE` paths, glyph-cache sizes, `ffi_host` present), and none of their tests + observes those differences. A crate that gains the feature or a cfg fails here until it is + added to HOSTSIM_SUITE (and the recipe's `-p` list).""" + text = (ROOT / "Makefile").read_text() + unit = re.search(r"^UNIT_SUITE\s*=\s*(.+)$", text, flags=re.M).group(1).split() + hostsim = re.search(r"^HOSTSIM_SUITE\s*=\s*(.+)$", text, flags=re.M).group(1).split() + self.assertEqual(hostsim, [p for p in unit if p in hostsim], "HOSTSIM_SUITE is UNIT_SUITE's order") + self.assertTrue(set(hostsim) <= set(unit)) + start = text.index("\ncheck-cargo-unit-hostsim:") + recipe = text[start:start + 6000].split("\n\n")[0] + self.assertIn("test --lib " + " ".join(f"-p {p}" for p in hostsim) + " --features hostsim", recipe) + manifests = {"plxnative-modules": ROOT / "rust-modules"} + for member in (ROOT / "rust-modules").iterdir(): + manifest = member / "Cargo.toml" + if manifest.is_file(): + name = re.search(r'^name\s*=\s*"([^"]+)"', manifest.read_text(), flags=re.M) + if name: + manifests[name.group(1)] = member + for crate in unit: + root = manifests[crate] + declares = re.search(r"^hostsim\s*=", (root / "Cargo.toml").read_text(), flags=re.M) is not None + sources = (root / "src").rglob("*.rs") + cfgs = [str(f.relative_to(ROOT)) for f in sources if 'feature = "hostsim"' in f.read_text(errors="replace")] + if crate in hostsim: + self.assertTrue(declares, f"{crate} is in HOSTSIM_SUITE but declares no `hostsim` feature, which `--features hostsim -p {crate}` needs") + else: + self.assertFalse(declares, f"{crate} declares `hostsim`: add it to HOSTSIM_SUITE and the recipe") + self.assertEqual(cfgs, [], f"{crate} has a hostsim cfg: add it to HOSTSIM_SUITE and the recipe") + def test_check_never_names_test_crate(self): text = (ROOT / "Makefile").read_text() for target in ("check-cargo-unit-default", "check-cargo-unit-hostsim"): diff --git a/ci/third-party-crates.json b/ci/third-party-crates.json index 116e19694f..197de08997 100644 --- a/ci/third-party-crates.json +++ b/ci/third-party-crates.json @@ -1,8 +1,8 @@ { "_comment": "Inputs of ci/gen-third-party-notices.py (THIRD-PARTY-NOTICES.md section 2.4). Versions are NOT here: they come from rust-modules/Cargo.lock and the std snapshot below.", "toolchain": { - "pin": "1.99.1", - "rustc": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", + "pin": "1.100.0", + "rustc": "rustc 1.100.0 (0ef1bc386 2026-11-09)", "backtrace": "0.3.76" }, "std_lock": { @@ -21,6 +21,7 @@ "std_not_shipped": [ "cc", "dlmalloc", + "find-msvc-tools", "foldhash", "fortanix-sgx-abi", "getopts", diff --git a/docs/agent-reference.md b/docs/agent-reference.md index 34045da996..d96f98566f 100644 --- a/docs/agent-reference.md +++ b/docs/agent-reference.md @@ -222,8 +222,11 @@ the pinned Sentry Native cross-build), and `sshpass` (Homebrew; deploy/run use y CI runs the three cargo targets plus those two as five parallel jobs (`host-lint`, `host-unit-default`, `host-unit-hostsim`, `host-python`, `host-python-harness`) behind an aggregator named `host checks (NOT a device gate)`; `ci/test_ci_split.py` pins that no gate falls between them. The cargo half runs `cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_platform -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens` - **twice: once on the default feature set and once with `--features hostsim`**, which is not a - duplicate run. The host feed seam (`play-feed/src/ffi_host.rs`) exists ONLY in the hostsim + **on the default feature set, and again with `--features hostsim` for the crates that declare it + (`HOSTSIM_SUITE`: all of `UNIT_SUITE` except `plx_net`, `plx_ui`, `plx_appkit`, `plx_screens`, + `plx_media_codecs`, `plx_play_uri` and `plx_playback_contract`, which have no `hostsim` cfg and run the + same test names in both passes; `ci/test_test_crate.py` fails if one gains the feature or a cfg)**, + which is not a duplicate run. The host feed seam (`play-feed/src/ffi_host.rs`) exists ONLY in the hostsim configuration, so every test that drives an access unit through `sf_feed` is compiled out of the default pass and cannot fail it — which is how the prime-livelock regression (`player::engine::prime_livelock_tests`) sat outside the gate entirely while 1398 default-feature @@ -1232,7 +1235,14 @@ every thin back-edge with `file:line` (the work list for breaking it up); `--dot eighth heartbeat, to exercise the freeze probe (`dev::freeze_on_purpose`; the trigger file is removed when it fires). A real freeze is a 5 s stall of the loop in the foreground: the watchdog (`plx_base::task::watchdog`) sends `SIGUSR2` to the main thread, `freeze_handler` in - `src/crashtrace.c` writes a `*** FREEZE` record, and the next launch reports it + `src/crashtrace.c` writes a `*** FREEZE` record, the observer thread appends + `freeze-at: seq= leg=` to the crash log (the loop leg the main thread was in, one of + `LoopPhase::word`'s eleven words; `LoopPhases::enter` stores seven of them and `span_leg`, called + by `diag::spans::span`, the other four for the span's duration (`scen`, `pump`, `land`, + `dframe`; restored on return or unwind), in every build, `threadcheck` or not and the frame + instrument armed or not, so a release report says where the loop stood, a freeze inside the + playback pump included; the importer joins the two lines by probe + number whichever came first), and the next launch reports it (`telemetry::crashreport`). The app is never stopped. A default (`threadcheck`) build aborts the stalled main thread at 2 s, before the 5 s probe, unless `/tmp/plxnative-guard` contains `log`: write `log` there before launching, or no freeze report is produced. @@ -1933,9 +1943,10 @@ There **is** a host unit suite, and it is not the real gate — both halves matt them is how this section used to be wrong in three files at once. **Tier 1 — `make check` (host).** `cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_platform -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens` (a bare `cargo test --lib` runs the application crate only and skips every layer crate: `plx_base`, `plx_machine`, `plx_platform`, `plx_gfx`, `plx_net`, `plx_ui`, `plx_plex`, `plx_telemetry`, `plx_data`, `plx_session`, `plx_media`, `plx_appkit`, `plx_screens`) runs the whole -host suite on the dev Mac, no TV involved — and `make check` runs it a SECOND time under -`--features hostsim`, because the host feed seam only exists there and the tests that need it are -compiled out of the first pass (see the build section). **Treat every test COUNT in this section as +host suite on the dev Mac, no TV involved — and `make check` runs the crates that declare `hostsim` +(`HOSTSIM_SUITE`, a subset of that list) a SECOND time under `--features hostsim`, because the host +feed seam only exists there and the tests that need it are compiled out of the first pass (the build +section's paragraph on the two passes says which crates are left out and why). **Treat every test COUNT in this section as already wrong, including the one in this sentence.** 386 measured 2026-08-13; 284 on 2026-08-02; a documented 59 before that, which was five times stale before anyone noticed — and the first version of this paragraph was stale within one *commit*, because two agents were adding tests to the same diff --git a/docs/distribution.md b/docs/distribution.md index 694014a8dc..180be3b234 100644 --- a/docs/distribution.md +++ b/docs/distribution.md @@ -206,6 +206,46 @@ account, and the session needs renewal) and Homebrew Channel (§1, §1.7). Every paragraph is the superseded 2026-08-23 analysis, kept as dated history; its QA findings (`docs/lg-self-checklist.md`) remain true statements about the app, not a submission plan. +**LG's own seller guide says the same thing in print** (read 2026-11-13). The Seller Lounge user +guide (`seller.lgappstv.com/seller/support/userGuide/RetrieveUserGuide.lge?pstgSeq=N`) has a working +native path, and it gates it on a contract: + +- *Register New App* (`pstgSeq=19`): the file types a webOS IPK supports are *"Web / Native / Native + Game"*. +- *File Upload* (`pstgSeq=20`, screenshot dated 2025-07-08): a non-web IPK is *"Automatically + configured as Seller-registered File Type (Native/Native Game)"*, and *"If you do not have a + separate standing contract with LGE, select web > All."* That sentence is the published form of the + 2026-10-20 answer: native submission belongs to sellers with a separate LG contract. The guide does + not spell out what happens to a native file from a seller without one; the support answer does. +- *Alpha Test* (`pstgSeq=23`) and *webOS Cloud Test Lab* (`pstgSeq=49`): a native file is tested per + chipset, and the Cloud Test Lab offers *"only devices with the same chipset as the chipset you + selected when uploading the file"* (§6, item 11). + +**A Flutter for webOS app, built and opened (2026-11-13).** LG's toolchain (flutter-webos with +Flutter 3.38.10, NDK 11.2.0, ares 3.2.6) built a release counter app on Ubuntu 22.04 under WSL2. +What it produced, and what that settles: + +- **It is an ordinary `native` package.** A 12.4 MB `.ipk` holding a C++ runner ELF (the app's own + `runner/main.cc` plus LG's `runner_base`), `libapp.so` (the Dart code, compiled ahead of time to + ARM), and LG's prebuilt `libflutter_engine.so`, `libflutter_webos_media.so` (the Wayland/Luna + embedder) and `libflutter_common.so`. Uploaded to Seller Lounge, it reads `File Type: Native` and + is offered the full chipset picker (from M14/H13, webOS 1.0, upward). Nothing in the upload form + tells a Flutter app from a hand-written native one. +- **There is no `flutter` package type.** The SDK's build tool falls back to a type it calls + `flutter`, which links the embedder from `/usr/lib/flutter//` on the set instead of + bundling it. That build does not link on a host, and `ares-package` 3.2.6 rejects the manifest: + *"type is not one of enum values: web,stub,native,native_builtin,native_appshell,qml"*. +- **Its reach is webOS 26 and later, and that is glibc, not CPU.** The runner and LG's prebuilt + libraries require `GLIBC_2.38` (and `GLIBCXX_3.4.32`); the NDK's sysroot is glibc 2.39. Our + toolchain targets glibc 2.12 (`docs/agent-reference.md`, toolchain section), so glibc is not what + bounds this binary's reach (§3.2 is). Anything compiled against NDK 11.2.0 cannot start on the sets + this app is for, and LG's engine is prebuilt, so its floor cannot be lowered from outside. +- **Two setup corrections to LG's getting-started guide:** ares 3.2.6 refuses Node below 20 (the + guide says 14 to 16), and the NDK installer takes `-d `, so it does not need root. + +So the Flutter route is a route to webOS 26+ sets only, and it does not change what the portal or the +seller guide require of a native package. + ### Superseded 2026-08-23 analysis **[corrected 2026-08-23]** This section used to be headed *"LG Content Store — no"* and to argue @@ -245,7 +285,8 @@ package cannot be submitted, which is the question, and which the portal has now **And LG's own tooling had already stopped agreeing with the quoted sentence.** LG publishes a webOS TV NDK on GitHub with no NDA or login — `github.com/lg-flutter-webos/ndk`, release 11.2.0 published -2026-06-29, a 340 MB starfish `ca9v1` **32-bit ARM** cross toolchain, the same class we build with. +2026-06-29, a 340 MB starfish `ca9v1` **32-bit ARM** cross toolchain: the same CPU target we build +for, but not the same reach (the 2026-11-13 Flutter paragraph at the top of this section). "Flutter for webOS" is an official Develop guide (announced 2026-06-30), and **LG's own project template writes `"type": "native"` into `appinfo.json`** — the value the reference page says is not allowed. Two caveats on that path, unchanged and still true: Flutter for webOS requires **webOS 26 @@ -348,6 +389,17 @@ refinements the table understated: `SDL_webOSCursorVisibility` resolved at runtime), and a 3.4.3 set plays. The `>=4.0` catalogue bound in `docs/webosbrew-package.yml` is unchanged pending wider 3.x testing. +**Next seam: ACG on webOS 27 (read 2026-11-13).** LG's ACG guide +(`webostv.developer.lge.com/develop/guides/acg-guide`) gives Luna access control a version table: +*"webOS TV 25 or lower: Not supported · webOS TV 26 Re:New: Supported (ACG enforcement is +available.) · webOS TV 27 or higher: Required"*, and *"All apps must include the requiredACG field +in appinfo.json — even if they do not make any Luna API calls."* `pkg/appinfo.json` declares the +older `requiredPermissions` field instead (LG's own Flutter build tool deletes `requiredPermissions` +and writes `requiredACG`), and the media stack's Luna access comes from the role file the Dev Mode +installer writes (§3.5), not from anything the manifest declares. On webOS 27 both would have to be +declared as `requiredACG` groups. Nothing changes on the firmware this app runs on today, which +predates ACG; no webOS 26 or 27 set has been tried. + ### 3.3 The pinning inside our own code (`audit:portability`, file-cited) - **ABI, the worst layer.** ~15 raw FFmpeg struct byte-offsets with **no runtime gate** — @@ -967,9 +1019,12 @@ Listed because each could change a decision above. `1920x1080` (cosmetic vs blocker) hangs entirely on this, and it's assumed. 3. ~~`webosbrew-ipk-verify` has never been run on the real binary.~~ **RESOLVED 2026-08-02 — it passes.** See §9; the run also found two packaging bugs that made the ipk uninstallable. -4. **LG's own terms are entirely uncovered** — nobody has read LG's SDK/NDK licence, the webOS TV - EULA, or any anti-reverse-engineering clause in either. That is the open question, and it is - genuinely unassessed. +4. **LG's own terms are mostly uncovered** — nobody has read the webOS TV EULA or assessed any + anti-reverse-engineering clause against this project. That is the open question, and it is + genuinely unassessed. One fact since 2026-11-13: the NDK 11.2.0 installer presents LG's SDK + licence, which forbids decompiling or reverse engineering *the SDK* and treats SDK material as + LG's confidential information. This repository uses nothing from that SDK, and the licence's + terms are about the SDK, not about firmware libraries. The facts underneath it are public and unremarkable: `src/starfish.c` binds mangled C++ symbols in `libAcbAPI`/`libpf-1.0` from offsets derived by decompilation — the source says so in its own @@ -1004,6 +1059,14 @@ Listed because each could change a decision above. create and from a 0600 survivor), not that Dev Manager's reader is in the group the file lands in on the television. 10. ~~**`requiredMemory: 60`** vs a measured ~74 MB peak.~~ **RESOLVED 2026-08-22 — the “~74 MB” was never a measurement.** It was an uncited sentence written into this very section (“things nobody has verified”) and then copied verbatim into five other files, where it reads as established. The real figure, taken on the dev set (M16p3, webOS 4.10.2) from a `features=release` build via `VmHWM`: **35 MB** at boot, **119 MB** browsing Home/detail, **155,292 kB ≈ 152 MiB peak** with playback. Note `VmRSS` on this TV already INCLUDES Mali pages — proven arithmetically, `smaps_rollup` 38,540 kB + `/proc/gpu` 20,159×4 kB = 119,176 kB against `VmRSS` 119,044 kB — so roughly two thirds of the footprint is texture memory and adding `/proc/gpu` on top double-counts. `requiredMemory` is now **160**; it was raised because webOS substitutes a default of **120** when the field is absent or ≤ 0, which made 60 strictly worse than declaring nothing at all. +11. **Does this binary run on webOS 26 at all?** Its glibc 2.12 floor does not stop it loading (§2, + 2026-11-13), but whether the private media stack (`libplayerAPIs`, `libpf`, the exported window) + is present and permitted there is untested; no webOS 26 set has been tried. Seller Lounge's + webOS Cloud Test Lab offers remote devices matched to a native file's chipset (§2), which may + answer it without owning a set. +12. **What is LG's "separate standing contract"?** The seller guide makes it the condition for a + native submission (§2). What it involves, and whether an independent developer can hold one, + is not documented anywhere public. --- diff --git a/docs/install-and-verify.md b/docs/install-and-verify.md index 0b5b5ec2b8..074c36701c 100644 --- a/docs/install-and-verify.md +++ b/docs/install-and-verify.md @@ -193,7 +193,7 @@ A crash writes no core file. ### What it reads outside its own directory -The television's codec table at `/etc/umediaserver/device_codec_capability_config.json`, and its firmware identity at `/var/run/nyx/os_info.json` and `/var/run/nyx/device_info.json`. All three are published by the platform, read once at boot, and never written. +The television's codec table at `/etc/umediaserver/device_codec_capability_config.json`, and its firmware identity at `/var/run/nyx/os_info.json` and `/var/run/nyx/device_info.json`. All three are published by the platform, read once at boot, and never written. When `os_info.json` cannot be read it also reads the firmware release, and nothing else, from `/usr/lib/os-release`, which the platform publishes the same way. ### What it reaches diff --git a/docs/lab-diagnostics.md b/docs/lab-diagnostics.md index 1e095d31e0..3228f7a1c2 100644 --- a/docs/lab-diagnostics.md +++ b/docs/lab-diagnostics.md @@ -39,7 +39,7 @@ Five pieces of this feature already exist, and the design is mostly wiring them bool or enum **by rule**: `app/diagnostics.rs`'s module doc is a written no-URL / no-credential / no-identity contract for exactly this data, because it is already photographed and posted into public issue threads. A snapshot built from `Diag` is redacted by construction. -* **Device identity.** `tv::device::info()` (release, codename, api, name, from `/var/run/nyx/os_info.json`), +* **Device identity.** `tv::device::info()` (release, codename, api, name, from `/var/run/nyx/os_info.json`; the release alone from `/usr/lib/os-release` when that file cannot be read), `devcaps::caps()` (the SoC's own codec table), `paths::app_id()`/`flavour()`, `env!("PLX_VERSION")` (the reported app version — `X.Y.Z` for a release build, and the next MINOR with the patch reset for every other one, `X.(Y+1).0-dev`; see `rust-modules/build.rs`). diff --git a/docs/owned-present-damage.md b/docs/owned-present-damage.md new file mode 100644 index 0000000000..7251be2c3d --- /dev/null +++ b/docs/owned-present-damage.md @@ -0,0 +1,76 @@ +# Owned presentation damage + +`Dispatcher::present` is the sole presentation owner. Content changes reach it as +`PresentEvent::Damage(Provenance)` through an owned `PresentHandle`, a machine's +`Effects::invalidate`, or the app runner's addressed result-landing boundary. +`Present::note_in_scope` addresses one Page or Surface effect without changing the +scope of subsequent work. Mutation-only caches never publish damage or worker wakes. + +## Source inventory by semantics + +- **Input/navigation/lifecycle:** the app ingress and dispatcher execute typed effects. + DecisionAlert, DocumentReader, Popover and tab-pulse setters do not independently + publish ambient damage. Their owning input/navigation effects select the first frame; + their Tick integration reports ongoing animation. Login's tick-time alert content + reconciliation and abrupt visibility changes explicitly invalidate through `Effects`. +- **A long hold's stale host card:** `Press::tick` returns a page-change result only + while a taken long hold visibly moves a card still painted into the host snapshot. + `InputMachine` turns it into `PressEvent::PageDamage`; the dispatcher applies Page/Input + damage. A tap or a lifted card produces no page-damage effect. This is not merely motion: + open-menu snapshots must refresh when the underlying card still belongs to the page. +- **Display-only resource replacement:** `ArtCycle::set_frames` returns whether its + retained frames changed; HudSettings applies Resource/Texture damage to its owner. + Test-pattern setters return success to the app ingress. RuntimeWarning returns its + presentation demand to the runner. Neither setter touches a global presentation flag. +- **Texture results:** texture upload/landing boundaries apply Resource/Texture damage. + Worker completion requests scheduling only; resource arrival is attributed on the UI + thread, not by the worker writing a global dirty generation. +- **Store results:** stores return changed outcomes/generations and addressed result + events. Their Bridge/runner boundary owns presentation effects; cache/store mutation + is not itself a presentation notification. Admission refusal and terminal failure + still need their owning boundary observed, even when there is no successful payload. +- **Frame animation:** springs, marquee travel and holds, cross-fades, skeleton sheen, + art arrival, scroll-chrome ramps, and Up Next's countdown use explicit frame-captured + motion infrastructure. A discontinuous spring jump is captured separately from a + continuing animation, so an already-resting jump does not owe another settle frame. + Frozen draw decorations report nothing. Card-speed sampling may request another + animation observation without asserting resource damage or worker provenance. + +## No compatibility damage adapter + +`motion/report.rs` contains no `invalidate`, `take_damage`, `select_damage`, +`present_dirty`, `take_page_damage`, `OwnScope`, or global damage counters. Its +thread-local cells are the explicitly captured frame-motion collector, not a damage +mailbox. `MotionScope` still attributes page/surface animation; it cannot classify content +changes. Main-thread deferred rendering addresses its own Presenter through frame effects; +only actual off-thread completions call `present::wake_from_worker()` directly. +Main-thread deadlines and deferred work use owned `PresentEvent::Wake`: it requests a +frame without content provenance, page damage, or page motion. + +Popover host capture uses only `Present::page_damaged()` for content attribution. +Surface damage cannot refresh the frozen host page. Motion and damage reported during +draw are merged before swap acknowledgement; acknowledgement retires only generations +captured at admission. Late draw effects therefore survive the actual swap. +`changed_after_admission` observes those late generations without confusing an owner's +pre-admission scheduling request with new work. + +## Regression coverage + +Independent Present owners, typed page/surface capture, mutation-only caches without a +global worker wake, long-hold page effects, scheduling without UI provenance, skipped +swaps, and post-admission damage/wakes have host regressions. Original idle, press, +marquee, tab-pulse, art-arrival and host-cache regressions remain; tests observe the +owned page-damage readout where the contract is content damage, and frame motion where +the contract is animation. Host results do not prove device rendering or performance. + +## Addressed deferred rendering + +GPU field sampling returns `FrameLatch::Pending`; it never schedules through a global door. +The visible `DrawFrame` records `request_frame()`, and the dispatcher consumes that frame-local +effect as `PresentEvent::Wake` on its own Presenter. Settings forwards child requests even when +a leaving child contributes no hit stops. Recording/discovery/blur-source walks cannot request frames. + +`GlDims` borrows the owning `PresentHandle`; load-dial preparation receives its Presenter explicitly. +Both schedule only that owner, without page damage or page motion. `report::wake` is removed, +and actual IO completions name `present::wake_from_worker` directly. The `owned-wake` source gate +rejects use of the worker door from UI, dev-frame logic, or the main loop. diff --git a/docs/playback-settings.md b/docs/playback-settings.md index 675df3924a..3447afbae2 100644 --- a/docs/playback-settings.md +++ b/docs/playback-settings.md @@ -42,7 +42,8 @@ paragraph); while Force is on, Default quality reads "Overridden" and its senten quality is overridden. Returning to Auto or Disabled needs no confirmation. -Audio passthrough remains the television's Digital Sound Output setting. +Audio passthrough remains the television's Digital Sound Output setting; if Atmos or E-AC3 audio +comes out slow or deep on a soundbar, see [the troubleshooting note](troubleshooting.md#audio-is-slow-deep-or-drifting-out-of-sync-on-a-soundbar). ## Playback engine @@ -68,7 +69,9 @@ still convert can go to the TV's pipeline. A video your Plex server converts (re that carries a subtitle stream (whether or not a subtitle is switched on) or a burned or client-drawn subtitle, a trailer preview, a non-1x speed, a relay link and Auto quality away from the LAN also still play in Standard. On webOS 5+, originals with multiple audio tracks also stay in Standard -because the TV service can order tracks differently from Plex. An Experimental failure takes at most one handoff per play: the video restarts in Standard +because the TV service can order tracks differently from Plex. Which sets reach the TV's pipeline at all +is decided per firmware major: webOS 4.x through ACB, and webOS 5.x through the TV's exported window (its +PRODUCT run is the 5.6.2 row of `docs/uri-mode.md`); a later major (6 and up) plays Standard until `EXPORTED_STRATA` admits it under the rule in `docs/uri-mode.md`. An Experimental failure takes at most one handoff per play: the video restarts in Standard (`route::backend_policy`). On webOS 4.x the Experimental engine binds the screen through ACB and waits for each release's completion callback before the next title; when that never arrives the plane stays quarantined until the app restarts, the next title's Experimental bind is refused and that title takes the diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index ac2cdab60d..784e03f4d3 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -210,6 +210,18 @@ decodes AV1 or VP9 and you want to try it: `av1=false` (`vp9=false`) when it doesn't, which tells us right away whether the TV or the app is at fault. +## Audio is slow, deep or drifting out of sync on a soundbar + +With a soundbar or receiver on HDMI (e)ARC, usually on Dolby Atmos or E-AC3 titles, the sound comes +out slow and low-pitched, drifts out of sync with the picture, and sometimes starts with a loud +crack. It may hit some starts of a title and not others, and the TV's own speakers play the same +title fine. + +In the TV's **Settings > Sound > Advanced Settings > Digital Sound Out**, choose **Auto** or **Pass +Through** instead of **PCM**, then start the title again. With PCM the TV decodes the Atmos track +itself and sends PCM over (e)ARC; that path is LG's, and the app cannot change it. The report this +comes from is [issue #1351](https://github.com/GLinnik21/plx-native/issues/1351). + ## Other playback failures Try the current release first, then photograph the failure screen and [collect the diff --git a/docs/ui-restructure-spec-v4.md b/docs/ui-restructure-spec-v4.md index 0ce9e153eb..d3f7505753 100644 --- a/docs/ui-restructure-spec-v4.md +++ b/docs/ui-restructure-spec-v4.md @@ -3,13 +3,13 @@ (spec §6.2)`) and it previously lived only in a private plans directory, unreadable to every contributor. Copied verbatim; the status notes below were added at the move. --> -> **STATUS (2026-09-20).** Phases 0–12 landed. This is the DESIGN RECORD, not a description of the -> shipped tree — read it for the contract and the rationale, and `rust-modules/src/ui/CLAUDE.md` -> for what actually exists. Known divergences: the containers shipped as `ui/containers/`, not -> `ui/nav/` (§11); `ui/nav.rs` and `ui/press.rs` are still present though §11 lists them for -> deletion (`ui/trail.rs` is gone); and `ui/present.rs` has not replaced `ui/idle.rs` — both -> exist, at 233 and 1069 lines. §0's done-criterion 9 (`doc_claim_auditor` clean against §11's -> prose list) is not yet met. +> **STATUS.** This is a design record, not a claim that every ownership goal has landed. +> For current UI guidance see `rust-modules/ui/src/CLAUDE.md`. Containers live under +> `rust-modules/ui/src/containers/`. Root `nav.rs`, `press.rs`, `trail.rs` and the old +> `machine/src/idle.rs` gate are removed. Navigation and press now use explicit frame +> snapshots; `Dispatcher::present` owns admission and actual-swap accounting. The executed +> ownership boundary is recorded in §11. Source migration does not itself establish full +> runtime/device acceptance or close §0's broader documentation audit. # PlxNative UI restructure — specification v4 @@ -302,6 +302,32 @@ The frame timer's origin moves to the TOP of the iteration; `Instruments::mark` ## 11. Modules and prose `app/{boot,run,events,lifecycle,playback,effects,adapters/{mod,net,disk,sys,poster}}.rs` (`adapters/poster.rs` is today's `posters.rs` minus its GL half, §10); `ui/{machine,dispatch,screen,hit,focus,frame,motion,present,tex,rec,nav/{stack,tabs,modal,transition,legacy(temp),fixture}}.rs` (`ui/present.rs` replaces `ui/idle.rs`); `screens/{registry,home,library,search,detail,person,filmography,settings,legal,consent,onboard,login,profiles,player/{mod,input},account_menu,item_menu,track_menu,info_panel,chapters_panel,more_menu,alt_sources,tracks_panel,about_panel,person_bio,up_next,diagnostics,lab_toast,skip_pill,source_list}.rs`; `stores/mod.rs`; `player/{machine,adapter}.rs` (engine and threads as today); `dev/scenarios.rs`; `diag/heartbeat.rs`; `route/{plan,decision}.rs`; `ci/{check-statics,check-deps}.sh`; `tools/plxnative-rec`; `tests/{mock_pms.py,focusfp.sh,fixtures/replay/*}`. Deleted: `ui/nav.rs`, `ui/trail.rs`, `ui/press.rs` (into `ui/dispatch/press.rs`), the app.rs ladders. Test-module homes: `input_event_tests` → events; `foreground_resume_tests`, `transport_pause_contract_tests`, `root_back_tests` → lifecycle; `hud_visibility_tests` → player/screen; `repeat_gate_tests`, `failed_player_input_tests`, `overlay_transport_key_tests`, `player_return_tests` → player/input; `replay_budget_tests`, `script_schedule_tests` → dev/scenarios; `unsupported_key_tests`, `key_layout_tests` → dispatch; `settings_child_input_tests` → deleted (dissolves into `input_owner()`); `play_landing_order_tests`, `delete_local_data_tests` → playback; `host_page_lifecycle_tests` → the fold table; `route_tests` → split into `chrome()` and `Leave` tests. Prose to re-audit: `ui/CLAUDE.md` (table rows, containers, rule 12, focus/pointer sections), `docs/agent-reference.md` (triggers, scenes, recordings, panel policy), `docs/ui-viewtree-plan.md` §E superseded, `docs/async-model-decision.md` step 3 reversed (five copies were sound while a screen was a singleton; not once it can be popped mid-flight), `docs/retui-invalidation-design.md` implemented, `docs/ui-framework-improvements.md` §1.7 built, `task.rs` doc, `docs/ui-system-migration.md` §D, `PRIVACY.md` (recorder is dev-only). +### Executed ownership boundary + +The workspace paths are now `ui/src/dispatch/press.rs`, `machine/src/present.rs` and +`machine/src/motion/report.rs`. Root `ui/src/nav.rs`, `ui/src/press.rs` and +`machine/src/idle.rs` are removed. `Input` owns press state and publishes explicit +`PressRead` values; navigation presentation is derived from the owning `NavStack` and +passed through `DrawFrame`, including consumers outside the page pass. + +`Dispatcher::present` is the sole runtime gate. The loop collects motion/damage, admits +a frame without consuming pending work, and acknowledges only after an actual swap. +Damage or worker wakes arriving after admission remain pending for the next frame. +The report module collects scoped motion only, never generic damage. It has no keepalive, +video-plane state or frame-admission authority. Actual store/publication deltas and resource +outcomes reach the owned gate through their runner/effect boundaries. Only off-thread +completions use the documented worker wake door. +The shadow `App.input.press` and pointer-only +`ArmControlRow` commit ladder are removed too: keyboard and pointer controls both arm +the dispatcher and receive addressed commits. Removing the duplicated press digest +advances the app recorder census to `AppFrameV5`; recordings with the previous +fingerprint are refused unless the validated key-only V4 profile proves the retired press +remained idle. That profile uses frozen V4 bytes for grading only, never a second input +owner; current recordings retain the V5 composition. +Settled screenshot decisions follow current-frame collection. Drawing is revalidated; +late work re-arms the one-shot rather than capturing/exiting prematurely. +Build/runtime/device acceptance is separate from this source-level ownership record. + ## 12. Behaviour changes (an INDEX of what the user or a log reader can notice; each rule lives in the section cited) 1. Background: route and trail no longer disagree; the player is a parked entry (§9). 2. `covered_by_child` becomes `Cover`/`Uncover` (§3.4). 3. Identity on detail landings, refusals and drops as events (§5.2); `idle::dt()` gone and press arms stamped from the input, so a commit may move by one frame (§4.1). 4. Springs' transcendental functions change in the last ~1e-6, below the rest test (§4.2). 5. Press, modal phase, present gate, focus and hit map each gain one owner; no pixel changes (§2.2). 6. Home's strip reachability and the pill→hero `Link` are unchanged in behaviour and declared as data (§6.2). 7. The one visible focus-policy change is that `Seat::Remembered` no longer depends on distance (§7.3 step 4); no group adopts `RememberedNear` at migration (Open question 1). 8. The GL upload + warm pair becomes a solo frame (§8.1); the poster quota is unchanged. 9. Committed fixtures are synthetic and the recorder is dev-only (§5.3, §5.6). 10. Legal stays a push inside the Settings family's own stack (§6.2 `SettingsSurface`; §10 "Legal declines" MasterDetail). 11. The `Job` decision is reversed (§11). diff --git a/docs/uri-mode.md b/docs/uri-mode.md index 943df66f20..a3582d9e29 100644 --- a/docs/uri-mode.md +++ b/docs/uri-mode.md @@ -24,7 +24,8 @@ displayed its URI fixture on the 4.5 dev set, as recorded below. |---|---|---| | webOS 4.10.0 / 4.4.2 | unpacked images + this project's 4.5 set | No `AVProxy` or `SDL_webOS*ExportedWindow`; the window option is ignored. Earlier probe loads decoded without a visible picture, and earlier ACB attempts returned `ERROR_06`. The controlled 2026-11-02 ACB pair later displayed moving SDR720p24 H.264/AAC URI video on the 4.5 dev set, both with and without `connectDass`; this does not establish other 4.x sets or formats. | | webOS 5.4.2 | LG 65UN80006LA (issue #1064) | `windowId` in `load` → picture, moving, with sound. `late` (`setWindowId` after `loadCompleted`) and `none` → `error code=104 "fail to create AVProxy"`. Both a `plex.direct` HTTPS direct play and an HLS transcode played. Where the picture sat and its aspect were not reported (the tester's report names picture and sound only), and the registration ladder ended on the named client (`shape=named`). | -| webOS 9.2.4 / 10.3.1 (33.31.68) | unpacked images | same mechanism as 5.5 and later (below); not yet confirmed on a device. | +| webOS 5.6.2 (build 5.6.2-21) | LG OLED CX (issue #1064: [the first run](https://github.com/GLinnik21/plx-native/issues/1064#issuecomment-6758688148), [the single-audio product run and drive probe](https://github.com/GLinnik21/plx-native/issues/1064#issuecomment-6844822550)) | **Admitted: major 5 is in `EXPORTED_STRATA`.** (a) The 5.5.0 and 5.6.2 images read `option.windowId` at load (decompile, below). (b) The PRODUCT run, on the CI build of run 43017142892 (main at `e8442d5e`, which carries #1314) installed over the existing debug app, Playback engine Experimental, quality Original, `plxnative-uriexported` armed at the jail's persistent path: a 1080p HEVC (1920x1040) MKV with ONE AAC 2.0 track and no subtitle streams, direct play. Every boot: `uri: product binding=Unbound mode=2 handle=false ptype=10 initialized=false major=5 evidence=none`, then `uri: product binding=Exported { canvas: (1920, 1080) } mode=2 evidence=override`. Play: `ls2uri: register shape=named ok after 6ms`, `uri: exported window placed src=1920x1040 rv=1`, `uri: audio index=0 is already selected (audioInfo); no selectTrack sent`, `uri: service playing`. The picture moved, full width with thin bars for 1.85:1, not stretched. Back: `ls2uri: released`. (c) The drive probe on the same build printed `load=ok playing=yes ... currentTime_advanced=yes videoInfo=seen audioInfo=seen window=exported ... shape=named end=script audio_at_load=0 clock_period_ms=200 pause=froze pause_delta=- resume=sent seek=hit seek_delta=-3898 text=sent audio=sent subs=ok eos=no pause_basis=paused_event_and_resume pause_samples=0 ... paused_event=yes seekdone=yes resume_from=2568`. `pause=froze` is printed by the current grader (#1314), so no amendment is used for it. The tester gives no paused position for the probe (no `drive pause pos=` line), so `resume_from=2568` is not compared here against rule (c)'s paused position minus 1000 ms; `pause_basis=paused_event_and_resume` is the grader's own check of the resume against the position it recorded. The audio token is `audio=sent` with `audio_at_load=0`, the rule's `audio_at_load=` alternative. Product controls: pause logged `ev=paused` and two service screenshots 2 s apart were identical (mean pixel difference 0.007 of 255); Play resumed at 39383 ms, where it paused (`timeline paused t=39s`); seek: `uri: control Seek(ContentTime(65606)) landed on the service's seekDone (its reply acknowledged first: yes)`, first `currentTime` after it 62692; a listener in the room confirmed sound in a second play: throughout, silent during a 5 s pause, back on resume and after a seek. Extra datapoint: a 4K HEVC Dolby Vision profile 8.6 MKV (3840x1604, one AC3 5.1 track) showed the TV's Dolby Vision badge, letterboxed for 2.39:1, with the same pause, seek and sound. The multi-audio film now starts in Standard and logs `uri: original declined (several audio tracks on the exported window)`; `exported_uri_leaves_multi_audio_originals_on_standard` (`rust-modules/media/src/route/uri_preflight.rs`) pins that route. History: the first run (a debug build of `main` at 5011614a, before #1314) printed `pause=unconfirmed` from its drive probe (no `currentTime` while paused, so no samples to grade), and its product run of that four-track file (AAC 5.1, AAC 5.1, Vorbis 5.1, Vorbis 5.1) failed the audio-track switch: the service lists the tracks as AAC, Vorbis, AAC, Vorbis, so `uri: selectTrack sent kind=audio index=1 stream=364534` selected Vorbis, the bus answered `{"error":{"errorCode":200,"errorText":"Audio Codec Not Supported"}}` and the play fell back to Standard. That is rule (c)'s amendment (2) case: such a file now starts in Standard, and the admission covers only the route as it now stands (audio switching on the URI path is avoided, not admitted). Not checked: subtitles on the URI path, HLS. | +| webOS 9.2.4 / 10.3.1 (33.31.68) | unpacked images; LG C2 on webOS 25 (10.x, 33.31.68; issue #1064) | The images show the same mechanism as 5.5 and later (below). The C2 ran the drive probe on an older build (the earlier grader), not the product backend, so **no major 10 entry**: millisecond `currentTime` clock with about a 1 s period; a `paused` event with no positions while paused; resume from 2729 after a pause at 2410; seek target 24937 landed on `seekDone` at 24195; audio `trackSelected` index 1 ok; subtitles rendered by the firmware. | | webOS 26: set on 11.1.0-3701, mechanism read on the 11.2.0 image | LG G4 (issue #1064) | `windowId` in `load` → 4K picture, Dolby Vision and Atmos through the TV's pipeline, our overlays composited over it, correct size and place. The set runs 11.1.0-3701; 11.2.0 is the unpacked image the mechanism above was read from, not the set. | | webOS 3.x | unpacked images | no `libSDL2` at all; out of scope. | @@ -138,10 +139,14 @@ covering at least half the dwell, including a report in the Resume observation f it leaves a stationary-position verdict unconfirmed. Advancing positions report movement. Method acknowledgements and service state events remain separate observations. -Open on 5+: whether a `paused` event exists at all, whether `play` after `pause` resumes or -restarts (the first position after resume dropped to 333 ms here), whether text `selectTrack` -produces `trackSelected` and a rendered subtitle, and what the seek bar can be fed — the service -reports `currentTime` but no duration, so a duration has to come from `sourceInfo` or from Plex. +Settled on 5+ by the 5.6.2 runs (Results; the product run and the drive probe) and the 10.x drive +probe: the service sends a `paused` event (then `playing` on resume) and no `currentTime` while +paused; `play` after `pause` resumes from the paused position rather than restarting (2439, then 2641 +on 5.6.2; 2410, then 2729 on 10.x); and a `seek` lands on the service's `seekDone`. Still open on 5+: +subtitles on the URI path (the 10.x set rendered them in the firmware, a probe report, not a product +run), native track identity and ordering (the 5.6.2 service lists audio tracks in a different order +from the container), HLS, majors other than 5, and what the seek bar can be fed — the service reports +`currentTime` but no duration, so a duration has to come from `sourceInfo` or from Plex. The production backend's first Play waits behind the startup selection of the viewer's audio track (the common startup owner sequences track, seek, then Play, each confirmed). On the 4.5 service that @@ -174,7 +179,7 @@ On the exported window (webOS 5+) the production backend places the window as th it creates it at the start and places it with the 1920x1080 canvas as the source, then, when the service's `videoInfo` reports the coded size, again with that size as the source; the destination is always the whole canvas (`uri: exported window placed src=WxH rv=N`). Production selects that binding -only for a firmware major in the evidence table described below, which is empty today. A debug build +only for a firmware major in the evidence table described below, which admits major 5 today. A debug build composes it for one boot when the file `plxnative-uriexported` exists in the install's runtime root (content ignored). Unlike `plxnative-uriprobe`, which is read at each Play, this trigger is read once, at boot, so it can be armed only by writing the file BEFORE the app launches: on @@ -182,30 +187,41 @@ plain `/tmp`, or at the jail's persistent path (routes 1 and 3 under "Arming the run below). Route 2, through `/proc//root` while the app runs, cannot arm it: that write comes after the boot read and the override stays off. The line that confirms it is `uri: product binding=Exported { canvas: (1920, 1080) } mode=2 evidence=override`, which follows the -production `uri: product binding=Unbound ..` line. A log without it proves nothing about the product -backend. The viewer still has to opt in to the URI engine, and the override does nothing on a display +production `uri: product binding=Unbound ..` line on a major the table has not admitted (on a 5.x set the +production line is already `binding=Exported { canvas: (1920, 1080) } ... major=5 evidence=table`, and +the override line, when armed, still follows it). A log without it proves nothing about the product +backend of a major the table has not admitted. The viewer still has to opt in to the URI engine, and the override does nothing on a display whose mode is not the exported window. Whether the service sends `videoInfo` before the first frame is not determined, so the first frames may be placed from the canvas source rectangle. Production selects the exported window per firmware major, from the table `EXPORTED_STRATA` -(`rust-modules/play-uri/src/backend.rs`), which is empty today: no release is admitted, so every -webOS 5+ release plays Standard (its boot line reads `major= evidence=none`; a major the table -admits reads `evidence=table`; a 4.x set reads `none` too and keeps its ACB path). An entry is a -webOS firmware major as the set reports it, and needs three things in this file's Results table, each -with the tester log's decisive lines. A release is never admitted on the probe's evidence alone: a run -of the product backend is required. +(`rust-modules/play-uri/src/backend.rs`), which admits major 5 today (the webOS 5.6.2 Results row +above): a 5.x set's boot line reads `major=5 evidence=table`. Every other webOS 5+ major still plays +Standard (its boot line reads `major= evidence=none`; a 4.x set reads `none` too and keeps its ACB +path). An entry is a webOS firmware major as the set reports it, so major 5 covers every 5.x release: +the product run was on 5.6.2, the earlier probe-only run on 5.4.2, and no other 5.x minor has a run. +An entry needs three things in this file's Results table, each with the tester log's decisive +lines. A release is never admitted on the probe's evidence alone: a run of the product backend is +required. - (a) the major's own firmware image reads `option.windowId` at load (decompile); - (b) picture: a tester's PRODUCT-path run on a debug build (the boot log shows `evidence=override`) shows a moving picture with sound, placed and proportioned right, supported by the probe's summary tokens `load=ok`, `playing=yes`, `currentTime_advanced=yes` and `window=exported`; -- (c) controls: the probe's `drive` tokens (`pause=froze`, `resume=sent` with `resume_from=` at or - after the paused position minus 1000 ms, `seek=hit`, and `audio=ok` or an `audio_at_load=`) AND the - product run's pause, seek and audio doing what the viewer asked. +- (c) controls: the probe's `drive` tokens (`pause=froze` on either `pause_basis`, `resume=sent` with + `resume_from=` at or after the paused position minus 1000 ms, `seek=hit`, and `audio=ok` or an + `audio_at_load=`) AND the product run's pause, seek and audio doing what the viewer asked. Two + amendments, each named in the row that uses it. (1) For a run made before the current grader, the + current grader's verdict on that run's recorded numbers, replayed in a unit test, stands in for the + printed `pause=froze`: the row names the test and says the run itself printed `pause=unconfirmed`. The + 5.6.2 row does not use it: its probe run printed `pause=froze`. (2) A control the product run showed + failing is acceptable only when the route now sends that case to Standard (the 5.6.2 audio-track + switch, routed by #1314 and since observed on the set as `uri: original declined (several audio tracks + on the exported window)`); the row names it, and the admission covers only the route as it now stands. One exception: a major with the image evidence but no tester run is admitted when both neighbouring majors are admitted on tester evidence, and its row then says "bracketed, no tester run". Nothing else -is inferred from a neighbouring major. Each entry names its Results row, and a webOS 5+ release without +is inferred from a neighbouring major. Each entry names its Results row, and a webOS 5+ major without an entry plays Standard, with no handoff. ## Reproducing it @@ -390,8 +406,9 @@ The reasons are local diagnostics: they route nothing, and nothing about them is ## Open questions -- Whether webOS 5+ can be driven as a player rather than only loaded: pause/resume semantics, seek - units and granularity, track selection, end-of-stream, and where a duration comes from. +- Whether webOS 5+ can be driven fully as a player: pause, resume and seek are settled on 5.6.2 and + on the 10.x probe (Results). Open: where a duration comes from, native track identity and ordering, + end-of-stream (no run has reached it), and HLS and majors other than 5 on the product path. - Whether a descriptor (PGS) or text track renders into the exported window, or whether subtitles must stay on our own overlay path. - Which formats the TV's pipeline plays that our buffer-feed path refuses, on stock firmware. diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 00efd4612d..6ce57a3605 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -43,7 +43,7 @@ plx_data = { path = "../rust-modules/data" } plx_net = { path = "../rust-modules/net" } # The registry-index targets sign with TEST ONLY keys (`src/signing.rs`) to reach what follows the signature # check. The same version and features as `plx_data`, so the lock gains nothing. -ed25519-compact = { version = "=2.6.0", default-features = false, features = ["opt_size"] } +ed25519-compact = { version = "=2.6.1", default-features = false, features = ["opt_size"] } # Named only to switch the layers below `plx_appkit` to their host stand-ins (`plx_media/hostsim` # forwards to every layer that has the feature); no code here calls it. plx_media = { path = "../rust-modules/media", features = ["hostsim"] } diff --git a/locales/be/core.json b/locales/be/core.json index f966ae463c..4a233e07e0 100644 --- a/locales/be/core.json +++ b/locales/be/core.json @@ -25,6 +25,7 @@ "core.preview_domain_attempted_delivery": "запытаная дастаўка", "core.preview_domain_source_video": "відэакодэк крыніцы (толькі ў справаздачах пра адмову)", "core.preview_domain_source_audio": "аўдыёкодэк крыніцы (толькі ў справаздачах пра адмову)", + "core.preview_domain_preview_refusal": "прычына адмовы ў аўтаматычным паказе трэйлера (толькі ў справаздачах пра адмову ў паказе)", "core.preview_domain_quality": "якасць", "core.preview_domain_observed_rate": "вымераная хуткасць", "core.preview_domain_raster": "разрозненне", diff --git a/locales/ca/core.json b/locales/ca/core.json index 3420576402..cff56f17f0 100644 --- a/locales/ca/core.json +++ b/locales/ca/core.json @@ -25,6 +25,7 @@ "core.preview_domain_attempted_delivery": "modalitat de transmissió sol·licitada", "core.preview_domain_source_video": "còdec del vídeo d'origen (només en informes de rebuig)", "core.preview_domain_source_audio": "còdec de l'àudio d'origen (només en informes de rebuig)", + "core.preview_domain_preview_refusal": "motiu del rebuig d'un tràiler automàtic (només en informes de rebuig de tràiler)", "core.preview_domain_quality": "qualitat", "core.preview_domain_observed_rate": "taxa observada", "core.preview_domain_raster": "resolució", diff --git a/locales/de/core.json b/locales/de/core.json index 2ef4801eb3..d8efe312d0 100644 --- a/locales/de/core.json +++ b/locales/de/core.json @@ -25,6 +25,7 @@ "core.preview_domain_attempted_delivery": "versuchte Übertragungsart", "core.preview_domain_source_video": "Videocodec der Quelle (nur Ablehnungsberichte)", "core.preview_domain_source_audio": "Audiocodec der Quelle (nur Ablehnungsberichte)", + "core.preview_domain_preview_refusal": "Grund der Ablehnung eines automatischen Trailers (nur Berichte über abgelehnte Trailer)", "core.preview_domain_quality": "Qualität", "core.preview_domain_observed_rate": "gemessene Bitrate", "core.preview_domain_raster": "Bildgröße", diff --git a/locales/en/core.json b/locales/en/core.json index 3721989cc3..e2bf2d7293 100644 --- a/locales/en/core.json +++ b/locales/en/core.json @@ -149,6 +149,10 @@ "value": "source audio codec (refused-plan reports only)", "description": "Field name in the consent preview's list of possible playback-error values: the audio format class of the file the server refused. Only reports about a refusal carry it." }, + "core.preview_domain_preview_refusal": { + "value": "reason an automatic trailer was refused (refused-trailer reports only)", + "description": "Field name in the consent preview's list of possible playback-error values: which condition refused the trailer that plays behind a detail page before it opened (the title has no media file, a direct play was not on offer, or Auto quality did not keep the original). Only reports about a refused trailer carry it." + }, "core.preview_domain_quality": { "value": "quality", "description": "Field name in the consent preview's list of possible playback-error values." diff --git a/locales/es/core.json b/locales/es/core.json index acb60763a3..39fe2a57eb 100644 --- a/locales/es/core.json +++ b/locales/es/core.json @@ -25,6 +25,7 @@ "core.preview_domain_attempted_delivery": "entrega solicitada", "core.preview_domain_source_video": "códec de vídeo de origen (solo en informes de rechazo)", "core.preview_domain_source_audio": "códec de audio de origen (solo en informes de rechazo)", + "core.preview_domain_preview_refusal": "motivo del rechazo de un tráiler automático (solo en informes de rechazo de tráiler)", "core.preview_domain_quality": "calidad", "core.preview_domain_observed_rate": "velocidad observada", "core.preview_domain_raster": "resolución", diff --git a/locales/fr/core.json b/locales/fr/core.json index 8b2b3df6e4..38ffa54725 100644 --- a/locales/fr/core.json +++ b/locales/fr/core.json @@ -25,6 +25,7 @@ "core.preview_domain_attempted_delivery": "diffusion tentée", "core.preview_domain_source_video": "codec vidéo source (rapports de refus uniquement)", "core.preview_domain_source_audio": "codec audio source (rapports de refus uniquement)", + "core.preview_domain_preview_refusal": "raison du refus d’une bande-annonce automatique (rapports de refus de bande-annonce uniquement)", "core.preview_domain_quality": "qualité", "core.preview_domain_observed_rate": "débit observé", "core.preview_domain_raster": "trame", diff --git a/locales/hu/core.json b/locales/hu/core.json index f1e02fa834..31537f5294 100644 --- a/locales/hu/core.json +++ b/locales/hu/core.json @@ -25,6 +25,7 @@ "core.preview_domain_attempted_delivery": "megkísérelt továbbítási mód", "core.preview_domain_source_video": "a forrás videokodekje (csak az elutasított lejátszási tervekről szóló jelentésekben)", "core.preview_domain_source_audio": "a forrás hangkodekje (csak az elutasított lejátszási tervekről szóló jelentésekben)", + "core.preview_domain_preview_refusal": "az automatikus előzetes elutasításának oka (csak az elutasított előzetesekről szóló jelentésekben)", "core.preview_domain_quality": "minőség", "core.preview_domain_observed_rate": "mért bitráta", "core.preview_domain_raster": "képméret", diff --git a/locales/it/core.json b/locales/it/core.json index bdf49d78ba..aa4110dd0d 100644 --- a/locales/it/core.json +++ b/locales/it/core.json @@ -25,6 +25,7 @@ "core.preview_domain_attempted_delivery": "modalità di trasmissione richiesta", "core.preview_domain_source_video": "codec video del file originale (solo se il server rifiuta)", "core.preview_domain_source_audio": "codec audio del file originale (solo se il server rifiuta)", + "core.preview_domain_preview_refusal": "motivo del rifiuto di un trailer automatico (solo se il trailer viene rifiutato)", "core.preview_domain_quality": "qualità", "core.preview_domain_observed_rate": "bitrate rilevato", "core.preview_domain_raster": "risoluzione dell'immagine", diff --git a/locales/nl/core.json b/locales/nl/core.json index f0d8570728..000d79474a 100644 --- a/locales/nl/core.json +++ b/locales/nl/core.json @@ -25,6 +25,7 @@ "core.preview_domain_attempted_delivery": "geprobeerde leveringswijze", "core.preview_domain_source_video": "videocodec van de bron (alleen weigeringsrapporten)", "core.preview_domain_source_audio": "audiocodec van de bron (alleen weigeringsrapporten)", + "core.preview_domain_preview_refusal": "reden voor de weigering van een automatische trailer (alleen rapporten over geweigerde trailers)", "core.preview_domain_quality": "kwaliteit", "core.preview_domain_observed_rate": "gemeten bitrate", "core.preview_domain_raster": "beeldformaat", diff --git a/locales/pl/core.json b/locales/pl/core.json index 7082f8108b..8cbfee71d4 100644 --- a/locales/pl/core.json +++ b/locales/pl/core.json @@ -25,6 +25,7 @@ "core.preview_domain_attempted_delivery": "próbowany sposób dostarczania", "core.preview_domain_source_video": "źródłowy kodek obrazu (tylko raporty odmowy planu)", "core.preview_domain_source_audio": "źródłowy kodek dźwięku (tylko raporty odmowy planu)", + "core.preview_domain_preview_refusal": "powód odmowy odtworzenia automatycznego zwiastuna (tylko raporty odmowy zwiastuna)", "core.preview_domain_quality": "jakość", "core.preview_domain_observed_rate": "zmierzona przepływność", "core.preview_domain_raster": "rozdzielczość obrazu", diff --git a/locales/pt/core.json b/locales/pt/core.json index c7e12828b8..c1301296cd 100644 --- a/locales/pt/core.json +++ b/locales/pt/core.json @@ -25,6 +25,7 @@ "core.preview_domain_attempted_delivery": "entrega tentada", "core.preview_domain_source_video": "codec de vídeo de origem (apenas relatórios de recusa)", "core.preview_domain_source_audio": "codec de áudio de origem (apenas relatórios de recusa)", + "core.preview_domain_preview_refusal": "motivo da recusa de um trailer automático (apenas relatórios de recusa de trailer)", "core.preview_domain_quality": "qualidade", "core.preview_domain_observed_rate": "débito observado", "core.preview_domain_raster": "resolução", diff --git a/locales/ru/core.json b/locales/ru/core.json index 6530b9a4dd..3574de2007 100644 --- a/locales/ru/core.json +++ b/locales/ru/core.json @@ -25,6 +25,7 @@ "core.preview_domain_attempted_delivery": "способ передачи при неудачной попытке", "core.preview_domain_source_video": "видеокодек источника (только при отказе)", "core.preview_domain_source_audio": "аудиокодек источника (только при отказе)", + "core.preview_domain_preview_refusal": "причина отказа в автозапуске трейлера (только при отказе в автозапуске)", "core.preview_domain_quality": "качество", "core.preview_domain_observed_rate": "измеренный битрейт", "core.preview_domain_raster": "размер кадра", diff --git a/rust-modules/Cargo.lock b/rust-modules/Cargo.lock index 38cc37dc9a..4e257a633a 100644 --- a/rust-modules/Cargo.lock +++ b/rust-modules/Cargo.lock @@ -262,9 +262,9 @@ dependencies = [ [[package]] name = "ed25519-compact" -version = "2.6.0" +version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1454db4f2edb7f0e8fe0c5b375b0c978fc63244cc9f010d160e417eb10139aa8" +checksum = "9547879431a90e352a35863a54416d92898a787b9af09e6ae2e09a96bd78be80" [[package]] name = "either" diff --git a/rust-modules/appkit/src/more_menu.rs b/rust-modules/appkit/src/more_menu.rs index 9a29f6ee38..b323ccf1f0 100644 --- a/rust-modules/appkit/src/more_menu.rs +++ b/rust-modules/appkit/src/more_menu.rs @@ -1585,9 +1585,9 @@ mod tests { let ps = plx_media::route::PlaybackSession::default(); let m = plx_base::fontcov::advances::ShippedMeasure; let step = |st: &mut MoreMenuState| { - plx_machine::idle::frame_begin(DT); + plx_machine::motion::report::frame_begin(DT); st.update(DT, &m, &ps); - plx_machine::idle::present_moving() + plx_machine::motion::report::present_moving() }; let mut st = menu(false, plx_media::route::quality()); st.motion.step(DT, st.panel_rect(&m)); @@ -1629,9 +1629,9 @@ mod tests { let ps = plx_media::route::PlaybackSession::default(); let m = plx_base::fontcov::advances::ShippedMeasure; let step = |st: &mut MoreMenuState| { - plx_machine::idle::frame_begin(DT); + plx_machine::motion::report::frame_begin(DT); st.update(DT, &m, &ps); - plx_machine::idle::present_moving() + plx_machine::motion::report::present_moving() }; // opened under Force Direct Play: no Quality row, a short panel let mut st = menu(true, plx_media::route::quality()); diff --git a/rust-modules/appkit/src/player_hud/classic.rs b/rust-modules/appkit/src/player_hud/classic.rs index 18fddc1b65..7d797457e5 100644 --- a/rust-modules/appkit/src/player_hud/classic.rs +++ b/rust-modules/appkit/src/player_hud/classic.rs @@ -454,11 +454,8 @@ pub(super) fn draw_player_title_at( let elapsed = clock.read(&key) as f32; let offset = plx_ui::marquee::TITLE.reveal_once(elapsed, full_width, width); if offset < full_width - width { - if elapsed < plx_ui::marquee::TITLE.hold_ms { - plx_machine::idle::wake(); - } else { - plx_machine::idle::invalidate(); - } + // The hold and reveal are one frame-captured animation, never worker work. + plx_machine::motion::report::note_motion(); } if offset > 0.0 { // an Arabic or Hebrew title's end is on its left: it moves right instead diff --git a/rust-modules/appkit/src/player_hud/motion.rs b/rust-modules/appkit/src/player_hud/motion.rs index 6216bfd23c..1af7d87fda 100644 --- a/rust-modules/appkit/src/player_hud/motion.rs +++ b/rust-modules/appkit/src/player_hud/motion.rs @@ -500,8 +500,8 @@ impl HudMotion { } /// Section button `i`'s focus pop this frame. - pub fn section_scale(&self, i: usize) -> f32 { - self.section_pop.scale(i) + pub fn section_scale(&self, i: usize, press: plx_machine::machine::PressRead) -> f32 { + self.section_pop.scale(i, press) } /// Do the title block, control row and bottom tabs take the pointer? Not while a scrub has @@ -519,8 +519,8 @@ impl HudMotion { /// Control `i`'s focus pop this frame — the read half of the row's springs, for the two /// stand-ins that draw into this row from their own modules (`up_next`, `skip_pill`). - pub fn scale(&self, i: c_int) -> f32 { - self.pop.scale(i.max(0) as usize) + pub fn scale(&self, i: c_int, press: plx_machine::machine::PressRead) -> f32 { + self.pop.scale(i.max(0) as usize, press) } /// Stamp the resume edge directly. `note_transport` derives it from `plx_play_feed::shared::FEED_TX`, which is diff --git a/rust-modules/appkit/src/player_hud/render.rs b/rust-modules/appkit/src/player_hud/render.rs index 8549cc81c5..e64a4ca211 100644 --- a/rust-modules/appkit/src/player_hud/render.rs +++ b/rust-modules/appkit/src/player_hud/render.rs @@ -100,6 +100,7 @@ use crate::up_next::{self, Countdown, Decor, Layout}; pub struct Frame<'a> { /// The entry the screen draws under: the key the chapters strip's Shelf reads focus from. pub entry: plx_machine::machine::EntryId, + pub press: plx_machine::machine::PressRead, pub ps: &'a plx_media::route::PlaybackSession, pub model: &'a HudModel, pub up: &'a Countdown, @@ -615,14 +616,14 @@ fn walk( let timer = if matches!(f.slot, ControlSlot::AutomaticUpNext(_)) { up_next::CountdownView::automatic(f.model.skip_progress) } else { f.up.view(f.now) }; - offer_drawn |= up_next::draw_over(f.ps, &layout, decor, look, row, timer, q, f.focus == GROUP_ROW, f.btn, f.measure); + offer_drawn |= up_next::draw_over(f.ps, &layout, decor, look, row, timer, q, f.focus == GROUP_ROW, f.btn, f.measure, f.press); } } DrawOp::SkipPill { rects, watch } => { if let ControlSlot::Skip(pr) = f.slot { let face = crate::hud_format::compile::SkipKind::for_prompt(pr) as usize; let (shown, beside) = (rects[face], pr.automatic.then_some(watch[face])); - skip_pill::draw_at(row, q, pr, shown, beside, f.focus == GROUP_ROW, f.btn, f.model.skip_progress); + skip_pill::draw_at(row, q, pr, shown, beside, f.focus == GROUP_ROW, f.btn, f.model.skip_progress, f.press); // a presented offer is every one of its buttons legibly inside the clip, as Up Next's offer_drawn |= q.opacity() >= 0.5 && std::iter::once(shown).chain(beside).all(|r| { let (rect, _, clip) = q.to_screen(r); @@ -861,10 +862,10 @@ fn draw_labelled(compiled: &Compiled, f: &Frame<'_>, row: &HudMotion, e: &plx_ui let Some(i) = c.section.as_deref().and_then(tab_of_section) else { return }; (f.focus == super::geometry::GROUP_TABS && f.tab == i, 1.0) } else if let Some(i) = row_index.and_then(|i| i32::try_from(i).ok()) { - (f.focus == GROUP_ROW && f.btn == i, row.scale(i)) + (f.focus == GROUP_ROW && f.btn == i, row.scale(i, f.press)) } else { let Some(i) = super::geometry::section_buttons(state).position(|k| k.id == c.id) else { return }; - ((f.focus == GROUP_SECTION && usize::try_from(f.btn).is_ok_and(|b| b == i)) || row.held_button() == Some(i), row.section_scale(i)) + ((f.focus == GROUP_SECTION && usize::try_from(f.btn).is_ok_and(|b| b == i)) || row.held_button() == Some(i), row.section_scale(i, f.press)) }; let model = match f.slot { ControlSlot::Discs(controls) => HudModel { controls, ..*f.model }, _ => *f.model }; let button = plx_ui::widgets::Button::new(label.as_ptr(), theme::size::BODY, c.rect) @@ -914,10 +915,10 @@ fn draw_control( let (i, focused, scale) = if c.is_action { let Some(i) = super::geometry::section_buttons(state).position(|k| k.id == c.id) else { return }; let Ok(index) = i32::try_from(i) else { return }; - (index, (f.focus == GROUP_SECTION && f.btn == index) || row.held_button() == Some(i), row.section_scale(i)) + (index, (f.focus == GROUP_SECTION && f.btn == index) || row.held_button() == Some(i), row.section_scale(i, f.press)) } else { let Some(i) = row_index.and_then(|i| i32::try_from(i).ok()) else { return }; - (i, f.focus == GROUP_ROW && f.btn == i, row.scale(i)) + (i, f.focus == GROUP_ROW && f.btn == i, row.scale(i, f.press)) }; let model = HudModel { controls, ..*f.model }; let button = TransportButton::new(i, c.rect) @@ -967,7 +968,7 @@ fn draw_control( return; }; let focused = (f.focus == GROUP_SECTION && usize::try_from(f.btn).is_ok_and(|b| b == i)) || row.held_button() == Some(i); - sections::button(f, q, e, c, focused, row.section_scale(i)); + sections::button(f, q, e, c, focused, row.section_scale(i, f.press)); } } } @@ -1065,7 +1066,7 @@ mod tests { let model = HudModel { paused: c.paused, duration_ns: 600_000_000_000, playpos_ns: 90_000_000_000, ..HudModel::default() }; let up = Countdown::default(); let mut row = HudMotion::new(); - let frame = Frame { + let frame = Frame { press: Default::default(), entry: EntryId(0), ps: &ps, model: &model, up: &up, @@ -1199,7 +1200,7 @@ mod tests { let model = HudModel::default(); let up = Countdown::default(); let mut row = HudMotion::new(); - let frame = Frame { + let frame = Frame { press: Default::default(), entry: EntryId(0), ps: &ps, model: &model, up: &up, @@ -1308,7 +1309,7 @@ mod tests { let up = Countdown::default(); let mut row = HudMotion::new(); row.set_section_appear_for_test(Section::Chapters, appear); - let frame = Frame { + let frame = Frame { press: Default::default(), entry: ENTRY, ps: &ps, model: &model, up: &up, slot: ControlSlot::Discs(Controls::NONE), busy: Busy::None, focus: GROUP_SCRUB, btn: 0, tab: 0, open: if closing { 0 } else { OPEN_CHAPTERS }, now: 1_000, transport: false, measure: &FM, meta: store.view(), }; @@ -1523,7 +1524,7 @@ mod tests { let up = Countdown::default(); let mut row = HudMotion::new(); row.set_section_appear_for_test(Section::Info, appear); - let frame = Frame { + let frame = Frame { press: Default::default(), entry: EntryId(0), ps: &ps, model: &model, up: &up, slot: ControlSlot::Discs(Controls::NONE), busy: Busy::None, focus: GROUP_SCRUB, btn: 0, tab: 0, open: if closing { 0 } else { OPEN_INFO }, now: 1_000, transport: false, measure: &FM, meta: store.view(), @@ -1813,7 +1814,7 @@ mod tests { let ps = plx_media::route::PlaybackSession::IDLE; let model = HudModel::default(); let up = Countdown::default(); - let frame = Frame { + let frame = Frame { press: Default::default(), entry: EntryId(0), ps: &ps, model: &model, up: &up, slot: ControlSlot::Discs(Controls::NONE), busy: Busy::None, focus, btn, tab, open: 0, now: 1_000, transport, measure: &FM, meta: store.view(), }; @@ -1856,13 +1857,13 @@ mod tests { for _ in 0..20 { row.step(slot, GROUP_SECTION, 1, 0.05, 1_000, Some(true), false); } - assert!(row.section_scale(1) > 1.0, "the focused section button pops: {}", row.section_scale(1)); - assert_eq!(row.section_scale(0), 1.0, "its sibling does not"); - assert_eq!(row.scale(1), 1.0, "and the control row's own springs are not the section's"); + assert!(row.section_scale(1, Default::default()) > 1.0, "the focused section button pops: {}", row.section_scale(1, Default::default())); + assert_eq!(row.section_scale(0, Default::default()), 1.0, "its sibling does not"); + assert_eq!(row.scale(1, Default::default()), 1.0, "and the control row's own springs are not the section's"); for _ in 0..40 { row.step(slot, GROUP_ROW, 1, 0.05, 1_000, Some(true), false); } - assert_eq!(row.section_scale(1), 1.0, "focus moved off the section group: it settles"); + assert_eq!(row.section_scale(1, Default::default()), 1.0, "focus moved off the section group: it settles"); } /// The drawn button wears the pop: the focused button's census differs from its resting one. @@ -1904,7 +1905,7 @@ mod tests { let store = plx_data::stores::metadata::MetadataStore::default(); let up = Countdown::default(); let mut row = HudMotion::new(); - let frame = Frame { + let frame = Frame { press: Default::default(), entry: EntryId(0), ps: &ps, model: &model, up: &up, slot, busy: Busy::None, focus, btn, tab: 0, open: 0, now: 1_000, transport: true, measure: &FM, meta: store.view(), }; @@ -2008,7 +2009,7 @@ mod tests { if let Some(a) = appear { row.set_section_appear_for_test(Section::Info, a); } - let frame = Frame { + let frame = Frame { press: Default::default(), entry: EntryId(0), ps: &ps, model: &model, up: &up, slot: ControlSlot::Discs(Controls::NONE), busy: Busy::None, focus: GROUP_SCRUB, btn: 0, tab: 0, open, now: 1_000, transport: true, measure: &FM, meta: store.view(), }; diff --git a/rust-modules/appkit/src/player_hud/render/tests/conformance.rs b/rust-modules/appkit/src/player_hud/render/tests/conformance.rs index e5f2e54e77..9f24842f2f 100644 --- a/rust-modules/appkit/src/player_hud/render/tests/conformance.rs +++ b/rust-modules/appkit/src/player_hud/render/tests/conformance.rs @@ -143,7 +143,7 @@ fn info_frame(compiled: &Compiled, focus: GroupId, btn: i32) -> Census { let mut row = HudMotion::new(); row.set_section_appear_for_test(Section::Info, 1.0); for _ in 0..30 { row.section_pop.step(Some(0), 0.016_667); } - let frame = Frame { entry: EntryId(0), ps: &ps, model: &model, up: &up, + let frame = Frame { press: Default::default(), entry: EntryId(0), ps: &ps, model: &model, up: &up, slot: ControlSlot::Discs(Controls::NONE), busy: Busy::None, focus, btn, tab: 0, open: crate::hud_format::compile::OPEN_INFO, now: 1_000, transport: true, measure: &FM, meta: store.view() }; census(|| with_df(|df| assert!(draw(compiled, &frame, df, &mut row, Painter::root())))) @@ -200,7 +200,7 @@ fn episode_frame(compiled: &Compiled, open: u8) -> Census { let up = Countdown::default(); let mut row = HudMotion::new(); if open != 0 { row.set_section_appear_for_test(Section::Info, 1.0); } - let frame = Frame { entry: EntryId(0), ps: &ps, model: &model, up: &up, slot: ControlSlot::Discs(Controls::NONE), busy: Busy::None, + let frame = Frame { press: Default::default(), entry: EntryId(0), ps: &ps, model: &model, up: &up, slot: ControlSlot::Discs(Controls::NONE), busy: Busy::None, focus: GROUP_SCRUB, btn: 0, tab: 0, open, now: 1_000, transport: true, measure: &FM, meta: store.view() }; census(|| with_df(|df| assert!(draw(compiled, &frame, df, &mut row, Painter::root())))) } @@ -325,7 +325,7 @@ fn chapter_frame_content(compiled: &Compiled, focused: bool, name: &str, episode let up = Countdown::default(); let mut row = HudMotion::new(); row.set_section_appear_for_test(Section::Chapters, 1.0); - let frame = Frame { entry: EntryId(0), ps: &ps, model: &model, up: &up, + let frame = Frame { press: Default::default(), entry: EntryId(0), ps: &ps, model: &model, up: &up, slot: ControlSlot::Discs(Controls::NONE), busy: Busy::None, focus: GROUP_STRIP, btn: 0, tab: 0, open: OPEN_CHAPTERS, now: 1_000, transport: true, measure: &FM, meta: store.view() }; let focus = FocusRead { current: focused.then_some(plx_machine::machine::FocusKey { diff --git a/rust-modules/appkit/src/player_hud/render/tests/transitions.rs b/rust-modules/appkit/src/player_hud/render/tests/transitions.rs index 9645a515ff..d64794446c 100644 --- a/rust-modules/appkit/src/player_hud/render/tests/transitions.rs +++ b/rust-modules/appkit/src/player_hud/render/tests/transitions.rs @@ -56,7 +56,7 @@ fn draw_in(compiled: &Compiled, row: &mut HudMotion, store: &plx_data::stores::m let ps = plx_media::route::PlaybackSession::IDLE; let up = Countdown::default(); let model = HudModel { duration_ns: 600_000_000_000, playpos_ns: 90_000_000_000, ..HudModel::default() }; - let frame = Frame { + let frame = Frame { press: Default::default(), entry: EntryId(0), ps: &ps, model: &model, up: &up, slot, busy: Busy::None, focus: GROUP_SCRUB, btn: 0, tab: 0, open, now: 1_000, transport, measure: &FM, meta: store.view(), }; @@ -68,7 +68,7 @@ fn walk_in(compiled: &Compiled, state: &CompiledState, row: &mut HudMotion, stor let ps = plx_media::route::PlaybackSession::IDLE; let up = Countdown::default(); let model = HudModel { duration_ns: 600_000_000_000, playpos_ns: 90_000_000_000, ..HudModel::default() }; - let frame = Frame { + let frame = Frame { press: Default::default(), entry: EntryId(0), ps: &ps, model: &model, up: &up, slot: NONE, busy: Busy::None, focus: GROUP_SCRUB, btn: 0, tab: 0, open, now: 1_000, transport, measure: &FM, meta: store.view(), }; @@ -561,10 +561,10 @@ fn the_titles_marquee_is_released_once_the_fade_is_over_and_not_at_its_first_fra // a title that has been running for a while let prime = |row: &HudMotion| { row.title_clock.read("a long title"); - plx_machine::idle::frame_begin(0.05); + plx_machine::motion::report::frame_begin(0.05); }; let running = |row: &HudMotion| { - plx_machine::idle::frame_begin(0.05); + plx_machine::motion::report::frame_begin(0.05); row.title_clock.read("a long title") > 10.0 }; diff --git a/rust-modules/appkit/src/player_hud/tests.rs b/rust-modules/appkit/src/player_hud/tests.rs index e6a568941d..f899cc6774 100644 --- a/rust-modules/appkit/src/player_hud/tests.rs +++ b/rust-modules/appkit/src/player_hud/tests.rs @@ -92,26 +92,29 @@ fn long_hud_titles_fit_before_every_control_slot() { for slot in slots { let right = compiled_title_right(&compiled, slot); let items = geometry(&compiled, 0, slot, true, false).items; + // What a title draws depends on the cell's right edge and the title, never on which + // control holds the focus or how far its pop has run (an unpaused title reads no clock): + // drawn once per slot and kicker, not again for every focused control and pop frame. + for kicker in [Kicker::Episode(long.as_ptr()), Kicker::Context(long.as_ptr())] { + let runs = plx_ui::draw_census::capture_runs(|| { + draw_player_title(Painter::recording(), kicker, long.as_ptr(), + right, measure, false, &clock); + }); + assert_eq!(runs.len(), 2); + for run in runs { + assert!(run.text.ends_with('…'), "{}: expected ellipsis: {run:?}", language.tag()); + assert_eq!(run.at.x, SB_X); + assert!(measure.width_str(&run.text, run.size, run.bold) <= right - SB_X + 1.0, + "{}: fitted title exceeds the control boundary: {run:?}", language.tag()); + } + } let mut row = HudMotion::new(); for focused in 0..slot.items() { for _ in 0..30 { row.pop.step(Some(focused as usize), 1.0 / 60.0); for i in 0..slot.items() { let Some(rect) = items[i as usize] else { continue }; - assert!(right + theme::space::MD <= rect.scaled(row.scale(i)).x + 0.001); - } - for kicker in [Kicker::Episode(long.as_ptr()), Kicker::Context(long.as_ptr())] { - let runs = plx_ui::draw_census::capture_runs(|| { - draw_player_title(Painter::recording(), kicker, long.as_ptr(), - right, measure, false, &clock); - }); - assert_eq!(runs.len(), 2); - for run in runs { - assert!(run.text.ends_with('…'), "{}: expected ellipsis: {run:?}", language.tag()); - assert_eq!(run.at.x, SB_X); - assert!(measure.width_str(&run.text, run.size, run.bold) <= right - SB_X + 1.0, - "{}: fitted title exceeds the control boundary: {run:?}", language.tag()); - } + assert!(right + theme::space::MD <= rect.scaled(row.scale(i, Default::default())).x + 0.001); } } } @@ -147,10 +150,10 @@ fn paused_title_reveals_once_and_resume_restores_ellipsis() { }); let start = paint(true); assert!(start[1].text.ends_with('…')); - plx_machine::idle::frame_begin(2.0); + plx_machine::motion::report::frame_begin(2.0); let moving = paint(true); assert!(moving[1].at.x < SB_X); - plx_machine::idle::frame_begin(30.0); + plx_machine::motion::report::frame_begin(30.0); let ended = paint(true); assert_eq!(ended[1].at.x, SB_X - (FM.width(long, HUD_TITLE_SZ, true) - (right - SB_X))); assert_eq!(paint(true)[1].at.x, ended[1].at.x, "the title must stay at the end"); @@ -173,12 +176,12 @@ fn a_paused_right_to_left_title_reveals_its_end_to_the_left() { long.as_ptr(), right, &FM, paused, &clock); }); let _ = paint(true); - plx_machine::idle::frame_begin(2.0); + plx_machine::motion::report::frame_begin(2.0); let moving = paint(true); let elapsed = 2000.0 - plx_ui::marquee::TITLE.hold_ms; let off = elapsed / 1000.0 * plx_ui::marquee::SPEED; assert_eq!(moving[1].at.x, SB_X + window - full + off, "first words flush right, moving right"); - plx_machine::idle::frame_begin(60.0); + plx_machine::motion::report::frame_begin(60.0); assert_eq!(paint(true)[1].at.x, SB_X, "the last words rest on the window's left edge"); assert_eq!(paint(true)[1].at.x, SB_X, "and stay"); } diff --git a/rust-modules/appkit/src/skip_pill.rs b/rust-modules/appkit/src/skip_pill.rs index e24a48dbfa..2f7dbc033c 100644 --- a/rust-modules/appkit/src/skip_pill.rs +++ b/rust-modules/appkit/src/skip_pill.rs @@ -94,13 +94,13 @@ pub fn prompt_for(m: metadata::Marker) -> Prompt { /// unfilled Watch button (item 0) cancels, the FILLED Skip (item 1) carries the countdown sweep and is what /// the clock performs, so pressing it acts now; `btn` says which one holds the ring. #[allow(clippy::too_many_arguments)] -pub fn draw_at(row: &crate::player_hud::motion::HudMotion, p: Painter, pr: Prompt, slot: Rect, watch: Option, focused: bool, btn: c_int, progress: Option) { +pub fn draw_at(row: &crate::player_hud::motion::HudMotion, p: Painter, pr: Prompt, slot: Rect, watch: Option, focused: bool, btn: c_int, progress: Option, press: plx_machine::machine::PressRead) { let Ok(label) = CString::new(pr.label()) else { return; }; // No leading icon: the label alone carries it, and a chevron on a control that does not // navigate anywhere was reading as "more" rather than "skip". - let (pop, ring) = if pr.automatic { (row.scale(crate::up_next::BTN_NEXT), focused && btn == crate::up_next::BTN_NEXT) } else { (row.scale(0), focused) }; + let (pop, ring) = if pr.automatic { (row.scale(crate::up_next::BTN_NEXT, press), focused && btn == crate::up_next::BTN_NEXT) } else { (row.scale(0, press), focused) }; // It stands in the transport discs' own slot, over the video plane and on the HUD's ramp, // so it wears their ground as well as their pop — see `ControlGround`. let button = Button::new(label.as_ptr(), theme::size::BODY, slot).scale(pop).focused(ring).ground(ControlGround::Unkeyed); @@ -108,7 +108,7 @@ pub fn draw_at(row: &crate::player_hud::motion::HudMotion, p: Painter, pr: Promp button.draw(&Env::inert(), p); if let (true, Some(watch), Ok(cancel)) = (pr.automatic, watch, CString::new(pr.watch_label())) { Button::new(cancel.as_ptr(), theme::size::BODY, watch) - .scale(row.scale(crate::up_next::BTN_CREDITS)) + .scale(row.scale(crate::up_next::BTN_CREDITS, press)) .focused(focused && btn == crate::up_next::BTN_CREDITS) .ground(ControlGround::Unkeyed) .draw(&Env::inert(), p); @@ -137,7 +137,7 @@ mod tests { let mut runs = Vec::new(); plx_ui::record_walk(|| plx_ui::draw_census::capture(|| { runs = plx_ui::draw_census::capture_runs(|| { - draw_at(&row, Painter::root(), prompt, skip, automatic.then_some(watch), true, crate::up_next::BTN_NEXT, automatic.then_some(0.4)); + draw_at(&row, Painter::root(), prompt, skip, automatic.then_some(watch), true, crate::up_next::BTN_NEXT, automatic.then_some(0.4), Default::default()); }); })); runs diff --git a/rust-modules/appkit/src/track_menu.rs b/rust-modules/appkit/src/track_menu.rs index 511747706c..12f4d0cceb 100644 --- a/rust-modules/appkit/src/track_menu.rs +++ b/rust-modules/appkit/src/track_menu.rs @@ -6914,9 +6914,9 @@ mod motion_tests { /// One loop frame, as the dispatcher runs it: forget last frame's motion, then update. Returns /// whether a spring moved (what keeps the present gate awake). fn frame(menu: &mut TrackMenuState, ps: &plx_media::route::PlaybackSession, store: &plx_data::stores::metadata::MetadataStore) -> bool { - plx_machine::idle::frame_begin(DT); + plx_machine::motion::report::frame_begin(DT); menu.update(DT, &ShippedMeasure, ps, store.view()); - plx_machine::idle::present_moving() + plx_machine::motion::report::present_moving() } fn run(menu: &mut TrackMenuState, ps: &plx_media::route::PlaybackSession, store: &plx_data::stores::metadata::MetadataStore, n: usize) { diff --git a/rust-modules/appkit/src/up_next.rs b/rust-modules/appkit/src/up_next.rs index 002b4ff371..9e61e36b7a 100644 --- a/rust-modules/appkit/src/up_next.rs +++ b/rust-modules/appkit/src/up_next.rs @@ -353,6 +353,7 @@ pub fn draw_over( focused: bool, btn: c_int, measure: &dyn plx_machine::machine::Measure, + press: plx_machine::machine::PressRead, ) -> bool { let Some(u) = plx_media::route::up_next(ps) else { return false; @@ -386,7 +387,7 @@ pub fn draw_over( } } - if !draw_buttons(l, look, row, timer, p, focused, btn) { return false; } + if !draw_buttons(l, look, row, timer, p, focused, btn, press) { return false; } p.opacity() >= 0.5 && [l.credits, l.next].into_iter().all(|r| { let (rect, _, clip) = p.to_screen(r); let hit = rect.intersect(clip); @@ -397,8 +398,8 @@ pub fn draw_over( /// The fixed command pair's presentation, factored so a host census can exercise every countdown without a decoder. #[allow(clippy::too_many_arguments)] fn draw_buttons(l: &Layout, look: Look, row: &crate::player_hud::motion::HudMotion, timer: CountdownView, - p: Painter, focused: bool, btn: c_int) -> bool { - let (pop_credits, pop_next) = (row.scale(BTN_CREDITS), row.scale(BTN_NEXT)); + p: Painter, focused: bool, btn: c_int, press: plx_machine::machine::PressRead) -> bool { + let (pop_credits, pop_next) = (row.scale(BTN_CREDITS, press), row.scale(BTN_NEXT, press)); let e = Env::inert(); // The focus pop is the CONTROL ROW's, not this card's: these two stand in the transport's own // slot and share its cursor, so they share its springs (`HudMotion::scale`). @@ -433,7 +434,7 @@ fn draw_buttons(l: &Layout, look: Look, row: &crate::player_hud::motion::HudMoti // A HELD clock (`remaining_ms`) draws one fixed fill, so there is nothing to redraw — the // same exception `widgets::Spinner` makes. if !plx_machine::motion::phase_clocks_held() { - plx_machine::idle::invalidate(); + plx_machine::motion::report::note_motion(); } let progress = 1.0 - (left as f32 / timer.duration_ms as f32).clamp(0.0, 1.0); b = match look.countdown { @@ -468,7 +469,7 @@ mod tests { let look = Look { countdown: face, ..Look::CLASSIC }; let mut runs = Vec::new(); let prims = plx_ui::record_walk(|| plx_ui::draw_census::capture(|| { - runs = plx_ui::draw_census::capture_runs(|| { draw_buttons(&l, look, &row, up.view(now), Painter::root(), true, BTN_NEXT); }); + runs = plx_ui::draw_census::capture_runs(|| { draw_buttons(&l, look, &row, up.view(now), Painter::root(), true, BTN_NEXT, Default::default()); }); })); (prims, runs) }; diff --git a/rust-modules/appkit/src/watchlist_disc.rs b/rust-modules/appkit/src/watchlist_disc.rs index ea058fe6ba..8311566b4c 100644 --- a/rust-modules/appkit/src/watchlist_disc.rs +++ b/rust-modules/appkit/src/watchlist_disc.rs @@ -149,10 +149,10 @@ impl Disc { /// Decorative (`idle::decorative`): the flip moves no layout, so it never holds a page image. pub fn step(&mut self, dt: f32) -> bool { let to = target(self.m); - plx_machine::idle::decorative(|| self.flip.step(to, plx_ui::widgets::K_DISC_UNFURL, dt)); + plx_machine::motion::report::decorative(|| self.flip.step(to, plx_ui::widgets::K_DISC_UNFURL, dt)); // A spring idle has stopped asking frames for can rest a hair short of its target; land it // exactly so a settled disc draws the plain face, never a 99.9 % fill clip. - if plx_machine::idle::settled(self.flip.pos, to, self.flip.vel) { + if plx_machine::motion::report::settled(self.flip.pos, to, self.flip.vel) { self.flip.jump(to); } self.animating() @@ -234,7 +234,7 @@ mod tests { fn frames(d: &mut Disc, n: usize) -> Vec { (0..n) .map(|_| { - plx_machine::idle::frame_begin(DT); + plx_machine::motion::report::frame_begin(DT); d.step(DT); d.pos() }) @@ -309,14 +309,14 @@ mod tests { let _serial = plx_base::testlock::serial(); let mut d = Disc::new(Membership::Off); d.set(Membership::On); - plx_machine::idle::frame_begin(DT); + plx_machine::motion::report::frame_begin(DT); assert!(d.step(DT), "mid-flip"); for _ in 0..600 { - plx_machine::idle::frame_begin(DT); + plx_machine::motion::report::frame_begin(DT); d.step(DT); } assert_eq!((d.flip.pos, d.flip.vel), (1.0, 0.0)); - plx_machine::idle::frame_begin(DT); + plx_machine::motion::report::frame_begin(DT); assert!(!d.step(DT), "at rest"); } diff --git a/rust-modules/base/src/diag/heartbeat.rs b/rust-modules/base/src/diag/heartbeat.rs index 10dab13b34..b8d5ec9fbb 100644 --- a/rust-modules/base/src/diag/heartbeat.rs +++ b/rust-modules/base/src/diag/heartbeat.rs @@ -221,7 +221,8 @@ pub struct Instruments { thresh_ms: f64, perf_freq: f64, stamps: [u64; 9], - /// The watchdog label of the leg `mark` last opened (label-only; a no-op without `threadcheck`). + /// The leg `mark` last opened: recorded for the freeze probe in every build, and published as + /// the watchdog's hang label only under `threadcheck`. leg: crate::task::watchdog::LoopPhases, /// Worst frame total this second (presented frames only), for the heartbeat peak. worst: f64, @@ -359,7 +360,8 @@ impl Instruments { pub fn mark(&mut self, phase: Phase) { use crate::task::watchdog::LoopPhase as Leg; // A mark ends the leg it names and opens the next one: the watchdog names the leg a hang - // lands in. Draw and Capture open nothing new (`draw_scope` / `present_scope` label them). + // lands in, and in every build the freeze probe records it. Draw and Capture open nothing + // new (`draw_scope` / `present_scope` label them). match phase { Phase::Top => { self.leg.enter(Leg::EventIngest); diff --git a/rust-modules/base/src/diag/spans.rs b/rust-modules/base/src/diag/spans.rs index ab32e2c10b..4acad4f122 100644 --- a/rust-modules/base/src/diag/spans.rs +++ b/rust-modules/base/src/diag/spans.rs @@ -14,7 +14,9 @@ //! paid. It is not GPU time; `plxnative-hwcnt` is. //! //! Armed with the rest of the frame instrument (`plxnative-framedrop`); unarmed, [`span`] is one -//! relaxed atomic load and a direct call. +//! relaxed atomic load and a direct call, plus, for the four spans that name a loop leg +//! (`scen`, `pump`, `land`, `dframe`), the leg's store and restore: those run armed or not, because +//! the freeze probe reads the leg in a shipping build too. use std::cell::RefCell; use std::sync::atomic::{AtomicBool, Ordering::Relaxed}; @@ -36,11 +38,14 @@ pub fn armed() -> bool { ON.load(Relaxed) } -/// Run `f`, and when armed add its wall time to this frame's `name`. Under `threadcheck` the -/// loop's own spans (`scen`, `pump`, `land`, `dframe`) also label the watchdog for the call. +/// Run `f`, and when armed add its wall time to this frame's `name`. The loop's own spans +/// (`scen`, `pump`, `land`, `dframe`) also name the loop leg for the freeze probe for the call, in +/// every build and armed or not; under `threadcheck` they also label the watchdog. #[inline] pub fn span(name: &'static str, f: impl FnOnce() -> R) -> R { - // The main-loop spans also name the phase for the hang watchdog (label-only). + // The main-loop spans name their leg for the freeze probe (every build; restored on return or + // unwind) and the phase for the hang watchdog (`threadcheck`, label-only). + let _leg = crate::task::watchdog::span_leg(name); #[cfg(feature = "threadcheck")] let _label = crate::task::watchdog::span_scope(name); if !armed() { @@ -109,4 +114,26 @@ mod tests { assert_eq!(take(), "spans=pagex2:4.0,field:20.3"); assert_eq!(take(), "", "taken: the next frame starts empty"); } + + /// The bug this guards: only the heartbeat marks wrote the leg cell, so a freeze inside + /// `span("pump", ..)` (the Starfish/ACB pump) was reported as the enclosing `results`. This + /// reads the real process cell. The serial lock keeps it from restoring "none yet" under the + /// other test that publishes a leg there; heartbeat tests step the cell without the lock, but + /// only to the seven legs they mark, so one read can still be overwritten from outside: a span + /// that names its leg shows it on the first try in practice, and one that does not never + /// shows it on any. + #[test] + fn a_loop_span_names_its_leg_whether_or_not_the_frame_instrument_is_armed() { + use crate::task::watchdog::{current_leg, LoopPhase}; + let _lock = crate::testlock::serial(); + for (name, leg) in [ + ("scen", LoopPhase::DevScenarios), + ("pump", LoopPhase::PlaybackPump), + ("land", LoopPhase::LandResults), + ("dframe", LoopPhase::DispatcherFrame), + ] { + let seen = (0..1_000).any(|_| span(name, current_leg) == Some(leg)); + assert!(seen, "span({name:?}) never published {leg:?}"); + } + } } diff --git a/rust-modules/base/src/task/watchdog.rs b/rust-modules/base/src/task/watchdog.rs index df0749a51d..7e8724871d 100644 --- a/rust-modules/base/src/task/watchdog.rs +++ b/rust-modules/base/src/task/watchdog.rs @@ -12,7 +12,7 @@ use std::{ cell::Cell, marker::PhantomData, rc::Rc, - sync::{atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicUsize, Ordering}, OnceLock}, + sync::{atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicU8, AtomicUsize, Ordering}, OnceLock}, time::{Duration, Instant}, }; @@ -78,6 +78,14 @@ pub fn freeze_end_record(seq: u32, bucket: FreezeBucket) -> String { format!("freeze-end: seq={seq} bucket={}", bucket.word()) } +/// The crash-log line that says where the loop was when probe `seq` was sent: +/// `freeze-at: seq= leg=`. Written by the observer thread at probe time, so it is on disk +/// even if the freeze is never recovered; the importer joins it to the `*** FREEZE seq=` record +/// of the same process. `leg` is one of [`LoopPhase::word`]'s fixed words. +pub fn freeze_at_record(seq: u32, leg: LoopPhase) -> String { + format!("freeze-at: seq={seq} leg={}", leg.word()) +} + #[derive(Debug, PartialEq, Eq)] enum Event { Began { ms: u64, label: &'static str }, @@ -266,9 +274,11 @@ pub fn present_scope() -> LabelScope { /// (`main-thread hang: 303ms in land results`) instead of reading `unlabeled`. They are not a /// third naming of the loop: each text is published by a mark or span the loop already has — /// a heartbeat leg (`heartbeat::Instruments::mark` opens the leg that follows its `Phase`) or a -/// named FRAMEDROP span (`diag::spans::span`, via [`span_scope`]). Label-only, like `draw_scope`: -/// no assertion, no permission to block, and none is a GPU phase, so the fatal policy sees each -/// exactly as it sees `unlabeled`. +/// named FRAMEDROP span (`diag::spans::span`, via [`span_scope`]). The label is label-only, like +/// `draw_scope`: no assertion, no permission to block, and none is a GPU phase, so the fatal +/// policy sees each exactly as it sees `unlabeled`. The leg itself is also recorded in every +/// build for the freeze probe ([`current_leg`]): by the same marks, and by [`span_leg`] for the +/// four spans. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum LoopPhase { EventIngest, @@ -291,6 +301,33 @@ impl LoopPhase { Self::PresentAndSwap, Self::FrameReport, ]; + /// The word the crash log and the report carry for this leg of the frame loop. **The one + /// table**, read by the writer here ([`freeze_at_record`]) and the importer + /// (`telemetry::crashreport`), so a leg on the wire is always one of these eleven fixed words + /// of the app's own loop and never free text. Single tokens (the log line is split on + /// whitespace); not the `threadcheck` descriptor texts, which have spaces and exist only in a + /// developer build. + pub fn word(self) -> &'static str { + match self { + Self::EventIngest => "event-ingest", + Self::Results => "results", + Self::DevScenarios => "dev-scenarios", + Self::PlaybackPump => "playback-pump", + Self::LandResults => "land-results", + Self::Navcommit => "navcommit", + Self::DispatcherFrame => "dispatcher-frame", + Self::Update => "update", + Self::PrepareWindow => "prepare-window", + Self::PresentAndSwap => "present-and-swap", + Self::FrameReport => "frame-report", + } + } + + /// The inverse of [`word`](Self::word); anything that is not exactly one of the words is `None`. + pub fn from_word(word: &str) -> Option { + Self::ALL.into_iter().find(|leg| leg.word() == word) + } + #[cfg(feature = "threadcheck")] const fn descriptor(self) -> &'static BlockingLabel { match self { @@ -308,8 +345,7 @@ impl LoopPhase { } } - /// The phase a FRAMEDROP span of this name stands for, if the loop labels it. - #[cfg(feature = "threadcheck")] + /// The phase a FRAMEDROP span of this name stands for, if the loop names it. fn of_span(name: &str) -> Option { Some(match name { "scen" => Self::DevScenarios, @@ -328,19 +364,95 @@ pub fn span_scope(name: &str) -> Option { LoopPhase::of_span(name).map(|phase| enter_label(phase.descriptor())) } +/// What the leg cell holds before the first leg is entered. +const NO_LEG: u8 = 0; + +/// **The leg the main loop is in, in EVERY build.** [`LoopPhases::enter`] (the seven heartbeat +/// legs) and [`span_leg`] (the four a FRAMEDROP span names, for the span's duration) store the +/// leg's code here (relaxed stores: no string, no thread-local, no allocation) and the observer +/// reads it when it probes a freeze, because the label the `threadcheck` build publishes does not +/// exist in a shipping one. A code is the leg's position in [`LoopPhase::ALL`] plus one, so +/// [`NO_LEG`] is "none yet". +static CURRENT_LEG: AtomicU8 = AtomicU8::new(NO_LEG); + +fn leg_code(phase: LoopPhase) -> u8 { + phase as u8 + 1 +} + +fn leg_of(code: u8) -> Option { + usize::from(code).checked_sub(1).and_then(|i| LoopPhase::ALL.get(i).copied()) +} + +/// The leg the main loop is in now: `None` before it has entered its first. +pub fn current_leg() -> Option { + leg_of(CURRENT_LEG.load(Ordering::Relaxed)) +} + +/// A leg a FRAMEDROP span names, held for the span's duration: the previous leg comes back when +/// the guard drops, on a normal return and on an unwind alike. Four of the loop's eleven legs +/// (`scen`, `pump`, `land`, `dframe`) have no heartbeat mark, so this is the only thing that ever +/// publishes them; without it a freeze inside the playback pump reads as the leg around it. +#[must_use = "the leg is the span's: dropping the guard at once ends it"] +pub struct LegScope { + cell: &'static AtomicU8, + previous: u8, +} + +impl Drop for LegScope { + #[inline] + fn drop(&mut self) { + self.cell.store(self.previous, Ordering::Relaxed); + } +} + +/// `diag::spans::span`'s leg, in EVERY build and armed or not: for the named spans the loop +/// marks, the span's leg in [`CURRENT_LEG`] until the guard drops (a load and two relaxed stores, +/// no string, no thread-local, no allocation); any other span name leaves the cell untouched. The +/// span names are mapped here, beside the leg table, so `base` still names no app layer. +#[inline] +pub fn span_leg(name: &str) -> Option { + span_leg_on(&CURRENT_LEG, name) +} + +#[inline] +fn span_leg_on(cell: &'static AtomicU8, name: &str) -> Option { + let phase = LoopPhase::of_span(name)?; + // One writer at a time (the main loop; the four spans run on it), so load-then-store needs + // no read-modify-write. + let previous = cell.load(Ordering::Relaxed); + cell.store(leg_code(phase), Ordering::Relaxed); + Some(LegScope { cell, previous }) +} + /// The heartbeat leg currently open. `enter` closes the previous leg and opens the next; the last /// stays open until the next `enter`. Owned by `heartbeat::Instruments`, whose `mark` is the only -/// caller. Without `threadcheck` this is a zero-sized no-op. -#[derive(Default)] +/// caller, and which enters seven of the eleven legs; the other four are [`span_leg`]'s. In every +/// build `enter` records the leg in [`CURRENT_LEG`] for the freeze probe; with `threadcheck` it +/// also publishes the leg's label for the hang line. pub struct LoopPhases { + cell: &'static AtomicU8, #[cfg(feature = "threadcheck")] open: Option, } +impl Default for LoopPhases { + fn default() -> Self { + Self::on(&CURRENT_LEG) + } +} + impl LoopPhases { + fn on(cell: &'static AtomicU8) -> Self { + Self { + cell, + #[cfg(feature = "threadcheck")] + open: None, + } + } + #[inline] - #[cfg_attr(not(feature = "threadcheck"), allow(unused_variables))] pub fn enter(&mut self, phase: LoopPhase) { + self.cell.store(leg_code(phase), Ordering::Relaxed); #[cfg(feature = "threadcheck")] { self.open = None; // restores the label that was current before the first leg @@ -612,6 +724,32 @@ fn handler_is_ours(handler: libc::sighandler_t) -> bool { } } +/// The observer's answer to a freeze probe: send it, and when it went out write +/// `freeze-at: seq= leg=` to the crash log. Returns whether the probe was sent and the +/// event-log line to write (which names the leg whether or not the probe was sent). +/// +/// The record is written on the OBSERVER thread (never in the signal handler) and at probe time, +/// not at recovery, so a freeze the platform ends by killing the app still carries its leg. It +/// follows the send, so it can land before, between or after the lines the handler writes on the +/// stuck thread; the importer joins it to its `*** FREEZE` by number whichever order they came in. +/// An unsent probe writes nothing: no `*** FREEZE` exists for a leg to belong to, and the number is +/// reused by the next probe. Without a leg (the loop has not entered one) nothing is written +/// either: there is no word to write. +fn answer_probe( + crash_log: &std::path::Path, + seq: u32, + ms: u64, + leg: Option, + send: impl FnOnce(u32) -> bool, +) -> (bool, String) { + let sent = send(seq); + if let (true, Some(leg)) = (sent, leg) { + let _ = crate::eventlog::append_record(crash_log, &freeze_at_record(seq, leg)); + } + let at = leg.map(|leg| format!(" in {}", leg.word())).unwrap_or_default(); + (sent, format!("main-thread freeze: {ms}ms without loop progress{at} (probe {seq}, recorded={sent})")) +} + fn observe_loop(main_thread: usize, #[cfg(feature = "threadcheck")] log_only: bool) { let origin = Instant::now(); let mut freezes = Freezes::default(); @@ -639,11 +777,13 @@ fn observe_loop(main_thread: usize, #[cfg(feature = "threadcheck")] log_only: bo let event = detector.observe(now, progress, label); match freezes.observe(now, progress, SIGNALS.foreground.load(Ordering::Acquire)) { Some(FreezeEvent::Probe { seq, ms }) => { - let sent = probe_main_thread(main_thread, seq); + let crash_log = crate::paths::in_runtime_dir(crate::paths::runtime_file::CRASH); + let (sent, line) = + answer_probe(&crash_log, seq, ms, current_leg(), |seq| probe_main_thread(main_thread, seq)); if !sent { freezes.unsent(); } - crate::eventlog::log(&format!("main-thread freeze: {ms}ms without loop progress (probe {seq}, recorded={sent})")); + crate::eventlog::log(&line); probed = sent.then_some(seq); } Some(FreezeEvent::Recovered { seq, ms }) => { @@ -1226,6 +1366,164 @@ mod tests { assert_eq!(freeze_end_record(2, FreezeBucket::Medium), "freeze-end: seq=2 bucket=10-30s"); } + #[test] + fn every_loop_leg_has_one_single_token_word_and_round_trips() { + let mut seen = std::collections::HashSet::new(); + for (i, leg) in LoopPhase::ALL.into_iter().enumerate() { + let word = leg.word(); + assert!(!word.is_empty() && word.bytes().all(|b| b.is_ascii_lowercase() || b == b'-'), "{word:?}"); + assert!(seen.insert(word), "{word:?} names two legs"); + assert_eq!(LoopPhase::from_word(word), Some(leg)); + assert_eq!(leg as usize, i, "the leg cell's code is the position in ALL"); + } + for not_a_leg in ["", "unlabeled", "event ingest", "Update", "update ", "7"] { + assert_eq!(LoopPhase::from_word(not_a_leg), None, "{not_a_leg:?}"); + } + } + + #[test] + fn the_leg_record_names_the_probe_and_a_fixed_word() { + assert_eq!(freeze_at_record(3, LoopPhase::Update), "freeze-at: seq=3 leg=update"); + assert_eq!(freeze_at_record(1, LoopPhase::PresentAndSwap), "freeze-at: seq=1 leg=present-and-swap"); + } + + #[test] + fn entering_a_leg_publishes_it_to_the_cell_in_every_build() { + let cell: &'static AtomicU8 = Box::leak(Box::new(AtomicU8::new(NO_LEG))); + let mut legs = LoopPhases::on(cell); + assert_eq!(leg_of(cell.load(Ordering::Relaxed)), None, "no leg before the first mark"); + legs.enter(LoopPhase::Update); + assert_eq!(leg_of(cell.load(Ordering::Relaxed)), Some(LoopPhase::Update)); + legs.enter(LoopPhase::PresentAndSwap); + assert_eq!(leg_of(cell.load(Ordering::Relaxed)), Some(LoopPhase::PresentAndSwap)); + for leg in LoopPhase::ALL { + legs.enter(leg); + assert_eq!(leg_of(cell.load(Ordering::Relaxed)), Some(leg)); + } + assert_eq!(leg_of(200), None, "a code outside the table names no leg"); + } + + fn private_cell() -> &'static AtomicU8 { + Box::leak(Box::new(AtomicU8::new(NO_LEG))) + } + + #[test] + fn each_named_loop_span_publishes_its_leg_for_its_duration_and_restores_the_enclosing_one() { + let cell = private_cell(); + let mut legs = LoopPhases::on(cell); + legs.enter(LoopPhase::Results); + for (name, leg) in [ + ("scen", LoopPhase::DevScenarios), + ("pump", LoopPhase::PlaybackPump), + ("land", LoopPhase::LandResults), + ("dframe", LoopPhase::DispatcherFrame), + ] { + let scope = span_leg_on(cell, name); + assert!(scope.is_some(), "{name} names a leg"); + assert_eq!(leg_of(cell.load(Ordering::Relaxed)), Some(leg), "inside {name}"); + drop(scope); + assert_eq!(leg_of(cell.load(Ordering::Relaxed)), Some(LoopPhase::Results), "after {name}"); + } + } + + #[test] + fn a_span_before_the_first_leg_restores_none_yet() { + let cell = private_cell(); + let scope = span_leg_on(cell, "pump"); + assert_eq!(leg_of(cell.load(Ordering::Relaxed)), Some(LoopPhase::PlaybackPump)); + drop(scope); + assert_eq!(leg_of(cell.load(Ordering::Relaxed)), None); + } + + #[test] + fn a_span_that_names_no_leg_leaves_the_cell_alone_even_nested_inside_one_that_does() { + let cell = private_cell(); + LoopPhases::on(cell).enter(LoopPhase::Update); + for name in ["", "text", "dpre", "feed", "results", "update", "sfv"] { + assert!(span_leg_on(cell, name).is_none(), "{name:?}"); + assert_eq!(leg_of(cell.load(Ordering::Relaxed)), Some(LoopPhase::Update), "{name:?}"); + } + let outer = span_leg_on(cell, "dframe"); + assert!(span_leg_on(cell, "dstep").is_none()); + assert_eq!(leg_of(cell.load(Ordering::Relaxed)), Some(LoopPhase::DispatcherFrame)); + { + let inner = span_leg_on(cell, "land"); + assert_eq!(leg_of(cell.load(Ordering::Relaxed)), Some(LoopPhase::LandResults)); + drop(inner); + } + assert_eq!(leg_of(cell.load(Ordering::Relaxed)), Some(LoopPhase::DispatcherFrame), "the inner span restores the outer's leg"); + drop(outer); + assert_eq!(leg_of(cell.load(Ordering::Relaxed)), Some(LoopPhase::Update)); + } + + #[test] + fn a_panic_unwinding_out_of_a_span_restores_the_enclosing_leg() { + let cell = private_cell(); + LoopPhases::on(cell).enter(LoopPhase::Results); + let inside = std::cell::Cell::new(None); + let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _scope = span_leg_on(cell, "pump"); + inside.set(leg_of(cell.load(Ordering::Relaxed))); + panic!("a leg that panics"); + })); + assert!(unwound.is_err()); + assert_eq!(inside.get(), Some(LoopPhase::PlaybackPump), "the span named its leg before it unwound"); + assert_eq!(leg_of(cell.load(Ordering::Relaxed)), Some(LoopPhase::Results)); + } + + #[test] + fn the_default_legs_publish_to_the_process_cell_the_observer_reads() { + // `diag::spans`' process-cell test restores the cell it found, which can be "none yet": + // under the same lock that cannot land between this store and the read. + let _lock = crate::testlock::serial(); + LoopPhases::default().enter(LoopPhase::Navcommit); + // Other tests may enter a leg too, so only "a leg is published" is stable here; which + // one is the private-cell test's business. + assert!(current_leg().is_some()); + } + + fn scratch(name: &str) -> std::path::PathBuf { + // `process_dir` replaces the directory on every call: made once, or a parallel test's + // call would remove another's file between its write and its read. + static DIR: OnceLock = OnceLock::new(); + let path = DIR.get_or_init(|| crate::testscratch::process_dir("freeze-at")).join(name); + let _ = std::fs::remove_file(&path); + path + } + + #[test] + fn a_probe_that_was_sent_writes_the_leg_record_and_names_the_leg_in_the_log_line() { + let log = scratch("sent"); + let (sent, line) = answer_probe(&log, 2, 5_000, Some(LoopPhase::PresentAndSwap), |seq| { + assert_eq!(seq, 2); + true + }); + assert!(sent); + assert_eq!( + line, + "main-thread freeze: 5000ms without loop progress in present-and-swap (probe 2, recorded=true)" + ); + assert_eq!(std::fs::read_to_string(&log).unwrap(), "freeze-at: seq=2 leg=present-and-swap\n"); + } + + #[test] + fn a_probe_that_was_not_sent_writes_no_record_but_the_line_still_names_the_leg() { + let log = scratch("unsent"); + let (sent, line) = answer_probe(&log, 1, 6_100, Some(LoopPhase::Update), |_| false); + assert!(!sent); + assert_eq!(line, "main-thread freeze: 6100ms without loop progress in update (probe 1, recorded=false)"); + assert!(!log.exists(), "an unsent probe has no `*** FREEZE` for a leg to belong to"); + } + + #[test] + fn a_probe_before_any_leg_was_entered_names_none() { + let log = scratch("noleg"); + let (sent, line) = answer_probe(&log, 1, 5_000, None, |_| true); + assert!(sent); + assert_eq!(line, "main-thread freeze: 5000ms without loop progress (probe 1, recorded=true)"); + assert!(!log.exists(), "no leg, no record: nothing is written that names nothing"); + } + #[test] fn the_probe_is_not_sent_where_no_handler_is_installed() { // The test harness installs no tracer, so SIGUSR2 has its default (fatal) disposition and diff --git a/rust-modules/data/Cargo.toml b/rust-modules/data/Cargo.toml index 9f765a5915..054f78e163 100644 --- a/rust-modules/data/Cargo.toml +++ b/rust-modules/data/Cargo.toml @@ -44,7 +44,7 @@ serde_json = { version = "1", default-features = false, features = ["alloc", "st # arithmetic out of line and drops its base-point table: with the release profile's flags for armv7 the library # grows the shipped binary by 376 KB without it and by 56 KB with it (a scratch staticlib under `lto = "fat"`, # `opt-level = 2`, `target-cpu = cortex-a9`), and one verification a day does not need the speed. -ed25519-compact = { version = "=2.6.0", default-features = false, features = ["opt_size"] } +ed25519-compact = { version = "=2.6.1", default-features = false, features = ["opt_size"] } [dev-dependencies] plx_base = { path = "../base", features = ["test-support"] } diff --git a/rust-modules/data/src/browse/mod.rs b/rust-modules/data/src/browse/mod.rs index 22e1701811..edd98f7b1e 100644 --- a/rust-modules/data/src/browse/mod.rs +++ b/rust-modules/data/src/browse/mod.rs @@ -1830,7 +1830,7 @@ impl BrowseState { source.retry_cd = 0; } self.bump_source_facts_gen(); - plx_machine::idle::invalidate(); + true } /// Ask for one of the current section's value lists, if it is owed and not already out. Nothing @@ -1907,7 +1907,7 @@ impl BrowseState { | adapter.letters.take_refused(self.letters_req) | adapter.bands.take_refused(self.bands_req); if refused { - plx_machine::idle::invalidate(); + } } /// Take the date the Library's ask carries into every section's state, where a calendar family's key @@ -2055,7 +2055,7 @@ impl BrowseState { touched[index] = true; self.record_pins(true, &touched); self.bump_sections_gen(); - plx_machine::idle::invalidate(); + true } #[cfg(any(test, feature = "test-support"))] @@ -2377,13 +2377,13 @@ impl BrowseState { /// profile's RECORD (`apply_pins_from`). Both end in the same question — what does /// `pins::resolve` say about every row now — so they ask it the same way rather than each /// keeping a version of the answer. A row that moves without `bump_sections_gen` + - /// `plx_machine::idle::invalidate` is a table nothing republishes, which is a pill strip and a set of + /// a changed publication outcome is a table nothing republishes, which is a pill strip and a set of /// shelves still drawing the previous resolve. fn reconcile_pins(&mut self, record: Option) -> bool { let moved = self.resolve_pins_with(record); if moved { self.bump_sections_gen(); - plx_machine::idle::invalidate(); + } moved } @@ -2439,7 +2439,7 @@ impl BrowseState { self.seed_saved_view(index); } self.bump_sections_gen(); - plx_machine::idle::invalidate(); + } #[cfg(test)] fn record_pins(&mut self, asked: bool, touched: &[bool]) @@ -2547,7 +2547,7 @@ impl BrowseState { if changed { self.repoint_cur(!current_had_pin); self.bump_sections_gen(); - plx_machine::idle::invalidate(); + } // Reconcile the pending selection immediately. Until its receipt lands, a captured // older session must not undo the viewer's edits. This is not a durability claim. @@ -2568,7 +2568,7 @@ impl BrowseState { source.retry_cd = 0; } } - plx_machine::idle::invalidate(); + } fn apply_discovery( &mut self, @@ -2579,7 +2579,7 @@ impl BrowseState { user: &str, adapter: &BrowseAdapter, ) -> crate::stores::StoreOutcome { - plx_machine::idle::invalidate(); + if epoch != self.table_epoch() { return Default::default(); } @@ -2779,7 +2779,7 @@ impl BrowseState { self.src_facts_gen = self.src_facts_gen.wrapping_add(changes); if changes != 0 { changed = true; - plx_machine::idle::invalidate(); + } } None => { @@ -2840,7 +2840,7 @@ impl BrowseState { source.sections_done = false; source.counts_done = false; } - plx_machine::idle::invalidate(); + } pub fn run_owned( &mut self, @@ -3021,7 +3021,7 @@ impl BrowseState { let taken = crate::stores::take_landing_owed(gate, crate::stores::StoreId::Browse, || fetch.busy(), || fetch.take()); let Some(result) = taken else { return false }; - plx_machine::idle::invalidate(); + if result.epoch != self.table_epoch() { return false; } @@ -3181,7 +3181,7 @@ impl BrowseState { let page = crate::stores::take_landing_owed(gate, crate::stores::StoreId::Browse, || adapter.page.busy(), || adapter.page.take()); if let Some(result) = page { - plx_machine::idle::invalidate(); + if let Some(source) = self.sections.get(result.sec).map(|section| section.src) { let client = result.client; let token_gen = result.token_gen; diff --git a/rust-modules/data/src/browse/section_hubs.rs b/rust-modules/data/src/browse/section_hubs.rs index 309a6c5ea8..f4d6df08bd 100644 --- a/rust-modules/data/src/browse/section_hubs.rs +++ b/rust-modules/data/src/browse/section_hubs.rs @@ -687,7 +687,7 @@ impl super::BrowseState { Flight::Row => st.hubs.inflight = None, } } - plx_machine::idle::invalidate(); + } /// Reads one row's window: a page the reader walked to, or the cards of a row that came back @@ -756,7 +756,7 @@ impl super::BrowseState { plx_base::eventlog::log(&format!("libhubs: section {} row {} read failed", result.sec, ask.id)); } let moved = state.hubs.land_row(&ask, shelf); - plx_machine::idle::invalidate(); + return moved || failed; } Outcome::List(Some(parsed)) => { @@ -782,7 +782,7 @@ impl super::BrowseState { state.hubs.owed = true; } } - plx_machine::idle::invalidate(); + true } diff --git a/rust-modules/data/src/collection.rs b/rust-modules/data/src/collection.rs index 00507f7414..305587956a 100644 --- a/rust-modules/data/src/collection.rs +++ b/rust-modules/data/src/collection.rs @@ -358,7 +358,7 @@ impl CollectionState { let reply = crate::stores::tape::take_store_landing( gate, crate::stores::StoreId::Collection, "collection", 0, &adapter.fetch, |m| m.gen); if let Some(reply) = reply { - plx_machine::idle::invalidate(); + if reply.gen == self.generation { changed |= self.apply(reply.what); } } self.maybe_spawn(adapter, keys); diff --git a/rust-modules/data/src/person.rs b/rust-modules/data/src/person.rs index 2ded58985a..f7b8c1a48c 100644 --- a/rust-modules/data/src/person.rs +++ b/rust-modules/data/src/person.rs @@ -1312,7 +1312,7 @@ impl PersonState { } // Every landing repaints, failures included: a shelf or stopped spinner must not // wait for the next keypress to become visible. - plx_machine::idle::invalidate(); + if reply.gen == self.generation { adapter.terminals.lock().unwrap_or_else(|e| e.into_inner()).pending.remove(&i); changed |= apply_landing(self, i, reply.what); @@ -1486,7 +1486,7 @@ fn sync_roster(state: &mut PersonState, adapter: &PersonAdapter, input: &PersonI p.roster_gen = gen; p.roster_sig = Some(sig); resettle(p); - plx_machine::idle::invalidate(); + true } @@ -1801,7 +1801,7 @@ fn maybe_spawn(state: &mut PersonState, adapter: &Arc, i: usize, let profile = i == F_PROFILE; if !input.controlled && (if profile { input.profile_refused } else { input.credits_refused }) { // A fixed provider refusal is terminal in this drain, with no job, claim or retry. - plx_machine::idle::invalidate(); + return apply_landing(state, i, Landing::Refused); } let identity = if input.controlled { Identity::Controlled } else { @@ -2031,7 +2031,7 @@ impl PersonState { if req.slot == F_PROFILE { if let Some(person) = &mut self.current { person.profile_tried = true; } } - plx_machine::idle::invalidate(); + } changed } diff --git a/rust-modules/data/src/pms.rs b/rust-modules/data/src/pms.rs index d425832af1..91a160f5d2 100644 --- a/rust-modules/data/src/pms.rs +++ b/rust-modules/data/src/pms.rs @@ -792,6 +792,11 @@ pub fn hubs_snapshot(state: &PmsState) -> HubsSnapshot { } } +/// The visible publication includes its readout, even when no catalog rows were replaced. +pub(crate) fn visible_projection(state: &PmsState) -> (u32, HubState) { + (state.catalog_gen, hub_state(state)) +} + impl HubsSnapshot { /// An explicit empty retained publication; fixture construction must not capture globals. #[cfg(any(test, feature = "test-support"))] @@ -3220,7 +3225,7 @@ fn commit(state: &mut PmsState, build: HubBuild) -> c_int { let n = new_cat.len(); state.published = Some(Arc::new(HomeCatalog { items: new_cat, hubs: new_hubs, heroes: new_pool })); state.catalog_gen = state.catalog_gen.wrapping_add(1); - plx_machine::idle::invalidate(); + n as c_int } @@ -3362,7 +3367,7 @@ fn settle_refused(state: &mut PmsState, adapter: &PmsAdapter) -> crate::stores:: } endpoints.insert(landed_fail(s)); } - if settled { plx_machine::idle::invalidate(); } + if settled { } endpoints } @@ -3573,9 +3578,9 @@ fn apply_landing(state: &mut PmsState, adapter: &Arc, landing: &Land /// Test-only compatibility landing for fixtures without a retained directory. #[cfg(any(test, feature = "test-support"))] pub fn land(state: &mut PmsState, adapter: &Arc, landing: &Landing) -> crate::stores::StoreOutcome { - let before = state.catalog_gen; + let before = visible_projection(state); let endpoints = apply_landing(state, adapter, landing); - crate::stores::StoreOutcome { changed: state.catalog_gen != before, endpoints } + crate::stores::StoreOutcome { changed: visible_projection(state) != before, endpoints } } /// Apply one addressed landing under the same retained directory policy the frame publishes. @@ -3586,10 +3591,10 @@ pub fn land_with_directory( directory: crate::stores::browse::DirectoryView<'_>, clients: &ClientKeys, ) -> crate::stores::StoreOutcome { - let before = state.catalog_gen; + let before = visible_projection(state); let endpoints = emitting(state, adapter, |state, launch| step_landings_with_scope(state, adapter, None, || vec![landing.clone()], &BrowseScope::retained(directory, clients), launch)); - crate::stores::StoreOutcome { changed: state.catalog_gen != before, endpoints } + crate::stores::StoreOutcome { changed: visible_projection(state) != before, endpoints } } /// `stores::hubs::HubsStore`'s one door onto every [`HubsCmd`](crate::stores::hubs::HubsCmd) (D3): @@ -3638,18 +3643,18 @@ fn run_settled( use crate::stores::hubs::HubsCmd; match cmd { paging @ (HubsCmd::Page { .. } | HubsCmd::CancelPage { .. }) => { - let before = state.catalog_gen; + let before = visible_projection(state); let endpoints = run_page_cmd(state, adapter, scope, paging, launch); - crate::stores::StoreOutcome { changed: before != state.catalog_gen, endpoints } + crate::stores::StoreOutcome { changed: before != visible_projection(state), endpoints } } HubsCmd::RefetchHubs => crate::stores::StoreOutcome { changed: true, endpoints: request_refetch_hubs_with_scope(state, adapter, scope, launch), }, HubsCmd::Hold { lo, hi } => { - let before = state.catalog_gen; + let before = visible_projection(state); let endpoints = run_hold(state, adapter, scope, lo, hi, launch); - crate::stores::StoreOutcome { changed: before != state.catalog_gen, endpoints } + crate::stores::StoreOutcome { changed: before != visible_projection(state), endpoints } } HubsCmd::Retry => { let gen = state.hub_gen; @@ -3673,9 +3678,9 @@ fn run_settled( endpoints: refetch_source_quiet(state, adapter, scope, sid, launch), }, HubsCmd::Publish { home_top_visible, focused_hub, press_live } => { - let before = state.catalog_gen; + let before = visible_projection(state); publish_staged(state, scope, home_top_visible, focused_hub, press_live); - crate::stores::StoreOutcome::changed(state.catalog_gen != before) + crate::stores::StoreOutcome::changed(visible_projection(state) != before) } } } @@ -3691,9 +3696,9 @@ pub fn controlled_work(state: &mut PmsState, adapter: &Arc, cmd: Opt let out = match cmd { Some(cmd) => run_with_scope(state, adapter, cmd, &BrowseScope::standalone()), None => { - let before = state.catalog_gen; + let before = visible_projection(state); let endpoints = pump_with_landings(state, adapter, dt, Vec::new); - crate::stores::StoreOutcome { changed: state.catalog_gen != before, endpoints } + crate::stores::StoreOutcome { changed: visible_projection(state) != before, endpoints } } }; start_for_test(state, launch); @@ -3853,7 +3858,7 @@ fn step_landings_with_scope(state: &mut PmsState, adapter: &PmsAdapter, dt: Opti // A landing that COMMITS repaints from inside `commit`; this is the one that does not — // a failure rewrites no shelf but does change the status caption, under a Home screen that // may have gone idle with nothing else on it to move. - plx_machine::idle::invalidate(); + } if let Some((build, took)) = build { let bytes = catalog_bytes(&build.0); diff --git a/rust-modules/data/src/pms_multi_source_merge_tests.rs b/rust-modules/data/src/pms_multi_source_merge_tests.rs index caab7a4824..e0cb565db3 100644 --- a/rust-modules/data/src/pms_multi_source_merge_tests.rs +++ b/rust-modules/data/src/pms_multi_source_merge_tests.rs @@ -405,31 +405,31 @@ fn a_failing_source_leaves_a_populated_home_completely_intact() { #[test] fn a_source_landing_repaints_a_settled_home() { let _g = plx_base::testlock::serial(); - let mut o = Owner::default(); - reset(&mut o.state, &o.adapter); - plx_machine::idle::set_enabled(true); - seed(&mut o.state, vec![ - src(0, "", HubState::Ready, Some(build_test(1))), - src(1, "friend", HubState::Loading, None), - ]); - - for (what, build) in [ - ("a share arriving", Some(build_test(2))), - ("a share failing", None), - ] { - plx_machine::idle::should_present(0); // takes-and-clears whatever was already pending - assert!( - !plx_machine::idle::should_present(0), - "the panel is settled with nothing happening" - ); + for (what, build) in [("a share arriving", Some(build_test(2))), ("a share failing", None)] { + let mut o = Owner::default(); + reset(&mut o.state, &o.adapter); + let own = if build.is_some() { src(0, "", HubState::Ready, Some(build_test(1))) } + else { src(0, "", HubState::Failed, None) }; + seed(&mut o.state, vec![own, src(1, "friend", HubState::Loading, None)]); + let mut present = plx_machine::present::Present::new(); + present.take(0); + present.acknowledge(0); + assert!(!present.peek(0)); + let before = (o.state.catalog_gen, hub_state(&o.state)); land(&o.state, &o.adapter, 1, build); - pump(&mut o.state, &o.adapter, 0.0); - assert!( - plx_machine::idle::should_present(0), - "{what} must invalidate the frame" - ); + let mut changed = false; + for result in take_landings(&o.adapter) { + changed |= super::land(&mut o.state, &o.adapter, &result).changed; + } + assert_ne!((o.state.catalog_gen, hub_state(&o.state)), before, "{what} changes the actual publication"); + assert!(changed, "{what} must return its visible change to the frame owner"); + assert!(!present.peek(0), "a data mutation cannot paint through a global adapter"); + if changed { present.note(plx_machine::present::PresentEvent::Damage( + plx_machine::present::Provenance::Landing(plx_machine::machine::MachineId::Store( + crate::stores::StoreId::Hubs.ord())))); } + assert!(present.take(0), "{what} must repaint its owning frame"); + reset(&mut o.state, &o.adapter); } - reset(&mut o.state, &o.adapter); } /// The total-failure read-out is reserved for a total failure. Any source answering makes Home diff --git a/rust-modules/data/src/search.rs b/rust-modules/data/src/search.rs index 5fb39c2f38..a5f41e95af 100644 --- a/rust-modules/data/src/search.rs +++ b/rust-modules/data/src/search.rs @@ -77,7 +77,7 @@ //! the results for `wallace`. Debounce is `ui/detail.rs`'s `season_settle` accumulator. Two rules //! that are easy to miss and both wedge the screen forever if missed: the in-flight flag must come //! back when the runner REFUSES the request ([`SearchPort`]'s `refused`, which the next pump reads -//! to back the source off), and [`plx_machine::idle::invalidate`] must be called on every landing +//! to back the source off), and every changed landing must reach the caller's owned presentation effect, //! including the failure branch. //! //! ## A fetch is a store job @@ -1145,7 +1145,7 @@ fn set_query_with_directory( state.settle_us = 0; state.armed = real_query; } - plx_machine::idle::invalidate(); + } /// Apply a view-state change to every result row it covers — the optimistic half of a view-state @@ -1417,7 +1417,7 @@ fn pump_with_optional_directory( } // every landing repaints, the failure branch included: without this the screen sits on a // spinner that has already been answered until the next keypress happens to invalidate it - plx_machine::idle::invalidate(); + true } diff --git a/rust-modules/data/src/search/recents.rs b/rust-modules/data/src/search/recents.rs index 74eda00529..25701eabd3 100644 --- a/rust-modules/data/src/search/recents.rs +++ b/rust-modules/data/src/search/recents.rs @@ -118,7 +118,7 @@ fn edit(input: &Input<'_>, profile_generation: u32, change: impl FnOnce(&[String true }); if changed || retry_drain { submit(); } - if changed { plx_machine::idle::invalidate(); } + if changed { } changed } diff --git a/rust-modules/data/src/stores/browse.rs b/rust-modules/data/src/stores/browse.rs index 554e6ed7e5..d19f61abe1 100644 --- a/rust-modules/data/src/stores/browse.rs +++ b/rust-modules/data/src/stores/browse.rs @@ -1202,6 +1202,12 @@ mod contract_tests { let _ = stores.take_notices(); let before_notice = stores.browse.borrow().gen(); let before_sources = stores.browse.borrow().source_list_gen_for_test(); + // Data publication cannot dirty or wake an independent presentation owner. + let mut present = plx_machine::present::Present::global(); + assert!(present.take(0)); + present.acknowledge(0); + assert!(!present.changed()); + let damage = (present.damage_epoch(), present.page_damage_epoch()); plx_plex::plex::register_for_test( "", "127.0.0.1", 9, "synthetic", "fixture"); let launches = refused_discovery_step(&stores); @@ -1211,7 +1217,8 @@ mod contract_tests { assert_eq!(stores.browse.borrow().gen(), before_notice + 1); assert_eq!(stores.take_notices(), [(StoreId::Browse, before_notice + 1)]); assert!(stores.take_notices().is_empty()); - let _ = plx_machine::idle::take_local_damage(); + assert_eq!((present.damage_epoch(), present.page_damage_epoch()), damage); + assert!(!present.changed(), "a data publication must not wake an unrelated owner"); let settled_notice = stores.browse.borrow().gen(); let settled_sources = stores.browse.borrow().source_list_gen_for_test(); @@ -1220,8 +1227,9 @@ mod contract_tests { assert_eq!(stores.browse.borrow().gen(), settled_notice); assert_eq!(stores.browse.borrow().source_list_gen_for_test(), settled_sources); assert!(stores.take_notices().is_empty()); - assert_eq!(plx_machine::idle::take_local_damage(), 0, - "an empty-to-empty machine identity must not invalidate the settled frame"); + assert_eq!((present.damage_epoch(), present.page_damage_epoch()), damage); + assert!(!present.changed(), + "an empty-to-empty machine identity must not dirty or wake an unrelated owner"); plx_plex::plex::reset_servers_for_test(); } diff --git a/rust-modules/data/src/stores/catalog.rs b/rust-modules/data/src/stores/catalog.rs index 4cae0ee270..60cfeb15a8 100644 --- a/rust-modules/data/src/stores/catalog.rs +++ b/rust-modules/data/src/stores/catalog.rs @@ -53,7 +53,7 @@ struct Mailbox { impl Mailbox { fn post(&self, landing: Landing) { self.mail.lock().unwrap_or_else(|e| e.into_inner()).push_back(landing); - plx_machine::idle::invalidate(); + } fn take_all(&self) -> Vec { diff --git a/rust-modules/data/src/stores/hubs.rs b/rust-modules/data/src/stores/hubs.rs index 8f4a0023b2..fd2ee458fb 100644 --- a/rust-modules/data/src/stores/hubs.rs +++ b/rust-modules/data/src/stores/hubs.rs @@ -309,9 +309,9 @@ impl HubsStore { directory: crate::stores::browse::DirectoryView<'_>, clients: &plx_plex::plex::ClientKeys, ) -> super::StoreOutcome { - let before = self.state.catalog_gen; + let before = crate::pms::visible_projection(&self.state); let endpoints = crate::pms::tick_with_directory(&mut self.state, &self.adapter, dt, directory, clients); - let changed = self.state.catalog_gen != before; + let changed = crate::pms::visible_projection(&self.state) != before; if changed { self.bump(); } super::StoreOutcome { changed, endpoints } } diff --git a/rust-modules/data/src/stores/watchlist.rs b/rust-modules/data/src/stores/watchlist.rs index ebbbd4dadd..b22e44ce48 100644 --- a/rust-modules/data/src/stores/watchlist.rs +++ b/rust-modules/data/src/stores/watchlist.rs @@ -130,7 +130,7 @@ impl WatchlistAdapter { #[cfg(any(test, feature = "test-support"))] fn post(&self, landed: Landed) { self.mail.lock().unwrap_or_else(|e| e.into_inner()).push_back(landed); - plx_machine::idle::invalidate(); + } fn take_all(&self) -> Vec { diff --git a/rust-modules/data/src/stores/watchlist_job.rs b/rust-modules/data/src/stores/watchlist_job.rs index 7929acb40a..574e3575f7 100644 --- a/rust-modules/data/src/stores/watchlist_job.rs +++ b/rust-modules/data/src/stores/watchlist_job.rs @@ -86,7 +86,7 @@ impl Port for ResolvePort { self.mailbox.0.lock().unwrap_or_else(|e| e.into_inner()).push(ResolveLanding { addr, tag: self.tag, sid: self.sid, rk: self.rk.clone(), key: self.key, end, }); - plx_machine::idle::invalidate(); + } fn refused(&self, addr: Addr) { self.done(addr, ResolveEnd::NotStarted); } } @@ -188,7 +188,7 @@ impl Port for WritePort { }; if previous.is_err() { return; } self.mailbox.0.lock().unwrap_or_else(|e| e.into_inner()).push(WriteLanding { addr, tag: self.tag, end }); - plx_machine::idle::invalidate(); + } fn refused(&self, addr: Addr) { self.done(addr, WriteEnd::NotStarted { write: self.write }); } } diff --git a/rust-modules/data/src/stores/watchlist_stream_port.rs b/rust-modules/data/src/stores/watchlist_stream_port.rs index 1d725b14cd..d2ccb0adae 100644 --- a/rust-modules/data/src/stores/watchlist_stream_port.rs +++ b/rust-modules/data/src/stores/watchlist_stream_port.rs @@ -67,7 +67,7 @@ impl StreamPort { self.mailbox.0.lock().unwrap_or_else(|e| e.into_inner()).push(StreamLanding { addr: self.addr, tag: self.tag, event, owed: Arc::clone(&self.owed), }); - plx_machine::idle::invalidate(); + } pub fn start(&self) -> Option> { let mut claim = self.claim.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/rust-modules/data/src/subsearch.rs b/rust-modules/data/src/subsearch.rs index 7506a89add..e46440c46f 100644 --- a/rust-modules/data/src/subsearch.rs +++ b/rust-modules/data/src/subsearch.rs @@ -346,7 +346,7 @@ impl SubSearchState { if let Some(mail) = mail { // every landing repaints, the failure branch included — a spinner already answered // must not wait for the next keypress - plx_machine::idle::invalidate(); + if mail.gen == self.generation { changed |= self.apply(mail.what); } } // A launch the runner refused freed its claim in the call that refused it, and said so: diff --git a/rust-modules/data/src/viewstate.rs b/rust-modules/data/src/viewstate.rs index ab77d1d157..ad36fb482e 100644 --- a/rust-modules/data/src/viewstate.rs +++ b/rust-modules/data/src/viewstate.rs @@ -770,7 +770,7 @@ pub fn publish_view( person(crate::stores::person::PersonCmd::ApplyView { at: at.clone(), edit }); collection(crate::stores::collection::CollectionCmd::ApplyView { at, edit }); } - plx_machine::idle::invalidate(); // the tick/veil/bar just changed with no spring behind it + // the tick/veil/bar just changed with no spring behind it endpoints } @@ -1038,7 +1038,7 @@ pub fn pump_with_gate( // the same staleness, one screen over: a library's own shelves carry watch state and its // own Continue Watching row, so the burst that made Home's hubs stale made these stale too browse(crate::stores::browse::BrowseCmd::HubsInvalidateAll); - plx_machine::idle::invalidate(); + } endpoints } diff --git a/rust-modules/gfx/src/gfx.rs b/rust-modules/gfx/src/gfx.rs index bc12222d36..ed3ccad350 100644 --- a/rust-modules/gfx/src/gfx.rs +++ b/rust-modules/gfx/src/gfx.rs @@ -2352,7 +2352,7 @@ pub fn spring(pos: *mut f32, vel: *mut f32, target: f32, k: f32, dt: f32) { *vel = (*vel - w * b * dt) * e; // Every animation in the app lands here or in `spring_zeta`, which is what lets // `plx_machine::idle` know EXACTLY whether the screen is still moving without any screen opting in. - plx_machine::idle::note_spring(*pos, target, *vel); + plx_machine::motion::report::note_spring(*pos, target, *vel); } } @@ -2378,7 +2378,7 @@ pub fn spring_zeta(pos: *mut f32, vel: *mut f32, target: f32, k: f32, zeta: f32, let b = (v0 + z * w * x0) / wd; *pos = target + e * (a * c + b * s); *vel = e * ((b * wd - z * w * a) * c - (a * wd + z * w * b) * s); - plx_machine::idle::note_spring(*pos, target, *vel); // see the note in `spring` + plx_machine::motion::report::note_spring(*pos, target, *vel); // see the note in `spring` } } @@ -6852,7 +6852,7 @@ static mut CULL_RECT: Option<[f32; 4]> = None; // and its two accessors live in `plx_machine::idle`, the machine layer: `idle::invalidate` has to read it, // and this module may name that layer but not the reverse. Every primitive below consults it // through these two names exactly as it did when the flag was declared here. -pub use plx_machine::idle::{page_frozen, set_page_frozen}; +pub use plx_machine::motion::report::{page_frozen, set_page_frozen}; thread_local! { /// **This frame's picture is a hardware VIDEO PLANE** (restructure spec §9), armed for the @@ -10013,7 +10013,7 @@ mod tests { #[test] fn the_dither_policy_refuses_small_fields() { - plx_machine::idle::frame_begin(1.0 / 60.0); + plx_machine::motion::report::frame_begin(1.0 / 60.0); let broad = 700.0; assert_eq!( dither_for_field(40.0, broad), diff --git a/rust-modules/jellyfin/Cargo.toml b/rust-modules/jellyfin/Cargo.toml index 5a69ed5446..bc402c4b63 100644 --- a/rust-modules/jellyfin/Cargo.toml +++ b/rust-modules/jellyfin/Cargo.toml @@ -20,7 +20,7 @@ crate-type = ["rlib"] plx_plex = { path = "../plex", features = ["alt-backend"] } # `task::OffFrame`, the worker token the live-update feed (`Backend::notifications`) runs under. plx_base = { path = "../base" } -# `idle::invalidate`, so a favourite's flip and its server's answer are drawn at once. +# `present::wake_from_worker`, so a favourite write's answer from the server is drawn at once. plx_machine = { path = "../machine" } # The app's translated strings (`i18n::msg`), for the shelf titles this layer names. plx_platform = { path = "../platform" } diff --git a/rust-modules/jellyfin/src/jellyfin/favorites.rs b/rust-modules/jellyfin/src/jellyfin/favorites.rs index 03ad0a74b7..adde8a6294 100644 --- a/rust-modules/jellyfin/src/jellyfin/favorites.rs +++ b/rust-modules/jellyfin/src/jellyfin/favorites.rs @@ -47,7 +47,6 @@ pub fn state(rating_key: &str) -> bool { /// the server is told on a worker, and a refusal flips it back. Never blocks the caller. pub fn set(rating_key: &str, favourite: bool, write: impl FnOnce(&str, bool) -> bool + Send + 'static) { note(rating_key, favourite); - plx_machine::idle::invalidate(); let rk = rating_key.to_string(); let spawned = plx_base::task::spawn_off_frame("favourite", move |_| { let ok = write(&rk, favourite); @@ -65,7 +64,7 @@ fn landed(rating_key: &str, favourite: bool, ok: bool) { } else { note(rating_key, !favourite); } - plx_machine::idle::invalidate(); + plx_machine::present::wake_from_worker(); } /// The server says `rating_key` is, or is not, a favourite (the socket's report of this user's @@ -88,7 +87,7 @@ pub fn heard(rating_key: &str, favourite: bool) -> bool { /// played items show there). The app re-reads Home as it does after a favourite of its own. pub fn owe_home() { LANDED.store(true, Ordering::Release); - plx_machine::idle::invalidate(); + plx_machine::present::wake_from_worker(); } /// Has a favourite write landed since the last call? FRAME THREAD: the app refetches Home's hubs diff --git a/rust-modules/machine/src/idle.rs b/rust-modules/machine/src/idle.rs deleted file mode 100644 index 05f818680c..0000000000 --- a/rust-modules/machine/src/idle.rs +++ /dev/null @@ -1,1178 +0,0 @@ -//! **Whole-frame present gating** — "nothing on screen changed, so don't repaint it". -//! -//! This is *not* the dirty-rectangle tracking [`mod.rs`](super)'s renderer doc rejects, and the -//! distinction is the whole reason this module is allowed to exist. That rule is about what -//! happens *inside* a frame: the renderer stays immediate-mode, every frame still clears and -//! rebuilds the entire view tree, and the way to not draw something is still to CULL it. This -//! module only decides whether to run that frame **at all**. When it says yes, nothing below it -//! changes; when it says no, the loop skips `glViewport`…`SDL_GL_SwapWindow` wholesale. No screen, -//! widget or painter learns anything new, and nothing tracks sub-frame damage. -//! -//! # Why it is worth having -//! -//! Measured on the device (2026-07-31, 60 s windows, `/proc` jiffy deltas): a **still** Home grid -//! cost 16.0% of one Cortex-A53 core in this process — and, because the compositor must blend our -//! 1080p surface every time we present, another ~19.4 points inside `surface-manager` (23.8% with -//! us up vs 4.4% with the app closed). That second charge is **content-independent** — it measured -//! the same on the flat profile picker, the Home grid and the hero billboard — so it is a per- -//! *present* charge, not a per-pixel one. Roughly 35 points of one core, indefinitely, to re-send -//! a picture that has not changed. A TV sits on Home for hours and the SoC is fan-less. -//! -//! # The model: exact motion, plus explicit invalidation -//! -//! Two independent signals, deliberately not one heuristic: -//! -//! 1. **Motion is detected exactly, not guessed.** Every animation in the app runs through -//! [`gfx::spring`](crate::gfx::spring) or [`gfx::spring_zeta`](crate::gfx::spring_zeta) — those -//! two functions are the only spring integrators there are — so they call [`note_spring`] and -//! the gate *knows* whether any of the ~439 springs a settled Home grid steps per frame is -//! still in flight. There is no settle-window guess to tune, and no animation can be truncated -//! mid-flight by a timer that expired early. -//! -//! 2. **Discrete changes call [`invalidate`].** A spring is not involved when a poster texture -//! lands, a hub refetch commits, or a keypress swaps a label. Those sites say so explicitly. -//! The full set is listed on [`invalidate`]; adding a new async landing means adding a call -//! there, and the [`KEEPALIVE_MS`] backstop below bounds the damage if someone forgets. -//! -//! **Springs are not the only clock, and that is the standing hazard.** Anything that animates -//! from raw time — a millisecond ramp, a phase accumulator, a countdown — is invisible to (1) by -//! construction and must report itself: through (2) when it changes content, through -//! [`note_motion`] when it is a decoration (the tab pulse), because damage under a standing popover -//! re-captures the frozen host. Two did not, and both froze in the product: -//! `Xfade` (`plx_ui::xfade`) (every CONTENT cross-fade — the Library's grid and page, Search's -//! results, Filmography's preview) and `Spinner` (`plx_ui::widgets::Spinner`) -//! (every loading read-out). They report from their own advance and draw respectively; the reasons -//! those two sides differ are on each call. `Xfade` was the ROUTE dip too until restructure phase -//! 12 (D1) lifted that onto `PageDip` (`plx_ui::containers::transition::PageDip`), which is -//! inside the container and reports `Motion` from its own `tick` by construction. `docs/retui-invalidation-design.md` is the accepted -//! plan for closing the class properly, by making `dt` a capability rather than an `f32`. -//! -//! The asymmetry is deliberate: a false "something moved" costs one wasted frame, a false -//! "nothing moved" freezes the screen. Both the rest threshold and the backstop are therefore -//! biased toward presenting. -//! -//! # What this module does NOT do -//! -//! It does not slow the **loop** — only the **present**. Input polling, the remote FIFO drain, -//! `ls2_pump`, `route::pump_play`, `metadata::pump_detail`, `app::adapters::poster::prepare` and every -//! screen's `*_update` keep running at full rate, so key latency is unchanged, timers still fire -//! (the hero billboard's 8 s auto-flip still flips), and async work still lands on schedule. Those -//! cost ~0.3% of a core between them; the 16% was the draw. -//! -//! It is also **not applied while the hardware video plane is bound** — see [`VIDEO_PLANE`], -//! [`note`] and `Player::video_plane_bound` below, fed by `Player::set_video_plane_bound`'s edges -//! rather than by which route is on screen. A pre-bind spinner or a post-unbind failure read-out -//! is an ordinary idle-gated frame; "we stop presenting for seconds while a plane is bound to our -//! surface" is a claim about this compositor that no amount of reading settles. Home never binds -//! the plane, which is what makes it the safe place to prove the mechanism. - -use std::sync::atomic::{AtomicBool, AtomicU32, Ordering::Relaxed}; - -/// A spring is in flight while the value it will DRAW this frame differs **visibly** from the one -/// it drew last frame. Two terms, and the second one is where the cost was. -/// -/// The first version of this module used one absolute `1e-3` for both the distance and the -/// velocity, on the argument that 1e-3 is invisible whether the spring is in pixels or in 0..1. -/// That is true of the DISTANCE term and false of the VELOCITY term, because velocity is in units -/// **per second**: `1e-3` on a pixel-valued spring means "still moving at a thousandth of a pixel -/// per second", which a critically-damped spring satisfies for a very long time after it has -/// visually arrived. Simulated against the real constants, that tail was **36–52% of every -/// interaction's presents** — 43 of the 83 frames a 280 px shelf scroll costs, all of them -/// sub-pixel. Those are whole presents, so each one also carried the compositor's per-present -/// charge, which is the larger half. -/// -/// So: scale the threshold to the spring's own magnitude (`REST_REL`), cap it below one pixel so a -/// large-magnitude spring can never stop somewhere visible (`REST_CAP`), and compare **velocity -/// times dt** — the distance this frame — rather than velocity itself. -/// -/// Erring small is still the safe direction: too large freezes a moving screen, too small costs a -/// few frames at the tail. `REST_CAP` is the guarantee that "too large" can never exceed a quarter -/// of a pixel, whatever the units turn out to be. -const REST_REL: f32 = 1e-3; - -/// Ceiling on the rest threshold, in the units of the largest springs (pixels). A quarter pixel is -/// below anything the panel can show, so this bounds the worst case for a `scroll_y` running to -/// four figures while leaving 0..1 springs entirely to [`REST_REL`] (for them the relative term is -/// ~1e-3 and this cap never binds). -const REST_CAP: f32 = 0.25; - -/// Present at least this often even when the gate sees no reason to. This is **insurance, not -/// pacing**: it bounds how long a screen can be stale if some future async landing forgets to call -/// [`invalidate`], and it keeps a commit flowing to the compositor rather than leaving the surface -/// silent for minutes on end — a state this wayland stack has never been asked to hold. -/// -/// At 2 s this is 0.5 fps, i.e. it gives back ~0.8% of the 60 fps cost while capping worst-case -/// staleness at two seconds. Set it to 0 to disable once the invalidation set has been proven -/// complete on device over a long soak. -const KEEPALIVE_MS: u32 = 2000; - -/// How long the loop sleeps on a frame it decided not to present. -/// -/// Device and macOS presented frames block in swap. WSLg/X11 hostsim frames are paced after its -/// nonblocking GLX swap; other Linux backends keep their own swap behaviour. A frame skipped by -/// this gate reaches none of those paths, so it must sleep here or a settled screen becomes a 100% -/// CPU spinner. One frame period keeps input polling near the normal presented-frame cadence; the -/// saving being chased is the GPU and compositor. -pub const IDLE_POLL_MS: u32 = 16; - -thread_local! { - /// Some spring moved during this frame's update phase. Cleared by [`frame_begin`]. - /// - /// **Thread-local, and that is the correct model, not a test workaround.** Springs are stepped - /// by the render loop; a spring stepped on some other thread has, by definition, nothing to do - /// with whether the panel needs repainting. Making it per-thread also makes the host suite - /// hermetic for free: `card_row`'s tests drive a local `CardRow` and are documented as ordinary - /// and parallel, so they step springs on other threads WITHOUT `testlock` — with a - /// process-global flag they would intermittently mark this module's "settled screen" - /// assertions as moving. - static MOVING: std::cell::Cell = const { std::cell::Cell::new(false) }; - - /// Motion noted while NO [`MotionScope`] was open — the PAGE's own springs, as distinct from a - /// popover's, which step inside `popover::own_motion`'s scope. [`MOVING`] merges both, and has - /// to (either keeps the present gate awake); this one is the half `popover::host` needs to - /// answer "did the page under a FADING panel move" — a page that takes input again on the - /// press frame, so its motion may not be masked by the fade's own. Same thread-local - /// rationale as `MOVING`. - static PAGE_MOVING: std::cell::Cell = const { std::cell::Cell::new(false) }; - /// How many [`MotionScope`]s are open right now — zero means a spring reporting now belongs - /// to the page. - static SCOPE_DEPTH: std::cell::Cell = const { std::cell::Cell::new(0) }; - - /// Page motion that is NOT decorative: [`PAGE_MOVING`] minus every spring stepped inside a - /// [`decorative`] region. The page-freeze's quiescence test reads this one - /// ([`page_layout_moving`]); everything that needs to know whether the page's PIXELS changed - /// keeps reading `PAGE_MOVING`. Same thread-local rationale as `MOVING`. - static PAGE_LAYOUT_MOVING: std::cell::Cell = const { std::cell::Cell::new(false) }; - /// How many [`decorative`] regions are open right now. - static DECOR_DEPTH: std::cell::Cell = const { std::cell::Cell::new(0) }; - - /// This frame's `dt`, stamped once by [`frame_begin`]. [`note_spring`] needs it to convert a - /// velocity into "distance this frame", which is the only form in which a velocity can be - /// judged visible. Same thread-local rationale as `MOVING`. - static DT: std::cell::Cell = const { std::cell::Cell::new(1.0 / 60.0) }; - - /// A monotonic microsecond clock, advanced once per frame by [`frame_begin`] — for a - /// clock-driven leaf that has no `Tick` of its own to hand it (`card_row`'s focused-title - /// marquee is the one caller: it advances from inside `draw`, reached through a generic - /// `Column::draw_child` trait method and several call sites across three lanes' files, none - /// of which carries a `Tick`). Unlike the retired `dt()` accessor this is never SUMMED by a - /// caller — a reader takes two readings and subtracts them ([`now_ms`]'s own doc), so no - /// caller can accumulate drift the way a per-frame `f32 dt` invited. `u64` microseconds - /// rather than `f32` seconds for the same reason `search.rs`'s debounce and `anim.rs`'s probe - /// clock convert once rather than sum: exact, with no realistic overflow horizon. - static MS_CLOCK_US: std::cell::Cell = const { std::cell::Cell::new(0) }; - - /// Last discrete-damage generation reported through [`should_present`] on this thread. Unlike - /// `DIRTY`, this is observational: it lets noidle report one-shot damage without consuming the - /// gate's sticky flag, preserving the rate-only diagnostic contract. - static PRESENT_DAMAGE_GEN: std::cell::Cell = const { std::cell::Cell::new(0) }; - - /// Discrete damage selected for this present, exposed so a host can combine its own scoped - /// spring motion with async/data landings without inheriting foreground-widget motion. - static PRESENT_DIRTY: std::cell::Cell = const { std::cell::Cell::new(true) }; -} -thread_local! { - /// Did the PREVIOUS iteration's update phase report motion? Read-and-replaced once per - /// iteration by [`should_present`], which is what turns the first still frame after a spring - /// lands into the SETTLE frame — see there. - static WAS_MOVING: std::cell::Cell = const { std::cell::Cell::new(false) }; -} - -/// A discrete change happened; present once more. Taken-and-cleared by [`should_present`] — NOT by -/// [`note_present`], so that a report raised during a draw survives to the frame it belongs to. -static DIRTY: AtomicBool = AtomicBool::new(true); -/// A frame requested for scheduling rather than because pixels changed (dynamic glass waiting for -/// its sample slot). Kept separate so that wake-up cannot masquerade as host-underlay damage. -static WAKE: AtomicBool = AtomicBool::new(false); -/// Monotonic observation channel for discrete damage. `DIRTY` remains the sticky gate signal; -/// this generation answers whether a new report arrived since the previous loop even under noidle. -static DAMAGE_GEN: AtomicU32 = AtomicU32::new(0); -/// `SDL_GetTicks` of the last present, for the [`KEEPALIVE_MS`] backstop. -static LAST_PRESENT: AtomicU32 = AtomicU32::new(0); -/// Presents since the last [`take_presents`] — the heartbeat's `fps=` field. -static PRESENTS: AtomicU32 = AtomicU32::new(0); -/// `now` of the last [`should_present`] that found a CHANGE (motion, damage, a wake, the settle -/// frame) — the keepalive and the bound video plane do not count. The simulator's settled-shot -/// clock (`shot::tick`) reads it; nothing on the television does. -#[cfg(feature = "hostsim")] -static LAST_CHANGE: AtomicU32 = AtomicU32::new(0); -/// Kill switch (`/tmp/plxnative-noidle`), so a device A/B is one file apart and a bad frame on the -/// panel is one `rm` from being ruled out as this feature's fault. -static ENABLED: AtomicBool = AtomicBool::new(true); -/// **Does playback retain video-plane ownership, including unresolved URI-probe ownership?** -/// Binding and quarantine keep this set; it does not prove a visible picture. -/// The gate's only non-damage INPUT (spec §4.4, -/// [`crate::present::PresentEvent::VideoPlane`]). While it is set every frame presents, -/// unconditionally: the plane is *slaved* to this wayland surface (`system::clear_opaque_region`), -/// and "we stop presenting while a plane is slaved to it" is a claim about this compositor that -/// reading cannot settle. -/// -/// **It has exactly ONE writer** — [`crate::player::machine::Player::set_video_plane_bound`], on -/// the bit's EDGES (spec §16 risk 10: a second formula term here is how the two disagree). The -/// loop must never poke it, and nothing here re-derives it from the route. -static VIDEO_PLANE: AtomicBool = AtomicBool::new(false); - -/// **Is the host page being served from the frame cache rather than rasterized?** -/// -/// Armed for the length of the page draw underneath an open popover that holds a snapshot, and -/// LIFTED around the popover's own drawing — `ui::popover::host` owns both edges. While it is on, -/// every primitive in `gfx` refuses its quad, because the pixels it would produce are already on -/// the framebuffer, one textured quad ago. -/// -/// **It is a REFUSAL, not a skipped call tree**, and that is what makes it safe to apply to a page -/// `gfx` knows nothing about: the page's draw code still runs, so its layout is still measured, -/// its pointer hit rects are still recorded and its poster textures are still uploaded. Only the -/// FILL is removed — which on this GPU is the whole of the cost. A detail page under an open track -/// panel measured `draw≈75 ms` per presented frame, entirely in fragments, against a -/// `drawmask=all` floor of 17 ms. -/// -/// **It lives in this module because [`invalidate`] reads it**, and `gfx` (which draws against it) -/// may name the machine layer but not the other way round: it was `gfx::PAGE_FROZEN`, and `gfx` -/// re-exports [`page_frozen`] and [`set_page_frozen`] at their old paths. Written by the render -/// thread only, like every other piece of draw state; an atomic because [`invalidate`] also runs -/// on workers. -static PAGE_FROZEN: AtomicBool = AtomicBool::new(false); - -/// Arm or lift the page freeze, returning the state that was in force. -/// -/// Callers restore what they were handed rather than storing `false`, so a popover's lift NESTS -/// inside the page pass instead of ending it — the page draw that follows the popover (another -/// panel, another scrim) is still frozen. -#[inline] -pub fn set_page_frozen(on: bool) -> bool { - PAGE_FROZEN.swap(on, Relaxed) -} - -/// Is the host page frozen right now? -/// -/// Read by `gfx`'s primitives, and by [`invalidate`]: a decoration that reports damage from inside -/// a draw which produced no pixels (a marquee, a spinner) must not keep re-dirtying the snapshot it -/// is standing in. -#[inline] -pub fn page_frozen() -> bool { - PAGE_FROZEN.load(Relaxed) -} - -/// Turn the gate off for this boot. Read once at startup from `/tmp/plxnative-noidle`. -pub fn set_enabled(on: bool) { - ENABLED.store(on, Relaxed); -} - -pub fn enabled() -> bool { - ENABLED.load(Relaxed) -} - -/// **The typed input to the LIVE gate** (spec §4.4). `plx_machine::present::Present` is the machine this -/// module becomes; until it is swapped in, the two share one vocabulary so they cannot drift, and -/// a caller says WHAT happened rather than poking a bool. -/// -/// The mapping onto this module's older doors, in full: -/// * `VideoPlane(b)` — the one input with state of its own; see [`VIDEO_PLANE`]. -/// * `Damage(_)` / `Fault(_)` — [`invalidate`]. The provenance is dropped: `plx_machine::idle` has no -/// ledger to record it on (`Present::why` is the machine's, and the recorder reads that one). -/// * `Motion` — [`invalidate`] as well, deliberately NOT the `MOVING` thread-local. `MOVING` is -/// the *rest test*'s answer, judged from a spring's own post-step state by [`note_spring`] (or -/// asserted by a time-driven decoration through [`note_motion`]), and -/// it feeds `page_moving`, which decides whether a frozen host is re-snapshotted. A caller who -/// only knows "something moved" cannot answer that, so it gets one frame — never a claim about -/// which springs were in flight. -pub fn note(ev: crate::present::PresentEvent) { - use crate::present::PresentEvent; - match ev { - PresentEvent::VideoPlane(bound) => VIDEO_PLANE.store(bound, Relaxed), - PresentEvent::Damage(_) | PresentEvent::Fault(_) | PresentEvent::Motion => invalidate(), - } -} - -/// The gate's current video-plane input. Read by the frame algorithm's step 8/9 consumers — the -/// opaque-region call and the capture skip — so all of them see ONE value. -#[inline] -pub fn video_plane_bound() -> bool { - VIDEO_PLANE.load(Relaxed) -} - -/// Report one spring step. Called from the two integrators in `gfx`, so it sees every animation -/// in the app without any screen having to opt in. -/// -/// Takes the post-step state by value: at rest the analytic form lands `pos` bit-identically on -/// `target` with `vel` decayed to zero, so a settled screen does not even reach the store. -#[inline] -pub fn note_spring(pos: f32, target: f32, vel: f32) { - if !settled(pos, target, vel) { - note_motion(); - } -} - -/// **A time-driven animation visibly moved this frame** — [`note_spring`]'s report without its -/// rest test, for an animator with no spring to judge: a fixed-length beat stepped by `dt` (the -/// tab pulse). Attributed exactly as a spring's motion is: to a popover inside a [`MotionScope`], -/// to the page otherwise, and not to the page's LAYOUT inside [`decorative`]. -/// -/// **Motion, not [`invalidate`], and the difference is the frozen host.** Discrete damage under a -/// standing popover means "the page changed": `popover::host` re-captures its snapshot, which -/// moves `page_epoch` and makes the modal dim re-read the page's light. Motion re-draws the page -/// live only while every panel is FADING and is paused under an open one — the rule every page -/// decoration already follows. A time-driven animator that reported through `invalidate` made the -/// item menu's close re-capture Home on each of its frames. -#[inline] -pub fn note_motion() { - MOVING.with(|m| m.set(true)); - if SCOPE_DEPTH.with(|d| d.get()) == 0 { - PAGE_MOVING.with(|m| m.set(true)); - if DECOR_DEPTH.with(|d| d.get()) == 0 { - PAGE_LAYOUT_MOVING.with(|m| m.set(true)); - } - } -} - -/// Run `f` — a page's DECORATIVE springs (a colour dissolve under the page, an in-place focus pop) -/// — so that their motion still wakes the present gate and still counts as page motion for every -/// pixel-facing reader ([`page_moving`]), but does not count toward [`page_layout_moving`]. -/// -/// The page-freeze holds a route's snapshot until the page stops moving so that first poster -/// admission can settle behind it; a spring that decorates the page and moves neither layout nor -/// the card grid must not be able to hold that snapshot for the whole -/// `PAGE_QUIESCENCE_HOLD_MAX_MS` cap. Declare it here rather than special-casing a screen in the -/// transition code. Does not nest with [`MotionScope`] semantics: it is independent of them. -pub fn decorative(f: impl FnOnce() -> T) -> T { - struct Guard; - impl Drop for Guard { - fn drop(&mut self) { - DECOR_DEPTH.with(|d| d.set(d.get().saturating_sub(1))); - } - } - DECOR_DEPTH.with(|d| d.set(d.get() + 1)); - let _g = Guard; - f() -} - -/// Whether a spring at `pos` heading for `target` with `vel` is visibly at rest — the exact test -/// [`note_spring`] applies, exported so an animator can snap a settled spring onto its target -/// (`Spring::jump`) and hand the compositor an exactly-resting final frame. -#[inline] -pub fn settled(pos: f32, target: f32, vel: f32) -> bool { - let t = (REST_REL * (1.0 + pos.abs().max(target.abs()))).min(REST_CAP); - // `vel * dt` is the travel this frame — the only form in which a velocity is comparable to a - // distance, and the whole reason the tail of every scroll used to keep the panel awake. - (pos - target).abs() <= t && (vel * DT.with(|d| d.get())).abs() <= t -} - -/// A `Spring::jump` (`plx_ui::Spring::jump`) teleported a value that was not already there. -/// -/// This is [`invalidate`], not a motion report, and the distinction is load-bearing: a jump can -/// happen inside an event handler, which runs BEFORE [`frame_begin`] clears the motion flag — so a -/// motion report would be wiped before the gate ever read it. A jump is a discrete change and -/// belongs on the sticky flag. -#[inline] -pub fn note_jump(changed: bool) { - if changed { - invalidate(); - } -} - -/// Something changed that no spring will report: a texture landing, new data from the server, a -/// keypress, a route change. -/// -/// Call sites today — keep this list current, it is the module's correctness argument: -/// - any SDL event dequeued, and any remote-FIFO token drained (`app.rs`) -/// - `metadata::pump_detail` landing (`app.rs`) -/// - **any** play plan landing (`route::apply_plan`) — including one that carries the server's -/// REFUSAL, which `app.rs` cannot see: `pump_play` returns false for a plan with no URL, so the -/// caller's invalidate is skipped for exactly the landing that flips the player from Resolving -/// to Error. It repainted anyway only because the player route bypasses this gate outright -/// - a poster texture uploaded (`app::adapters::poster::prepare`) -/// - a hub catalog being installed (`pms::commit`) — EVERY install, whichever path built it: the -/// boot fetch, a landing through `pms::pump`, a view-state edit, a roster sync, and the empty -/// commit `pms::reset` performs. The call used to sit at the call sites instead, where two of -/// the five did not make it -/// - a view-state write's OPTIMISTIC edit (`ViewStateStore::run` / `pms::edit_item`) and the refresh -/// its owned landing pass kicks (`ViewStateStore::pump`) — a watched tick, a corner veil and a resume bar all -/// change with no spring behind any of them, and the press is the only thing that moved -/// - a browse page landing (`BrowseStore::pump`) -/// - a server's self-description landing (`plex::serverinfo::store`) — its version and Plex Pass -/// tristate are what the stats panel's Server row, the detail hero's "hardware conversion -/// needs [PLEX PASS]" note and the failure read-out's capsule are drawn from, and it lands on a -/// worker seconds after the screen that shows them has settled -/// - a `Spring::jump` that actually teleported something (via [`note_jump`]) -/// - `Press::tick` (`plx_ui::press`), on each frame the release spring of a press that latched -/// long (a hold) visibly moves its card, by [`settled`], and on its phase changes: a card the -/// item menu's lift owns (a page left it out through `DrawFrame::leaves_out`: a card section's -/// tile, a Detail episode cell) springs without any report, but an opener no page leaves out -/// (season tabs, hero buttons, the Home hero) springs under the frozen host snapshot, which must be re-taken until -/// it rests. A tap's press never reports -/// - an `Xfade` ramp mid-flight, and a `Spinner` being drawn — the two time-driven animators -/// `note_spring` cannot see -/// -/// **A report raised while the host page is FROZEN is dropped** ([`page_frozen`]). -/// Two of the call sites above — the focused-title marquee and the spinner — report from inside a -/// DRAW, and under an open popover that draw produces no pixels: the page is one cached quad. -/// Honouring them would invalidate the very snapshot they were drawn from, i.e. a full page redraw -/// every frame with nothing on screen to show for it, and it is the one way a page could defeat the -/// cache without any screen doing anything wrong. It is also the correct PICTURE — a decoration on -/// a page the user cannot reach is meant to pause, which is what the profile menu's frozen host has -/// always done. Nothing genuine can be swallowed: the freeze is armed only for the length of the -/// page draw, and every real landing (server data, a poster texture, input) reports from the update -/// phase or from a worker, with the freeze off. -#[inline] -pub fn invalidate() { - if page_frozen() { - return; - } - DIRTY.store(true, Relaxed); - DAMAGE_GEN.fetch_add(1, Relaxed); - if OWN_SCOPE.with(|d| d.get()) > 0 { - OWN_DAMAGE_N.fetch_add(1, Relaxed); - } - #[cfg(any(test, feature = "test-support"))] - LOCAL_DAMAGE.with(|c| c.set(c.get() + 1)); -} - -#[cfg(any(test, feature = "test-support"))] -thread_local! { - /// How many times THIS thread has raised discrete damage — the test-only half of `DIRTY`. - /// `DIRTY` and `DAMAGE_GEN` are process-wide on purpose (a worker thread's landing must wake - /// the main loop), which makes them useless for grading "did this animation ask for a frame" - /// under `cargo test`: any unlocked test on another thread that repaints anything flips them, - /// and a test asserting a QUIET frame then fails at random under load. This counter cannot be - /// moved by another thread, so a test reads what its own code path reported and nothing else. - static LOCAL_DAMAGE: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Discrete damage raised on this thread since the last call. See [`LOCAL_DAMAGE`]. -#[cfg(any(test, feature = "test-support"))] -pub fn take_local_damage() -> u32 { - LOCAL_DAMAGE.with(|c| c.replace(0)) -} - -/// Drain leftover gate state so another module's spring test can assert a quiet frame. -/// Callers still take [`plx_base::testlock::serial`] first — this is not the lock. -#[cfg(any(test, feature = "test-support"))] -pub fn reset_for_test() { - set_enabled(true); - frame_begin(1.0 / 60.0); - DIRTY.store(false, Relaxed); - WAKE.store(false, Relaxed); - LAST_PRESENT.store(0, Relaxed); - PRESENTS.store(0, Relaxed); - DAMAGE_GEN.store(0, Relaxed); - PRESENT_DAMAGE_GEN.with(|c| c.set(0)); - PRESENT_DIRTY.with(|c| c.set(false)); - WAS_MOVING.with(|c| c.set(false)); - OWN_DAMAGE_N.store(0, Relaxed); - TAKEN_GEN.store(0, Relaxed); - VIDEO_PLANE.store(false, Relaxed); - let _ = take_local_damage(); -} - -thread_local! { - /// Depth of open [`OwnScope`]s: while non-zero, every [`invalidate`] is a POPOVER's own damage. - static OWN_SCOPE: std::cell::Cell = const { std::cell::Cell::new(0) }; -} -/// Damage this frame raised inside a popover's [`OwnScope`] — the panel's own. Taken against -/// [`DAMAGE_GEN`] by [`take_page_damage`]. -static OWN_DAMAGE_N: AtomicU32 = AtomicU32::new(0); -/// The [`DAMAGE_GEN`] value at the last [`take_page_damage`]. -static TAKEN_GEN: AtomicU32 = AtomicU32::new(0); - -/// **Everything invalidated while this guard is held is a POPOVER's own damage, not the page's.** -/// -/// Opened by `popover::own_motion` around a panel's `update`, by `popover::host::live` around its -/// drawing, and by `popover::host::input_scope` around every INPUT event (never a lifecycle or -/// window event, which is the app's) while a panel holds the page — the three places a panel raises -/// damage (the appear spring's `invalidate`, a table's -/// marquee, the per-event repaint and whatever a key handler adds). Attributing those by -/// construction is what lets [`take_page_damage`] answer the host cache's real question — DID THE -/// PAGE UNDERNEATH CHANGE — with no per-frame bit or explicit claim for a handler to get wrong. -/// Nests; drop closes it. -#[must_use = "damage is attributed only for this guard's lifetime"] -pub struct OwnScope(()); - -impl OwnScope { - pub fn open() -> Self { - OWN_SCOPE.with(|d| d.set(d.get() + 1)); - OwnScope(()) - } -} - -impl Drop for OwnScope { - fn drop(&mut self) { - OWN_SCOPE.with(|d| d.set(d.get().saturating_sub(1))); - } -} - -/// **Did the PAGE change since the last take?** Once per drawn frame, by `popover::host::begin_frame`. -/// -/// Every [`invalidate`] since the last take, minus those raised inside an [`OwnScope`] — more -/// invalidations than the panel's own means at least one came from the page (a poster landing, -/// hub data, a marker), and the frozen host must be drawn again. The subtraction is by COUNT -/// rather than by a per-frame bit so that a page landing on the same frame as a popover key press, -/// or during the popover's own motion, is still seen: with one merged bit either of those was -/// consumed unseen and the snapshot kept the un-landed page for as long as the panel stayed open -/// (Codex review, 2026-09-04). -pub fn take_page_damage() -> bool { - let gen = DAMAGE_GEN.load(Relaxed); - let bumps = gen.wrapping_sub(TAKEN_GEN.swap(gen, Relaxed)); - page_damage(bumps, OWN_DAMAGE_N.swap(0, Relaxed)) -} - -/// [`take_page_damage`]'s arithmetic: invalidations this frame against the popover's claims. -#[inline] -fn page_damage(bumps: u32, own: u32) -> bool { - bumps > own -} - -/// Buy a frame without claiming that UI pixels changed. Reports raised during a draw survive just -/// like [`invalidate`], but [`present_dirty`] stays false on the frame this schedules. -#[inline] -pub fn wake() { - WAKE.store(true, Relaxed); -} - -/// Start of an iteration: forget last frame's motion (the update phase is about to re-derive it), -/// stamp this frame's `dt` for [`note_spring`], and advance [`MS_CLOCK_US`] for [`now_ms`] — by -/// the exact whole-microsecond conversion of `dt`, not a summed `f32`, for the same reason -/// `search.rs`'s debounce and `anim.rs`'s probe clock do it that way. -#[inline] -pub fn frame_begin(dt: f32) { frame_begin_judging_rest_with(dt, dt) } - -/// [`frame_begin`] with a separate `dt` for the rest test ([`settled`]'s `velocity * dt`): the -/// frame dump's held repeat stands the clock still (`dt == 0`) but must judge a creeping spring -/// exactly as the first pass of its virtual frame did, so it passes that pass's `dt` as `rest_dt`. -/// Outside a dump the two are the same number. -#[inline] -pub fn frame_begin_judging_rest_with(dt: f32, rest_dt: f32) { - MOVING.with(|m| m.set(false)); - PAGE_MOVING.with(|m| m.set(false)); - PAGE_LAYOUT_MOVING.with(|m| m.set(false)); - DT.with(|d| d.set(rest_dt)); - let dt_us = (dt * 1_000_000.0).round().max(0.0) as u64; - MS_CLOCK_US.with(|c| c.set(c.get() + dt_us)); -} - -/// A monotonic millisecond reading, for a clock-driven animator that has no `Tick` of its own to -/// hand it — the same hazard the module doc calls out for `Xfade` (`plx_ui::xfade::Xfade`) and -/// `Spinner` (`plx_ui::widgets::Spinner`): a millisecond ramp is invisible to [`note_spring`] and -/// must report itself, through [`invalidate`] for content or [`note_motion`] for a decoration. `card_row`'s focused-title marquee is the third — -/// it advances from inside `draw`, reached through a generic `Column::draw_child` trait method -/// and several call sites across three lanes' files, none of which carries a `Tick` — so it reads -/// this instead of widening that trait's fixed parameter list. -/// -/// **Take two readings and subtract them (`u32::wrapping_sub`)**, exactly as `motion::Phase` -/// does with a real `Tick.ms` — never accumulate a per-frame delta into a running total, which is -/// the `check-deps.sh` `dt` gate's whole complaint and the reason this replaced a `dt()` accessor -/// callers used to sum themselves. -#[inline] -pub fn now_ms() -> u32 { - MS_CLOCK_US.with(|c| (c.get() / 1000) as u32) -} - -/// Run one host page's update with an isolated view of spring motion, then merge its result back -/// into the frame-wide motion bit. This is not dirty-rectangle tracking: it only prevents a modal's -/// foreground springs from masquerading as movement in the page captured behind that modal. -pub fn scoped_motion(f: impl FnOnce() -> T) -> (T, bool) { - let scope = MotionScope::open(); - let value = f(); - (value, scope.close()) -} - -/// [`scoped_motion`] as an explicit open/close pair, for a caller whose scoped region is a whole -/// function body rather than a closure — a popover's `update`, which steps three or four springs -/// through several early returns and would otherwise have to be reindented into a closure to say -/// the same thing. -/// -/// **It closes on `Drop` as well as on [`close`](Self::close)**, which is what lets it be held as a -/// plain guard over a region with early returns — the dispatcher's per-surface step and draw -/// (§4.4), where the alternative is a `close()` on every path out. Before that it had no `Drop` at -/// all, so a scope that was dropped rather than closed left [`SCOPE_DEPTH`] raised for the rest of -/// the frame: every later spring in the app would then report as a popover's, and nothing would -/// fail — the gate would simply stop seeing the page move. `close` still consumes the guard and -/// returns the verdict; the `Drop` that follows it is a no-op. -pub struct MotionScope { - before: bool, - /// Still raising [`SCOPE_DEPTH`] — false once [`close`](Self::close) has merged it back. - open: bool, -} - -impl MotionScope { - pub fn open() -> Self { - SCOPE_DEPTH.with(|d| d.set(d.get() + 1)); - Self { - before: MOVING.with(|m| m.replace(false)), - open: true, - } - } - - /// Merge the scope back into the frame-wide bit and report whether anything inside it moved. - pub fn close(mut self) -> bool { - self.merge() - } - - fn merge(&mut self) -> bool { - if !self.open { - return false; - } - self.open = false; - let before = self.before; - SCOPE_DEPTH.with(|d| d.set(d.get().saturating_sub(1))); - MOVING.with(|m| { - let own = m.get(); - m.set(before || own); - own - }) - } -} - -impl Drop for MotionScope { - fn drop(&mut self) { - let _ = self.merge(); - } -} - -/// Should this iteration draw and swap? -/// -/// Call AFTER the update phase (so this frame's spring steps have been seen) and before -/// `glViewport`. The caller owns the route policy — this answers only "has anything changed". -/// Should this iteration draw and swap? -/// -/// **TAKES-AND-CLEARS the discrete flag**, which is why it must be called exactly once per -/// iteration and why the caller's route check must be on the RIGHT of the `||` — see `app.rs`. -/// Clearing here rather than after the draw is what lets a report raised DURING a draw survive: -/// `Spinner::draw` is the first such reporter, and with the flag cleared post-draw its report was -/// destroyed on the frame it was raised, so the spinner would freeze on its very first link. -/// -/// **The first still frame after motion is presented too — the SETTLE frame.** A spring in flight -/// is judged by the rest test at the top of this file, so the last frame it forces is one whose -/// residual is under a quarter pixel; the frame after it, where the spring reports nothing, is the -/// picture that stays on the panel until the next key. It was added for an at-rest term in the -/// renderer — `gfx::page_wash_dither`, which dropped the ±1 LSB dither from Home's and Detail's -/// page wash while their artwork moved and restored it on the frame the artwork's springs came to -/// rest, a frame that forced no present of its own. That gate is gone (2026-09-19: every gradient -/// wash dithers on every frame, `gfx::draw_ambient`), so no renderer term differs between the last -/// moving frame and the first still one any more; the settle present is kept as the one extra -/// frame that guarantees the resting picture is the fully-settled one. One frame, once per -/// settle, and the idle gate then closes as before. (This repairs the LIVE page only. A frozen-host snapshot is -/// drawn again on page damage or, under a fading panel, on page motion — -/// `popover::host::begin_frame`'s rule — and never by this frame.) -pub fn should_present(now: u32) -> bool { - let damage_gen = DAMAGE_GEN.load(Relaxed); - let new_damage = PRESENT_DAMAGE_GEN.with(|seen| { - let changed = seen.get() != damage_gen; - seen.set(damage_gen); - changed - }); - let moving = MOVING.with(|m| m.get()); - let settling = WAS_MOVING.with(|w| w.replace(moving)) && !moving; - if !ENABLED.load(Relaxed) { - PRESENT_DIRTY.with(|c| c.set(new_damage)); - return true; - } - let wake = WAKE.swap(false, Relaxed); - let dirty = DIRTY.swap(false, Relaxed); - let dirty = dirty || new_damage; - let changed = moving || dirty || wake || settling; - #[cfg(feature = "hostsim")] - if changed { - LAST_CHANGE.store(now, Relaxed); - } - PRESENT_DIRTY.with(|c| c.set(dirty)); - // The video-plane term is HERE, below every take-and-clear above it, and not `|| fr.player` at - // the call site as it was through phase 8. Two reasons, and the second is the bug: a term on - // the right of the caller's `||` short-circuits this whole function away on the frames it is - // true for, leaving `DIRTY`/`WAKE` set to fire spuriously on the way back out; and the term - // itself was the ROUTE, so the frames before the plane binds and after it unbinds — a spinner, - // a HUD fade, the failure read-out — were exempted from the gate for no reason the compositor - // knows about. They are ordinary idle frames now, which is what makes every player-side - // animator's motion report load-bearing. - if changed || VIDEO_PLANE.load(Relaxed) { - return true; - } - let keepalive = KEEPALIVE_MS != 0 && now.wrapping_sub(LAST_PRESENT.load(Relaxed)) >= KEEPALIVE_MS; - if !keepalive { - // A skipped frame takes nothing (`take_page_damage` runs on drawn frames); an own count - // cannot normally exist here (an invalidate would have made the frame present), so this - // only keeps a count from ever carrying into a later drawn frame's arithmetic. - OWN_DAMAGE_N.store(0, Relaxed); - } - keepalive -} - -/// Did new discrete damage (input, async data, a texture landing) select this present? Unlike -/// [`present_changed`], this excludes every spring outside the host's own [`scoped_motion`] result. -#[inline] -pub fn present_dirty() -> bool { - PRESENT_DIRTY.with(|c| c.get()) -} - -/// Did any spring move during this update phase? A full-page glass host may combine this with -/// [`present_dirty`]; a modal host should prefer its own [`scoped_motion`] result. -#[inline] -pub fn present_moving() -> bool { - MOVING.with(|m| m.get()) -} - -/// Did a spring OUTSIDE every [`MotionScope`] report motion this frame — i.e. the page's own, not a -/// popover's? `popover::host::begin_frame`'s question for a page under a fading panel. -#[inline] -pub fn page_moving() -> bool { - PAGE_MOVING.with(|m| m.get()) -} - -/// Did a page spring OUTSIDE every [`MotionScope`] AND outside every [`decorative`] region report -/// motion this frame? The page-freeze's "is the page quiescent" question. -#[inline] -pub fn page_layout_moving() -> bool { - PAGE_LAYOUT_MOVING.with(|m| m.get()) -} - -/// `now` of the last frame that had something to change — see [`LAST_CHANGE`]. Simulator only. -#[cfg(feature = "hostsim")] -pub fn last_change_ms() -> u32 { - LAST_CHANGE.load(Relaxed) -} - -/// Record that a frame was presented. Deliberately does NOT clear the discrete flag — a report -/// raised by the draw this call follows belongs to the NEXT frame, and [`should_present`] already -/// consumed the one that justified this one. -/// -/// The `devtriggers` poster-gate counters (`ui::card_motion_metrics::presented`) are fed from the -/// loop's own call site, on the line after this one (`app::run`): this module is the machine layer -/// and names nothing in `ui` but its own siblings. -#[inline] -pub fn note_present(now: u32) { - LAST_PRESENT.store(now, Relaxed); - PRESENTS.fetch_add(1, Relaxed); -} - -/// Presents since the last call — drained once a second into the heartbeat as `fps=`, which is the -/// only field there that is a frame rate. -/// -/// Its neighbour `loop=` deliberately counts LOOP iterations: it is the app's liveness signal and -/// `tests/run.py` anchors `pos=` to it, so it must not read 0 on a screen that is merely idle. -/// `fps=` is the number this module actually moves, and `fps=0` beside a healthy `loop=` is this -/// module working, not a fault. -pub fn take_presents() -> u32 { - PRESENTS.swap(0, Relaxed) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The gate's statics are reached from `gfx::spring`, which every other module's spring tests - /// also drive — so this contends across modules, not just within this file. `testlock`, not a - /// module-local mutex (see `lib.rs::testlock`). - fn fresh() -> plx_base::testlock::Serial { - let g = plx_base::testlock::serial(); - reset_for_test(); - g - } - - /// **Spec §9, §4.4, §16 risk 10 — the whole-frame gate is turned off by the PLANE'S BIT, and - /// only by it.** This is the gate's half of the claim, graded against the bit's own door - /// ([`note`] with [`PresentEvent::VideoPlane`]); the half that needs the player — the bit is - /// published on its EDGES only, the false edge raises the damage that presents the unbind frame, - /// and the loop asks the compositor from the bit on every frame — is - /// `app::run::video_plane_gate_tests`, the one layer that owns a `Player` and the loop's source. - /// - /// 1. *Only while bound.* The term used to be `|| fr.player` at the call site, i.e. "the - /// player SCREEN is up" — true through the whole pre-bind spinner and the whole post-unbind - /// fade, when the compositor has an ordinary UI surface and nothing is slaved to it. - /// 2. *Lowering the bit is not damage.* The frame the plane goes away on is very often one the - /// gate would otherwise skip, which is why the edge's writer raises damage with it; the gate - /// itself adds no term for it (a second formula term feeding the gate is what risk 10 names). - #[test] - fn the_present_gate_answers_true_only_while_the_plane_bit_is_set() { - use crate::present::PresentEvent; - let _g = fresh(); - assert!(!video_plane_bound(), "a fresh gate has no plane"); - - invalidate(); - assert!(should_present(0), "the damage just raised selects this frame"); - assert!(!should_present(16), "settled, inside the keepalive: nothing to send"); - - // ---- the TRUE edge, and what it buys ---- - note(PresentEvent::VideoPlane(true)); - assert!(video_plane_bound(), "the bit's own door is the gate's only input"); - for t in [32u32, 48, 64, 80] { - assert!( - should_present(t), - "while the plane is bound every frame presents, unconditionally — nothing about \ - this frame moved", - ); - } - let _ = take_local_damage(); - note(PresentEvent::VideoPlane(true)); - assert_eq!(take_local_damage(), 0, "publishing the bit raises no damage of its own"); - - // ---- the FALSE edge: the bit alone buys nothing, the edge's own damage does ---- - note(PresentEvent::VideoPlane(false)); - assert!(!video_plane_bound()); - assert!( - !should_present(96), - "lowering the bit adds no term to the gate — the unbind frame is the damage the edge's \ - writer raises beside it", - ); - invalidate(); // what `Player::set_video_plane_bound(false)` raises on that edge - assert!(should_present(112), "the edge's damage presents the unbind frame"); - assert!( - !should_present(128), - "…and the frame after it is an ordinary idle frame again, which is the whole point", - ); - } - - /// The host cache's question — did the PAGE change — answered by count: damage raised inside - /// a popover's own scope (its update, its drawing, the input it holds) is not the page's, and - /// one page invalidation beside any amount of the panel's own is still seen. - #[test] - fn page_damage_is_what_no_popover_scope_raised() { - let _g = fresh(); - assert!(!take_page_damage(), "nothing happened"); - { - let _own = OwnScope::open(); - invalidate(); // the appear spring, a marquee, a key the panel handled — its own - invalidate(); - } - assert!(!take_page_damage(), "damage inside an own scope is not the page's"); - { - let _own = OwnScope::open(); - invalidate(); // the panel's key press... - let _nested = OwnScope::open(); - invalidate(); // ...and its handler's own repaint, nested - } - invalidate(); // AND a poster landing, same frame, outside every scope - assert!(take_page_damage(), "one invalidation the panel did not raise is the page's"); - assert!(!take_page_damage(), "taken"); - assert!(!page_damage(1, 1) && page_damage(2, 1) && page_damage(1, 0)); - // A frame with nothing to draw takes nothing and leaves nothing behind for the next. - frame_begin(1.0 / 60.0); - should_present(10_000); - note_present(10_000); - frame_begin(1.0 / 60.0); - assert!(!should_present(10_016), "nothing to draw"); - invalidate(); - assert!(take_page_damage(), "the landing after a skipped frame is the page's"); - } - - /// A frame that stands the clock still (`dt == 0`, the frame dump's held repeat) reads a spring - /// that is still travelling as at rest, because `velocity * 0` is no distance. Giving the rest - /// test its own `dt` judges it as the frame before did, and the clock still does not move. - #[test] - fn a_standing_clock_can_judge_rest_with_another_dt() { - let _g = fresh(); - let (pos, target, vel) = (1.0, 1.0, 100.0); - frame_begin(0.0); - assert!(settled(pos, target, vel), "no time passes, so no travel: reads as rest"); - let before = now_ms(); - frame_begin_judging_rest_with(0.0, 1.0 / 60.0); - assert!(!settled(pos, target, vel), "judged with the frame's own dt, it is still moving"); - assert_eq!(now_ms(), before, "the clock `now_ms` reads advances by `dt`, which is 0"); - frame_begin_judging_rest_with(1.0 / 60.0, 1.0 / 60.0); - assert!(!settled(pos, target, vel), "an ordinary frame is the same call with one number"); - } - - #[test] - fn settled_screen_stops_presenting() { - let _g = fresh(); - // a spring sitting exactly on target reports nothing - note_spring(1.0, 1.0, 0.0); - note_present(10_000); - frame_begin(1.0 / 60.0); - note_spring(1.0, 1.0, 0.0); - assert!(!should_present(10_016), "a settled screen must not repaint"); - } - - #[test] - fn motion_forces_a_present() { - let _g = fresh(); - note_present(10_000); - frame_begin(1.0 / 60.0); - note_spring(0.5, 1.0, 0.0); // far from target - assert!(should_present(10_016)); - - frame_begin(1.0 / 60.0); - note_spring(1.0, 1.0, 0.4); // on target but still carrying velocity - assert!(should_present(10_016)); - } - - /// A 0..1 spring is judged by the RELATIVE term: its threshold is ~1e-3 and the sub-pixel cap - /// never binds for it. - #[test] - fn sub_epsilon_residue_is_at_rest() { - let _g = fresh(); - note_present(10_000); - frame_begin(1.0 / 60.0); - note_spring(1.0 + REST_REL / 4.0, 1.0, REST_REL / 4.0); - assert!(!should_present(10_016)); - } - - /// THE REGRESSION THIS PREDICATE EXISTS FOR. A 280 px shelf scroll that has arrived to within a - /// twentieth of a pixel, still carrying 5 px/s — 0.08 px of travel in the next frame — used to - /// read as moving, because 5.0 > 1e-3. That tail was 43 of the scroll's 83 presents. - #[test] - fn a_scroll_that_has_visually_arrived_is_at_rest() { - let _g = fresh(); - note_present(10_000); - frame_begin(1.0 / 60.0); - note_spring(280.0 - 0.05, 280.0, 5.0); - assert!( - !should_present(10_016), - "sub-pixel travel must not hold the panel awake" - ); - } - - /// ...but the same spring one pixel out, or moving a pixel per frame, still is. - #[test] - fn a_scroll_still_visibly_moving_presents() { - let _g = fresh(); - note_present(10_000); - frame_begin(1.0 / 60.0); - note_spring(279.0, 280.0, 0.0); - assert!(should_present(10_016), "a whole pixel out is visible"); - - frame_begin(1.0 / 60.0); - note_spring(280.0, 280.0, 60.0); // 1 px this frame - assert!( - should_present(10_016), - "a pixel of travel per frame is visible" - ); - } - - #[test] - fn scoped_motion_keeps_host_and_foreground_motion_distinct() { - let _g = fresh(); - frame_begin(1.0 / 60.0); - note_spring(0.0, 1.0, 0.0); // foreground motion before the host scope - let (_, host_moving) = scoped_motion(|| note_spring(1.0, 1.0, 0.0)); - assert!( - !host_moving, - "a settled host must not inherit foreground motion" - ); - assert!( - should_present(10_000), - "the frame-wide gate must retain that foreground motion" - ); - - frame_begin(1.0 / 60.0); - let (_, host_moving) = scoped_motion(|| note_spring(0.0, 1.0, 0.0)); - assert!(host_moving, "host motion is reported to its glass owner"); - assert!( - should_present(10_016), - "and remains part of frame-wide motion" - ); - } - - /// The cap is what stops the relative term from growing past visibility on a deep scroll: at - /// pos 1500 the relative threshold would be 1.5 px, which is a visible stop. - #[test] - fn the_threshold_never_exceeds_a_quarter_pixel() { - let _g = fresh(); - note_present(10_000); - frame_begin(1.0 / 60.0); - note_spring(1500.0 - 0.3, 1500.0, 0.0); - assert!( - should_present(10_016), - "0.3px out must still repaint however large the value" - ); - } - - /// A jump reports only when it actually moved — `home.rs` jumps to the same value every frame - /// while the hub list is empty, and an unguarded report would pin 60fps on that exact screen. - /// This is the gate's half, through [`note_jump`] — the door `Spring::jump` reports by; the - /// guard on the `Spring` side (`self.pos != v || self.vel != 0.0`) is graded where `Spring` - /// lives, `ui::spring_tests`. - #[test] - fn a_jump_reports_only_when_it_changes_something() { - let _g = fresh(); - note_present(10_000); - frame_begin(1.0 / 60.0); - note_jump(false); // already there - assert!(!should_present(10_016)); - - frame_begin(1.0 / 60.0); - note_jump(true); // teleported - assert!(should_present(10_032)); - } - - /// The ordering fix: a report raised DURING the draw (a spinner) must survive to the next - /// frame. `should_present` takes-and-clears, so `note_present` after the draw cannot eat it. - #[test] - fn a_report_raised_during_a_draw_survives_to_the_next_frame() { - let _g = fresh(); - frame_begin(1.0 / 60.0); - assert!(should_present(10_000)); - note_present(10_000); // ... the draw runs here, and the spinner reports: - invalidate(); - frame_begin(1.0 / 60.0); - assert!( - should_present(10_016), - "the spinner's own chain must not break on its first link" - ); - } - - #[test] - fn invalidate_buys_exactly_one_frame() { - let _g = fresh(); - note_present(10_000); - frame_begin(1.0 / 60.0); - invalidate(); - assert!(should_present(10_016)); - assert!(present_dirty(), "a discrete landing is real content damage"); - note_present(10_016); // the frame it bought - frame_begin(1.0 / 60.0); - assert!( - !should_present(10_032), - "one landing must not pin the loop on" - ); - } - - #[test] - fn wake_buys_a_frame_without_reporting_content_damage() { - let _g = fresh(); - note_present(10_000); - frame_begin(1.0 / 60.0); - wake(); - assert!(should_present(10_016)); - assert!(!present_dirty(), "but it is not host-underlay damage"); - } - - #[test] - fn keepalive_bounds_staleness() { - let _g = fresh(); - note_present(10_000); - frame_begin(1.0 / 60.0); - assert!(!should_present(10_000 + KEEPALIVE_MS - 1)); - assert!(should_present(10_000 + KEEPALIVE_MS)); - assert!( - !present_dirty(), - "an insurance commit must not dirty dynamic glass" - ); - } - - /// The tick counter wraps every ~49 days, and the keepalive is the one place the gate does - /// arithmetic on it. Straight subtraction would read ~4 billion ms across the wrap and pin the - /// loop presenting forever; the reverse case must err toward presenting, not stall. - #[test] - fn tick_wrap_is_arithmetically_sound() { - let _g = fresh(); - note_present(u32::MAX - 10); - frame_begin(1.0 / 60.0); - // 16 ms past the wrap: elapsed is 16, not 4e9 — the keepalive is not due - assert!(!should_present(5)); - // and it still comes due on time across that same wrap - assert!(should_present((u32::MAX - 10).wrapping_add(KEEPALIVE_MS))); - // a tick BEFORE the last present is only reachable at a wrap — repaint, never stall - LAST_PRESENT.store(5, Relaxed); - frame_begin(1.0 / 60.0); - assert!(should_present(u32::MAX - 10)); - } - - #[test] - fn kill_switch_always_presents() { - let _g = fresh(); - set_enabled(false); - note_present(10_000); - frame_begin(1.0 / 60.0); - assert!(should_present(10_016)); - set_enabled(true); - } - - /// OVER-REPORTING IS THE SILENT FAILURE. A gate that presents too often loses the entire - /// saving while every floor-style assertion still passes, so a whole settled tree — the ~439 - /// springs a Home grid steps per frame, all at rest — must produce exactly nothing. - #[test] - fn a_whole_settled_tree_asks_for_nothing() { - let _g = fresh(); - note_present(10_000); - frame_begin(1.0 / 60.0); - for i in 0..439 { - let v = 1.0 + (i as f32) * 0.001; // a spread of magnitudes, every one AT its target - note_spring(v, v, 0.0); - } - assert!( - !should_present(10_016), - "439 springs at rest must not repaint" - ); - } - - /// One moving spring anywhere in that tree is enough. (The asymmetry is the design: a false - /// "moved" costs one frame, a false "still" freezes the screen.) - #[test] - fn one_mover_in_a_settled_tree_is_enough() { - let _g = fresh(); - note_present(10_000); - frame_begin(1.0 / 60.0); - for _ in 0..438 { - note_spring(1.0, 1.0, 0.0); - } - note_spring(1.0, 1.5, 0.0); - assert!(should_present(10_016)); - } - - /// Motion is re-derived every frame, never remembered: last frame's movement buys exactly ONE - /// more present — the settle frame — and must not leak past it, or a single animation would - /// pin the loop permanently. - #[test] - fn motion_does_not_survive_the_frame_that_had_it() { - let _g = fresh(); - frame_begin(1.0 / 60.0); - note_spring(0.0, 1.0, 0.0); // moving - assert!(should_present(10_000)); - note_present(10_000); - frame_begin(1.0 / 60.0); // next frame: nothing steps - assert!(should_present(10_016), "the settle frame, once"); - note_present(10_016); - frame_begin(1.0 / 60.0); - assert!( - !should_present(10_032), - "yesterday's motion must not repaint past the settle frame" - ); - } - - /// `dt` scales the velocity term, so a long frame counts as more travel. A spring drifting at - /// 12 px/s is at rest in a 16 ms frame (0.2 px) and moving in a 50 ms one (0.6 px) — the dt - /// clamp's worst case, and the reason the velocity test cannot be a bare constant. - #[test] - fn a_longer_frame_covers_more_travel() { - let _g = fresh(); - note_present(10_000); - frame_begin(1.0 / 60.0); - note_spring(300.0, 300.0, 12.0); - assert!( - !should_present(10_016), - "0.2px in a 60Hz frame is not visible" - ); - - frame_begin(0.05); // app.rs's dt clamp - note_spring(300.0, 300.0, 12.0); - assert!(should_present(10_032), "0.6px in a long frame is"); - } - - /// The kill switch must not silently consume the dirty flag — `/tmp/plxnative-noidle` is the - /// A/B instrument, so arming it has to change the frame RATE and nothing else. - #[test] - fn the_kill_switch_leaves_the_dirty_flag_alone() { - let _g = fresh(); - note_present(10_000); // park the keepalive; this test is about the flag, not the backstop - set_enabled(false); - invalidate(); - assert!(should_present(10_000)); - assert!(present_dirty()); - assert!(should_present(10_000)); - assert!(!present_dirty(), "noidle changes rate, not content damage"); - set_enabled(true); - assert!( - should_present(10_000), - "the flag must still be there to consume" - ); - assert!(!should_present(10_000), "...and consumed exactly once"); - } - - #[test] - fn presents_drain_once() { - let _g = fresh(); - note_present(1); - note_present(2); - assert_eq!(take_presents(), 2); - assert_eq!(take_presents(), 0); - } -} diff --git a/rust-modules/machine/src/idle_regression_tests.rs b/rust-modules/machine/src/idle_regression_tests.rs new file mode 100644 index 0000000000..9cd830b87f --- /dev/null +++ b/rust-modules/machine/src/idle_regression_tests.rs @@ -0,0 +1,272 @@ +//! Original idle regression cases, exercised through an owned gate and explicit reports. +use crate::motion::report::*; +use crate::present::{Present, PresentEvent, Provenance, Scope, KEEPALIVE_MS}; + +struct Runtime { + gate: Present, + selected_damage: bool, + _serial: plx_base::testlock::Serial, +} +impl Runtime { + fn fresh() -> Self { + let serial = plx_base::testlock::serial(); + reset_for_test(); + let mut gate = Present::global(); + gate.take(0); + gate.acknowledge(0); + gate.take_presents(); + Self { gate, selected_damage: false, _serial: serial } + } + fn presented(&mut self, now: u32) { + self.gate.take(now); + self.gate.acknowledge(now); + } + fn swap(&mut self, now: u32) -> bool { + collect_into(&mut self.gate, now); + self.selected_damage = self.gate.page_damaged(); + let demand = self.gate.take(now); + if demand { self.gate.acknowledge(now); } + demand + } +} +#[test] +fn the_present_gate_answers_true_only_while_the_plane_bit_is_set() { + let mut r = Runtime::fresh(); + assert!(!r.gate.video_plane()); + r.gate.note(PresentEvent::Damage(Provenance::Input)); + assert!(r.swap(0)); + assert!(!r.swap(16)); + r.gate.note(PresentEvent::VideoPlane(true)); + for now in [32, 48, 64, 80] { assert!(r.swap(now)); } + assert!(!r.gate.page_damaged()); + r.gate.note(PresentEvent::VideoPlane(true)); + assert!(!r.gate.page_damaged(), "an unchanged plane edge reports no damage"); + r.gate.note(PresentEvent::VideoPlane(false)); + assert!(r.swap(96), "the owned edge paints the unbind frame"); + assert!(!r.swap(112)); +} +#[test] +fn page_damage_is_what_no_popover_scope_raised() { + let mut r = Runtime::fresh(); + assert!(!r.gate.page_damaged()); + r.gate.note_in_scope(Scope::Surface, PresentEvent::Damage(Provenance::Input)); + r.gate.note_in_scope(Scope::Surface, PresentEvent::Damage(Provenance::Input)); + assert!(!r.gate.page_damaged()); + r.gate.note_in_scope(Scope::Surface, PresentEvent::Damage(Provenance::Input)); + r.gate.note_in_scope(Scope::Surface, PresentEvent::Damage(Provenance::Input)); + r.gate.note_in_scope(Scope::Page, PresentEvent::Damage(Provenance::Input)); + assert!(r.gate.page_damaged()); + r.presented(0); + assert!(!r.gate.page_damaged()); + frame_begin(1.0 / 60.0); + r.swap(10_000); + frame_begin(1.0 / 60.0); + assert!(!r.swap(10_016)); + r.gate.note(PresentEvent::Damage(Provenance::Input)); + assert!(r.gate.page_damaged()); +} +#[test] +fn a_standing_clock_can_judge_rest_with_another_dt() { + let _r = Runtime::fresh(); + frame_begin(0.0); + assert!(settled(1.0, 1.0, 100.0)); + let before = now_ms(); + frame_begin_judging_rest_with(0.0, 1.0 / 60.0); + assert!(!settled(1.0, 1.0, 100.0)); + assert_eq!(now_ms(), before); +} +#[test] +fn settled_screen_stops_presenting() { + let mut r = Runtime::fresh(); + r.presented(10_000); + frame_begin(1.0 / 60.0); + note_spring(1.0, 1.0, 0.0); + assert!(!r.swap(10_016)); +} +#[test] +fn motion_forces_a_present() { + let mut r = Runtime::fresh(); + r.presented(10_000); + frame_begin(1.0 / 60.0); + note_spring(0.5, 1.0, 0.0); + assert!(r.swap(10_016)); + frame_begin(1.0 / 60.0); + note_spring(1.0, 1.0, 0.4); + assert!(r.swap(10_032)); +} +#[test] +fn sub_epsilon_residue_is_at_rest() { + let mut r = Runtime::fresh(); + r.presented(10_000); + frame_begin(1.0 / 60.0); + note_spring(1.0 + 0.001 / 4.0, 1.0, 0.001 / 4.0); + assert!(!r.swap(10_016)); +} +#[test] +fn a_scroll_that_has_visually_arrived_is_at_rest() { + let mut r = Runtime::fresh(); + r.presented(10_000); + frame_begin(1.0 / 60.0); + note_spring(280.0 - 0.05, 280.0, 5.0); + assert!(!r.swap(10_016), "subpixel travel must not keep presenting"); +} +#[test] +fn a_scroll_still_visibly_moving_presents() { + let mut r = Runtime::fresh(); + r.presented(10_000); + frame_begin(1.0 / 60.0); + note_spring(279.0, 280.0, 0.0); + assert!(r.swap(10_016)); + frame_begin(1.0 / 60.0); + note_spring(280.0, 280.0, 60.0); + assert!(r.swap(10_032)); +} +#[test] +fn scoped_motion_keeps_host_and_foreground_motion_distinct() { + let mut r = Runtime::fresh(); + frame_begin(1.0 / 60.0); + note_spring(0.0, 1.0, 0.0); + let (_, host_moving) = scoped_motion(|| note_spring(1.0, 1.0, 0.0)); + assert!(!host_moving); + assert!(r.swap(10_000)); + frame_begin(1.0 / 60.0); + let (_, host_moving) = scoped_motion(|| note_spring(0.0, 1.0, 0.0)); + assert!(host_moving); + assert!(r.swap(10_016)); +} +#[test] +fn the_threshold_never_exceeds_a_quarter_pixel() { + let mut r = Runtime::fresh(); + r.presented(10_000); + frame_begin(1.0 / 60.0); + note_spring(1500.0 - 0.3, 1500.0, 0.0); + assert!(r.swap(10_016)); +} +#[test] +fn a_jump_reports_only_when_it_changes_something() { + let mut r = Runtime::fresh(); + r.presented(10_000); + frame_begin(1.0 / 60.0); + note_jump(false); + assert!(!r.swap(10_016)); + note_jump(true); + assert!(r.swap(10_032)); +} +#[test] +fn a_report_raised_during_a_draw_survives_to_the_next_frame() { + let mut r = Runtime::fresh(); + frame_begin(1.0 / 60.0); + collect_into(&mut r.gate, 10_000); + assert!(r.gate.take(10_000)); + r.gate.note(PresentEvent::Damage(Provenance::Input)); + r.gate.acknowledge(10_000); + frame_begin(1.0 / 60.0); + assert!(r.swap(10_016)); +} +#[test] +fn invalidate_buys_exactly_one_frame() { + let mut r = Runtime::fresh(); + r.presented(10_000); + r.gate.note(PresentEvent::Damage(Provenance::Input)); + assert!(r.swap(10_016)); + assert!(r.selected_damage); + frame_begin(1.0 / 60.0); + assert!(!r.swap(10_032)); +} +#[test] +fn wake_buys_a_frame_without_reporting_content_damage() { + let mut r = Runtime::fresh(); + r.presented(10_000); + r.gate.note(PresentEvent::Wake); + assert!(r.swap(10_016)); + assert!(!r.selected_damage); + assert!(!r.gate.page_damaged()); +} +#[test] +fn keepalive_bounds_staleness() { + let mut r = Runtime::fresh(); + r.presented(10_000); + assert!(!r.swap(10_000 + KEEPALIVE_MS - 1)); + assert!(r.swap(10_000 + KEEPALIVE_MS)); + assert!(!r.selected_damage); +} +#[test] +fn tick_wrap_is_arithmetically_sound() { + let mut r = Runtime::fresh(); + r.presented(u32::MAX - 10); + assert!(!r.swap(5)); + assert!(r.swap((u32::MAX - 10).wrapping_add(KEEPALIVE_MS))); + r.presented(5); + assert!(r.swap(u32::MAX - 10)); +} +#[test] +fn kill_switch_always_presents() { + let mut r = Runtime::fresh(); + r.presented(10_000); + r.gate.set_enabled(false); + assert!(r.swap(10_016)); +} +#[test] +fn a_whole_settled_tree_asks_for_nothing() { + let mut r = Runtime::fresh(); + r.presented(10_000); + for i in 0..439 { + let value = 1.0 + i as f32 * 0.001; + note_spring(value, value, 0.0); + } + assert!(!r.swap(10_016)); +} +#[test] +fn one_mover_in_a_settled_tree_is_enough() { + let mut r = Runtime::fresh(); + r.presented(10_000); + for _ in 0..438 { note_spring(1.0, 1.0, 0.0); } + note_spring(1.0, 1.5, 0.0); + assert!(r.swap(10_016)); +} +#[test] +fn motion_does_not_survive_the_frame_that_had_it() { + let mut r = Runtime::fresh(); + note_spring(0.0, 1.0, 0.0); + assert!(r.swap(10_000)); + frame_begin(1.0 / 60.0); + assert!(r.swap(10_016), "one settle frame"); + frame_begin(1.0 / 60.0); + assert!(!r.swap(10_032)); +} +#[test] +fn a_longer_frame_covers_more_travel() { + let mut r = Runtime::fresh(); + r.presented(10_000); + frame_begin(1.0 / 60.0); + note_spring(300.0, 300.0, 12.0); + assert!(!r.swap(10_016)); + frame_begin(0.05); + note_spring(300.0, 300.0, 12.0); + assert!(r.swap(10_032)); +} +#[test] +fn the_kill_switch_leaves_the_dirty_flag_alone() { + let mut r = Runtime::fresh(); + r.presented(10_000); + r.gate.set_enabled(false); + r.gate.note(PresentEvent::Damage(Provenance::Input)); + collect_into(&mut r.gate, 10_016); + assert!(r.gate.take(10_016)); + assert!(r.gate.page_damaged()); + collect_into(&mut r.gate, 10_032); + assert!(r.gate.take(10_032)); + assert!(r.gate.page_damaged(), "noidle changes rate, never consumes pending content damage"); + r.gate.set_enabled(true); + assert!(r.gate.peek(10_032), "skipped swaps cannot consume the flag"); + r.gate.acknowledge(10_032); + assert!(!r.swap(10_048)); +} +#[test] +fn presents_drain_once() { + let mut r = Runtime::fresh(); + r.presented(1); + r.presented(2); + assert_eq!(r.gate.take_presents(), 2); + assert_eq!(r.gate.take_presents(), 0); +} diff --git a/rust-modules/machine/src/lib.rs b/rust-modules/machine/src/lib.rs index 27f77c5b84..c75efba6c8 100644 --- a/rust-modules/machine/src/lib.rs +++ b/rust-modules/machine/src/lib.rs @@ -1,20 +1,23 @@ //! plx_machine: the deterministic state-machine runtime of the PlxNative application core. //! -//! Machines and effects (`machine`), the present gate (`present`), the whole-frame idle/wake gate -//! (`idle`), the landing schedule and its record/replay gate (`landing`, `landgate`) and the +//! Machines and effects (`machine`), the owned present gate (`present`), scoped motion reporting +//! (`motion::report`), the landing schedule and its record/replay gate (`landing`, `landgate`) and the //! spring integrators with their own soft-float maths (`motion`). It is the `machine` layer of //! `ci/module-layers.ini`: it uses `base` and nothing else, and it is not UI, though it lived under //! `ui/` until the split. //! //! `test-support` exposes the `cfg(test)` fixtures other layers' tests build on -//! (`landgate::fixture_gate`, `idle::reset_for_test`, `machine::{BareArg, BareMeasure}`, ...) and +//! (`landgate::fixture_gate`, `motion::report::reset_for_test`, `machine::{BareArg, BareMeasure}`, ...) and //! keeps this crate's test-mode behaviour (a private wake door per `Present`, the per-thread //! damage counter) when a dependent's tests build it. The application crate enables it in //! `[dev-dependencies]` only, so no shipped build sees it. pub mod machine; // the layer-neutral contract: Host, Machine, Effects, Fx, Canon, Tick (spec §3.1) -pub mod present; // the present gate as a machine with an owner (spec §4.4) -pub mod idle; // whole-FRAME present gating: a screen with nothing moving on it stops repainting +pub mod present; // the Dispatcher-owned present gate, admission and actual-swap acknowledgement +#[cfg(test)] +mod present_contract_tests; +#[cfg(test)] +mod idle_regression_tests; // former idle cases now drive an owned Present and frame report pub mod landgate; // a replay delivers a landing on its RECORDED frame (spec §3.3 step 3) pub mod landing; // the bounded per-addressee result queue (spec §5.2) pub mod job; // the job lane: a machine emits a typed `Job`, the owner's runner starts it, a `Port` takes the one answer diff --git a/rust-modules/machine/src/machine.rs b/rust-modules/machine/src/machine.rs index 10f5f912f6..c1d11a5c8d 100644 --- a/rust-modules/machine/src/machine.rs +++ b/rust-modules/machine/src/machine.rs @@ -293,6 +293,10 @@ pub fn fit_line_by( #[derive(Clone, Copy, Debug)] pub struct PressRead { pub scale: f32, + /// Identity of the input owner's arm, retained through spring-back (not a global counter). + pub identity: u32, + pub live: bool, + pub active: bool, pub is_long: bool, /// Milliseconds a HOLDABLE (card) press has been held down right now, still undecided: `None` /// for no press, a control face's press (no hold gesture), a released or cancelled one. @@ -308,7 +312,7 @@ pub struct PressRead { impl Default for PressRead { fn default() -> Self { - Self { scale: 0.0, is_long: false, held_ms: None, owner: None } + Self { scale: 0.0, identity: 0, live: false, active: false, is_long: false, held_ms: None, owner: None } } } @@ -875,12 +879,30 @@ impl Canon { } } + // `inline(always)` and plain index loops, not `for b in bytes` / `to_le_bytes()` iterators: this + // runs over the whole logical state several times a frame in a debug build (the dispatcher's + // `state_hash` assertions), where every iterator `next` is a call that is never inlined, and + // they were most of a dispatcher test frame. The bytes fed, and so the hash, are unchanged + // (`canon_is_fnv_1a_over_tagged_little_endian_bytes`). + #[inline(always)] fn byte(&mut self, b: u8) { self.h ^= b as u64; self.h = self.h.wrapping_mul(Self::PRIME); self.len += 1; } + #[inline(always)] + fn bytes(&mut self, bytes: &[u8]) { + let mut h = self.h; + let mut i = 0; + while i < bytes.len() { + h = (h ^ bytes[i] as u64).wrapping_mul(Self::PRIME); + i += 1; + } + self.h = h; + self.len += bytes.len() as u64; + } + pub fn u8(&mut self, v: u8) -> &mut Self { self.tag(1); self.byte(v); @@ -889,17 +911,13 @@ impl Canon { pub fn u32(&mut self, v: u32) -> &mut Self { self.tag(2); - for b in v.to_le_bytes() { - self.byte(b); - } + self.bytes(&v.to_le_bytes()); self } pub fn u64(&mut self, v: u64) -> &mut Self { self.tag(3); - for b in v.to_le_bytes() { - self.byte(b); - } + self.bytes(&v.to_le_bytes()); self } @@ -912,18 +930,14 @@ impl Canon { /// Floats are their BITS: NaN, +0/-0 and Inf are all distinct and all stable. pub fn f32(&mut self, v: f32) -> &mut Self { self.tag(5); - for b in v.to_bits().to_le_bytes() { - self.byte(b); - } + self.bytes(&v.to_bits().to_le_bytes()); self } pub fn str(&mut self, v: &str) -> &mut Self { self.tag(6); self.u32(v.len() as u32); - for b in v.bytes() { - self.byte(b); - } + self.bytes(v.as_bytes()); self } @@ -953,6 +967,7 @@ impl Canon { self } + #[inline(always)] fn tag(&mut self, t: u8) { self.byte(t); } @@ -1025,6 +1040,46 @@ mod canon_tests { assert_ne!(z.finish(), nz.finish(), "+0 and -0 are different bits"); } + /// The encoder is FNV-1a over a tag byte and little-endian bytes, `finish` folding the byte count + /// in. Recorded replay anchors hash through it, so its byte stream is pinned two ways: against a + /// one-byte-at-a-time reference written from that sentence, and against the value the encoder + /// produced before its loops were rewritten to run cheaply in a debug build. + #[test] + fn canon_is_fnv_1a_over_tagged_little_endian_bytes() { + let mut c = Canon::new(); + c.u8(0xAB) + .u32(0xDEAD_BEEF) + .u64(0x0123_4567_89AB_CDEF) + .bool(true) + .f32(-1.5) + .str("héllo — ☃") + .discriminant(7) + .seq(3) + .option(Some(5u32), |c, v| { + c.u32(v); + }) + .option::(None, |c, v| { + c.u32(v); + }); + let mut stream = vec![1, 0xAB, 2]; + stream.extend(0xDEAD_BEEFu32.to_le_bytes()); + stream.push(3); + stream.extend(0x0123_4567_89AB_CDEFu64.to_le_bytes()); + stream.extend([4, 1, 5]); + stream.extend((-1.5f32).to_bits().to_le_bytes()); + stream.extend([6, 2]); + stream.extend(("héllo — ☃".len() as u32).to_le_bytes()); + stream.extend("héllo — ☃".bytes()); + stream.extend([7, 2, 7, 0, 0, 0, 8, 2, 3, 0, 0, 0, 10, 2, 5, 0, 0, 0, 9]); + let (mut h, mut len) = (0xcbf2_9ce4_8422_2325u64, 0u64); + for b in stream { + h = (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3); + len += 1; + } + assert_eq!(c.finish(), h ^ len.rotate_left(32), "the byte stream is not the specified one"); + assert_eq!(c.finish(), 7_471_706_773_540_265_486, "the value the encoder produced before its loops were rewritten"); + } + struct NoHost; #[derive(Clone)] struct NoArg; diff --git a/rust-modules/machine/src/motion.rs b/rust-modules/machine/src/motion.rs index 35b52d2857..09732aa905 100644 --- a/rust-modules/machine/src/motion.rs +++ b/rust-modules/machine/src/motion.rs @@ -29,6 +29,10 @@ //! |x| ≈ 1e4 with three-part Cody-Waite reduction) and say what they do past it. #![allow(dead_code)] // phase 2: the reporting integrators gain callers as screens migrate +pub mod report; +#[cfg(test)] +mod report_tests; + use super::machine::{PresentHandle, Tick}; use super::present::PresentEvent; @@ -434,6 +438,7 @@ mod tests { fn a_spring_reports_motion_until_it_rests() { let mut present = Present::new(); let _ = present.take(0); + present.acknowledge(0); let (mut pos, mut vel) = (0.0f32, 0.0f32); let t = Tick { ms: 0, @@ -447,6 +452,7 @@ mod tests { if !present.take(frames * 16) { break; } + present.acknowledge(frames * 16); assert!(frames < 600, "never rested"); } assert!((pos - 100.0).abs() < 0.25 && frames > 5, "pos={pos} frames={frames}"); @@ -456,12 +462,14 @@ mod tests { fn a_ramp_reports_motion_from_inside_advance() { let mut present = Present::new(); let _ = present.take(0); + present.acknowledge(0); let mut r = Ramp::default(); r.start(Tick { ms: 0, dt_us: 0 }, 200); let mut ph = PresentHandle(&mut present); let p = r.advance(Tick { ms: 100, dt_us: 0 }, &mut ph); assert!((p - 0.5).abs() < 1e-6); assert!(present.take(100), "a running ramp presents"); + present.acknowledge(100); let mut ph = PresentHandle(&mut present); assert_eq!(r.advance(Tick { ms: 250, dt_us: 0 }, &mut ph), 1.0); assert!(!r.running); @@ -472,6 +480,7 @@ mod tests { fn a_phase_reports_motion_from_inside_advance_and_starts_lazily() { let mut present = Present::new(); let _ = present.take(0); + present.acknowledge(0); let mut ph_clock = Phase::default(); // never explicitly `reset` — the first `advance` call anchors it, so a freshly constructed // `Phase` (what every screen's `Default`-derived state gets) needs no `Tick` up front. @@ -489,6 +498,7 @@ mod tests { fn a_phase_reset_restarts_the_clock_from_the_given_tick() { let mut present = Present::new(); let _ = present.take(0); + present.acknowledge(0); let mut ph_clock = Phase::default(); let mut ph = PresentHandle(&mut present); assert_eq!(ph_clock.advance(Tick { ms: 5_000, dt_us: 0 }, &mut ph), 0.0); @@ -510,6 +520,7 @@ mod tests { fn a_held_phase_clock_reads_the_held_value_and_reports_no_motion() { let mut present = Present::new(); let _ = present.take(0); + present.acknowledge(0); let mut ph_clock = Phase::default(); super::hold_phase_clocks(Some(190)); // All inside the keepalive window, so a `true` could only be motion. @@ -532,6 +543,7 @@ fn a_ramp_can_wait_quietly_and_exclude_a_suspended_interval() { let tick = |ms| Tick { ms, dt_us: 16_000 }; let mut present = super::present::Present::new(); let _ = present.take(0); + present.acknowledge(0); ramp.start(tick(100), 1000); let before = ramp.sample(tick(600)); assert!(!present.take(0), "a quiet deadline must not report motion"); diff --git a/rust-modules/machine/src/motion/report.rs b/rust-modules/machine/src/motion/report.rs new file mode 100644 index 0000000000..b18cf9078e --- /dev/null +++ b/rust-modules/machine/src/motion/report.rs @@ -0,0 +1,137 @@ +//! Per-thread frame motion collector, not a present gate. +//! Rendering scopes report page/surface/decorative motion here; the runtime explicitly +//! reads the report and merges it into its owned `Present` before admission. +use std::cell::Cell; + +pub const IDLE_POLL_MS: u32 = 16; + +thread_local! { + static MOVING: Cell = const { Cell::new(false) }; + static PAGE_MOVING: Cell = const { Cell::new(false) }; + static PAGE_LAYOUT_MOVING: Cell = const { Cell::new(false) }; + static JUMPED: Cell = const { Cell::new(false) }; + static PAGE_JUMPED: Cell = const { Cell::new(false) }; + + static DEPTH: Cell = const { Cell::new(0) }; + static DECOR: Cell = const { Cell::new(0) }; + + static DT: Cell = const { Cell::new(1.0 / 60.0) }; + static CLOCK_US: Cell = const { Cell::new(0) }; + #[cfg(any(test, feature = "test-support"))] + static LOCAL_MOTION: Cell = const { Cell::new(0) }; + + static FROZEN: Cell = const { Cell::new(false) }; +} + +#[derive(Clone, Copy, Debug, Default)] +pub struct FrameReport { + pub moving: bool, + pub page_moving: bool, + pub page_layout_moving: bool, + /// A discontinuity already at rest; unlike running motion it owes no settle frame. + pub jumped: bool, + pub page_jumped: bool, + +} +pub fn read() -> FrameReport { + FrameReport { moving: present_moving(), page_moving: page_moving(), + page_layout_moving: page_layout_moving(), jumped: JUMPED.get(), page_jumped: PAGE_JUMPED.get() } +} +/// Main-thread runner boundary for motion only. Content damage and its provenance +/// belong to the addressed Present, never to this frame collector. +pub fn collect_into(present: &mut crate::present::Present, tick_ms: u32) { + present.collect(tick_ms, read()); +} +pub fn frame_begin(dt: f32) { frame_begin_judging_rest_with(dt, dt); } +pub fn frame_begin_judging_rest_with(dt: f32, rest_dt: f32) { + MOVING.set(false); + PAGE_MOVING.set(false); + PAGE_LAYOUT_MOVING.set(false); + JUMPED.set(false); + PAGE_JUMPED.set(false); + + DT.set(rest_dt); + CLOCK_US.set(CLOCK_US.get().wrapping_add((dt * 1_000_000.0).round().max(0.0) as u64)); +} +pub fn now_ms() -> u32 { (CLOCK_US.get() / 1000) as u32 } +pub fn settled(pos: f32, target: f32, vel: f32) -> bool { + let dt = DT.get(); + // Invalid arithmetic must never make a visibly broken animation look quiet. + pos.is_finite() && target.is_finite() && vel.is_finite() && dt.is_finite() + && !super::moving(pos, target, vel, dt) +} +pub fn note_spring(pos: f32, target: f32, vel: f32) { + if !settled(pos, target, vel) { merge_motion(); } +} +pub fn note_motion() { + if page_frozen() { return; } + #[cfg(any(test, feature = "test-support"))] + LOCAL_MOTION.set(LOCAL_MOTION.get().wrapping_add(1)); + merge_motion(); +} +/// A frame of a paused animation still needs its clock sampled, but no pixel is moving. +/// Unlike the worker door this request belongs only to this captured frame report. +pub fn note_wait() { + // The animation's clock is running even while its pixels hold. This is a + // frame-captured animation report, not a pending wake mailbox or content damage. + if !page_frozen() { MOVING.set(true); } +} +fn merge_motion() { + if page_frozen() { return; } + MOVING.set(true); + if DEPTH.get() == 0 { + PAGE_MOVING.set(true); + if DECOR.get() == 0 { PAGE_LAYOUT_MOVING.set(true); } + } +} +pub fn present_moving() -> bool { MOVING.get() } +pub fn page_moving() -> bool { PAGE_MOVING.get() } +pub fn page_layout_moving() -> bool { PAGE_LAYOUT_MOVING.get() } +pub fn decorative(f: impl FnOnce() -> T) -> T { + struct Guard; + impl Drop for Guard { fn drop(&mut self) { DECOR.set(DECOR.get().saturating_sub(1)); } } + DECOR.set(DECOR.get() + 1); + let _guard = Guard; + f() +} +pub struct MotionScope { before: bool, open: bool } +impl MotionScope { + pub fn open() -> Self { + DEPTH.set(DEPTH.get() + 1); + Self { before: MOVING.replace(false), open: true } + } + fn merge(&mut self) -> bool { + if !self.open { return false; } + self.open = false; + DEPTH.set(DEPTH.get().saturating_sub(1)); + let moving = MOVING.get(); + MOVING.set(self.before || moving); + moving + } + pub fn close(mut self) -> bool { self.merge() } +} +impl Drop for MotionScope { fn drop(&mut self) { self.merge(); } } +pub fn scoped_motion(f: impl FnOnce() -> T) -> (T, bool) { + let scope = MotionScope::open(); + let result = f(); + (result, scope.close()) +} +pub fn set_page_frozen(on: bool) -> bool { FROZEN.replace(on) } +pub fn page_frozen() -> bool { FROZEN.get() } +/// A discontinuous spring move is motion too; this is not content damage. +pub fn note_jump(changed: bool) { + if !changed || page_frozen() { return; } + #[cfg(any(test, feature = "test-support"))] + LOCAL_MOTION.set(LOCAL_MOTION.get().wrapping_add(1)); + JUMPED.set(true); + if DEPTH.get() == 0 { PAGE_JUMPED.set(true); } +} + +#[cfg(any(test, feature = "test-support"))] +pub fn take_local_motion() -> u32 { LOCAL_MOTION.replace(0) } +#[cfg(any(test, feature = "test-support"))] +pub fn reset_for_test() { + frame_begin(1.0 / 60.0); + FROZEN.set(false); + LOCAL_MOTION.set(0); +} diff --git a/rust-modules/machine/src/motion/report_tests.rs b/rust-modules/machine/src/motion/report_tests.rs new file mode 100644 index 0000000000..d5e5e1140a --- /dev/null +++ b/rust-modules/machine/src/motion/report_tests.rs @@ -0,0 +1,116 @@ +use super::report::*; + +#[test] +fn surface_and_decorative_motion_do_not_move_page_layout() { + frame_begin(1.0 / 60.0); + let scope = MotionScope::open(); + note_motion(); + assert!(scope.close()); + assert!(present_moving()); + assert!(!page_moving()); + assert!(!page_layout_moving()); + frame_begin(1.0 / 60.0); + decorative(note_motion); + assert!(page_moving()); + assert!(!page_layout_moving()); + note_motion(); + assert!(page_layout_moving()); +} + +#[test] +fn dropped_and_nested_scopes_restore_attribution() { + frame_begin(1.0 / 60.0); + { + let _outer = MotionScope::open(); + let _inner = MotionScope::open(); + note_motion(); + } + assert!(!page_moving()); + note_motion(); + assert!(page_moving()); +} + +#[test] +fn velocity_is_judged_by_visible_frame_travel() { + frame_begin(1.0 / 60.0); + assert!(settled(1000.0, 1000.0, 1.0)); + assert!(!settled(1000.0, 1000.0, 100.0)); + assert!(!settled(1000.0, 1000.3, 0.0)); + frame_begin_judging_rest_with(0.0, 1.0 / 60.0); + assert!(!settled(1000.0, 1000.0, 100.0)); +} + +#[test] +fn scoped_damage_preserves_concurrent_page_damage() { + let _guard = plx_base::testlock::serial(); + use crate::present::{Present, PresentEvent, Provenance, Scope}; + reset_for_test(); + let mut present = Present::new(); + present.take(0); + present.acknowledge(0); + present.note_in_scope(Scope::Surface, PresentEvent::Damage(Provenance::Input)); + assert!(!present.page_damaged()); + present.note_in_scope(Scope::Surface, PresentEvent::Damage(Provenance::Input)); + present.note_in_scope(Scope::Page, PresentEvent::Damage(Provenance::Lifecycle)); + assert!(present.page_damaged()); + present.take(1); + present.acknowledge(1); + assert!(!present.page_damaged()); +} + +#[test] +fn frozen_draw_reports_are_ignored_but_worker_landings_survive() { + let _guard = plx_base::testlock::serial(); + reset_for_test(); + use crate::present::{Present, PresentEvent, Provenance}; + let mut present = Present::global(); + present.take(0); + present.acknowledge(0); + set_page_frozen(true); + note_motion(); + assert_eq!(take_local_motion(), 0); + std::thread::spawn(crate::present::wake_from_worker).join().unwrap(); + assert!(present.changed(), "worker completion wakes scheduling despite a frozen decoration"); + assert!(!present.page_damaged(), "workers cannot assert UI provenance"); + present.note(PresentEvent::Damage(Provenance::Lifecycle)); + assert!(present.page_damaged(), "the runner's typed landing is not suppressed by draw freeze"); + set_page_frozen(false); +} + +#[test] +fn captured_draw_motion_survives_actual_swap_acknowledgement() { + use crate::present::Present; + reset_for_test(); + let mut present = Present::new(); + collect_into(&mut present, 0); + assert!(present.take(0)); + note_motion(); + collect_into(&mut present, 0); // visible draw's reports land before swap acknowledgement + assert!(present.changed_after_admission()); + present.acknowledge(0); + frame_begin(1.0 / 60.0); + assert!(present.changed(), "frame reset cannot erase already-owned draw motion"); + assert!(present.page_moving()); + assert!(!present.page_damaged(), "animation never fabricates content provenance"); + assert!(present.take(16)); +} + +#[test] +fn draw_damage_survives_owner_admission_and_swap() { + use crate::present::Present; + let _guard = plx_base::testlock::serial(); + reset_for_test(); + let mut present = Present::new(); + collect_into(&mut present, 0); + assert!(present.take(0)); + present.note(crate::present::PresentEvent::Damage(crate::present::Provenance::Input)); + present.acknowledge(0); + collect_into(&mut present, 1); + assert!(present.take(1)); + assert!(present.page_damaged()); + assert!(present.page_damaged(), "frame readout is stable across consumers"); + present.acknowledge(1); + collect_into(&mut present, 2); + assert!(!present.peek(2)); + assert!(!present.page_damaged()); +} diff --git a/rust-modules/machine/src/present.rs b/rust-modules/machine/src/present.rs index 1eccd8a1a9..0c4c8c940c 100644 --- a/rust-modules/machine/src/present.rs +++ b/rust-modules/machine/src/present.rs @@ -1,40 +1,34 @@ -//! The present gate as a MACHINE with an owner (spec §4.4). `Present` is an `App` field with one -//! typed entrance on the main thread — `note(PresentEvent)`, reached through `PresentHandle` — and -//! one per-frame question, `take(tick)`, asked exactly once at §3.3 step 8. Workers get exactly -//! one documented atomic door (`wake_from_worker`, phase 2); nothing else touches the atomics. -//! -//! Phase 2-i: the logical half only. `machine/src/idle.rs` stays the product's gate until phase 2 swaps -//! this in under it; the two agree on the one behaviour a test can pin — a settled screen stops -//! presenting and the keepalive bounds staleness. -#![allow(dead_code)] // phase 2-i: no consumer until phase 2 (spec §13) - -use std::sync::atomic::{AtomicBool, Ordering}; +//! Dispatcher-owned present admission and actual-swap accounting. +//! Admission is observational: pending damage and worker wakes survive a skipped swap. +//! Acknowledgement retires only the generations captured before prepare/draw. + + +use std::sync::atomic::{AtomicU32, Ordering}; use super::machine::{MachineId, TimerId}; /// The ONE worker-side door (spec §4.4): a poster decode completing, the lab uploader — anything -/// off the main thread that needs the next frame to present. It is a flag, not an event: the -/// main thread's `take` folds it into the frame's verdict as `Damage` with no provenance of its -/// own, because a worker cannot say which machine it woke on behalf of. Nothing else touches -/// the atomic (`ci/check-deps.sh` gates `present::` atomics to this file). -static WAKE: AtomicBool = AtomicBool::new(false); +/// off the main thread that needs the next frame to present. Its generation requests +/// scheduling, never content damage. Admission snapshots it; actual-swap acknowledgement +/// retires only that generation, so a wake racing prepare/draw survives for another frame. +static WAKE: AtomicU32 = AtomicU32::new(0); /// Wake the gate from a worker thread. Safe to call from any thread, any number of times. pub fn wake_from_worker() { - WAKE.store(true, Ordering::Release); + WAKE.fetch_add(1, Ordering::Release); } /// Test seam: a wake left by a test must not leak into the next. #[cfg(test)] fn clear_worker_wake() { - WAKE.store(false, Ordering::Release); + WAKE.store(0, Ordering::Release); } impl Present { /// The product's gate, on the GLOBAL door. `new()` under `cfg(test)` hands out a private door /// so parallel tests cannot wake each other's gates; the one test of the door itself asks for /// this. - #[cfg(test)] + #[cfg(any(test, feature = "test-support"))] pub fn global() -> Self { let mut p = Self::new(); p.door = &WAKE; @@ -68,6 +62,8 @@ pub enum Fault { pub enum PresentEvent { Damage(Provenance), Motion, + /// Owned main-thread scheduling demand: no content provenance or page motion. + Wake, /// An INPUT to the gate from `Player.video_plane_bound`; the gate's state has no other writer. VideoPlane(bool), Fault(Fault), @@ -89,16 +85,28 @@ pub enum Scope { pub struct Present { dirty: bool, motion: bool, - /// Motion reported under `Scope::Page` since the last take. + /// Page motion not yet acknowledged by an actual swap. page_motion: bool, scope: Scope, video_plane: bool, fault: Option, last_present_ms: u32, - /// The provenance of the first damage since the last take — what the recorder writes. + /// First unacknowledged damage provenance — what the recorder writes. why: Option, /// The worker door this gate reads (`WAKE`, or a private flag in a test). - door: &'static AtomicBool, + door: &'static AtomicU32, + wake_seen: u32, + damage_generation: u64, + motion_generation: u64, + page_motion_generation: u64, + page_damage_generation: u64, + page_damage_acknowledged: u64, + admitted: Option<(u64, u64, u64, u64, u32)>, + after_admission: Option, + enabled: bool, + was_moving: bool, + presents: u32, + last_change_ms: u32, } impl Default for Present { @@ -118,6 +126,18 @@ impl Present { fault: None, last_present_ms: 0, why: None, + wake_seen: 0, + damage_generation: 0, + motion_generation: 0, + page_motion_generation: 0, + page_damage_generation: 0, + page_damage_acknowledged: 0, + admitted: None, + after_admission: None, + enabled: true, + was_moving: false, + presents: 0, + last_change_ms: 0, // a test's gate reads a PRIVATE door: tests run in parallel, and one wake must not // present a frame in another test's dispatcher (`global()` is the exception) // (`test-support` is how a dependent's tests, which build this crate without @@ -125,60 +145,149 @@ impl Present { #[cfg(not(any(test, feature = "test-support")))] door: &WAKE, #[cfg(any(test, feature = "test-support"))] - door: Box::leak(Box::new(AtomicBool::new(false))), + door: Box::leak(Box::new(AtomicU32::new(0))), } } + /// Apply one addressed effect without changing attribution of subsequent work. + pub fn note_in_scope(&mut self, scope: Scope, ev: PresentEvent) { + let previous = self.scope; + self.scope = scope; + self.note(ev); + self.scope = previous; + } + pub fn note(&mut self, ev: PresentEvent) { match ev { - PresentEvent::Damage(p) => { - self.dirty = true; - if self.why.is_none() { - self.why = Some(p); - } - } + PresentEvent::Damage(p) => self.damage(p, self.scope == Scope::Page), PresentEvent::Motion => { + self.motion_generation = self.motion_generation.wrapping_add(1); self.motion = true; if self.scope == Scope::Page { + self.page_motion_generation = self.page_motion_generation.wrapping_add(1); self.page_motion = true; } } - PresentEvent::VideoPlane(b) => self.video_plane = b, - PresentEvent::Fault(f) => self.fault = Some(f), + PresentEvent::Wake => { + // Pending scheduling uses the same admission-protected generation, but + // never page generations, content provenance or motion continuation. + self.motion_generation = self.motion_generation.wrapping_add(1); + self.motion = true; + } + PresentEvent::VideoPlane(b) => { + if self.video_plane != b { + self.video_plane = b; + self.note(PresentEvent::Damage(Provenance::Lifecycle)); + } + } + PresentEvent::Fault(f) => { + self.fault = Some(f); + self.note(PresentEvent::Damage(Provenance::Lifecycle)); + } + } + } + + fn damage(&mut self, p: Provenance, page: bool) { + if self.admitted.is_some() && self.after_admission.is_none() { + self.after_admission = Some(p); } + self.damage_generation = self.damage_generation.wrapping_add(1); + if page { self.page_damage_generation = self.page_damage_generation.wrapping_add(1); } + self.dirty = true; + if self.why.is_none() { self.why = Some(p); } + } + + /// Typed page damage not yet represented by an acknowledged swap. Surface-only + /// damage never changes this readout, even when it selects the same frame. + pub fn page_damaged(&self) -> bool { + self.page_damage_generation != self.page_damage_acknowledged } - /// Side-effect-free: did anything CHANGE since the last take — damage, motion or a worker's + /// Read-only epochs for instrumentation; observations never consume pending damage. + pub fn damage_epoch(&self) -> u64 { self.damage_generation } + pub fn page_damage_epoch(&self) -> u64 { self.page_damage_generation } + + /// Side-effect-free: is there unacknowledged CHANGE — damage, motion or a worker's /// wake? `peek` without its two unconditional terms (the bound video plane and the keepalive), /// which present a frame without anything on it having moved. pub fn changed(&self) -> bool { - self.dirty || self.motion || self.door.load(Ordering::Acquire) + self.dirty || self.motion || self.door.load(Ordering::Acquire) != self.wake_seen } /// Side-effect-free: what `take` would answer (the worker door included, un-consumed). pub fn peek(&self, tick_ms: u32) -> bool { - self.video_plane + !self.enabled + || self.video_plane || self.dirty || self.motion - || self.door.load(Ordering::Acquire) + || self.door.load(Ordering::Acquire) != self.wake_seen || tick_ms.wrapping_sub(self.last_present_ms) >= KEEPALIVE_MS } - /// The take-and-clear, once per frame (§3.3 step 8). Answers `true` unconditionally while the - /// video plane is bound. Consumes the worker door. + /// Admit before prepare/draw. Does not consume pending work or advance the clock. + /// Call even for budget-only frames, so their eventual swap has a matching snapshot. pub fn take(&mut self, tick_ms: u32) -> bool { let will = self.peek(tick_ms); - self.door.swap(false, Ordering::AcqRel); - self.dirty = false; - self.motion = false; - self.page_motion = false; - self.why = None; - if will { - self.last_present_ms = tick_ms; - } + self.after_admission = None; + self.admitted = Some((self.damage_generation, self.motion_generation, + self.page_motion_generation, self.page_damage_generation, self.door.load(Ordering::Acquire))); will } + /// Read-only post-draw validation. A pre-admission scheduling request (for example + /// a screenshot's own Wake) is not new work; damage/motion/wakes raised by draw are. + /// No admission snapshot is conservatively busy. + pub fn changed_after_admission(&self) -> bool { + self.admitted != Some((self.damage_generation, self.motion_generation, + self.page_motion_generation, self.page_damage_generation, self.door.load(Ordering::Acquire))) + } + + /// A real swap completed. Damage and wakes arriving after admission remain pending. + pub fn acknowledge(&mut self, tick_ms: u32) { + let Some((damage, motion, page, page_damage, wake)) = self.admitted.take() else { return }; + if damage == self.damage_generation { + self.dirty = false; + self.why = None; + } else { + self.why = self.after_admission.take(); + } + if motion == self.motion_generation { self.motion = false; } + if page == self.page_motion_generation { self.page_motion = false; } + self.page_damage_acknowledged = page_damage; + self.wake_seen = wake; + self.last_present_ms = tick_ms; + self.presents = self.presents.wrapping_add(1); + } + + pub fn set_enabled(&mut self, enabled: bool) { self.enabled = enabled; } + pub fn enabled(&self) -> bool { self.enabled } + pub fn take_presents(&mut self) -> u32 { std::mem::take(&mut self.presents) } + pub fn last_change_ms(&self) -> u32 { self.last_change_ms } + + /// Merge only frame-captured motion. Content damage must arrive through a typed + /// owned handle at its input, effect or result-landing boundary. + pub fn collect(&mut self, tick_ms: u32, frame: crate::motion::report::FrameReport) { + if frame.jumped { + self.note_in_scope(if frame.page_jumped { Scope::Page } else { Scope::Surface }, PresentEvent::Motion); + } + + self.report_motion(frame.moving, frame.page_moving); + if self.changed() { self.last_change_ms = tick_ms; } + } + + /// Merge the explicit frame collector, including the final resting frame. + pub fn report_motion(&mut self, moving: bool, page: bool) { + if moving || self.was_moving { + self.motion_generation = self.motion_generation.wrapping_add(1); + self.motion = true; + if page { + self.page_motion_generation = self.page_motion_generation.wrapping_add(1); + self.page_motion = true; + } + } + self.was_moving = moving; + } + pub fn video_plane(&self) -> bool { self.video_plane } @@ -188,7 +297,7 @@ impl Present { self.scope = scope; } - /// Did the PAGE move since the last take (the host-snapshot question)? Cleared by `take`. + /// Unacknowledged PAGE motion (the host-snapshot question), independent of surface motion. pub fn page_moving(&self) -> bool { self.page_motion } @@ -205,6 +314,44 @@ impl Present { #[cfg(test)] mod tests { + fn swap(p: &mut super::Present, tick: u32) -> bool { + let admitted = p.take(tick); + if admitted { p.acknowledge(tick); } + admitted + } + #[test] + fn skipped_swap_keeps_damage_pending() { + use super::{Present, PresentEvent, Provenance}; + + let mut present = Present::new(); + assert!(swap(&mut present, 0)); + present.note(PresentEvent::Damage(Provenance::Input)); + assert!(present.take(1), "admission should request a frame"); + // A suspended surface or unavailable backbuffer can prevent the swap after admission. + assert!(present.peek(2), "damage must survive an unpresented frame"); + assert_eq!(present.why(), Some(Provenance::Input)); + } + + #[test] + fn skipped_swap_does_not_advance_keepalive_clock() { + let mut present = super::Present::new(); + assert!(swap(&mut present, 0)); + present.note(super::PresentEvent::Damage(super::Provenance::Input)); + assert!(present.take(100), "admission should request a frame"); + assert!(present.peek(super::KEEPALIVE_MS), "a skipped swap must not advance the present clock"); + } + + #[test] + fn skipped_swap_keeps_worker_wake_pending() { + use std::sync::atomic::Ordering; + + let mut present = super::Present::new(); + assert!(swap(&mut present, 0), "the initial frame is presented"); + present.door.fetch_add(1, Ordering::Release); + assert!(present.take(1), "the worker wake admits a frame"); + assert!(present.peek(2), "a skipped swap must not consume the wake"); + } + /// Spec §15.1: a worker reaches the gate through `wake_from_worker` and nothing else; the /// main thread's `take` consumes the wake exactly once. #[test] @@ -212,30 +359,127 @@ mod tests { let _g = plx_base::testlock::serial(); super::clear_worker_wake(); let mut p = super::Present::global(); - assert!(p.take(0), "the first frame always draws"); - assert!(!p.take(1), "settled, inside the keepalive: nothing to present"); + assert!(swap(&mut p, 0), "the first frame always draws"); + assert!(!swap(&mut p, 1), "settled, inside the keepalive: nothing to present"); std::thread::spawn(super::wake_from_worker).join().unwrap(); assert!(p.peek(2), "the door is visible to peek"); - assert!(p.take(2), "…and folded into the frame's verdict"); - assert!(!p.take(3), "consumed exactly once"); + assert!(swap(&mut p, 2), "…and folded into the frame's verdict"); + assert!(!swap(&mut p, 3), "consumed exactly once"); // a second wake is a second frame, not a lost one super::wake_from_worker(); - assert!(p.take(4)); - assert!(!p.take(5)); + assert!(swap(&mut p, 4)); + assert!(!swap(&mut p, 5)); } use super::*; + #[test] + fn owned_handles_keep_page_and_surface_damage_independent_through_swap() { + use crate::machine::PresentHandle; + let mut a = Present::new(); + let mut b = Present::new(); + assert!(swap(&mut a, 0)); + assert!(swap(&mut b, 0)); + a.set_scope(Scope::Surface); + PresentHandle::of(&mut a).note(PresentEvent::Damage(Provenance::Input)); + assert!(a.changed()); + assert!(!a.page_damaged()); + assert!(!b.changed()); + assert!(a.take(16)); + a.set_scope(Scope::Page); + PresentHandle::of(&mut a).note(PresentEvent::Damage(Provenance::Resource(ResourceKind::Texture))); + a.acknowledge(16); + assert!(a.page_damaged(), "draw-phase damage outlives acknowledgement of admission"); + assert_eq!(a.why(), Some(Provenance::Resource(ResourceKind::Texture))); + assert!(!b.page_damaged()); + assert!(!b.changed()); + assert!(swap(&mut a, 32)); + assert!(!a.changed()); + assert!(!a.page_damaged()); + } + + #[test] + fn an_owned_wake_is_isolated_and_survives_a_late_draw_without_ui_provenance() { + let mut a = Present::new(); + let mut b = Present::new(); + assert!(swap(&mut a, 0)); + assert!(swap(&mut b, 0)); + a.note(PresentEvent::Wake); + assert!(a.take(16)); + assert!(!a.changed_after_admission(), "the owner's pre-admission wake is not late draw work"); + assert!(!a.page_damaged()); + assert!(!a.page_moving()); + assert_eq!(a.why(), None); + assert!(!b.changed()); + a.note(PresentEvent::Wake); + assert!(a.changed_after_admission(), "late owned scheduling is observable before ack"); + a.acknowledge(16); + assert!(a.changed(), "a scheduling request during draw survives actual swap"); + assert!(!a.page_moving()); + assert!(swap(&mut a, 32)); + assert!(!a.changed()); + assert!(!b.changed()); + } + + #[test] + fn independent_gates_keep_damage_and_motion_separate() { + let mut a = Present::new(); + let mut b = Present::new(); + assert!(swap(&mut a, 0)); + assert!(swap(&mut b, 0)); + a.note(PresentEvent::Damage(Provenance::Input)); + assert!(a.peek(1)); + assert!(!b.peek(1)); + a.set_scope(Scope::Surface); + a.note(PresentEvent::Motion); + assert!(!a.page_moving()); + a.set_scope(Scope::Page); + a.note(PresentEvent::Motion); + assert!(a.page_moving()); + assert!(!b.changed()); + } + + #[test] + fn skipped_admission_preserves_damage_and_actual_present_clock() { + let mut p = Present::new(); + assert!(swap(&mut p, 0)); + p.note(PresentEvent::Damage(Provenance::Input)); + assert!(p.peek(100), "admit a frame that cannot swap yet"); + assert!(p.changed(), "admission must not consume pending damage"); + assert_eq!(p.why(), Some(Provenance::Input)); + assert!(p.peek(200), "the skipped frame remains pending"); + assert!(swap(&mut p, 200), "the eventual swap consumes the damage"); + assert!(!p.peek(KEEPALIVE_MS), "keepalive starts at the actual swap"); + assert!(p.peek(200 + KEEPALIVE_MS)); + } + + #[test] + fn acknowledgement_preserves_damage_and_wake_raised_after_admission() { + let mut p = Present::new(); + assert!(swap(&mut p, 0)); + p.note(PresentEvent::Damage(Provenance::Input)); + assert!(p.take(100)); + p.note(PresentEvent::Damage(Provenance::Nav)); + p.door.fetch_add(1, Ordering::Release); + p.acknowledge(100); + assert!(p.changed()); + assert_eq!(p.why(), Some(Provenance::Nav)); + assert!(swap(&mut p, 101)); + assert!(!p.changed()); + assert!(!p.peek(KEEPALIVE_MS)); + assert!(p.peek(101 + KEEPALIVE_MS)); + } + #[test] fn a_settled_gate_stops_presenting_and_the_keepalive_bounds_staleness() { let mut p = Present::new(); - assert!(p.take(0), "the first frame draws"); - assert!(!p.take(16), "nothing happened: no present"); + assert!(swap(&mut p, 0), "the first frame draws"); + assert!(!swap(&mut p, 16), "nothing happened: no present"); p.note(PresentEvent::Damage(Provenance::Input)); assert_eq!(p.why(), Some(Provenance::Input)); - assert!(p.take(32)); - assert!(!p.take(48)); - assert!(p.take(48 + KEEPALIVE_MS), "the keepalive"); + assert!(swap(&mut p, 32)); + assert!(!swap(&mut p, 48)); + assert!(swap(&mut p, 48 + KEEPALIVE_MS), "the keepalive"); p.note(PresentEvent::VideoPlane(true)); assert!(p.take(3000) && p.take(3016), "bound plane: every frame"); } diff --git a/rust-modules/machine/src/present_contract_tests.rs b/rust-modules/machine/src/present_contract_tests.rs new file mode 100644 index 0000000000..9daf3c3527 --- /dev/null +++ b/rust-modules/machine/src/present_contract_tests.rs @@ -0,0 +1,83 @@ +use super::present::*; + +fn swap(p: &mut Present, now: u32) -> bool { + let demand = p.take(now); + if demand { p.acknowledge(now); } + demand +} +#[test] +fn video_plane_edges_have_one_recipient_and_unbind_paints_once() { + let mut p = Present::new(); + swap(&mut p, 0); + p.note(PresentEvent::VideoPlane(true)); + assert!(swap(&mut p, 16)); + assert!(swap(&mut p, 32)); + p.note(PresentEvent::VideoPlane(false)); + assert!(swap(&mut p, 48)); + assert!(!p.peek(64)); +} +#[test] +fn noidle_is_rate_only_and_damage_raised_during_draw_survives() { + let mut p = Present::new(); + swap(&mut p, 0); + p.set_enabled(false); + assert!(p.take(1)); + p.note(PresentEvent::Damage(Provenance::Input)); + p.acknowledge(1); + p.set_enabled(true); + assert!(swap(&mut p, 2)); + assert_eq!(p.take_presents(), 3); + assert!(!p.peek(3)); +} +#[test] +fn one_resting_frame_follows_motion_without_moving_the_page_snapshot() { + let mut p = Present::new(); + swap(&mut p, 0); + p.report_motion(true, false); + assert!(!p.page_moving()); + assert!(swap(&mut p, 16)); + p.report_motion(false, false); + assert!(swap(&mut p, 32)); + assert!(!p.page_moving()); + p.report_motion(false, false); + assert!(!p.peek(48)); +} +#[test] +fn actual_present_keepalive_handles_tick_wrap() { + let mut p = Present::new(); + swap(&mut p, u32::MAX - 100); + assert!(!p.peek(100)); + assert!(p.peek(KEEPALIVE_MS)); + assert_eq!(p.take_presents(), 1); + assert!(p.take(KEEPALIVE_MS)); + assert_eq!(p.take_presents(), 0, "admission is not a swap"); +} +#[test] +fn newer_surface_motion_does_not_keep_acknowledged_page_motion_alive() { + let mut p = Present::new(); + swap(&mut p, 0); + p.note(PresentEvent::Motion); + assert!(p.page_moving()); + p.take(1); + p.set_scope(Scope::Surface); + p.note(PresentEvent::Motion); + p.acknowledge(1); + assert!(p.changed(), "new surface motion remains pending"); + assert!(!p.page_moving(), "only the page generation was acknowledged"); +} +#[test] +fn skipped_admission_preserves_first_provenance_until_actual_ack() { + let mut p = Present::new(); + swap(&mut p, 0); + p.note(PresentEvent::Damage(Provenance::Input)); + p.take(1); + p.note(PresentEvent::Damage(Provenance::Nav)); + assert_eq!(p.why(), Some(Provenance::Input)); + // This admission never swapped: admitting again must not drop its older cause. + p.take(2); + assert_eq!(p.why(), Some(Provenance::Input)); + p.note(PresentEvent::Damage(Provenance::Lifecycle)); + p.acknowledge(2); + assert_eq!(p.why(), Some(Provenance::Lifecycle)); + assert!(p.peek(3)); +} diff --git a/rust-modules/media/src/player/ass_source.rs b/rust-modules/media/src/player/ass_source.rs index cf817f648d..e3f3cfadc8 100644 --- a/rust-modules/media/src/player/ass_source.rs +++ b/rust-modules/media/src/player/ass_source.rs @@ -1259,18 +1259,24 @@ mod tests { fn a_backward_seek_after_a_deep_read_keeps_the_events_at_the_target() { let mut s = Store::new(); let g = s.begin("fixture", vec![(0, TrackHeader::Authored(b"header".to_vec()))], vec![]); - // A typeset-heavy file read 30 000 events in; the window holds the latest 8 192. - for n in 0..30_000 { + // A typeset-heavy file read past the window: the window holds the latest 8 192, and every + // event the file has to give is behind its first one. (A push copies and ranks the whole + // window, so reading further than this only repeats the same eviction at a quadratic cost; + // the 30 000 events this once read held the identical 8 192 latest at the seek.) + let read = MAX_EVENTS as i64 + 300; + for n in 0..read { s.push(g, 0, timed(n), 0); } - // The viewer rewinds to event 10 000 (the floor follows the rebased clock). + assert_eq!(embedded(&s, 0).len(), MAX_EVENTS, "the window is full"); + // The viewer rewinds to event 100, more than `STALE_AHEAD_MS` behind everything the window + // holds (the floor follows the rebased clock). s.seek(g); - let floor_ms = 10_000_000 - 62_000; - for n in 10_000..10_100 { + let floor_ms = 100_000 - 62_000; + for n in 100..200 { s.push(g, 0, timed(n), floor_ms); } let held = embedded(&s, 0); - for n in 10_000..10_100 { + for n in 100..200 { assert!(held.contains(&timed(n)), "event {n} at the seek target was lost"); } assert!(held.len() <= 8192); diff --git a/rust-modules/media/src/player/machine.rs b/rust-modules/media/src/player/machine.rs index e4f4ff31d1..110af56bbc 100644 --- a/rust-modules/media/src/player/machine.rs +++ b/rust-modules/media/src/player/machine.rs @@ -90,8 +90,8 @@ impl Player { /// formula term feeding it — exactly the risk the spec names, where the gate and the machine /// come to disagree about which frame the plane went away on and the false edge lands on a /// frame that was never presented. - /// `Some(bound)` when this was an EDGE — the loop forwards that, and only that, to the two - /// `plx_machine::present::Present` machines it owns beside the live gate. + /// `Some(bound)` when this was an EDGE — the loop forwards that, and only that, to the one runtime-owned + /// `plx_machine::present::Present` gate. pub fn set_video_plane_bound(&mut self, bound: bool) -> Option { if self.video_plane_bound == bound { return None; @@ -105,14 +105,10 @@ impl Player { } else { "videoplane: unbound — ordinary idle rules from here" }); - plx_machine::idle::note(plx_machine::present::PresentEvent::VideoPlane(bound)); - // The FALSE edge has to reach the panel, and the frame it lands on is very often one the - // gate would otherwise skip — the picture is gone and nothing is animating (spec §3.3 - // step 9). `invalidate` is what makes that frame present, so the opaque region is really - // cleared and the UI surface really goes back to being blended. - if !bound { - plx_machine::idle::invalidate(); - } + + // The runner forwards this explicit edge as PresentEvent::VideoPlane. Both edges owe + // a surface frame (including clearing the opaque region on false); no global damage. + Some(bound) } diff --git a/rust-modules/media/src/player/mod.rs b/rust-modules/media/src/player/mod.rs index c516177c18..3fba8cfd89 100644 --- a/rust-modules/media/src/player/mod.rs +++ b/rust-modules/media/src/player/mod.rs @@ -1492,7 +1492,8 @@ pub(crate) fn note_server_stop(playback: &str, wire_session: &str, reason: &str, }; SHARED.server_stopped.store(true, std::sync::atomic::Ordering::Release); } - plx_machine::idle::invalidate(); + // The addressed server-stop note is observed by the foreground runner; no UI provenance + // is published by this notification worker. } fn with_server_stop(playback: &str, read: impl FnOnce(&ServerStopNote) -> T) -> Option { @@ -2547,8 +2548,7 @@ pub fn set_audio_enhancements(a: plx_plex::plex::AudioEnhancements) { pub fn request_audio_enhancement(ps: &mut crate::route::PlaybackSession, a: plx_plex::plex::AudioEnhancements) { set_audio_enhancements(a); crate::route::reconcile_enhancement(ps, false); - // the rows' checkmarks move on this — see `route::choose` - plx_machine::idle::invalidate(); + // The input owner repaints the rows; route::preference_values observes confirmed writes. } /// Restore the persisted preference without writing it back (what `route::restore_profile_rows` @@ -2570,7 +2570,7 @@ pub fn set_subtitle_tone(tone: plx_plex::plex::session::SubtitleTone) { /// (`route::persist_subtitle_offset`) — see [`SUBTITLE_OFFSET_MS`]. pub fn set_subtitle_offset(offset_ms: i64) { SUBTITLE_OFFSET_MS.store(clamp_subtitle_offset_ms(offset_ms), Relaxed); - plx_machine::idle::invalidate(); + // The input owner repaints the subtitle controls; no ambient damage side effect. } /// Carry a retry's offset through [`reset_subtitle`] (`route::reset_track_selection`). The diff --git a/rust-modules/media/src/player/preview.rs b/rust-modules/media/src/player/preview.rs index d0e25fc9ef..05ae579078 100644 --- a/rust-modules/media/src/player/preview.rs +++ b/rust-modules/media/src/player/preview.rs @@ -47,6 +47,7 @@ //! admitted Loads, under the ratio rather than on it. Do not quote 14 as a television result. use plx_plex::plex::ServerId; +use plx_telemetry::telemetry::classes::PreviewRefusal; /// Admitted Loads per process, from the source arithmetic above. Not a device measurement. pub const CYCLE_BUDGET: u32 = 14; @@ -437,6 +438,37 @@ pub fn accepts_direct_play(direct_play: bool, part_nonempty: bool, adaptive: boo direct_play && part_nonempty && !adaptive } +/// **Which condition refused a preview** (Sentry PLX-NATIVE-23), or `None` when +/// [`accepts_direct_play`] accepts it. The first failing condition, in this fixed order: +/// +/// 1. no part: [`PreviewRefusal::NoPart`]; +/// 2. `direct_play_offered` was false: [`PreviewRefusal::NotDirect`]; +/// 3. a direct play WAS on offer and `adaptive` (Auto chose HLS) is what refused it: +/// [`PreviewRefusal::Adaptive`]; +/// 4. anything else, a late demotion such as an enhancement's remux: [`PreviewRefusal::NotDirect`]. +/// +/// `direct_play_offered` is the route's direct-play answer BEFORE Auto's override, not the +/// `direct_play` the gate sees: Auto sets that false whenever it picks HLS, so reading the reason +/// off the gate's own inputs would call every Auto-quality refusal `adaptive`, including a preview +/// the server would have transcoded anyway. +pub fn refusal( + direct_play: bool, + direct_play_offered: bool, + part_nonempty: bool, + adaptive: bool, +) -> Option { + if accepts_direct_play(direct_play, part_nonempty, adaptive) { + return None; + } + Some(if !part_nonempty { + PreviewRefusal::NoPart + } else if direct_play_offered && adaptive { + PreviewRefusal::Adaptive + } else { + PreviewRefusal::NotDirect + }) +} + plx_base::devtrig::latched_flag!( /// `/tmp/plxnative-nopreview` — disable background trailer autoplay. Latched: `enabled()` /// runs on `preview_tick`'s every-frame path (via `blocked`) while the detail hero holds @@ -1179,6 +1211,38 @@ mod tests { assert!(!accepts_direct_play(true, false, false)); } + /// Every input combination: the reason exists exactly when the gate refuses, and names the + /// first failing condition in the documented order. `adaptive` implies a false `direct_play` + /// (Auto's override), which is why only the reachable rows are enumerated for `adaptive`. + #[test] + fn the_refusal_reason_is_the_first_failing_condition_in_a_fixed_order() { + use PreviewRefusal::{Adaptive, NoPart, NotDirect}; + for direct_play in [false, true] { + for offered in [false, true] { + for part in [false, true] { + for adaptive in [false, true] { + let got = refusal(direct_play, offered, part, adaptive); + assert_eq!(got.is_none(), accepts_direct_play(direct_play, part, adaptive), + "gate and reason disagree: dp={direct_play} offered={offered} part={part} adaptive={adaptive}"); + } + } + } + } + // 1. A missing part outranks everything, including Auto's HLS and a refused direct play. + assert_eq!(refusal(true, true, false, false), Some(NoPart)); + assert_eq!(refusal(false, true, false, true), Some(NoPart)); + assert_eq!(refusal(false, false, false, true), Some(NoPart)); + // 2. No direct play on offer before Auto chose: `not_direct`, even if Auto also went HLS. + assert_eq!(refusal(false, false, true, false), Some(NotDirect)); + assert_eq!(refusal(false, false, true, true), Some(NotDirect)); + // 3. A direct play was on offer and Auto's bandwidth decision refused it. + assert_eq!(refusal(false, true, true, true), Some(Adaptive)); + // 4. On offer, Auto kept the original, and a later demotion (an enhancement remux) refused it. + assert_eq!(refusal(false, true, true, false), Some(NotDirect)); + // None: the plain direct play a preview takes. + assert_eq!(refusal(true, true, true, false), None); + } + #[test] fn chrome_recedes_only_after_a_picture() { let mut m = Machine::default(); diff --git a/rust-modules/media/src/player/report.rs b/rust-modules/media/src/player/report.rs index 398dae28b9..c7bb724ac5 100644 --- a/rust-modules/media/src/player/report.rs +++ b/rust-modules/media/src/player/report.rs @@ -674,6 +674,7 @@ fn error_context_with_source(ps: &crate::route::PlaybackSession, http_status: HttpClass::exact_status(http_status), pipeline_error: facts.pipeline_error.unwrap_or(0), refusal, + preview_refusal: crate::route::preview_refusal(ps), }; if crate::route::preview_request(ps) { as_preview(context) @@ -1320,6 +1321,7 @@ pub fn watched_class(position_ns: i64, duration_ns: i64) -> &'static str { #[cfg(test)] mod tests { use super::*; + use plx_telemetry::telemetry::classes::PreviewRefusal; use plx_play_feed::shared::FEED_SHARED; #[test] @@ -1559,7 +1561,7 @@ mod tests { crate::route::PlayVerdict::Server(String::new(), Default::default()), crate::route::PlayVerdict::DirectPlayDisabled, crate::route::PlayVerdict::Forced(crate::route::ForcedFailure::Video), - crate::route::PlayVerdict::PreviewNeedsDirectPlay, + crate::route::PlayVerdict::PreviewNeedsDirectPlay { reason: PreviewRefusal::NotDirect }, ] { let mut ps = crate::route::PlaybackSession::default(); crate::route::refuse_for_test(&mut ps, verdict.clone()); @@ -1689,7 +1691,7 @@ mod tests { for verdict in [ crate::route::PlayVerdict::DirectPlayDisabled, crate::route::PlayVerdict::Forced(crate::route::ForcedFailure::Video), - crate::route::PlayVerdict::PreviewNeedsDirectPlay, + crate::route::PlayVerdict::PreviewNeedsDirectPlay { reason: PreviewRefusal::NotDirect }, ] { let mut ps = crate::route::PlaybackSession::default(); crate::route::refuse_for_test(&mut ps, verdict.clone()); @@ -1929,9 +1931,36 @@ mod tests { assert_eq!(v["tags"]["playback.kind"], "preview_not_direct"); assert_eq!(v["tags"]["playback.attempt_origin"], "preview"); assert_eq!(v["fingerprint"], serde_json::json!(["playback-error", "preview", "preview_not_direct"])); + // The rig's item has no Part, so the first failing condition is `no_part`. + assert_eq!(v["tags"]["playback.preview_refusal"], "no_part"); }); } + /// **Sentry PLX-NATIVE-23.** The refused preview's reason rides its report as one tag, whatever + /// the reason, and no other verdict carries one. The grouping is the kind's, as before. + #[test] + fn a_refused_previews_reason_rides_the_report_and_no_other_verdict_carries_one() { + let _g = plx_base::testlock::serial(); + for reason in PreviewRefusal::ALL { + let mut ps = crate::route::PlaybackSession::default(); + crate::route::refuse_for_test(&mut ps, crate::route::PlayVerdict::PreviewNeedsDirectPlay { reason }); + assert_eq!(error_context(&ps).preview_refusal, Some(reason)); + let v = event_for(&ps); + assert_eq!(v["tags"]["playback.kind"], "preview_not_direct", "{reason:?}"); + assert_eq!(v["tags"]["playback.preview_refusal"], reason.code(), "{reason:?}"); + } + for verdict in [ + crate::route::PlayVerdict::DirectPlayDisabled, + crate::route::PlayVerdict::Forced(crate::route::ForcedFailure::Video), + crate::route::PlayVerdict::Server("Cannot convert this item.".into(), Default::default()), + ] { + let mut ps = crate::route::PlaybackSession::default(); + crate::route::refuse_for_test(&mut ps, verdict.clone()); + assert_eq!(error_context(&ps).preview_refusal, None, "{verdict:?}"); + assert!(event_for(&ps)["tags"].get("playback.preview_refusal").is_none(), "{verdict:?}"); + } + } + /// **Sentry PLX-NATIVE-15.** A detail-page preview never passes [`requested`], so its failure /// seals a trace with no `Requested` step; it used to report kind `unspecified`, delivery /// `unknown` and the first-open defaults of whatever film played last, and landed in the diff --git a/rust-modules/media/src/route/decision.rs b/rust-modules/media/src/route/decision.rs index 350acc3219..83c29e2038 100644 --- a/rust-modules/media/src/route/decision.rs +++ b/rust-modules/media/src/route/decision.rs @@ -6937,7 +6937,15 @@ pub fn play_refused(ps: &PlaybackSession) -> bool { /// Did the resolve refuse this as a PREVIEW that was not a direct play /// ([`PlayVerdict::PreviewNeedsDirectPlay`])? Our own refusal, not the server's. pub(crate) fn play_refused_as_preview(ps: &PlaybackSession) -> bool { - matches!(ps.play_verdict, Some(PlayVerdict::PreviewNeedsDirectPlay)) + preview_refusal(ps).is_some() +} +/// Which condition refused this PREVIEW ([`PlayVerdict::PreviewNeedsDirectPlay`]'s `reason`), or +/// `None` for any other session. The failure report's `playback.preview_refusal` tag reads it. +pub(crate) fn preview_refusal(ps: &PlaybackSession) -> Option { + match ps.play_verdict { + Some(PlayVerdict::PreviewNeedsDirectPlay { reason }) => Some(reason), + _ => None, + } } /// The app/worker failed to produce a playable plan, as distinct from a PMS `/decision` refusal. /// There is no Engine whose pump could publish Error, so `player::state()` derives it beside the @@ -11646,13 +11654,9 @@ fn apply_plan(ps: &mut PlaybackSession, meta: &mut plx_data::stores::metadata::M // (`reset_track_selection`); hold it to the range of the subtitle that actually landed, so an // advance never outlives its sidecar. crate::player::reclamp_subtitle_offset(); - // A landing is a DISCRETE change to what is on screen, so it owes the present gate a poke — - // `plx_machine::idle::invalidate`'s call-site list is that module's correctness argument. The caller - // (`app.rs`'s pump) invalidates only when `pump_play` returns TRUE, and a REFUSING plan returns - // false by construction (empty url) while flipping the player from Resolving to Error. That it - // still repainted was an accident of the player route bypassing the gate entirely; here it is - // the rule instead. - plx_machine::idle::invalidate(); + // pump_play returns Some(ResolvedStart) for accepted AND refusing plans. The main-thread + // runner owns the landing damage, even when this start contract is None (the Error page). + start } diff --git a/rust-modules/media/src/route/decision_queue_predecessor_tests.rs b/rust-modules/media/src/route/decision_queue_predecessor_tests.rs index 5c885e707f..a2664201b4 100644 --- a/rust-modules/media/src/route/decision_queue_predecessor_tests.rs +++ b/rust-modules/media/src/route/decision_queue_predecessor_tests.rs @@ -301,9 +301,13 @@ fn the_window_reread_waits_for_the_outgoing_stop_within_its_bound() { // The outgoing episode's stop is announced and still on its way. let stop = TIMELINE_STOP_FENCE.announce(); let waiting = continuation.clone().awaiting(TIMELINE_STOP_FENCE.announced()); + // The clock starts HERE, before the reader exists and so before the sleep below can begin: a + // reader the scheduler starts late (a loaded runner) must not shorten what this measures. Taken + // inside the reader, a late start put its clock after the sleep's, and a read that did wait for + // the stop measured under 250 ms. + let started = std::time::Instant::now(); let read = std::thread::scope(|scope| { let reader = scope.spawn(|| { - let started = std::time::Instant::now(); let _ = waiting.refreshed_within(client, Duration::from_secs(20)); started.elapsed() }); diff --git a/rust-modules/media/src/route/plan.rs b/rust-modules/media/src/route/plan.rs index cb5a68124c..113b541a42 100644 --- a/rust-modules/media/src/route/plan.rs +++ b/rust-modules/media/src/route/plan.rs @@ -1213,8 +1213,10 @@ pub enum PlayVerdict { /// Force Direct Play is on, and this is why the original cannot play. Forced(ForcedFailure), /// A hero/trailer preview resolved to a route that is not a direct play. A muted preview takes - /// only the original, so the plan is refused here, with no URL. - PreviewNeedsDirectPlay, + /// only the original, so the plan is refused here, with no URL. `reason` is the first failing + /// condition in [`crate::player::preview::refusal`]'s fixed order; it is typed data for the + /// failure report (`playback.preview_refusal`) and changes nothing about how the refusal reads. + PreviewNeedsDirectPlay { reason: plx_telemetry::telemetry::classes::PreviewRefusal }, /// This build has no Feed executor and no source-specific URI qualification was granted. NoQualifiedBackend, } @@ -1247,7 +1249,7 @@ impl PlayVerdict { match self { Self::Server(sentence, _) => Borrowed(sentence), Self::DirectPlayDisabled => Borrowed(msg::widgets_verdict_direct_play_disabled()), - Self::PreviewNeedsDirectPlay => Borrowed(msg::widgets_reason_open()), + Self::PreviewNeedsDirectPlay { .. } => Borrowed(msg::widgets_reason_open()), Self::NoQualifiedBackend => Borrowed(msg::widgets_reason_open()), Self::Forced(why) => match why { ForcedFailure::NoOriginal => Borrowed(msg::widgets_verdict_forced_no_original()), @@ -2747,6 +2749,11 @@ pub(super) fn build_stream(off: &plx_base::task::OffFrame, rk: &str, part: &str, } let auto_original = decision.as_ref().is_some_and(|d| d.original); let adaptive = auto_uses_hls(playback_quality, auto_original); + // Whether a direct play was on offer BEFORE the override just below sets `directplay` false + // for HLS. The preview gate's reason needs it: after the override `directplay` is false for + // every Auto-quality HLS pick, so the gate's own inputs cannot tell a preview Auto sent to + // HLS from one the server would have transcoded anyway. + let direct_play_offered = directplay; if adaptive { allowed = flavors_allowed( link, @@ -2904,11 +2911,13 @@ pub(super) fn build_stream(off: &plx_base::task::OffFrame, rk: &str, part: &str, plan.memory_note = true; } log_memory(memory_unshown.is_some()); - if env.preview && !crate::player::preview::accepts_direct_play(directplay, !part.is_empty(), adaptive) { - crate::player::log("preview: refused — not a direct play"); - plan.url.clear(); - plan.verdict = Some(PlayVerdict::PreviewNeedsDirectPlay); - return plan; + if env.preview { + if let Some(reason) = crate::player::preview::refusal(directplay, direct_play_offered, !part.is_empty(), adaptive) { + crate::player::log(&format!("preview: refused — not a direct play ({})", reason.code())); + plan.url.clear(); + plan.verdict = Some(PlayVerdict::PreviewNeedsDirectPlay { reason }); + return plan; + } } if (directplay || rk.is_empty()) && !part.is_empty() && (rk.is_empty() || !pms_uri_possible || env.feed_original_eligible) { diff --git a/rust-modules/media/src/route/plan_audio_enhancement_tests.rs b/rust-modules/media/src/route/plan_audio_enhancement_tests.rs index f588f45319..eb54812e12 100644 --- a/rust-modules/media/src/route/plan_audio_enhancement_tests.rs +++ b/rust-modules/media/src/route/plan_audio_enhancement_tests.rs @@ -1006,3 +1006,87 @@ fn burn_route_offered_but_no_enhancement_wanted_is_not_forced_into_a_re_encode() } plx_plex::plex::reset_servers_for_test(); } + +// --------------------------------------------------------------------------------------------- +// The preview gate's REASON (Sentry PLX-NATIVE-23). The gate refuses everything but a plain direct +// play; which condition refused is typed data on the verdict, graded here on real resolves against +// the loopback PMS because the interesting cases are wire facts (what the server's decision said, +// whether Auto's Remote probe came back). + +/// The reason a resolve's refusal carries, or `None` for a plan that was not refused as a preview. +fn preview_refusal_of(r: &Resolve) -> Option { + match &r.plan.verdict { + Some(PlayVerdict::PreviewNeedsDirectPlay { reason }) => Some(*reason), + _ => None, + } +} + +/// An item with no media part has nothing to play, whatever the server says about direct play. +#[test] +#[cfg(feature = "devtriggers")] +fn a_preview_with_no_part_is_refused_as_no_part() { + use plx_telemetry::telemetry::classes::PreviewRefusal; + let mut ps = PlaybackSession::IDLE; + let _g = fresh_registry(&mut ps); + let r = resolve(&mut ps, MDE_DIRECTPLAY, EnhMode::Honor("ac3"), 0, "", "ac3", ac3_item, |env, _| { + env.set_preview(true); + }); + assert!(r.plan.url.is_empty()); + assert_eq!(preview_refusal_of(&r), Some(PreviewRefusal::NoPart), "{:?}", r.plan.verdict); + plx_plex::plex::reset_servers_for_test(); +} + +/// The server's decision is a transcode: a direct play was never on offer. +#[test] +#[cfg(feature = "devtriggers")] +fn a_preview_the_server_would_transcode_is_refused_as_not_direct() { + use plx_telemetry::telemetry::classes::PreviewRefusal; + let mut ps = PlaybackSession::IDLE; + let _g = fresh_registry(&mut ps); + let r = resolve(&mut ps, MDE_TRANSCODE, EnhMode::Honor("ac3"), 0, MKV, "ac3", ac3_item, |env, _| { + env.set_preview(true); + }); + assert!(r.plan.url.is_empty()); + assert_eq!(preview_refusal_of(&r), Some(PreviewRefusal::NotDirect), "{:?}", r.plan.verdict); + plx_plex::plex::reset_servers_for_test(); +} + +/// **The hypothesis this tag exists to test.** The server would direct-play the item, but Auto +/// quality's Remote bandwidth probe came back empty (the loopback PMS serves no media bytes), so +/// Auto chose HLS: a direct play was on offer and the bandwidth decision refused it. +#[test] +#[cfg(feature = "devtriggers")] +fn a_direct_playable_preview_that_auto_sends_to_hls_is_refused_as_adaptive() { + use plx_telemetry::telemetry::classes::PreviewRefusal; + let mut ps = PlaybackSession::IDLE; + let _g = fresh_registry(&mut ps); + let r = resolve(&mut ps, MDE_DIRECTPLAY, EnhMode::Honor("ac3"), 0, MKV, "ac3", ac3_item, |env, client| { + client.set_link(plx_plex::plex::probe::Location::Remote); + env.quality = Quality::Auto; + env.set_preview(true); + }); + assert!(r.plan.url.is_empty()); + assert_eq!(preview_refusal_of(&r), Some(PreviewRefusal::Adaptive), "{:?}", r.plan.verdict); + plx_plex::plex::reset_servers_for_test(); +} + +/// **The order is part of the contract.** Auto's override sets `directplay` false whenever it picks +/// HLS, so a preview the server would transcode ALSO ends on an adaptive plan under Auto. The first +/// failing condition is the one that was true BEFORE Auto chose: no direct play was on offer, so +/// `not_direct`, not `adaptive`. (Reading the refusal off the values the gate sees would report +/// every Auto-quality refusal as `adaptive` and make the hypothesis above unfalsifiable.) +#[test] +#[cfg(feature = "devtriggers")] +fn a_transcoded_preview_under_auto_is_not_direct_even_though_auto_also_chose_hls() { + use plx_telemetry::telemetry::classes::PreviewRefusal; + let mut ps = PlaybackSession::IDLE; + let _g = fresh_registry(&mut ps); + let r = resolve(&mut ps, MDE_TRANSCODE, EnhMode::Honor("ac3"), 0, MKV, "ac3", ac3_item, |env, client| { + client.set_link(plx_plex::plex::probe::Location::Remote); + env.quality = Quality::Auto; + env.set_preview(true); + }); + assert!(r.plan.url.is_empty()); + assert_eq!(preview_refusal_of(&r), Some(PreviewRefusal::NotDirect), "{:?}", r.plan.verdict); + plx_plex::plex::reset_servers_for_test(); +} diff --git a/rust-modules/media/src/route/prefs.rs b/rust-modules/media/src/route/prefs.rs index 9d8d041c4e..60cb893037 100644 --- a/rust-modules/media/src/route/prefs.rs +++ b/rust-modules/media/src/route/prefs.rs @@ -406,11 +406,13 @@ pub struct LiveRow { /// Always `S::SCOPE`; every live row is `Profile` since the nine moved (T-live checks it). pub scope: plx_plex::plex::session::prefs::Scope, restore: fn(&Preferences, Option<&ProfilePrefs>, &Overrides), + read: fn() -> u16, } impl LiveRow { - pub const fn of() -> LiveRow { - LiveRow { key: S::KEY, live: S::LIVE, scope: S::SCOPE, restore: restore_row:: } + pub const fn of() -> LiveRow where S::Value: Packed { + LiveRow { key: S::KEY, live: S::LIVE, scope: S::SCOPE, restore: restore_row::, + read: || S::live().to_bits() } } } @@ -438,6 +440,12 @@ pub const LIVE_ROWS: &[LiveRow] = &[ LiveRow::of::(), ]; +/// Capture the actual packed values of every live preference, in LIVE_ROWS order. +/// The app compares these at its IO boundary; this is not a dirty flag or an event queue. +pub fn preference_values() -> Vec { + LIVE_ROWS.iter().map(|row| (row.read)()).collect() +} + // ---- restore -------------------------------------------------------------------------------- /// What a caller of [`restore_profile_rows`] forces over the record. Each caller computes it @@ -851,7 +859,7 @@ fn choose_via(v: S::Value, how: How, normalize: impl FnOnce(S::V } How::Optimistic(reply) => { S::publish(v); - plx_machine::idle::invalidate(); + // The input runner observes the live preference values. if let Some(reply) = reply { let _ = reply.send(false); } @@ -864,13 +872,13 @@ fn choose_via(v: S::Value, how: How, normalize: impl FnOnce(S::V let _ = plx_base::storage_worker::submit_retained(move || { let saved = confirm_with::(&write, v); let _ = reply.send(saved); - plx_machine::idle::invalidate(); + // Reply is the addressed completion; the worker claims no UI damage. }); } How::Optimistic(reply) => { PROFILE_PREFS.put::(&write, v); S::publish(v); - plx_machine::idle::invalidate(); + // The input runner observes the live preference values. let _ = plx_base::storage_worker::submit_retained(move || { let saved = persist_profile_pref::(&write, v); if !saved { @@ -882,7 +890,7 @@ fn choose_via(v: S::Value, how: How, normalize: impl FnOnce(S::V if let Some(reply) = reply { let _ = reply.send(saved); } - plx_machine::idle::invalidate(); + // Reply is the addressed completion; the worker claims no UI damage. }); } } @@ -917,7 +925,7 @@ fn confirm_with(write: &ProfileWrite, v: S::Value) -> bool { if session::current_seat() == write.seat() { S::publish(v); } - plx_machine::idle::invalidate(); + // Confirmed live values are captured at the main-thread Bridge boundary. S::after_saved(v); } saved diff --git a/rust-modules/net/src/ws/transport_tests.rs b/rust-modules/net/src/ws/transport_tests.rs index f1b855bf54..7d39cbb225 100755 --- a/rust-modules/net/src/ws/transport_tests.rs +++ b/rust-modules/net/src/ws/transport_tests.rs @@ -413,16 +413,26 @@ fn an_address_keeps_its_query_and_gains_a_root_path() { assert_eq!(split("ws://relay.example/v1/ws?x=1"), Some((false, "relay.example", "/v1/ws?x=1".to_owned()))); } +/// A peer that writes without a pause keeps the socket readable, so the pass that reads it must end +/// by its byte budget ([`PASS_BUDGET`]) for the loop to see a cancel at all. The bound is stated in +/// what the transport controls, not in wall time: the callback below is the test's own cost (a +/// 200 us sleep per message, which a coarse timer, such as a virtualised macOS runner's, stretches to +/// over a millisecond: the pass in flight then took longer than the second the old assertion +/// allowed, on every run, with the transport doing exactly what it should). So it asserts (a) how +/// many messages arrive after the cancel was raised, which a missing budget would leave at tens of +/// thousands (the peer writes for ten seconds), and (b) that the time the transport spent outside +/// the callback between the cancel and its return, the going-away close included, is under a second. #[test] fn a_peer_that_never_pauses_cannot_hold_off_a_cancel() { let _serial = plx_base::testlock::serial(); if !curl_ready() { return; } + const FRAME: usize = 1000 + 4; // a 1000-byte text frame has a four-byte header let (url, server) = serve_ws(|mut peer, _| { let mut burst = Vec::new(); while burst.len() < 1 << 16 { - encode(Opcode::Text, true, "x".repeat(1000).as_bytes(), None, &mut burst); + encode(Opcode::Text, true, "x".repeat(FRAME - 4).as_bytes(), None, &mut burst); } let until = Instant::now() + Duration::from_secs(10); while Instant::now() < until && peer.io.write_all(&burst).is_ok() {} @@ -430,19 +440,29 @@ fn a_peer_that_never_pauses_cannot_hold_off_a_cancel() { let cancel = AtomicBool::new(false); let (_outbox, inbox) = channel().unwrap(); let mut first = None; + let mut after_cancel = 0usize; + let mut in_callback = Duration::ZERO; let end = run(&OffFrame::for_test(), plain(&url), &cancel, inbox, &mut |event| { if matches!(event, Event::Text(_)) { - thread::sleep(Duration::from_micros(200)); + let entered = Instant::now(); if first.is_none() { - first = Some(Instant::now()); + first = Some(entered); cancel.store(true, Ordering::Release); + } else { + after_cancel += 1; } + thread::sleep(Duration::from_micros(200)); + in_callback += entered.elapsed(); } }); let took = first.unwrap().elapsed(); server.join().unwrap(); assert_eq!(end, End::Cancelled); - assert!(took < Duration::from_secs(1), "{took:?}"); + // the pass in flight stops once it has read its budget, plus the chunk that crossed it + let one_pass = (PASS_BUDGET + READ_CHUNK) / FRAME + 2; + assert!(after_cancel <= one_pass, "{after_cancel} messages after the cancel, one pass is at most {one_pass}"); + let transport = took.saturating_sub(in_callback); + assert!(transport < Duration::from_secs(1), "{transport:?} in the transport of {took:?}"); } #[test] diff --git a/rust-modules/platform/src/tv/device.rs b/rust-modules/platform/src/tv/device.rs index bf471670ae..a7474574cf 100644 --- a/rust-modules/platform/src/tv/device.rs +++ b/rust-modules/platform/src/tv/device.rs @@ -10,7 +10,8 @@ pub struct Info { /// e.g. "4.10.2" — empty when unknown pub release: String, /// The exact firmware build, e.g. "6.5.3-47" (nyx's `core_os_release`: the release and the - /// build id); falls back to `release` when the file has no such key, empty when unknown. A + /// build id); falls back to `release` when the file has no such key, empty when unknown (and + /// when the release came from `/usr/lib/os-release`, which names no build). A /// patch within one release changes this and not `release`. pub build: String, /// e.g. "goldilocks2-grampians" — webosbrew buckets firmware by this @@ -33,8 +34,10 @@ static NO_INFO: Info = Info { major: 0, }; -/// What the set reported. All-empty with `major == 0` when the file could not be read — which is -/// the honest answer and is what the panel prints. A plain `get()` (never `get_or_init`), so a read +/// What the set reported. All-empty with `major == 0` when neither `os_info.json` nor +/// `/usr/lib/os-release` could be read — which is the honest answer and is what the panel prints. +/// A release that only `/usr/lib/os-release` named leaves the codename, API version, name and +/// build empty. A plain `get()` (never `get_or_init`), so a read /// that races ahead of the boot probe sees the empty answer for itself and leaves the cell open for /// [`publish_info`]. pub fn info() -> &'static Info { @@ -146,7 +149,9 @@ impl NyxFile { } /// What the boot probe found in each of nyx's two files: `os_info.json` (the webOS release, which -/// fills [`Info`]) and `device_info.json` (the set, which fills [`Hardware`]). +/// fills [`Info`]) and `device_info.json` (the set, which fills [`Hardware`]). The verdict is on the +/// FILE: an unreadable `os_info.json` reads `unreadable` even when `/usr/lib/os-release` supplied +/// the release. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct Probe { pub os_info: NyxFile, diff --git a/rust-modules/platform/src/webos.rs b/rust-modules/platform/src/webos.rs index d70bae310c..f71e0b7619 100644 --- a/rust-modules/platform/src/webos.rs +++ b/rust-modules/platform/src/webos.rs @@ -15,7 +15,8 @@ //! //! # Where it comes from //! -//! `/var/run/nyx/os_info.json`, read once, at boot. Kodi asks +//! `/var/run/nyx/os_info.json`, read once, at boot (and `/usr/lib/os-release`, for the release only, +//! when that file cannot be read: see [`probe`]). Kodi asks //! `luna://com.webos.service.config/getConfigs` for `tv.nyx.platformCode`; this is the same //! information from the file nyx writes, and it needs no LS2 client, no subscription and no //! thread. Verified present on the dev set (webOS 4.5), which reports: @@ -29,6 +30,11 @@ //! bucket (their `library-version` guide — `goldilocks` is 4.0~4.4, `goldilocks2` 4.5~4.10). So //! logging it says which of THEIR buckets a report belongs to, not just a number. //! +//! The fallback exists because the nyx file is not always there: a set whose first boot of the app +//! found it missing (issue #1351, a 6.5.3 set) logged the version as unknown. `/usr/lib/os-release` +//! is mounted read-only in the developer-mode jail and carries `VERSION_ID`, which is the release +//! and nothing else: no codename, no API version and no build id, so those stay empty. +//! //! Parsed by hand because this is a flat object of string values and a parser that cannot fail is //! the right shape for something that must never keep the app from booting. This is not a pattern //! for service replies: [`caps`] uses `serde_json` and strict types because uncertainty there is a @@ -79,7 +85,8 @@ fn parse(s: &str) -> Info { } } -/// Read it once and log it. Called at boot; safe to call when the file does not exist. +/// Read it once and log it. Called at boot; safe to call when the file does not exist. When +/// nyx's file cannot be read, `/usr/lib/os-release` is read for the release. pub fn probe() { let text = match std::fs::read_to_string(OS_INFO) { Ok(s) => Some(s), @@ -90,8 +97,16 @@ pub fn probe() { None } }; - let (info, os_info) = os_info_from(text.as_deref()); - if info.major > 0 { + let os_release = if text.is_none() { std::fs::read_to_string(OS_RELEASE).ok() } else { None }; + let Firmware { info, os_info, from_os_release } = firmware_from(text.as_deref(), os_release.as_deref()); + if from_os_release { + plx_base::eventlog::log(&format!( + "webos: release={} major={} (from {OS_RELEASE}; nyx os_info.json {})", + info.release, + info.major, + os_info.code() + )); + } else if info.major > 0 { plx_base::eventlog::log(&format!( "webos: {} release={} codename={} api={} major={}", info.name, info.release, info.codename, info.api, info.major @@ -138,6 +153,74 @@ fn os_info_from(text: Option<&str>) -> (Info, NyxFile) { (info, if answered { NyxFile::Ok } else { NyxFile::NoKeys }) } +/// The firmware's own release file. The developer-mode jail mounts `/usr/lib` read-only, so it is +/// readable where nyx's `/var/run/nyx/os_info.json` is not, and it names the release on every +/// firmware image from 5.5 to 11.2 that was checked. +const OS_RELEASE: &str = "/usr/lib/os-release"; + +/// The lowest major whose firmware ships [`OS_RELEASE`]. Measured on every unpacked image: none of +/// 3.4.3, 3.9.2, 4.4.2, 4.4.3, 4.10.0 and 4.10.2 has the file, every one from 5.5.0 to 11.2.0 has it. +const OS_RELEASE_FIRST_MAJOR: u32 = 5; + +/// The value of `key` in an os-release(5) text: `KEY=value`, the value bare or in one pair of +/// single or double quotes. The last assignment of a key wins, as it does when a shell sources the +/// file; a comment line or a longer key that merely ends in `key` never answers. +fn os_release_value<'a>(s: &'a str, key: &str) -> Option<&'a str> { + s.lines() + .filter_map(|line| { + let (k, v) = line.trim().split_once('=')?; + let v = v.trim(); + let unquoted = ['"', '\''] + .into_iter() + .find_map(|q| v.strip_prefix(q).and_then(|v| v.strip_suffix(q))); + (k == key).then_some(unquoted.unwrap_or(v)) + }) + .next_back() +} + +/// PURE: the release an `/usr/lib/os-release` text names, from `VERSION_ID` (`6.5.3`) and its first +/// component, or `None` when the text is not webOS TV's (`ID=starfish` on every image checked), +/// `VERSION_ID` is missing or not dotted decimal numbers, or its major is below +/// [`OS_RELEASE_FIRST_MAJOR`]: no firmware older than that writes this file, so such a text is not +/// this set's own, and a major 1 to 4 would flip the decisions that read it (the credential +/// default, VP9 10-bit, the DV platform gate, the old-ABI seek). The ID check is what keeps a Linux +/// host that runs the simulator from reading its distribution's `VERSION_ID` as a firmware. +/// +/// The file carries no codename, API version or build id, so those stay empty rather than invented; +/// in particular [`Info::build`] stays empty, not the release, so that this boot and a nyx boot of +/// the same set (`6.5.3-47`) never read as two builds. +fn os_release_info(s: &str) -> Option { + if os_release_value(s, "ID") != Some("starfish") { + return None; + } + let release = os_release_value(s, "VERSION_ID")?; + if !release.split('.').all(|c| !c.is_empty() && c.bytes().all(|b| b.is_ascii_digit())) { + return None; + } + let major = release.split('.').next()?.parse::().ok().filter(|m| *m >= OS_RELEASE_FIRST_MAJOR)?; + Some(Info { release: release.to_string(), major, ..Info::default() }) +} + +/// What [`probe`] publishes about the firmware, and where it came from. +struct Firmware { + info: Info, + /// The verdict on nyx's `os_info.json` itself: `Unreadable` stays `Unreadable` when the + /// release came from `/usr/lib/os-release`. + os_info: NyxFile, + from_os_release: bool, +} + +/// PURE: the firmware from both files' text (`None` is a file that could not be read). nyx's file +/// answers whenever it was read, whatever it holds; `/usr/lib/os-release` is consulted only when +/// the nyx read FAILED, and then fills the version only, never the nyx verdict. +fn firmware_from(nyx: Option<&str>, os_release: Option<&str>) -> Firmware { + let (info, os_info) = os_info_from(nyx); + match nyx.is_none().then(|| os_release.and_then(os_release_info)).flatten() { + Some(info) => Firmware { info, os_info, from_os_release: true }, + None => Firmware { info, os_info, from_os_release: false }, + } +} + /// PURE: the SoC class from `/etc/prefs/properties/machineName`, for a set whose /// `device_info.json` names none. The file is a flat text value whose leading run of lowercase /// letters and digits is the board family (`k5lp`, `k3lp`, `o22`…), the same prefix @@ -1231,6 +1314,119 @@ mod tests { assert!(info.release.is_empty()); } + /// `/usr/lib/os-release` as 6.5.3 firmware ships it, verbatim (quoted values). + const OS_RELEASE_653: &str = "ID=\"starfish\"\nNAME=\"webOS TV\"\nVERSION=\"6.5.3\"\nVERSION_ID=\"6.5.3\"\nPRETTY_NAME=\"webOS TV 6.5.3\"\n"; + /// 5.6.2 firmware: the same five lines. + const OS_RELEASE_562: &str = "ID=\"starfish\"\nNAME=\"webOS TV\"\nVERSION=\"5.6.2\"\nVERSION_ID=\"5.6.2\"\nPRETTY_NAME=\"webOS TV 5.6.2\"\n"; + /// 11.2.0 firmware: unquoted values, and a sixth line. + const OS_RELEASE_1120: &str = "ID=starfish\nNAME=\"webOS TV\"\nVERSION=\"11.2.0\"\nVERSION_ID=11.2.0\nPRETTY_NAME=\"webOS TV 11.2.0\"\nCPE_NAME=\"cpe:/o:openembedded:starfish:11.2.0\"\n"; + /// What a Linux host (the simulator under WSLg, a CI runner) has at the same path. + const OS_RELEASE_UBUNTU: &str = "PRETTY_NAME=\"Ubuntu 24.04.1 LTS\"\nNAME=\"Ubuntu\"\nVERSION_ID=\"24.04\"\nVERSION=\"24.04.1 LTS (Noble Numbat)\"\nID=ubuntu\nID_LIKE=debian\n"; + + #[test] + fn os_release_names_the_release_and_the_major_and_nothing_more() { + let i = os_release_info(OS_RELEASE_653).expect("6.5.3 firmware names its release"); + assert_eq!((i.release.as_str(), i.major), ("6.5.3", 6)); + // No codename, API version or name is in the file, and none is invented. Nor is a build: + // `core_os_release` ("6.5.3-47") carries a build id this file does not, and a build that + // read "6.5.3" on this boot and "6.5.3-47" on a nyx boot would look like two builds. + assert!(i.codename.is_empty() && i.api.is_empty() && i.name.is_empty() && i.build.is_empty(), "{i:?}"); + let i = os_release_info(OS_RELEASE_562).expect("5.6.2 firmware names its release"); + assert_eq!((i.release.as_str(), i.major), ("5.6.2", 5)); + } + + #[test] + fn os_release_values_may_be_quoted_or_bare() { + let i = os_release_info(OS_RELEASE_1120).expect("bare values"); + assert_eq!((i.release.as_str(), i.major), ("11.2.0", 11), "a two-digit major, not its first digit"); + let single = "ID='starfish'\nVERSION_ID='7.6.0'\n"; + assert_eq!(os_release_info(single).map(|i| i.major), Some(7)); + // Whitespace around a line, CRLF line ends, a comment that names the key, a later line + // for the same key (the shell's reading: the last assignment wins). + let noisy = "# VERSION_ID=\"1.0.0\"\r\n ID=starfish\r\nVERSION_ID=\"9.2.4\"\r\n\r\nVERSION_ID=\"9.2.5\"\r\n"; + let i = os_release_info(noisy).expect("noisy file"); + assert_eq!(i.release, "9.2.5"); + } + + #[test] + fn os_release_without_a_numeric_version_id_names_nothing() { + for text in [ + "", + "ID=starfish\n", + "ID=starfish\nVERSION_ID=\n", + "ID=starfish\nVERSION_ID=\"\"\n", + "ID=starfish\nVERSION_ID=\"abc\"\n", + "ID=starfish\nVERSION_ID=\"6.x\"\n", + "ID=starfish\nVERSION_ID=\"6..3\"\n", + "ID=starfish\nVERSION_ID=\"+6.5.3\"\n", + "ID=starfish\nVERSION_ID=\"6.5.3-47\"\n", + "ID=starfish\nVERSION_ID=\"0.0.0\"\n", + "ID=starfish\n# VERSION_ID=\"6.5.3\"\n", + "ID=starfish\nXVERSION_ID=\"6.5.3\"\n", + ] { + assert!(os_release_info(text).is_none(), "{text:?}"); + } + } + + /// The probe also runs in the simulator, which installs the webOS port's table: on a Linux + /// host `/usr/lib/os-release` is the host's, and Ubuntu's `VERSION_ID` is numeric. Only a file + /// that says it is webOS TV's (`ID=starfish`, on every firmware image checked from 5.5 to + /// 11.2) may name a firmware. + #[test] + fn a_linux_hosts_os_release_does_not_name_a_webos() { + assert!(os_release_info(OS_RELEASE_UBUNTU).is_none()); + assert!(os_release_info("VERSION_ID=\"6.5.3\"\n").is_none(), "no ID at all"); + } + + /// No 3.x or 4.x firmware image ships `/usr/lib/os-release` (measured on every unpacked image: + /// 3.4.3, 3.9.2, 4.4.2, 4.4.3, 4.10.0 and 4.10.2 have none; 5.5.0 to 11.2.0 all have it), so a + /// `VERSION_ID` below 5 is not a file this firmware wrote. Naming a major 1 to 4 would flip the + /// decisions that read it (credential default, VP9 10-bit, DV gate, the old-ABI seek). + #[test] + fn an_os_release_below_webos_5_names_nothing() { + for release in ["4.10.2", "4.4.3", "3.9.2", "1.0.0"] { + let text = format!("ID=starfish\nVERSION_ID=\"{release}\"\n"); + assert!(os_release_info(&text).is_none(), "{release}"); + let fw = firmware_from(None, Some(&text)); + assert_eq!((fw.info.major, fw.os_info, fw.from_os_release), (0, NyxFile::Unreadable, false), "{release}"); + } + assert_eq!(os_release_info("ID=starfish\nVERSION_ID=\"5.0.0\"\n").map(|i| i.major), Some(5), "5 is the lowest"); + } + + #[test] + fn a_nyx_file_that_was_read_is_never_second_guessed() { + let fw = firmware_from(Some(REAL), Some(OS_RELEASE_653)); + assert_eq!((fw.info.release.as_str(), fw.info.major), ("4.10.2", 4)); + assert_eq!(fw.info.codename, "goldilocks2-grampians"); + assert_eq!(fw.info.build, "4.10.2-31"); + assert_eq!(fw.os_info, NyxFile::Ok); + assert!(!fw.from_os_release); + // A file that was read but carries no keys stays "no keys" and unknown: only a read that + // FAILED falls back. + let fw = firmware_from(Some("{}"), Some(OS_RELEASE_653)); + assert_eq!((fw.info.major, fw.os_info, fw.from_os_release), (0, NyxFile::NoKeys, false)); + } + + #[test] + fn an_unreadable_nyx_file_falls_back_to_os_release_and_is_still_reported_unreadable() { + let fw = firmware_from(None, Some(OS_RELEASE_653)); + assert_eq!((fw.info.release.as_str(), fw.info.major), ("6.5.3", 6)); + assert!(fw.info.codename.is_empty() && fw.info.api.is_empty() && fw.info.build.is_empty()); + // The verdict on nyx's own file (the event log line and the crash report's `hardware.probe` + // field) stays `unreadable`; it is not a statement about whether the release is known. + assert_eq!(fw.os_info, NyxFile::Unreadable); + assert!(fw.from_os_release); + } + + #[test] + fn with_neither_source_the_firmware_stays_unknown() { + for os_release in [None, Some(""), Some("ID=starfish\nVERSION_ID=\"abc\"\n"), Some(OS_RELEASE_UBUNTU)] { + let fw = firmware_from(None, os_release); + assert_eq!((fw.info.major, fw.os_info, fw.from_os_release), (0, NyxFile::Unreadable, false), "{os_release:?}"); + assert!(fw.info.release.is_empty() && fw.info.build.is_empty()); + } + } + /// Absent key, present file. #[test] fn a_missing_key_is_none() { diff --git a/rust-modules/platform/src/webos/caps.rs b/rust-modules/platform/src/webos/caps.rs index 226c3e7d30..bf6f88d53c 100644 --- a/rust-modules/platform/src/webos/caps.rs +++ b/rust-modules/platform/src/webos/caps.rs @@ -54,7 +54,8 @@ fn publish(probe: DvProbe, started: Instant, code: Option, detail: Option<& probe.provenance(), )); } - plx_machine::idle::invalidate(); + // The boot worker publishes DvProbe only. Bridge captures the typed probe before present + // admission and owns the Page damage when this diagnostic fact changes. } /// Start the one boot probe. The registration and its private GLib context are both created and diff --git a/rust-modules/play-feed/src/seek.rs b/rust-modules/play-feed/src/seek.rs index deed41dcf3..3b5ddbdf6f 100644 --- a/rust-modules/play-feed/src/seek.rs +++ b/rust-modules/play-feed/src/seek.rs @@ -157,8 +157,9 @@ pub fn session_seek_mode( /// StarfishMediaAPIs is a different object from the 4.5 one, and the first fast-forward on a /// 3.4.0 set crashed through those offsets. The old-ABI Feed (`sf_feed_abi_is_cow`) is the /// direct evidence, and it covers 3.9.x too. A KNOWN release below 4 is refused as well; an -/// UNKNOWN one (`major == 0`, os_info unreadable) with the C++11 Feed keeps in-place seek, as -/// before #578, because that Feed says the library is 4.x or later. +/// UNKNOWN one (`major == 0`: neither `os_info.json` nor `/usr/lib/os-release` named a release) +/// with the C++11 Feed keeps in-place seek, as before #578, because that Feed says the library +/// is 4.x or later. /// - A layout-unknown library on the ACB plane in a KNOWN webOS 3 release /// ([`old_abi_seek_tested`]) -> [`SeekMode::NativeSeek`] too. `Seek` takes a `const char*`, so /// its symbol and calling convention are the same on both C++ ABIs; that it also behaves the diff --git a/rust-modules/play-feed/src/sf_event.rs b/rust-modules/play-feed/src/sf_event.rs index ff412d51dc..845e0a0df6 100644 --- a/rust-modules/play-feed/src/sf_event.rs +++ b/rust-modules/play-feed/src/sf_event.rs @@ -172,7 +172,8 @@ pub fn media_to_fed(media_ns: i64) -> i64 { /// libpf on webOS 4.10 (`CustomPipeline::updateDroppedFrame` → 0x2e = 46, /// `updateDisplayedFrame` → 0x2f = 47); every type above 0x1c is two higher on webOS 5+ /// (Kodi's `if (webOSVersion < 5 && type > ENDOFSTREAM) type += 2`), so 48/49 there. An unknown -/// major (0, os_info unreadable) is read as the numbering this project has actually measured. +/// major (0: neither `os_info.json` nor `/usr/lib/os-release` named a release) is read as the +/// numbering this project has actually measured. pub fn sink_counter_kind(ty: c_int, major: u32) -> Option { let normalised = if major == 0 || major < 5 { ty + 2 } else { ty }; match normalised { diff --git a/rust-modules/play-uri/src/backend.rs b/rust-modules/play-uri/src/backend.rs index c6729a6377..1cc8228d82 100644 --- a/rust-modules/play-uri/src/backend.rs +++ b/rust-modules/play-uri/src/backend.rs @@ -44,7 +44,7 @@ pub use plx_playback_contract::uri::Binding; /// parameter (never a `cfg(test)` constant) so a test passes its own. A major of 0, the /// unknown answer, is never admitted, whatever the table lists, and nothing is inferred from a /// neighbouring major; -/// - otherwise nothing: a webOS 5+ release without an entry plays Standard. +/// - otherwise nothing: a webOS 5+ major without an entry plays Standard. /// /// `plane` and `initialized` are the URI engine's own handle's (player type 0, the plane owner's /// `facts_of(PlaneHandle::Uri)` and `initialized(PlaneHandle::Uri)`), never Feed's: a normal boot @@ -65,8 +65,8 @@ pub fn product_binding(display_mode: i32, plane: plx_platform::tv::plane::PlaneF /// The firmware majors on which the product backend selects the exported window /// ([`product_binding`]): the only way production ever composes [`Binding::Exported`]. An entry is /// a webOS firmware major as `device::info().major` reports it (5 for 5.x, 11 for 11.x). The table -/// is empty, so every webOS 5+ release plays Standard until a major earns an entry (a webOS 4.x set -/// takes the ACB plane, which this table does not touch). +/// admits major 5 and no other, so every other webOS 5+ major plays Standard until it earns an entry +/// (a webOS 4.x set takes the ACB plane, which this table does not touch). /// /// A major is admitted only with all three parts of the evidence in `docs/uri-mode.md`'s Results /// table, each recorded there with the tester log's decisive lines. A release is never admitted on @@ -78,9 +78,14 @@ pub fn product_binding(display_mode: i32, plane: plx_platform::tv::plane::PlaneF /// `evidence=override`) shows a moving picture with sound, placed and proportioned right, /// supported by the probe's summary tokens `load=ok`, `playing=yes`, /// `currentTime_advanced=yes` and `window=exported`; -/// - (c) controls: the probe's `drive` tokens (`pause=froze`, `resume=sent` with `resume_from=` -/// at or after the paused position minus 1000 ms, `seek=hit`, and `audio=ok` or an -/// `audio_at_load=`) AND the product run's pause, seek and audio doing what the viewer asked. +/// - (c) controls: the probe's `drive` tokens (`pause=froze` on either `pause_basis`, `resume=sent` +/// with `resume_from=` at or after the paused position minus 1000 ms, `seek=hit`, and `audio=ok` +/// or an `audio_at_load=`) AND the product run's pause, seek and audio doing what the viewer +/// asked. Two amendments, each named in the row that uses it. (1) A run made before the current +/// grader may stand on the current grader's verdict on that run's recorded numbers, replayed in +/// a unit test: the row names the test and says the run itself printed `pause=unconfirmed`. +/// (2) A control the product run showed failing is acceptable only when the route now sends that +/// case to Standard; the row names it, and the admission covers only the route as it now stands. /// /// One exception: a major with (a) but no tester run is admitted when BOTH neighbouring majors /// (`major - 1` and `major + 1`) are already admitted on tester evidence, and its own image shows @@ -89,7 +94,17 @@ pub fn product_binding(display_mode: i32, plane: plx_platform::tv::plane::PlaneF /// /// Each entry carries a comment naming its Results row. `0` is never an entry: it is the unknown /// answer. -pub const EXPORTED_STRATA: &[u32] = &[]; +pub const EXPORTED_STRATA: &[u32] = &[ + // webOS 5.6.2, LG OLED CX (build 5.6.2-21): `docs/uri-mode.md` Results row "webOS 5.6.2 (build + // 5.6.2-21)", #1064. (a) the 5.5.0 and 5.6.2 images read `option.windowId`; (b) a product run on a + // debug build of main at e8442d5e (carries #1314; single audio track, SDR and Dolby Vision) played + // a placed, correctly letterboxed picture with sound; (c) the drive probe on that build printed + // pause=froze (pause_basis=paused_event_and_resume), seek=hit and audio_at_load=0, and the + // product run's pause, seek and sound answered, so amendment (1) is not used. The earlier + // four-audio-track run's audio-track switch failed; such a file now starts in Standard (#1314, + // amendment (2); `exported_uri_leaves_multi_audio_originals_on_standard` pins the route). + 5, +]; /// The canvas the exported window is placed over: the destination of EVERY placement, the whole /// 1920x1080 canvas, as Feed (`feed_pump`) and the developer probe (`uriprobe_drive`) place it. Only diff --git a/rust-modules/plex/src/plex/identity.rs b/rust-modules/plex/src/plex/identity.rs index 6c2baec431..526b0bdd4b 100644 --- a/rust-modules/plex/src/plex/identity.rs +++ b/rust-modules/plex/src/plex/identity.rs @@ -102,7 +102,7 @@ pub const PLATFORM: &str = "webOS"; /// reporting 4.5 from a 6.5.2 television (issue #22). PMS augments our named Generic profile /// from the X-Plex-Client-Profile-Extra we send, so the version is informational today — but it /// is also how a server-side profile could ever distinguish firmware generations, and a false -/// one poisons that forever. The fallback when `os_info.json` is unreadable keeps the literal +/// one poisons that forever. The fallback when neither `os_info.json` nor `/usr/lib/os-release` names a release keeps the literal /// this replaces — the exact claim every release so far has made — rather than inventing an /// empty-string case no server has ever been shown. Safe by boot order: `tv::probe_device()` runs /// before any PMS request, so none can precede the read. diff --git a/rust-modules/plex/src/plex/serverinfo.rs b/rust-modules/plex/src/plex/serverinfo.rs index a9ac0cada8..8f6f3dd494 100644 --- a/rust-modules/plex/src/plex/serverinfo.rs +++ b/rust-modules/plex/src/plex/serverinfo.rs @@ -68,7 +68,7 @@ struct Entry { /// The owner's Plex Pass answer, `Unknown` until a fetch lands. sub: Subscription, /// The server's full build string ("1.43.3.10861-cd85035e7"), "" until its fetch lands. - version: String, + version: std::sync::Arc, /// Single-flight: boot registers a server and a profile pick re-registers it moments later; /// two live workers would answer the same question twice and double the log line. Per server /// rather than global because two servers' fetches are different questions — a shared server @@ -103,12 +103,28 @@ pub fn subscription_of(id: ServerId) -> Subscription { with_table(|t| t.get(&id.raw()).map_or(Subscription::Unknown, |e| e.sub)) } +/// One addressed answer, cheaply retained by the app's visual-input observer. +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct ServerInfoFacts { + pub subscription: Subscription, + pub version: std::sync::Arc, +} + +pub fn facts_of(id: ServerId) -> ServerInfoFacts { + if super::client_for(id).is_none() { + return ServerInfoFacts::default(); + } + with_table(|t| t.get(&id.raw()).map(|e| ServerInfoFacts { + subscription: e.sub, version: e.version.clone(), + }).unwrap_or_default()) +} + /// [`version`] for a NAMED server; "" while unknown. pub fn version_of(id: ServerId) -> String { if super::client_for(id).is_none() { return String::new(); } - with_table(|t| t.get(&id.raw()).map(|e| e.version.clone()).unwrap_or_default()) + with_table(|t| t.get(&id.raw()).map(|e| e.version.to_string()).unwrap_or_default()) } /// The CURRENT server owner's Plex Pass state, for DIAGNOSTICS — the stats panel and the playback @@ -261,15 +277,9 @@ fn fetch_once(id: ServerId, c: &Client) { /// and the property that matters — one server's answer never reaching another's reader — lives /// entirely below. /// -/// **This is an async LANDING, so it owes the present gate a poke.** It runs on a worker, seconds -/// after boot or after a share is registered, and it changes what a SETTLED screen says: the stats -/// panel's Server row, the detail hero's "hardware conversion needs \[PLEX PASS\]" note, and the -/// failure read-out's capsule all read it. Without the [`plx_machine::idle::invalidate`] call the new -/// fact arrives invisibly and the screen keeps stating the old one until the next keypress — bounded -/// only by the 2 s keepalive, which is insurance and not pacing (that module's rule: *a new async -/// landing that repaints must add a call there*). Unconditional rather than change-guarded: a -/// re-registration that stores the same answer costs one frame, and a guard here would be a second -/// place that has to agree with what the readers draw. +/// This worker publishes addressed server facts only. The app captures [`facts_of`] before +/// admission and attributes changed facts to its owned Page gate, including arrivals while a +/// settled page or a surface is visible. No worker claims UI provenance. fn store(id: ServerId, sub: Subscription, version: &str) { if !id.is_set() { return; @@ -281,9 +291,9 @@ fn store(id: ServerId, sub: Subscription, version: &str) { } let e = t.entry(id.raw()).or_default(); e.sub = sub; - e.version = version.to_owned(); + e.version = version.into(); }); - plx_machine::idle::invalidate(); + } /// Test-only: publish one server's answer without a round trip. @@ -508,49 +518,31 @@ mod tests { assert!(servers::ids().any(|id| id == far), "the far server is in the roster the readers walk"); } - /// **This is an async LANDING, so it owes the frame gate a poke.** The answer arrives on a - /// worker seconds after boot — later still for a share registered while the user is reading a - /// page — by which time the screen that reads it has settled and stopped presenting: the stats - /// panel's Server row, the detail hero's "hardware conversion needs [PLEX PASS]" note, and the - /// failure read-out's capsule. Without the `plx_machine::idle::invalidate` inside [`store`] the new fact - /// reaches the panel only on the next keypress (bounded by the 2 s keepalive, which is - /// insurance and not pacing) — the "arrives invisibly" failure `plx_machine::idle::invalidate`'s - /// call-site list exists to prevent. - /// - /// Takes `testlock::serial()`: the gate's flag is a crate global that `plx_machine::idle`'s own - /// "a settled screen does not repaint" assertions read, so an unlocked test here would fail - /// ANOTHER module's tests intermittently — `ui::xfade`'s test module states the same rule, and - /// this borrows its isolation helper. + /// A worker publishes facts; only their main-thread observation damages an owned Page gate. #[test] fn a_landed_server_fact_asks_the_frame_gate_to_repaint() { + use plx_machine::present::{Present, PresentEvent, Provenance, Scope}; let _g = plx_base::testlock::serial(); - // `frame_begin` forgets last frame's motion, `note_present` retires the 2 s keepalive, and - // `should_present` TAKES-AND-CLEARS — so each call answers for exactly the frames since the - // previous one, and nothing but the store below can be what answered. - let asked = || { - plx_machine::idle::set_enabled(true); // a test that disabled the gate leaves it off - plx_machine::idle::frame_begin(1.0 / 60.0); - plx_machine::idle::note_present(0); - plx_machine::idle::should_present(0) - }; - asked(); // drain whatever the previous test left on the shared flag - assert!( - !asked(), - "the gate is quiet before the landing — or this proves nothing" - ); - - let id = ServerId::from_raw(0); + super::super::servers::reset_for_test(); + let id = super::super::servers::register_with_client_id("facts-test", "127.0.0.1", 32400, "tok", "cid"); + let before = facts_of(id); + let mut present = Present::new(); + present.take(0); + present.acknowledge(0); store(id, Subscription::No, "1.32.0.6918-free"); - assert!( - asked(), - "a subscription that just landed must reach the screen stating it" - ); - - store(id, Subscription::Unknown, ""); - assert!(asked(), "…and so must the boot state being put back"); - - // a write through an id that names no server publishes nothing, so it wakes nothing + assert!(!present.take(1), "publication alone cannot attribute UI damage"); + let after = facts_of(id); + assert_ne!(before, after); + assert_eq!(after.subscription, Subscription::No); + present.set_scope(Scope::Page); + plx_machine::machine::PresentHandle::of(&mut present) + .note(PresentEvent::Damage(Provenance::Lifecycle)); + assert!(present.take(1), "main-thread observation repaints without keepalive"); + present.acknowledge(1); + let before = facts_of(id); store(ServerId::UNSET, Subscription::Yes, "nowhere"); - assert!(!asked(), "a write that landed in no slot changed no screen"); + assert_eq!(before, facts_of(id)); + assert!(!present.take(2)); + super::super::servers::reset_for_test(); } } diff --git a/rust-modules/plex/src/plex/servers.rs b/rust-modules/plex/src/plex/servers.rs index d98e4b813a..3c7fd5533c 100644 --- a/rust-modules/plex/src/plex/servers.rs +++ b/rust-modules/plex/src/plex/servers.rs @@ -174,6 +174,7 @@ pub fn same_item(a: (ServerId, &str), b: (ServerId, &str)) -> bool { /// Deliberately NOT fields on `Client`: a `Client` is re-pointed whenever the address moves, and /// a re-point must not forget whose server it is. Published by the same leak-and-store the client /// slots use, so [`facts`] hands out `&'static` on exactly the same terms as [`client_for`]. +#[derive(Debug, PartialEq, Eq)] pub struct ServerFacts { /// The MACHINE name — "nas-home". "People in content, machines in settings": this is drawn /// only where the grant itself is the subject, i.e. the Sources list's group headers. @@ -676,9 +677,7 @@ pub fn publish_probe_result(id: ServerId, outcome: Outcome) { return; }; s.probe.store(probe_code(outcome), Ordering::Release); - // The Sources list follows this atomic from `browse::sync_roster`; wake an idle frame so the - // new word/tier is visible immediately rather than at the two-second keepalive. - plx_machine::idle::invalidate(); + // The app observes this addressed server outcome at its main-thread visual boundary. } /// Publish what a generic PMS request proved, but only if the slot still names the exact client @@ -735,7 +734,7 @@ pub fn commit_reachability_if_current( // registry; callers keep it to their own main-thread stores. let committed = commit(outcome); drop(w); - plx_machine::idle::invalidate(); + // Some(committed) is the caller's explicit landing outcome. Some(committed) } @@ -836,12 +835,7 @@ fn describe_locked(id: ServerId, name: &str, credit: Option<&str>, grant: GrantE // The PUBLISHED FACTS moved, which every cached projection of them has to be able to notice — // see [`FACTS_GEN`], and note the ordering hazard it closes. FACTS_GEN.fetch_add(1, Ordering::AcqRel); - // A server learning its own name CHANGES PIXELS — the Search screen's scope line and the - // Library's Source chip both read it — and it lands asynchronously, well after the first frame. - // `plx_machine::idle` gates the whole present on detected motion and cannot see a `static` being - // written, so without this the new name sat invisible until the 2 s keepalive or the next - // keypress: a screen showing "your server and your server" for two seconds after it knew better. - plx_machine::idle::invalidate(); + // The app captures FACTS_GEN and these immutable facts before present admission. } /// Record a server's MACHINE NAME and nothing else — for a describer that learned it from the @@ -1355,7 +1349,7 @@ pub fn revoke_for_profile_switch() { live.len() )); } - plx_machine::idle::invalidate(); + // ROSTER_GEN is observed by the app's owned visual-input boundary. } /// Finish a profile/roster replacement with exactly the slots the caller just installed. @@ -1416,7 +1410,7 @@ pub fn revoke_before_foreign_retoken(machine_id: &str, token: &str) { if let Some(s) = slot_of(id) { s.probe.store(PROBE_UNKNOWN, Ordering::Release); } - plx_machine::idle::invalidate(); + // The app observes the client's grant epoch and probe outcome. } } @@ -1448,7 +1442,7 @@ fn commit_installed_roster(installed: &[ServerId]) { CURRENT.store(next.0 as u32, Ordering::Release); if set_active_only(&exact) { ROSTER_GEN.fetch_add(1, Ordering::AcqRel); - plx_machine::idle::invalidate(); + // ROSTER_GEN is observed by the app's owned visual-input boundary. } } @@ -1501,10 +1495,7 @@ pub fn revoke_all() { n - floor )); } - // The Sources list, the Search scope line and every shelf heading are drawn from this table, - // and `plx_machine::idle` gates the whole present on detected motion — it cannot see a `static` being - // written. Same reason `describe` invalidates. - plx_machine::idle::invalidate(); + // ROSTER_GEN is observed by the app's owned visual-input boundary. } /// **Re-ask the grant table for every client a grant was carrying** ([`Slot::on_grant`]), after a plaintext grant was @@ -1538,7 +1529,7 @@ pub fn regrade_credentials() { plx_base::eventlog::log(&format!( "plex: {regraded} server(s) lost their plaintext credential — the grant ended" )); - plx_machine::idle::invalidate(); + // The app observes the roster, eligibility and probe outcome together. } } diff --git a/rust-modules/plex/src/plex/session.rs b/rust-modules/plex/src/plex/session.rs index 37e285a43a..8743f17c1e 100644 --- a/rust-modules/plex/src/plex/session.rs +++ b/rust-modules/plex/src/plex/session.rs @@ -3713,7 +3713,7 @@ mod cache_timing_tests { // serial fixture: a later test's time zero would otherwise wrap the keepalive arithmetic. struct ResetIdle; impl Drop for ResetIdle { - fn drop(&mut self) { plx_machine::idle::reset_for_test(); } + fn drop(&mut self) { plx_machine::motion::report::reset_for_test(); } } /// What a frame thread's landing step reads of the cache: whether the visible generation moved @@ -3777,7 +3777,7 @@ mod cache_timing_tests { READ_RETURNED.store(true, std::sync::atomic::Ordering::SeqCst); ReadState::Ready { session: std::sync::Arc::new(test_support::signed_in()), plaintext: false, retry_canonical: false } }))); - plx_machine::idle::reset_for_test(); + plx_machine::motion::report::reset_for_test(); let ticket = plx_base::storage_worker::submit_retained(refresh_cache_job(need.generation)); CACHE_READ_FOR_TEST.with(|slot| slot.set(None)); entered.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); @@ -3789,8 +3789,12 @@ mod cache_timing_tests { release.send(()).unwrap(); assert_eq!(ticket.wait_blocking().unwrap(), CacheRefreshOutcome::Settled); plx_base::storage_worker::drain_for_test(); - assert!(!plx_machine::idle::should_present(0), "the worker only publishes data"); - assert_eq!(plx_machine::idle::take_local_damage(), 0, "the peeks raise no frame damage of their own"); + let mut present = plx_machine::present::Present::new(); + present.take(0); + present.acknowledge(0); + plx_machine::motion::report::collect_into(&mut present, 0); + assert!(!present.take(0), "the worker only publishes data"); + assert!(!present.take(1), "the peeks raise no owned frame damage of their own"); let _frame = plx_base::task::FrameScope::enter(); assert!(frame_step.lands(), "the frame step observes the published session"); assert_eq!(peek().client_id, "cid-1"); @@ -3918,19 +3922,27 @@ mod cache_timing_tests { session: std::sync::Arc::new(test_support::signed_in()), plaintext: true, retry_canonical: false, }) as fn() -> ReadState, false), ] { - plx_machine::idle::reset_for_test(); - plx_machine::idle::note_present(10_000); + plx_machine::motion::report::reset_for_test(); + let mut present = plx_machine::present::Present::new(); + present.take(10_000); + present.acknowledge(10_000); CACHE_READ_FOR_TEST.with(|slot| slot.set(Some(read))); let job = refresh_cache_job(CACHE_GENERATION.load(std::sync::atomic::Ordering::Relaxed)); CACHE_READ_FOR_TEST.with(|slot| slot.set(None)); drop(plx_base::storage_worker::submit_retained(job)); plx_base::storage_worker::drain_for_test(); - assert!(!plx_machine::idle::should_present(10_001), "workers cannot wake the UI"); - assert_eq!(plx_machine::idle::take_local_damage(), 0); + plx_machine::motion::report::collect_into(&mut present, 10_001); + assert!(!present.take(10_001), "workers cannot wake the UI"); + assert!(!present.take(10_001), "only the owned landing boundary can damage the gate"); let _frame = plx_base::task::FrameScope::enter(); assert_eq!(frame_step.lands(), landed); assert!(!frame_step.lands(), "one landing per change"); - assert_eq!(plx_machine::idle::take_local_damage(), 0, "landing the cache raises no frame damage of its own"); + assert!(!present.take(10_001), "landing the cache raises no owned damage of its own"); + if landed { + plx_machine::machine::PresentHandle::of(&mut present).note( + plx_machine::present::PresentEvent::Damage(plx_machine::present::Provenance::Lifecycle)); + } + assert_eq!(present.take(10_001), landed, "the caller attributes the typed landing once"); } } diff --git a/rust-modules/rust-toolchain.toml b/rust-modules/rust-toolchain.toml index bdeb228c73..0f93eae9ab 100644 --- a/rust-modules/rust-toolchain.toml +++ b/rust-modules/rust-toolchain.toml @@ -17,7 +17,7 @@ # `targets` is the ARMv7 std the cross-build links (`armv7-unknown-linux-gnueabi`): a prebuilt # rust-std component, so the build needs neither nightly, `rust-src` nor `-Z build-std`. [toolchain] -channel = "1.99.1" +channel = "1.100.0" profile = "minimal" components = ["clippy", "rustfmt"] targets = ["armv7-unknown-linux-gnueabi"] diff --git a/rust-modules/screens/src/account_menu.rs b/rust-modules/screens/src/account_menu.rs index 0adae8579d..d0a7cdebc0 100644 --- a/rust-modules/screens/src/account_menu.rs +++ b/rust-modules/screens/src/account_menu.rs @@ -499,7 +499,7 @@ impl Screen for AccountMenuScreen { let r = self.frame(measure); // The glass and the rows ride the MORPH (`Popover::panel` / `morph_rows`), not the // container's appear: the panel begins and ends as the chip it grows from. - let m = self.popover.content_painter_on(f.painter, 0.0); + let m = self.popover.content_painter_on(f.painter.alpha(f.nav_page_alpha), 0.0); self.popover.panel(m, r, PANEL_RAD, f.underlay, plx_ui::widgets::Ground::Menu); plx_ui::profile::phase("glass.foreground", || { self.popover.morph_rows(m, r, PANEL_RAD, |m| self.form.table.draw(m, r, measure)); diff --git a/rust-modules/screens/src/catalog.rs b/rust-modules/screens/src/catalog.rs index a0a8da2a0d..85484eb9f7 100644 --- a/rust-modules/screens/src/catalog.rs +++ b/rust-modules/screens/src/catalog.rs @@ -331,19 +331,17 @@ impl CatalogScreen { /// The app hands the page its store snapshot: on the first frames, and again whenever the /// record, the membership or a server match moved. Only what is drawn from it changes; a /// match landing while the page is open re-derives the status line and nothing else. - pub fn input(&mut self, vm: CatalogViewModel) { - if self.vm != vm { - self.vm = vm; - plx_machine::idle::invalidate(); - } + pub fn input(&mut self, vm: CatalogViewModel) -> bool { + if self.vm == vm { return false; } + self.vm = vm; + true // the runner applies the changed snapshot to its owned Present } /// The reachable server that proxies the art (`None`: neutral ground). - pub fn set_art_server(&mut self, server: Option) { - if self.art_server != server { - self.art_server = server; - plx_machine::idle::invalidate(); - } + pub fn set_art_server(&mut self, server: Option) -> bool { + if self.art_server == server { return false; } + self.art_server = server; + true // resource attribution belongs to the runner, not this retained snapshot } pub fn view_model(&self) -> &CatalogViewModel { @@ -523,7 +521,7 @@ impl CatalogScreen { .icon(face.icon) .focused(focused) .ground(ControlGround::Keyed) - .scale(self.pop.scale(0)) + .scale(self.pop.scale_with(0, f.press)) .draw(&Env::inert(), p); f.stop( p, diff --git a/rust-modules/screens/src/collection/cards_harness.rs b/rust-modules/screens/src/collection/cards_harness.rs index 09412977ef..07c65e92f4 100644 --- a/rust-modules/screens/src/collection/cards_harness.rs +++ b/rust-modules/screens/src/collection/cards_harness.rs @@ -62,7 +62,7 @@ impl Harness { fn step(&mut self, ev: ScreenEvent) -> bool { let mut present = plx_machine::present::Present::new(); let mut out = Vec::new(); - let (_, moving) = plx_machine::idle::scoped_motion(|| { + let (_, moving) = plx_machine::motion::report::scoped_motion(|| { let cx = Cx { views: self.store.view(), tick: Tick { ms: self.ms, dt_us: 16_667 }, measure: &FixtureMeasure, press: PressRead { scale: self.press, owner: self.focus, ..Default::default() }, focus: FocusRead { current: self.focus, ..Default::default() }, owner: InputOwner::Entry(ENTRY) }; diff --git a/rust-modules/screens/src/consent.rs b/rust-modules/screens/src/consent.rs index 43c23e1df0..93c7ef5c5a 100644 --- a/rust-modules/screens/src/consent.rs +++ b/rust-modules/screens/src/consent.rs @@ -447,7 +447,7 @@ impl ConsentPage { } } - fn view(&self) -> ConsentView<'_> { + fn view(&self, press: plx_machine::machine::PressRead) -> ConsentView<'_> { let layout = self.layout; let labels = self.band_labels(); ConsentView { @@ -459,7 +459,7 @@ impl ConsentPage { has_crumb: self.crumb().is_some(), entry: self.entry, labels, - scales: [self.pop.scale(0), self.pop.scale(1)], + scales: [self.pop.scale_with(0, press), self.pop.scale_with(1, press)], alert_open: self.alert.is_open(), alert_frames: self.alert_frames.get(), alert_choice: self.alert.choice(), @@ -735,7 +735,7 @@ impl Focusable for ConsentView<'_> { } } -plx_ui::focusable_via_view!(ConsentPage, InnerHost, view); +plx_ui::focusable_via_view!(ConsentPage, InnerHost, view, press); impl Machine for ConsentPage { type Ev = ScreenEvent; @@ -852,7 +852,7 @@ impl Machine for ConsentPage { && !self.alert.visible() && cx.focus.current.is_some_and(|key| band_index(key.elem).is_some()) && matches!(self.mode, Mode::FirstRun { .. }) => { - let frame = self.view().disclosure_frame(cx.measure); + let frame = self.view(cx.press).disclosure_frame(cx.measure); let body = self.body(); let (position, moved) = self.disclosure.move_measured( if *key == Key::Up { -1 } else { 1 }, body, frame, cx.measure); @@ -960,7 +960,7 @@ impl Screen for ConsentPage { let layout = self.layout; if matches!(self.mode, Mode::FirstRun { .. }) { Header::new(layout, self.crumb(), self.title(), "").paint(p, f.measure); - let frame = self.view().disclosure_frame(f.measure); + let frame = self.view(f.press).disclosure_frame(f.measure); let body = self.body(); self.disclosure.draw(p, frame, None, body); } else { @@ -989,7 +989,7 @@ impl Screen for ConsentPage { group: BAND_GROUP, entry: self.entry, uncommitted, - scales: [self.pop.scale(0), self.pop.scale(1)], + scales: [self.pop.scale_with(0, f.press), self.pop.scale_with(1, f.press)], palette: palette(), danger: None, note: self.band_note(), @@ -1003,8 +1003,8 @@ impl Screen for ConsentPage { // the delete alert over everything, its own scrim first; its answers are the stops the // engine seats on while it is open if self.alert.visible() { - self.alert.draw_scrim(); - self.alert.draw(plx_platform::i18n::msg::settings_cancel_c(), plx_platform::i18n::msg::settings_delete_c(), f.measure); + self.alert.draw_scrim(f); + self.alert.draw(plx_platform::i18n::msg::settings_cancel_c(), plx_platform::i18n::msg::settings_delete_c(), f.measure, f.route_navigation(), f.press); let frames = self.alert.frames(f.measure); self.alert_frames.set(Some(frames)); // **Register the two hit stops only once the entrance spring has actually arrived.** diff --git a/rust-modules/screens/src/consent_delete_alert_tests.rs b/rust-modules/screens/src/consent_delete_alert_tests.rs index 1c10230a32..d4cce7ff45 100644 --- a/rust-modules/screens/src/consent_delete_alert_tests.rs +++ b/rust-modules/screens/src/consent_delete_alert_tests.rs @@ -176,7 +176,7 @@ fn the_alert_index_mapping_is_pinned_through_a_real_press_commit() { clip: Rect::FULL, index: None, }; - let seated = Focusable::::seat(&page.view(), ALERT_GROUP, placed, &c); + let seated = Focusable::::seat(&page.view(plx_machine::machine::PressRead::::default()), ALERT_GROUP, placed, &c); assert_eq!(seated.elem, ALERT, "a freshly opened alert seats on Cancel, element 0 — never the destructive answer"); // Element 0 (Cancel) must never delete anything, driven through the real event `step` @@ -345,7 +345,7 @@ fn reconcile_keeps_the_alerts_own_choice_when_a_stray_key_names_something_outsid // A stray pointer hover on some unrelated table row — exactly what `FocusEngine::set` // parks into the engine's persisted scope with no regard for the modal being up. let stray = FocusKey { entry: EntryId(1), elem: 0 }; - let reconciled = Focusable::::reconcile(&page.view(), stray, &c); + let reconciled = Focusable::::reconcile(&page.view(plx_machine::machine::PressRead::::default()), stray, &c); assert_eq!( reconciled, FocusKey { entry: EntryId(1), elem: ALERT + 1 }, diff --git a/rust-modules/screens/src/consent_focus_tests.rs b/rust-modules/screens/src/consent_focus_tests.rs index a9ea8546cc..314563014b 100644 --- a/rust-modules/screens/src/consent_focus_tests.rs +++ b/rust-modules/screens/src/consent_focus_tests.rs @@ -517,7 +517,7 @@ mod composed { /// twin of `page.step(...)` for the half of the focus protocol a screen's own `step` /// never answers. fn go(engine: &mut FocusEngine, owner: InputOwner, page: &ConsentPage, dir: Dir, c: &Cx<'_, InnerHost>) -> Outcome { - engine.move_dir(owner, &page.view(), &[], dir, c) + engine.move_dir(owner, &page.view(plx_machine::machine::PressRead::::default()), &[], dir, c) } /// **The second half of this audit's LEFT-escape defect, and the RIGHT half legacy never @@ -741,13 +741,13 @@ fn overflowing_disclosure_scrolls_before_draw_with_visible_choice_focus_and_repl assert!(page.place(&BAND, &cx, At::SpringTarget).is_some(), "the visible action keeps the input focus"); assert!(out.is_empty(), "reading cannot submit or change focus"); assert_eq!(page.draft, (false, false)); - let outcome = engine.move_dir(owner, &page.view(), &[], Dir::Right, &cx); + let outcome = engine.move_dir(owner, &page.view(plx_machine::machine::PressRead::::default()), &[], Dir::Right, &cx); assert!(matches!(outcome, Outcome::Moved { .. })); cx.focus.current = engine.current(owner); assert_eq!(cx.focus.current.unwrap().elem, BAND + 1, "the other answer stays directly reachable"); page.step(&key_down(Key::Up), &cx, &mut mk_fx(&mut out, &mut present)); assert_eq!(page.state.hash(), before, "either answer can scroll back to the same position"); - engine.move_dir(owner, &page.view(), &[], Dir::Right, &cx); + engine.move_dir(owner, &page.view(plx_machine::machine::PressRead::::default()), &[], Dir::Right, &cx); assert!(engine.current(owner).is_some_and(|key| page.form.index_of_key(RowKey(key.elem)).is_some())); page.step(&key_down(Key::Back), &cx, &mut mk_fx(&mut out, &mut present)); assert!(out.iter().any(|event| matches!(event.fx, Fx::App(AppFx::Loop(LoopReq::BackAtRoot))))); diff --git a/rust-modules/screens/src/detail/cards_harness.rs b/rust-modules/screens/src/detail/cards_harness.rs index 4f68c230cb..c1da5474e5 100644 --- a/rust-modules/screens/src/detail/cards_harness.rs +++ b/rust-modules/screens/src/detail/cards_harness.rs @@ -127,7 +127,7 @@ impl Harness { fn step(&mut self, ev: ScreenEvent) -> bool { let mut present = plx_machine::present::Present::new(); let mut out = Vec::new(); - let (_, moving) = plx_machine::idle::scoped_motion(|| { + let (_, moving) = plx_machine::motion::report::scoped_motion(|| { static MEASURE: FixtureMeasure = FixtureMeasure; let cx = Cx:: { views: (), tick: Tick { ms: self.ms, dt_us: 16_667 }, measure: &MEASURE, press: PressRead { scale: self.press, owner: self.focus, ..Default::default() }, diff --git a/rust-modules/screens/src/detail/cast.rs b/rust-modules/screens/src/detail/cast.rs index 66c4a89ef7..e63bc40b4c 100644 --- a/rust-modules/screens/src/detail/cast.rs +++ b/rust-modules/screens/src/detail/cast.rs @@ -215,7 +215,7 @@ mod tests { safe.x + safe.w - RowStyle::CAST.w * 0.5] { let at = label_frame(center, 100.0, 0.0, &LabelMeasure); restart_clocks(); - plx_machine::idle::frame_begin(1.0 / 60.0); + plx_machine::motion::report::frame_begin(1.0 / 60.0); let log = |focused| plx_ui::draw_census::capture(|| { label(Painter::recording(), "Ana", caption, center, 100.0, focused, 0.0, &LabelMeasure); }); @@ -260,17 +260,17 @@ mod tests { fn a_focused_cast_name_that_does_not_fit_marquees() { let _serial = plx_base::testlock::serial(); restart_clocks(); - plx_machine::idle::frame_begin(1.0 / 60.0); - let _ = plx_machine::idle::take_local_damage(); + plx_machine::motion::report::frame_begin(1.0 / 60.0); + let _ = plx_machine::motion::report::take_local_motion(); let (rest, _) = runs(LONG_NAME, "", true); assert_eq!(rest.len(), 2, "a run and its follower: {rest:?}"); - assert_eq!(plx_machine::idle::take_local_damage(), 0, "resting is not damage"); + assert_eq!(plx_machine::motion::report::take_local_motion(), 0, "resting is not damage"); let x0 = rest.iter().map(|r| r.x).fold(f32::MAX, f32::min); - plx_machine::idle::frame_begin((marquee::TITLE.hold_ms + 500.0) / 1000.0); + plx_machine::motion::report::frame_begin((marquee::TITLE.hold_ms + 500.0) / 1000.0); let (gliding, _) = runs(LONG_NAME, "", true); let x1 = gliding.iter().map(|r| r.x).fold(f32::MAX, f32::min); assert!(x1 < x0, "the name has moved left: {x0} -> {x1}"); - assert!(plx_machine::idle::take_local_damage() > 0, "a gliding frame reports"); + assert!(plx_machine::motion::report::take_local_motion() > 0, "a gliding frame reports"); } /// And nothing else moves: a fitting focused name and any UNFOCUSED name draw one still run. @@ -279,11 +279,11 @@ mod tests { let _serial = plx_base::testlock::serial(); restart_clocks(); for _ in 0..3 { - plx_machine::idle::frame_begin(1.5); - let _ = plx_machine::idle::take_local_damage(); + plx_machine::motion::report::frame_begin(1.5); + let _ = plx_machine::motion::report::take_local_motion(); assert_eq!(runs("Ana", "", true).0.len(), 1, "a fitting focused name"); assert_eq!(runs(LONG_NAME, "", false).0.len(), 1, "an unfocused name elides"); - assert_eq!(plx_machine::idle::take_local_damage(), 0); + assert_eq!(plx_machine::motion::report::take_local_motion(), 0); } } @@ -294,19 +294,19 @@ mod tests { fn a_focused_role_that_overflows_marquees_one_that_fits_does_not() { let _serial = plx_base::testlock::serial(); restart_clocks(); - plx_machine::idle::frame_begin(1.0 / 60.0); - let _ = plx_machine::idle::take_local_damage(); + plx_machine::motion::report::frame_begin(1.0 / 60.0); + let _ = plx_machine::motion::report::take_local_motion(); let (_, rest) = runs("Ana", LONG_ROLE, true); assert_eq!(rest.len(), 2, "a run and its follower: {rest:?}"); let y = rest[0].y; assert!(rest.iter().all(|r| r.y == y), "one line, not a wrapped block"); - assert_eq!(plx_machine::idle::take_local_damage(), 0, "resting is not damage"); - plx_machine::idle::frame_begin((marquee::TITLE.hold_ms + 500.0) / 1000.0); + assert_eq!(plx_machine::motion::report::take_local_motion(), 0, "resting is not damage"); + plx_machine::motion::report::frame_begin((marquee::TITLE.hold_ms + 500.0) / 1000.0); let (_, gliding) = runs("Ana", LONG_ROLE, true); let x0 = rest.iter().map(|r| r.x).fold(f32::MAX, f32::min); let x1 = gliding.iter().map(|r| r.x).fold(f32::MAX, f32::min); assert!(x1 < x0, "the role has moved left: {x0} -> {x1}"); - assert!(plx_machine::idle::take_local_damage() > 0); + assert!(plx_machine::motion::report::take_local_motion() > 0); restart_clocks(); assert_eq!(runs("Ana", "Director", true).1.len(), 1, "a fitting role is one still run"); @@ -320,7 +320,7 @@ mod tests { #[test] fn a_cast_label_is_one_name_line_and_one_role_line_focused_or_not() { let _serial = plx_base::testlock::serial(); - plx_machine::idle::frame_begin(1.0 / 60.0); + plx_machine::motion::report::frame_begin(1.0 / 60.0); let ys = |runs: &[Rect]| -> Vec { let mut v: Vec = runs.iter().map(|r| r.y.round() as i32).collect(); v.sort_unstable(); @@ -352,7 +352,7 @@ mod tests { fn a_focused_name_and_role_that_both_overflow_glide_in_lockstep() { let _serial = plx_base::testlock::serial(); restart_clocks(); - plx_machine::idle::frame_begin(1.0 / 60.0); + plx_machine::motion::report::frame_begin(1.0 / 60.0); let (name0, role0) = runs(LONG_NAME, LONG_ROLE, true); let (name_x, role_x) = (name0[0].x, role0[0].x); assert_eq!((name0.len(), role0.len()), (2, 2)); @@ -360,7 +360,7 @@ mod tests { let name_period = marquee::TITLE.period(measure.width_str(LONG_NAME, theme::size::LABEL, true)); let role_period = marquee::TITLE.period(measure.width_str(LONG_ROLE, theme::size::CAPTION, false)); assert!(name_period + 3000.0 < role_period, "the fixture needs a much longer role"); - plx_machine::idle::frame_begin((name_period + 3000.0) / 1000.0); + plx_machine::motion::report::frame_begin((name_period + 3000.0) / 1000.0); let (name, role) = runs(LONG_NAME, LONG_ROLE, true); assert!(name.iter().any(|r| (r.x - name_x).abs() < 0.5), "the name waits at rest for the role instead of looping: {name:?}"); diff --git a/rust-modules/screens/src/detail/hero.rs b/rust-modules/screens/src/detail/hero.rs index e5f1c998d4..954a729489 100644 --- a/rust-modules/screens/src/detail/hero.rs +++ b/rust-modules/screens/src/detail/hero.rs @@ -2080,16 +2080,20 @@ mod tests { #[test] fn the_trailer_unfurl_spring_reports_while_opening_and_is_quiet_at_rest() { let _g = plx_base::testlock::serial(); - plx_machine::idle::reset_for_test(); + plx_machine::motion::report::reset_for_test(); // What the spring REPORTS is graded on this thread's own motion channel (`scoped_motion`), // not through `should_present`: that also reads the process-wide `DIRTY`, which an unlocked // test's repaint on another thread sets at any moment, so a quiet-frame assertion on it // failed at random under load. The `invalidate` from another thread between the steps below // is that repaint, raised on purpose: the verdict must not read it. let step = |spring: &mut plx_ui::Spring, target: f32| { - plx_machine::idle::scoped_motion(|| spring.step(target, plx_ui::widgets::K_DISC_UNFURL, 1.0 / 60.0)).1 + plx_machine::motion::report::scoped_motion(|| spring.step(target, plx_ui::widgets::K_DISC_UNFURL, 1.0 / 60.0)).1 }; - let foreign_repaint = || std::thread::spawn(plx_machine::idle::invalidate).join().expect("the repaint thread"); + let foreign_repaint = || std::thread::spawn(|| { + let mut other = plx_machine::present::Present::new(); + other.note(plx_machine::present::PresentEvent::Damage(plx_machine::present::Provenance::Input)); + assert!(other.page_damaged()); + }).join().expect("the repaint thread"); let mut springs = [plx_ui::Spring::at(0.0); 3]; for spring in springs.iter_mut() { foreign_repaint(); diff --git a/rust-modules/screens/src/detail/mod.rs b/rust-modules/screens/src/detail/mod.rs index 8495e4d2e5..15fd2e3791 100644 --- a/rust-modules/screens/src/detail/mod.rs +++ b/rust-modules/screens/src/detail/mod.rs @@ -525,11 +525,10 @@ impl DetailScreen { /// The membership the bookmark disc wears: On draws the filled face, Off and Unknown the outline /// (the PUT is idempotent, so an unknown membership offers Add). A change flips the disc. - pub fn set_watchlist(&mut self, membership: plx_data::catalog::Membership) { - // When the disc snaps and when it animates is its own rule (`watchlist_disc::Disc::set`). - if self.watchlist.set(membership) { - plx_machine::idle::invalidate(); - } + pub fn set_watchlist(&mut self, membership: plx_data::catalog::Membership) -> bool { + // The runner applies this changed-input effect to its owned Present. When + // the disc snaps or animates is still the disc's own motion rule. + self.watchlist.set(membership) } /// The membership the disc currently wears. @@ -924,7 +923,7 @@ impl DetailScreen { d.cur_season, Some(i), self.tab_scroll.pos, - self.season_pop.scale(0), + self.season_pop.scale(0, f.press), ), Some(Located::Episode(i, row)) => episodes::draw_focused( f.painter, @@ -1715,7 +1714,7 @@ impl Focusable f let base = hero::hero_btn_rect_at(set, i, self.hero_chain(measure, meta).btn_y - vertical, widths); ( - base.scaled(self.ctl_pop.scale(i)), + base.scaled(self.ctl_pop.scale(i, cx.press)), base.scaled(plx_ui::widgets::CTRL_FOCUS_SCALE), Some(i as u32), ) @@ -1727,7 +1726,7 @@ impl Focusable f self.tab_scroll.pos, )?; ( - base.scaled(self.season_pop.scale(0)), + base.scaled(self.season_pop.scale(0, cx.press)), base.scaled(plx_ui::widgets::CTRL_FOCUS_SCALE), Some(i as u32), ) @@ -2569,7 +2568,7 @@ impl Screen for _ => None, }, self.tab_scroll.pos, - self.season_pop.scale(0), + self.season_pop.scale(0, f.press), ), 2 => { episodes::draw( @@ -3064,7 +3063,7 @@ impl DetailScreen { for (i, ctl) in controls[..n].iter().copied().enumerate() { let rect = hero::hero_btn_rect_at(set, i, y, widths); let fill = self.ctl_pop.focus(i); - let scale = self.ctl_pop.scale(i); + let scale = self.ctl_pop.scale(i, cx.press); match ctl { hero::HeroCtl::Play => Button::new( hero::hero_pill_label(set.restart).as_ptr(), diff --git a/rust-modules/screens/src/detail/tests.rs b/rust-modules/screens/src/detail/tests.rs index c0f004d4da..7e8dd3b83b 100644 --- a/rust-modules/screens/src/detail/tests.rs +++ b/rust-modules/screens/src/detail/tests.rs @@ -5338,7 +5338,7 @@ fn the_held_episode_still_is_left_out_of_the_page_pass_and_drawn_once_by_the_lif } const DIP: f32 = 0.918; let mut context = cx(&measure, Some(key.elem)); - context.press = PressRead { scale: DIP, is_long: true, held_ms: Some(400), owner: Some(key) }; + context.press = PressRead { scale: DIP, is_long: true, held_ms: Some(400), owner: Some(key), ..Default::default() }; let mut census = |lifted: Option>, lift: bool| { plx_ui::popover::set_lift_owns(false); @@ -5405,7 +5405,7 @@ fn the_hold_hint_over_an_episode_still_waits_while_the_season_loads() { let measure = plx_ui::fixture::FixtureMeasure; let elem = episode_key(&screen, 0, episodes::Row::Still).unwrap(); let mut context = cx(&measure, Some(elem)); - context.press = PressRead { scale: 1.0, is_long: false, held_ms: Some(200), owner: None }; + context.press = PressRead { scale: 1.0, is_long: false, held_ms: Some(200), owner: None, ..Default::default() }; let located = Some(Located::Episode(0, episodes::Row::Still)); let hinted = |screen: &DetailScreen| screen.hint_input(&context, located).focus.is_some(); diff --git a/rust-modules/screens/src/filmography.rs b/rust-modules/screens/src/filmography.rs index bf4860a11c..bce3f05b7d 100644 --- a/rust-modules/screens/src/filmography.rs +++ b/rust-modules/screens/src/filmography.rs @@ -472,7 +472,7 @@ impl FilmographyScreen { } /// The department strip — capsules and pills — inside the caller's clip. - fn draw_tabs(&self, p: plx_ui::Painter, measure: &dyn Measure) { + fn draw_tabs(&self, p: plx_ui::Painter, measure: &dyn Measure, press: plx_machine::machine::PressRead) { widgets::draw_strip( p, &self.tabs, @@ -481,7 +481,7 @@ impl FilmographyScreen { PILL_H, self.tab_hscroll.pos, TabGround::Plated { - pop: self.pop.scale(0), + pop: self.pop.scale_with(0, press), }, ); } @@ -685,7 +685,7 @@ impl FilmographyScreen { .painter .translate((1.0 - f.page_alpha) * SCR_W, 0.0) .alpha(f.page_alpha); - self.ground.draw_host(p); + if self.ground.draw_host(p) { f.request_frame(); } self.ground_ready = opaque_ground_ready(f.page_alpha); let layout = route_layout(f.measure); let total: usize = self.model.iter().map(|d| d.total).sum(); @@ -712,7 +712,7 @@ impl FilmographyScreen { // Capsules and pills through ONE scroll offset (issue 14): the capsules used to be // drawn here in content space through this un-scrolled painter while the pills were // laid out already scrolled, so a scrolled row showed the focus plate off its label. - self.draw_tabs(p, f.measure); + self.draw_tabs(p, f.measure, f.press); p.clip_clear(); if self.tab_hscroll.pos > 0.5 { @@ -1340,7 +1340,7 @@ mod tests { } scrolled = scrolled.max(s.tab_hscroll.pos); let log = plx_ui::draw_census::capture(|| { - s.draw_tabs(plx_ui::Painter::recording(), &measure); + s.draw_tabs(plx_ui::Painter::recording(), &measure, plx_machine::machine::PressRead::<()>::default()); }); if frame < 39 { continue; @@ -1520,6 +1520,7 @@ mod tests { assert!(!has_content(&out, |_| true)); } PressEvent::Commit(_, _, _) => commits += 1, + PressEvent::PageDamage => {} } } } diff --git a/rust-modules/screens/src/home/cards_harness.rs b/rust-modules/screens/src/home/cards_harness.rs index 2b3362819c..1592535bf1 100644 --- a/rust-modules/screens/src/home/cards_harness.rs +++ b/rust-modules/screens/src/home/cards_harness.rs @@ -94,7 +94,7 @@ impl Harness { fn step(&mut self, ev: ScreenEvent) -> bool { let mut present = plx_machine::present::Present::new(); let mut out = Vec::new(); - let (_, moving) = plx_machine::idle::scoped_motion(|| { + let (_, moving) = plx_machine::motion::report::scoped_motion(|| { let cx = Cx:: { views: self.snap.view(), tick: Tick { ms: self.ms, dt_us: 16_667 }, measure: &FixtureMeasure, press: PressRead { scale: self.press, owner: self.focus, ..Default::default() }, focus: FocusRead { current: self.focus, ..Default::default() }, owner: InputOwner::Entry(ENTRY) }; diff --git a/rust-modules/screens/src/home/hero_watchlist_tests.rs b/rust-modules/screens/src/home/hero_watchlist_tests.rs index 80dc6febdb..b69986ba52 100644 --- a/rust-modules/screens/src/home/hero_watchlist_tests.rs +++ b/rust-modules/screens/src/home/hero_watchlist_tests.rs @@ -258,7 +258,7 @@ fn hero_runs(s: &mut HomeScreen, view: HubsView<'_>, slot: Option) -> Vec let env = s.env(0.0); plx_gfx::text::capture_text_runs_for_test(|| { let focus = slot.map(Located::Hero); - s.draw_hero_actions(hero, &env, Painter::recording(), 0.0, true, 0.5, focus, &plx_ui::fixture::FixtureMeasure, 1.0); + s.draw_hero_actions(hero, &env, Painter::recording(), 0.0, true, 0.5, focus, &plx_ui::fixture::FixtureMeasure, Default::default()); }) } diff --git a/rust-modules/screens/src/home/mod.rs b/rust-modules/screens/src/home/mod.rs index 1f6a0bfc8e..7b24b29f8c 100644 --- a/rust-modules/screens/src/home/mod.rs +++ b/rust-modules/screens/src/home/mod.rs @@ -275,10 +275,10 @@ impl HeroTint { return; } // decorative, like the wash's own dissolve: must not hold the page-freeze snapshot - plx_machine::idle::decorative(|| { + plx_machine::motion::report::decorative(|| { for (spring, v) in self.key.iter_mut().zip(target) { spring.step(v, AmbientWash::K, dt); - if plx_machine::idle::settled(spring.pos, v, spring.vel) { + if plx_machine::motion::report::settled(spring.pos, v, spring.vel) { spring.jump(v); } } @@ -492,7 +492,7 @@ impl Backdrop { ) { self.bind(hero, outgoing, selected, snap); // decorative hero-art reveal dissolve (same reason as the wash below) - plx_machine::idle::decorative(|| { + plx_machine::motion::report::decorative(|| { // A layer that has arrived is LANDED on 1.0 (`Spring::land`), as the wash below lands its // own springs: `step` parks one ulp short (0.9999998, a velocity of ~7.7e-7) and walks that // last ulp seconds later on a jittering frame time, and the art's tint alpha is an argument @@ -519,7 +519,7 @@ impl Backdrop { self.grid_target = AmbientWash::keyed(item.blur, PageGround::CARD_W); } // decorative colour dissolve under the page — must not hold the page-freeze snapshot - plx_machine::idle::decorative(|| { + plx_machine::motion::report::decorative(|| { self.wash.step( wash_corners(hero.map(|h| h.item), self.grid_target, snap), AmbientWash::K, @@ -1912,7 +1912,7 @@ impl HomeScreen { }; // decorative: an in-place scale of the focused control, no layout — must not hold the // page-freeze snapshot (`idle::decorative`) - plx_machine::idle::decorative(|| self.hero_pop.step(hero_focus, dt)); + plx_machine::motion::report::decorative(|| self.hero_pop.step(hero_focus, dt)); // The bookmark disc: the title it is for (read by the application's feed) and its flip. self.disc.shown = status_read(view) .is_none() @@ -2282,7 +2282,7 @@ impl HomeScreen { f.page_alpha, focus, f.measure, - f.press.scale, + f.press, ) }); } @@ -2320,7 +2320,7 @@ impl HomeScreen { page_alpha: f32, focus: Option, measure: &dyn Measure, - press_scale: f32, + press_scale: plx_machine::machine::PressRead, ) { let Some(hero) = self.selected_hero(view) else { return; @@ -2394,7 +2394,7 @@ impl HomeScreen { page_alpha: f32, focus: Option, measure: &dyn Measure, - press_scale: f32, + press_scale: plx_machine::machine::PressRead, ) { let (label, progress) = hero_action(hero); let HeroRects { play: pill, disc, info } = hero_rects(measure, hero, &label, progress.is_some()); @@ -2951,7 +2951,7 @@ impl Focusable for HomeScreen { base.x += self.slide_offsets().map_or(0.0, |(_, incoming)| incoming); } let scale = match at { - At::Drawn => self.hero_pop.scale_with(index, cx.press.scale), + At::Drawn => self.hero_pop.scale_with(index, cx.press), At::SpringTarget => { if self.focused_loc(cx.focus.current) == Some(Located::Hero(index)) { plx_ui::widgets::CTRL_FOCUS_SCALE diff --git a/rust-modules/screens/src/home/tests.rs b/rust-modules/screens/src/home/tests.rs index 5e00111c64..1b96b5ef46 100644 --- a/rust-modules/screens/src/home/tests.rs +++ b/rust-modules/screens/src/home/tests.rs @@ -591,6 +591,10 @@ fn drawn_hero_geometry_follows_slide_and_the_captured_press_scale() { for press in [0.93, 1.0, 1.025] { let mut context = cx(snapshot.view(), Some(key)); context.press.scale = press; + context.press.live = press != 1.0; + context.press.active = press != 1.0; + context.press.identity = 1; + context.press.owner = Some(key); let base = s.hero_button_rect(snapshot.view(), 0, context.measure).unwrap(); let drawn = Focusable::::place(&s, &key.elem, &context, At::Drawn).unwrap(); let target = Focusable::::place(&s, &key.elem, &context, At::SpringTarget).unwrap(); @@ -2530,9 +2534,8 @@ fn a_settled_hero_counting_down_lets_the_gate_close_and_still_flips() { let mut s = screen(view); let context = cx(view, None); let mut present = plx_machine::present::Present::new(); - // `take` at tick_ms 0 throughout keeps the keepalive term out: this counts only what the - // screen itself asked for. The first take drains the fresh gate's first-frame `dirty`. - present.take(0); + // Simulated swaps at tick_ms 0 keep the keepalive term out of the screen's requests. + swap_requested_frame(&mut present); let mut asked_while_counting = 0u32; let mut flipped_at = None; // 10 s of 16 ms ticks: past HERO_AUTO_S, so the countdown expires exactly once. @@ -2547,7 +2550,7 @@ fn a_settled_hero_counting_down_lets_the_gate_close_and_still_flips() { let tick = ScreenEvent::Tick(Tick { ms: frame * 16, dt_us: 16_000 }); Machine::::step(&mut s, &tick, &context, &mut fx); } - let asked = present.take(0); + let asked = swap_requested_frame(&mut present); if s.outgoing.is_some() { flipped_at.get_or_insert(frame); assert!(asked, "the flip's slide is motion and must present"); @@ -2569,10 +2572,17 @@ fn a_settled_hero_counting_down_lets_the_gate_close_and_still_flips() { /// Step `s` through `ticks` 16 ms frames with `focus` held, on one shared gate (`take` at tick ms 0 /// keeps the keepalive term out: this counts only what the screen itself asks for). Returns the frame /// the hero first began a slide on (if it did) and how many frames before that asked to present. +/// Admit and acknowledge only frames the test actually simulates presenting. +fn swap_requested_frame(present: &mut plx_machine::present::Present) -> bool { + let asked = present.take(0); + if asked { present.acknowledge(0); } + asked +} + fn run_hero_frames(s: &mut HomeScreen, view: HubsView<'_>, focus: Option>, ticks: u32) -> (Option, u32) { let context = cx(view, focus); let mut present = plx_machine::present::Present::new(); - present.take(0); + swap_requested_frame(&mut present); let (mut flipped_at, mut asked_before) = (None, 0u32); for frame in 1..=ticks { let mut out = Vec::new(); @@ -2581,7 +2591,7 @@ fn run_hero_frames(s: &mut HomeScreen, view: HubsView<'_>, focus: Option::step(s, &tick, &context, &mut fx); } - let asked = present.take(0); + let asked = swap_requested_frame(&mut present); if s.outgoing.is_some() { flipped_at.get_or_insert(frame); } else if flipped_at.is_none() && asked { @@ -3370,10 +3380,10 @@ fn decorative_wash_and_hero_pop_do_not_hold_page_quiescence() { let mut saw_decor = false; let mut layout_moving_frames = 0; for i in 1..40u32 { - plx_machine::idle::frame_begin(1.0 / 60.0); + plx_machine::motion::report::frame_begin(1.0 / 60.0); step(&mut s, snapshot.view(), Some(key), &ScreenEvent::Tick(Tick { ms: i * 16, dt_us: 16_667 })); - saw_decor |= plx_machine::idle::page_moving(); - layout_moving_frames += usize::from(plx_machine::idle::page_layout_moving()); + saw_decor |= plx_machine::motion::report::page_moving(); + layout_moving_frames += usize::from(plx_machine::motion::report::page_layout_moving()); } assert!(saw_decor, "the hero pop / wash dissolve must still report visible page motion"); assert_eq!(layout_moving_frames, 0, "decorative springs must not count as page layout motion"); @@ -4002,11 +4012,11 @@ fn the_hint_never_shows_while_the_page_is_still_gliding() { fn a_held_ok_fills_the_cap_from_the_press_clock_and_shows_the_hint_early() { with_hint_home(|mut s, view| { let card = Some(first_card(&s)); - let half = plx_ui::press::LONG_MS / 2; + let half = plx_ui::dispatch::press::LONG_MS / 2; hint_ticks(&mut s, view, card, Some(half), 0, 30); assert!(s.hold_hint.visible(), "the hold shows it without waiting out the dwell"); assert!((s.hold_hint.fill() - 0.5).abs() < 1e-6, "half of LONG_MS held is a half-filled cap"); - let input = s.hint_input(&{ let mut c = cx(view, card); c.press.held_ms = Some(plx_ui::press::LONG_MS * 2); c }, false); + let input = s.hint_input(&{ let mut c = cx(view, card); c.press.held_ms = Some(plx_ui::dispatch::press::LONG_MS * 2); c }, false); assert_eq!(input.hold, Some(1.0), "the constructor clamps the fraction; no screen divides"); // released early: the fill drains hint_ticks(&mut s, view, card, None, 0, hint_secs(0.4)); @@ -4039,7 +4049,7 @@ fn a_settled_hint_lets_the_gate_close() { // Home settled with the hint standing still: nothing in the tick may ask for a present. let context = cx(view, card); let mut present = plx_machine::present::Present::new(); - present.take(0); + swap_requested_frame(&mut present); let mut out = Vec::new(); let mut asked = 0; for i in 1..=60u32 { @@ -4048,7 +4058,7 @@ fn a_settled_hint_lets_the_gate_close() { let tick = ScreenEvent::Tick(Tick { ms: ms + i * HINT_TICK_MS, dt_us: HINT_TICK_MS * 1000 }); Machine::::step(&mut s, &tick, &context, &mut fx); } - asked += u32::from(present.take(0)); + asked += u32::from(swap_requested_frame(&mut present)); } assert_eq!(asked, 0, "a hint at rest must not hold the loop at full rate"); }); @@ -4066,7 +4076,7 @@ fn the_hint_does_not_stand_up_by_itself_while_the_screenshot_clocks_are_held() { assert!(!s.hold_hint.visible(), "pinned clocks: no self-appearing hint in a documentation figure"); let ms = hint_ticks(&mut s, view, card, Some(100), ms, 30); assert!(!s.hold_hint.visible(), "a short click stays hidden even with pinned clocks"); - hint_ticks(&mut s, view, card, Some(plx_ui::press::LONG_MS / 2), ms, 30); + hint_ticks(&mut s, view, card, Some(plx_ui::dispatch::press::LONG_MS / 2), ms, 30); assert!(s.hold_hint.visible(), "a deliberate hold is input and still shows it"); plx_machine::motion::hold_phase_clocks(None); }); diff --git a/rust-modules/screens/src/hud_settings.rs b/rust-modules/screens/src/hud_settings.rs index 09383285db..290b89c3fb 100644 --- a/rust-modules/screens/src/hud_settings.rs +++ b/rust-modules/screens/src/hud_settings.rs @@ -1059,7 +1059,9 @@ impl Machine for HudPage { } } let mut cycle = std::mem::take(&mut self.preview_cycle); - cycle.set_frames(&self.preview_frames()); + if cycle.set_frames(&self.preview_frames()) { + fx.invalidate(plx_machine::present::Provenance::Resource(plx_machine::present::ResourceKind::Texture)); + } cycle.tick(*t, self.preview_active(), &mut fx.present()); self.preview_cycle = cycle; self.form.table.update(t.dt(), RouteLayout::settings_page().sectioned_table().h); diff --git a/rust-modules/screens/src/library/cards_harness.rs b/rust-modules/screens/src/library/cards_harness.rs index 10c715b04a..aeb3087aec 100644 --- a/rust-modules/screens/src/library/cards_harness.rs +++ b/rust-modules/screens/src/library/cards_harness.rs @@ -133,7 +133,7 @@ impl Harness { fn step(&mut self, ev: ScreenEvent) -> bool { let mut present = plx_machine::present::Present::new(); let mut out = Vec::new(); - let (_, moving) = plx_machine::idle::scoped_motion(|| { + let (_, moving) = plx_machine::motion::report::scoped_motion(|| { let cx: Cx<'_, LibHost> = Cx { views: Views { listing: self.listing.view(), directory: self.directory.view(), hubs: self.hubs.view() }, tick: Tick { ms: self.ms, dt_us: 16_667 }, measure: &FixtureMeasure, diff --git a/rust-modules/screens/src/library/collections_listing_tests.rs b/rust-modules/screens/src/library/collections_listing_tests.rs index ac6f09fc29..0244cb13f4 100644 --- a/rust-modules/screens/src/library/collections_listing_tests.rs +++ b/rust-modules/screens/src/library/collections_listing_tests.rs @@ -180,7 +180,7 @@ fn a_long_collection_name_is_held_to_its_lifted_tile_with_a_fade_and_marquees() use plx_machine::machine::Measure as _; let _guard = plx_base::testlock::serial(); let _lang = plx_platform::i18n::language_on_this_thread_for_test(plx_platform::i18n::Preference::from_tag("en")); - plx_machine::idle::frame_begin(1.0 / 60.0); + plx_machine::motion::report::frame_begin(1.0 / 60.0); let name = "The Complete Blender Foundation Open Movie Projects: Every Short Film and Making-Of, Extended Cuts, \ Commentary Tracks, Concept Art and the Complete Behind-the-Scenes Production Diaries, Box Set"; let item = plx_data::pms::PmsMovie { diff --git a/rust-modules/screens/src/library/grid_motion_tests.rs b/rust-modules/screens/src/library/grid_motion_tests.rs index 3e2cbd57e9..0a8081d502 100644 --- a/rust-modules/screens/src/library/grid_motion_tests.rs +++ b/rust-modules/screens/src/library/grid_motion_tests.rs @@ -570,12 +570,12 @@ fn relist_regression_the_removed_tail_card_has_its_ghost_pixels() { let (playing, ghosts) = page.pair.detail.relist_probe(); assert!(playing); assert_eq!(ghosts, [Some("7".to_string())], "the removed last tile must fade with its own pixels"); - plx_machine::idle::frame_begin(1.0 / 60.0); - let (_, moving) = plx_machine::idle::scoped_motion(|| frame(&mut page, &mut engine, &fixture, 4032)); + plx_machine::motion::report::frame_begin(1.0 / 60.0); + let (_, moving) = plx_machine::motion::report::scoped_motion(|| frame(&mut page, &mut engine, &fixture, 4032)); assert!(moving, "the landing buys frames while moving"); settle(&mut page, &mut engine, &fixture, 4048); - plx_machine::idle::frame_begin(1.0 / 60.0); - let (_, moving) = plx_machine::idle::scoped_motion(|| frame(&mut page, &mut engine, &fixture, 8000)); + plx_machine::motion::report::frame_begin(1.0 / 60.0); + let (_, moving) = plx_machine::motion::report::scoped_motion(|| frame(&mut page, &mut engine, &fixture, 8000)); assert!(!moving, "a settled landing buys no frames"); assert_eq!(page.pair.detail.relist_probe(), (false, Vec::new())); } diff --git a/rust-modules/screens/src/library/header.rs b/rust-modules/screens/src/library/header.rs index dd3280013f..8ccef117c6 100644 --- a/rust-modules/screens/src/library/header.rs +++ b/rust-modules/screens/src/library/header.rs @@ -444,7 +444,7 @@ impl LibraryScreen { // the control's whole menu-open stretch, during which the engine's focus is on the menu's // rows and the row's motion HOLDS. let lifted = f.lifted.filter(|key| key.entry == self.entry).map(|key| key.elem); - row.draw_with(p, self.scroll.pos, &self.header_capsules, self.header_pop.scale_with(0, f.press.scale), lifted, &self.header_swap); + row.draw_with(p, self.scroll.pos, &self.header_capsules, self.header_pop.scale_with(0, f.press), lifted, &self.header_swap); } /// **The opener lift for a header control** (`Screen::redraw_focused`): `elem`, the control a @@ -458,6 +458,6 @@ impl LibraryScreen { pub(super) fn draw_header_opener(&self, f: &DrawFrame<'_, '_, H>, elem: u32) { let Some(row) = self.header.row() else { return }; let p = f.painter.alpha(f.page_alpha * self.page_fade.alpha() * self.handoff.clearance(layout::HEADER_Y - self.scroll.pos)); - row.draw_opener_with(p, self.scroll.pos, self.header_pop.scale_with(0, f.press.scale), elem, &self.header_swap); + row.draw_opener_with(p, self.scroll.pos, self.header_pop.scale_with(0, f.press), elem, &self.header_swap); } } diff --git a/rust-modules/screens/src/library/lookahead.rs b/rust-modules/screens/src/library/lookahead.rs index 61d5d16c80..b803d333ef 100644 --- a/rust-modules/screens/src/library/lookahead.rs +++ b/rust-modules/screens/src/library/lookahead.rs @@ -115,7 +115,7 @@ impl Rest { None => {} } self.target = Some(target); - self.still >= SETTLE_FRAMES && plx_machine::idle::settled(scroll, target, 0.0) + self.still >= SETTLE_FRAMES && plx_machine::motion::report::settled(scroll, target, 0.0) } pub(super) fn forward(&self) -> bool { self.forward } diff --git a/rust-modules/screens/src/library/menu.rs b/rust-modules/screens/src/library/menu.rs index 5921bb47d8..aab45e6922 100644 --- a/rust-modules/screens/src/library/menu.rs +++ b/rust-modules/screens/src/library/menu.rs @@ -888,7 +888,7 @@ impl Screen for LibraryMenu { // container's appear: the panel begins and ends as the control it grows from. let field = f.underlay; let frame = self.frame(measure); - let m = self.popover.content_painter_on(f.painter, 0.0); + let m = self.popover.content_painter_on(f.painter.alpha(f.nav_page_alpha), 0.0); plx_ui::profile::phase("lb.menu", || { let shown = self.motion.shown(frame); self.popover.panel(m, shown, PANEL_RADIUS, field, plx_ui::widgets::Ground::Menu); diff --git a/rust-modules/screens/src/library/rail.rs b/rust-modules/screens/src/library/rail.rs index 7799443791..6e49d2354d 100644 --- a/rust-modules/screens/src/library/rail.rs +++ b/rust-modules/screens/src/library/rail.rs @@ -410,7 +410,7 @@ mod tests { fn rail_scroll_and_presence_animate_then_settle_outside_the_grid_region() { let _guard = plx_base::testlock::serial(); let mut rail = model(); - let (_, moving) = plx_machine::idle::scoped_motion(|| rail.step_motion(Some(39), true, 0.016)); + let (_, moving) = plx_machine::motion::report::scoped_motion(|| rail.step_motion(Some(39), true, 0.016)); assert!(moving, "entering the region reports its scroll and fade motion"); assert!(rail.scroll.pos > 0.0 && rail.scroll.pos < rail.scroll_target); assert!(rail.alpha.pos > 0.0 && rail.alpha.pos < 1.0); @@ -419,7 +419,7 @@ mod tests { assert!((rail.alpha.pos - 1.0).abs() < 0.001 && rail.alpha.vel.abs() < 0.001); for _ in 0..400 { rail.step_motion(None, false, 0.016); } assert!(rail.alpha.pos.abs() < 0.001 && rail.alpha.vel.abs() < 0.001); - let (_, moving) = plx_machine::idle::scoped_motion(|| rail.step_motion(None, false, 0.016)); + let (_, moving) = plx_machine::motion::report::scoped_motion(|| rail.step_motion(None, false, 0.016)); assert!(!moving, "a resting hidden rail requests no further animated presents"); } @@ -632,7 +632,7 @@ impl LibraryLike for RailHost { let _guard = plx_base::testlock::serial(); let mut rail = model(); for _ in 0..400 { rail.step_motion(Some(0), RailHint::default().wants_rail(false), 0.016); } - let (_, moving) = plx_machine::idle::scoped_motion(|| rail.step_motion(Some(0), false, 0.016)); + let (_, moving) = plx_machine::motion::report::scoped_motion(|| rail.step_motion(Some(0), false, 0.016)); assert!(!moving); assert!(rail.alpha.pos.abs() < 0.001); } diff --git a/rust-modules/screens/src/library/recommended.rs b/rust-modules/screens/src/library/recommended.rs index c38f633d50..7f90340a9b 100644 --- a/rust-modules/screens/src/library/recommended.rs +++ b/rust-modules/screens/src/library/recommended.rs @@ -1306,7 +1306,7 @@ impl RecommendedScreen { /// The page's title row: " › Recommended". pub(super) fn draw_title(&self, f: &DrawFrame<'_, '_, H>) { self.header(f.cx).draw(f.painter.alpha(f.page_alpha), self.scroll.pos, &self.header_capsules, - self.header_pop.scale_with(0, f.press.scale), None); + self.header_pop.scale_with(0, f.press), None); } fn library_title<'a, H: LibraryLike>(cx: &Cx<'a, H>) -> &'a str { diff --git a/rust-modules/screens/src/library/shelf_action_tests.rs b/rust-modules/screens/src/library/shelf_action_tests.rs index 0060fe4c80..98b0aef67e 100644 --- a/rust-modules/screens/src/library/shelf_action_tests.rs +++ b/rust-modules/screens/src/library/shelf_action_tests.rs @@ -88,6 +88,7 @@ fn shelf_activate_and_hold_keep_the_deck_promise_and_engine_item_identity() { is_long: true, held_ms: None, owner: None, + ..Default::default() }, owner, }; diff --git a/rust-modules/screens/src/library/tests.rs b/rust-modules/screens/src/library/tests.rs index fb3cf14300..2327041835 100644 --- a/rust-modules/screens/src/library/tests.rs +++ b/rust-modules/screens/src/library/tests.rs @@ -660,7 +660,8 @@ fn owned_card_stops_clip_pointer_hits_and_hold_the_engine_item() { assert_eq!(resolved.activate, Some((chosen, plx_ui::screen::Activate::Press))); input.engine.set(OWNER, chosen, page.group_of(&chosen.elem, &cx), By::Pointer); input.arm(PressArm { key: chosen, from: PressFrom::Pointer, holdable: true }, MachineId::Instance(InstanceId(19)), 0); - let held = input.tick(plx_ui::press::LONG_MS + 1, 0.016); + let held: Vec<_> = input.tick(plx_ui::dispatch::press::LONG_MS + 1, 0.016).into_iter() + .filter(|event| !matches!(event, PressEvent::PageDamage)).collect(); assert!(matches!(held.as_slice(), [PressEvent::Hold(_, _, key)] if *key == chosen)); let PressEvent::Hold(id, _, _) = held[0] else { unreachable!() }; let mut out = Vec::new(); diff --git a/rust-modules/screens/src/login.rs b/rust-modules/screens/src/login.rs index 6166ba2620..4a9c3862c9 100644 --- a/rust-modules/screens/src/login.rs +++ b/rust-modules/screens/src/login.rs @@ -1165,6 +1165,7 @@ impl LoginScreen { /// the alert down when the offer it asks about has gone, and step the motion. fn tick_report(&mut self, t: Tick, cx: &Cx<'_, H>, fx: &mut Effects<'_, H>) { use auth::owner::IncidentState as S; + let alert_was_visible = self.report.alert.visible(); let offer = self.report.offer.clone(); let id = offer.as_ref().map(|o| o.id); if self.report.support_for != id { @@ -1235,7 +1236,12 @@ impl LoginScreen { use plx_ui::decision_alert::Answers; let body = self.report.details_body(); let answers = if self.report.sendable() { Answers::Two } else { Answers::One }; - self.report.alert.reconcile_card(plx_platform::i18n::msg::settings_login_details_c(), body, answers); + if self.report.alert.reconcile_card(plx_platform::i18n::msg::settings_login_details_c(), body, answers) { + fx.invalidate(plx_machine::present::Provenance::Lifecycle); + } + } + if alert_was_visible != self.report.alert.visible() { + fx.invalidate(plx_machine::present::Provenance::Lifecycle); } self.report.alert.update(t.dt()); let focused = cx @@ -1694,7 +1700,7 @@ impl LoginScreen { mut o: StatusOverlay<'_>, focus: Option, ) { - let press = f.press.scale; + let press = f.press; let pop = &self.report.pop; if o.action.is_some() { o = o @@ -1902,7 +1908,7 @@ impl LoginScreen { if let Some(rect) = details { Button::new(plx_platform::i18n::msg::settings_login_details_c().as_ptr(), theme::size::BODY, rect) .focused(focus == Some(DETAILS)) - .scale(self.report.pop.scale_with(1, f.press.scale)) + .scale(self.report.pop.scale_with(1, f.press)) .draw(&Env::inert(), p); } #[cfg(feature = "finnative")] @@ -1958,13 +1964,13 @@ impl LoginScreen { if !self.report.alert.visible() { return; } - self.report.alert.draw_scrim(); + self.report.alert.draw_scrim(f); let (cancel, affirm) = match self.report.sheet { Sheet::Question => (plx_platform::i18n::msg::settings_plaintext_not_now_c(), plx_platform::i18n::msg::settings_login_send_report_c()), Sheet::Details => (plx_platform::i18n::msg::settings_login_close_c(), plx_platform::i18n::msg::settings_login_send_report_c()), Sheet::Plaintext => PlaintextQuestion::verbs(), }; - self.report.alert.draw(cancel, affirm, f.measure); + self.report.alert.draw(cancel, affirm, f.measure, f.route_navigation(), f.press); let frames = self.report.alert.frames(f.measure); if self.report.alert.is_open() && self.report.alert.settled() { for &elem in self.alert_elems() { diff --git a/rust-modules/screens/src/onboard.rs b/rust-modules/screens/src/onboard.rs index b79167b8d9..a5e63dbf81 100644 --- a/rust-modules/screens/src/onboard.rs +++ b/rust-modules/screens/src/onboard.rs @@ -471,7 +471,7 @@ struct OnboardView<'a> { } impl<'a> OnboardView<'a> { - fn screen(&'a self) -> TableScreen<'a> { + fn screen(&'a self, press: plx_machine::machine::PressRead) -> TableScreen<'a> { let layout = RouteLayout::screen(); TableScreen::new(Header::new(layout, None, "", ""), &self.screen.form.table, TABLE_GROUP, self.screen.entry) .keyed(&self.screen.form) @@ -482,7 +482,7 @@ impl<'a> OnboardView<'a> { group: BAND_GROUP, entry: self.screen.entry, uncommitted: false, - scales: [self.screen.pop.scale(0), 1.0], + scales: [self.screen.pop.scale_with(0, press), 1.0], palette: palette(), danger: None, note: None, @@ -492,22 +492,22 @@ impl<'a> OnboardView<'a> { impl plx_ui::screen::Focusable for OnboardView<'_> { fn groups(&self, cx: &Cx<'_, H>, out: &mut Vec) { - plx_ui::screen::Focusable::::groups(&self.screen(), cx, out) + plx_ui::screen::Focusable::::groups(&self.screen(cx.press), cx, out) } fn group_of(&self, key: &u32, cx: &Cx<'_, H>) -> Option { - plx_ui::screen::Focusable::::group_of(&self.screen(), key, cx) + plx_ui::screen::Focusable::::group_of(&self.screen(cx.press), key, cx) } fn neighbour(&self, key: plx_machine::machine::FocusKey, dir: plx_ui::screen::Dir, cx: &Cx<'_, H>) -> plx_ui::screen::Step { - plx_ui::screen::Focusable::::neighbour(&self.screen(), key, dir, cx) + plx_ui::screen::Focusable::::neighbour(&self.screen(cx.press), key, dir, cx) } fn place(&self, key: &u32, cx: &Cx<'_, H>, at: plx_ui::screen::At) -> Option { - plx_ui::screen::Focusable::::place(&self.screen(), key, cx, at) + plx_ui::screen::Focusable::::place(&self.screen(cx.press), key, cx, at) } fn reconcile(&self, want: plx_machine::machine::FocusKey, cx: &Cx<'_, H>) -> plx_machine::machine::FocusKey { - plx_ui::screen::Focusable::::reconcile(&self.screen(), want, cx) + plx_ui::screen::Focusable::::reconcile(&self.screen(cx.press), want, cx) } fn seat(&self, g: GroupId, from: plx_ui::screen::Placed, cx: &Cx<'_, H>) -> plx_machine::machine::FocusKey { - plx_ui::screen::Focusable::::seat(&self.screen(), g, from, cx) + plx_ui::screen::Focusable::::seat(&self.screen(cx.press), g, from, cx) } } @@ -782,7 +782,7 @@ impl Screen for OnboardScreen { group: BAND_GROUP, entry: self.entry, uncommitted: false, - scales: [self.pop.scale(0), 1.0], + scales: [self.pop.scale_with(0, f.press), 1.0], palette: pal, danger: None, note: None, diff --git a/rust-modules/screens/src/person/cards_harness.rs b/rust-modules/screens/src/person/cards_harness.rs index 8456783204..57924ae7aa 100644 --- a/rust-modules/screens/src/person/cards_harness.rs +++ b/rust-modules/screens/src/person/cards_harness.rs @@ -76,7 +76,7 @@ impl Harness { fn step(&mut self, ev: ScreenEvent) -> bool { let mut present = plx_machine::present::Present::new(); let mut out = Vec::new(); - let (_, moving) = plx_machine::idle::scoped_motion(|| { + let (_, moving) = plx_machine::motion::report::scoped_motion(|| { let cx = Cx { views: self.store.view(), tick: Tick { ms: self.ms, dt_us: 16_667 }, measure: &FixtureMeasure, press: PressRead { scale: self.press, owner: self.focus, ..Default::default() }, focus: FocusRead { current: self.focus, ..Default::default() }, owner: InputOwner::Entry(ENTRY) }; diff --git a/rust-modules/screens/src/plaintext_question.rs b/rust-modules/screens/src/plaintext_question.rs index 4a23eccd52..4975b96dca 100644 --- a/rust-modules/screens/src/plaintext_question.rs +++ b/rust-modules/screens/src/plaintext_question.rs @@ -361,9 +361,9 @@ impl PlaintextAlert { if !self.alert.visible() { return; } - self.alert.draw_scrim(); + self.alert.draw_scrim(f); let (cancel, affirm) = PlaintextQuestion::verbs(); - self.alert.draw(cancel, affirm, f.measure); + self.alert.draw(cancel, affirm, f.measure, f.route_navigation(), f.press); let frames = self.alert.frames(f.measure); self.frames.set(Some(frames)); if self.alert.is_open() && self.alert.settled() { diff --git a/rust-modules/screens/src/player/hud_pins_tests.rs b/rust-modules/screens/src/player/hud_pins_tests.rs index 04a3c88042..760c214360 100644 --- a/rust-modules/screens/src/player/hud_pins_tests.rs +++ b/rust-modules/screens/src/player/hud_pins_tests.rs @@ -2572,20 +2572,7 @@ mod sections { Shown { group, held, btn, tab, open: self.open_sections() } } - /// **What the app does with `ArmControlRow`** (a click on the control row): the press dips, and the loop's commit - /// frame performs the command of the row item the cursor holds (`app::playback::activate_player_row`). Here the - /// part that reaches the page: a `toggle_section` is answered with the addressed event, as `perform` does for the - /// command OK asks. - fn perform_armed_row(&mut self) { - if !self.rig.perform || !self.rig.reqs.contains(&PlayerReq::ArmControlRow) { - return; - } - let btn = self.screen().hud.nav.btn; - if let Some(HudCommand::ToggleSection(section)) = self.screen().row_command(btn) { - let page = MachineId::Instance(self.d.top_page().expect("the player page is mounted")); - self.d.emit(page, Fx::Deliver(page, Delivery::Screen(ScreenEvent::App(AppMsg::HudSection(section))))); - } - } + } /// The reference with `section` opened from its disc, `how`, and the disc's row index. A click needs a drawn @@ -2872,19 +2859,22 @@ mod sections { assert_idle_playhead(); let _chapters = Chaptered::install(); let mut run = classic_run(Occupant::Plain); - run.open_from_tab(1); - let seat = (run.held().unwrap() - ELEM_CHAPTER_BASE) as usize; + run.walk("DDR"); + run.tap(Key::Ok); + let mut seat = None; let mut first = None; for _ in 0..40 { if first.is_none() && run.appear(Section::Chapters) > 0.0 { - first = Some(run.screen().row.strip_shelf().unwrap().pop_of(seat)); + let index = (run.held().unwrap() - ELEM_CHAPTER_BASE) as usize; + seat = Some(index); + first = Some(run.screen().row.strip_shelf().unwrap().pop_of(index)); } run.frames(1); } let first = first.expect("the section appears"); assert!(first < 1.02, "the seat is at pop {first} when the section first moves, not grown from rest"); run.frames(120); - let settled = run.screen().row.strip_shelf().unwrap().pop_of(seat); + let settled = run.screen().row.strip_shelf().unwrap().pop_of(seat.expect("the opening section seats a chapter")); assert!((settled - plx_ui::widgets::CARD_FOCUS_SCALE).abs() < 0.001, "…and reaches the focus scale: {settled}"); } @@ -2900,13 +2890,13 @@ mod sections { run.open_from_tab(0); run.step('D'); run.frames(30); - assert!(run.screen().row.section_scale(1) > 1.0, "the second button is popped while it holds the focus"); + assert!(run.screen().row.section_scale(1, Default::default()) > 1.0, "the second button is popped while it holds the focus"); run.step('D'); run.frames(300); assert!(run.presented().is_empty()); run.toggle(Section::Info); // the first button has begun to grow toward the focus the card opens on; the second has none - let scale = run.screen().row.section_scale(1); + let scale = run.screen().row.section_scale(1, Default::default()); assert_eq!(scale.to_bits(), 1.0f32.to_bits(), "the second button opens at rest, not at {scale}"); } @@ -3168,7 +3158,7 @@ mod sections { let now = self.now; self.frame(now, vec![pointer_event(plx_machine::machine::InputKind::Click { x, y, hit: None }, now)]); self.frame(now + 60, vec![key_up(Key::Ok, tick(now + 60))]); - self.perform_armed_row(); + self.settle(now + 60); self.now += 600; } diff --git a/rust-modules/screens/src/player/mod.rs b/rust-modules/screens/src/player/mod.rs index 4224d83c05..f5a9c953d2 100644 --- a/rust-modules/screens/src/player/mod.rs +++ b/rust-modules/screens/src/player/mod.rs @@ -12,11 +12,9 @@ //! region and the capture skip — are the loop's three privileged calls (§3.3 steps 1, 9 and 10) and //! are not made here. //! -//! **What is here and what is not.** Phase 9 moves the STATE and the DRAW; the key ladder in -//! `app/run.rs` remains a CALLER of this screen for the bare transport, exactly as `ui::press`'s -//! typed facade left the ladders callers of `App.input.press` in phase 2 (§14, "Press during -//! coexistence"). The overlays are different: they are entries on this page's own -//! `ModalStack` and own their input outright, so their arms left the ladder with them. +//! **Input ownership.** The dispatcher delivers keys and pointer input to this page and its +//! overlays. Both row input modes arm the dispatcher's single press and receive an addressed +//! commit; the application performs only the resulting typed command or stand-in request. //! //! Two fields are PUBLISHED rather than owned by `player::TX` (§2.3): `hud.until` and `scrub.ns`. //! [`PlayerScreen::publish`] mirrors both into the atomics the draw path and the engine read, and @@ -373,6 +371,12 @@ impl PlayerScreen { .then(|| self.auto_skip.progress()); let frame = plx_appkit::player_hud::render::Frame { entry: self.entry, + press: plx_machine::machine::PressRead { + scale: df.press.scale, identity: df.press.identity, + live: df.press.live, active: df.press.active, + is_long: df.press.is_long, held_ms: df.press.held_ms, + owner: df.press.owner.and_then(|k| k.elem.index().map(|elem| plx_machine::machine::FocusKey { entry: k.entry, elem })), + }, ps, model: &model, up: &self.up_next, @@ -496,7 +500,7 @@ impl PlayerScreen { /// **Everything this page draws from a CLOCK, folded into ONE value** (spec §8.3, §9). /// - /// The loop compares it with the previous frame's and raises `plx_machine::idle::invalidate()` when it + /// The loop compares it with the previous frame's and applies owned lifecycle damage when it /// changes; `Player::note_clock` owns the comparison. This is what replaces the exemption the /// player route used to have from the present gate. /// @@ -669,8 +673,8 @@ impl Machine for PlayerScreen /// [`Stop`]s — see [`Screen::draw`]) is resolved the same way `PlayerOverlayScreen::step` /// resolves one. Anything privileged (pausing/resuming, seeking, presenting an overlay, leaving /// the player) is a `fx.push(Fx::App(AppFx::Player(PlayerReq::…)))` request, exactly as - /// [`PlayerOverlayScreen::ask`] performs one — `PlayerReq::OpenOverlay`/`ArmControlRow`/`Exit` - /// are the three variants this package added for it. `Exit`, the remote's own key, is the one + /// [`PlayerOverlayScreen::ask`] performs one — for example `PlayerReq::OpenOverlay`/`Exit`. + /// `Exit`, the remote's own key, is the one /// this screen deliberately does NOT try to own (see the doc this replaced); it is not matched /// below and falls to `Handled::No`. /// @@ -1206,7 +1210,7 @@ impl PlayerScreen { } self.hud.nav.btn = btn; self.seat_elem(fx, e); - self.arm_control_row(fx); + self.arm_control_row(e, fx); Handled::Yes } e if (ELEM_TAB_BASE..ELEM_FAILURE_BASE).contains(&e) => { @@ -1324,7 +1328,7 @@ impl PlayerScreen { match input::failed_key_action(key, self.failure_sel, n) { input::FailedKeyAction::Focus(i) => { self.failure_sel = i; - plx_machine::idle::invalidate(); + fx.invalidate(plx_machine::present::Provenance::Input); } input::FailedKeyAction::Activate(i) => self.failure_activate(ps, i, fx), input::FailedKeyAction::Return => Self::ask(fx, PlayerReq::Exit), @@ -1568,11 +1572,15 @@ impl PlayerScreen { } } - /// The control row's deferred press (`PlayerReq::ArmControlRow`). It takes the page from the - /// scrubber, so a pending target is cancelled with it. - fn arm_control_row(&mut self, fx: &mut Effects<'_, H>) { + /// Arm the exact clicked row control in the dispatcher's input owner. Commit follows the + /// same addressed `PressCommit` and command/stand-in path as a keyboard press. + fn arm_control_row(&mut self, elem: u32, fx: &mut Effects<'_, H>) { self.scrub.cancel(); - Self::ask(fx, PlayerReq::ArmControlRow); + fx.push(Fx::Press(plx_machine::machine::PressArm { + key: FocusKey { entry: self.entry, elem }, + from: plx_machine::machine::PressFrom::Pointer, + holdable: false, + })); } /// **The screen's answer to `Step::Edge`**: the dispatcher re-delivers a direction the engine @@ -2699,9 +2707,8 @@ impl Screen for PlayerScreen { // // `Activate::Direct` on them, and it is not the same statement `ElemKind` makes // elsewhere: the transport's control row DOES dip, and OK on it is the engine's own press - // (`key_ok` leaves it alone, the commit is `row_pressed`). A pointer CLICK on it is still - // the loop's (`PlayerReq::ArmControlRow` → `press.begin_ctl` → `activate_player_row` on the - // spring-back), which the hit census pins; both converge on `perform_hud_command`. Direct + // (`key_ok` leaves it alone, the commit is `row_pressed`). A pointer click arms the same + // dispatcher input with the clicked row key; both converge on `row_pressed`. Direct // delivery, and the screen decides what the element means — including the scrubber, whose // meaning needs the click's `x` and so cannot be carried by a bare `ScreenEvent::Activate` // at all, and the tabs, which ask their section's toggle at once with no dip to wait for. @@ -2724,8 +2731,8 @@ impl Screen for PlayerScreen { // the scrim; BEFORE the overlay panels, which the container draws above this page. plx_appkit::player_hud::classic::draw_readout(ps, self.busy, now, self.failure_sel, f.measure); if self.repair_alert.visible() { - self.repair_alert.draw_scrim(); - self.repair_alert.draw(plx_platform::i18n::msg::settings_cancel_c(), plx_platform::i18n::msg::widgets_repair_action_c(), f.measure); + self.repair_alert.draw_scrim(f); + self.repair_alert.draw(plx_platform::i18n::msg::settings_cancel_c(), plx_platform::i18n::msg::widgets_repair_action_c(), f.measure, f.route_navigation(), f.press); } self.record_stops(f, hud_drawn); } @@ -2782,24 +2789,25 @@ mod clock_animator_tests { /// the machine's comparison, exactly as `app::run`'s prepare phase runs them. `true` = THIS /// path raised damage, i.e. this frame is owed a present. /// - /// Graded on `idle::take_local_damage`, which counts what this THREAD reported, rather than on - /// `should_present`, which reads the process-wide `DIRTY`/`DAMAGE_GEN` that every unlocked - /// test repainting anything also moves — the flake `plx_machine::idle`'s own `LOCAL_DAMAGE` doc - /// describes, and which cost this test two red runs in six before it was written this way. - /// The gate's own half is asserted once, below, where it cannot be made false by another - /// thread: a spurious `invalidate` elsewhere can only make `should_present` MORE true. + /// Apply the clock comparison's explicit changed outcome to an independent owner; + /// another input or a worker cannot publish or consume this owner's page damage. fn reported(pl: &mut Player, screen: &PlayerScreen, ps: &PlaybackSession, now: u32) -> bool { - let _ = plx_machine::idle::take_local_damage(); - if pl.note_clock(screen.clock_fingerprint(ps, now)) { - plx_machine::idle::invalidate(); + let mut present = plx_machine::present::Present::new(); + present.take(now); + present.acknowledge(now); + let changed = pl.note_clock(screen.clock_fingerprint(ps, now)); + if changed { + present.note_in_scope(plx_machine::present::Scope::Page, + plx_machine::present::PresentEvent::Damage(plx_machine::present::Provenance::Lifecycle)); } - plx_machine::idle::take_local_damage() > 0 + assert_eq!(present.take(now), changed, "the actual report must schedule precisely its owned frame"); + present.page_damaged() } /// Run the page to a standstill, so that a report below can only be this test's own doing. fn settled(pl: &mut Player, screen: &PlayerScreen, ps: &PlaybackSession, now: u32) { - plx_machine::idle::set_enabled(true); - plx_machine::idle::frame_begin(1.0 / 60.0); + + plx_machine::motion::report::frame_begin(1.0 / 60.0); for t in 0..4 { reported(pl, screen, ps, now + t); } @@ -2811,9 +2819,7 @@ mod clock_animator_tests { } /// The other half, asserted once per test: a report really does open the gate. - fn presents(now: u32) -> bool { - plx_machine::idle::should_present(now) - } + /// **The MEDIA CLOCK class** — the scrub bar, the playhead, both clocks, the hold-to-scrub /// ramp. Everything derived from `playpos_ns`, which LG's media thread writes and no spring @@ -2840,7 +2846,6 @@ mod clock_animator_tests { reported(&mut pl, &screen, &ps, 1_005), "the playhead moved half a second: the scrub bar and both clocks must report", ); - assert!(presents(1_005), "…and a report is a frame"); } /// **The DEADLINE class** — the HUD's auto-hide. At `now == until` the whole transport leaves @@ -2860,7 +2865,6 @@ mod clock_animator_tests { reported(&mut pl, &screen, &ps, 2_600), "the transport disappeared on this frame: it must report", ); - assert!(presents(2_600), "…and a report is a frame"); } /// **The TRANSPORT MARK class** — the two-second `Play` glyph, whose own doc used to record @@ -2886,7 +2890,6 @@ mod clock_animator_tests { reported(&mut pl, &screen, &ps, after), "the Play mark stopped being drawn on this frame: it must report", ); - assert!(presents(after), "…and a report is a frame"); } /// **The READ-OUT class** — `busy`, i.e. the centred status surface appearing and vanishing. @@ -2909,7 +2912,6 @@ mod clock_animator_tests { reported(&mut pl, &screen, &ps, 9_005), "the failure read-out took the screen on this frame: it must report", ); - assert!(presents(9_005), "…and a report is a frame"); } } @@ -3232,6 +3234,16 @@ mod step_ladder_tests { &cx(), &mut Effects::new(&mut out, MachineId::Instance(INST), &mut present), ); + if player_hud::row_index(elem).is_some() { + let arms: Vec<_> = out.iter().filter_map(|e| match &e.fx { + Fx::Press(arm) => Some(arm), + _ => None, + }).collect(); + assert_eq!(arms.len(), 1, "one dispatcher arm for a clicked control"); + assert_eq!(arms[0].key, FocusKey { entry: ENTRY, elem }); + assert_eq!(arms[0].from, plx_machine::machine::PressFrom::Pointer); + assert!(!arms[0].holdable); + } let reqs = out .into_iter() .filter_map(|e| match e.fx { @@ -3580,12 +3592,12 @@ mod step_ladder_tests { page.repair_alert.close(); continue; } - assert!(!reqs.is_empty(), "{name}: a click on {elem} asked for nothing"); + assert!(player_hud::row_index(elem).is_some() || !reqs.is_empty(), "{name}: a click on {elem} asked for nothing"); assert!(!reqs.iter().any(|r| matches!(r, PlayerReq::Transport(_))), "{name}: {elem} -> {reqs:?}"); assert!(page.hud.until >= 1_000 + input::HUD_LINGER_MS, "{name}: a click re-arms the linger"); if player_hud::row_index(elem).is_some() { assert_eq!(page.hud.nav.btn, (elem - ELEM_CONTROL_BASE) as i32, "{name}: the CLICKED item arms"); - assert_eq!(reqs, vec![PlayerReq::ArmControlRow]); + assert!(reqs.is_empty(), "the pointer arm is a dispatcher effect"); } if elem == ELEM_TAB_BASE { assert_eq!(reqs, vec![PlayerReq::Command(HudCommand::ToggleSection(Section::Info))], "{name}: Info"); @@ -4102,7 +4114,7 @@ mod step_ladder_tests { assert_eq!(handled, Handled::Yes); assert_eq!(page.hud.nav.focus, GROUP_ROW); assert_eq!(page.hud.nav.btn, player_hud::BTN_AUDIO); - assert_eq!(reqs, vec![PlayerReq::ArmControlRow]); + assert!(reqs.is_empty(), "the pointer arm is a dispatcher effect"); } /// The scrubber's registered `Stop` is the exact band `scrub_hit` tests, so a click resolved @@ -5224,7 +5236,7 @@ mod scrub_ownership_tests { { let mut out = Vec::new(); let mut present = plx_machine::present::Present::new(); - page.arm_control_row(&mut Effects::::new(&mut out, MachineId::Instance(INST), &mut present)); + page.arm_control_row(player_hud::control_elem(page.hud.nav.btn), &mut Effects::::new(&mut out, MachineId::Instance(INST), &mut present)); } settled(&mut page, "the control row's press"); let mut page = pending(); @@ -5655,7 +5667,7 @@ mod automatic_marker_tests { at: Tick { ms: 2_000, dt_us: 0 }, source: Source::Sdl, kind: InputKind::Click { x: 1_600.0, y: 830.0, hit: Some(player_hud::control_elem(button)) }, })); - assert_eq!(reqs, if button == up_next::BTN_NEXT { vec![PlayerReq::ArmControlRow] } else { vec![] }); + assert!(reqs.is_empty(), "pointer presses arm dispatcher input, not app requests"); assert_eq!(page.hud.nav.focus, GROUP_ROW); assert_eq!(page.hud.nav.btn, button, "the pointer seats the button it chose"); assert_eq!(rig.current(), Some(player_hud::control_elem(button))); diff --git a/rust-modules/screens/src/player/overlay_tests.rs b/rust-modules/screens/src/player/overlay_tests.rs index 6b1abd2af1..66014ff09c 100644 --- a/rust-modules/screens/src/player/overlay_tests.rs +++ b/rust-modules/screens/src/player/overlay_tests.rs @@ -456,7 +456,7 @@ fn the_more_title_band_is_a_pointer_only_stop_and_slides_with_its_page() { f.into_stops() }; let tick = |page: &mut PlayerOverlayScreen, ms: u32| { - plx_machine::idle::frame_begin(1.0 / 60.0); + plx_machine::motion::report::frame_begin(1.0 / 60.0); deliver(page, ScreenEvent::Tick(Tick { ms, dt_us: 16_667 })); }; tick(&mut page, 1_000); @@ -712,7 +712,7 @@ fn the_pointer_is_held_while_a_page_slides_and_released_at_rest() { let meta = plx_data::stores::metadata::MetadataStore::default(); let mut page = PlayerOverlayScreen::new(&ps, meta.view(), ENTRY, OverlayKind::Tracks { tab: 1 }); let tick = |page: &mut PlayerOverlayScreen, ms: u32| { - plx_machine::idle::frame_begin(1.0 / 60.0); + plx_machine::motion::report::frame_begin(1.0 / 60.0); deliver(page, ScreenEvent::Tick(Tick { ms, dt_us: 16_667 })); }; tick(&mut page, 1_000); diff --git a/rust-modules/screens/src/profiles.rs b/rust-modules/screens/src/profiles.rs index 4808e0b597..5215dcd54b 100644 --- a/rust-modules/screens/src/profiles.rs +++ b/rust-modules/screens/src/profiles.rs @@ -842,7 +842,7 @@ impl ProfilesScreen { /// Advance the wrong-PIN flash by one frame, and invalidate on the phase FLIPS alone — the two /// halves `ui/CLAUDE.md` demands of anything that animates from a CLOCK rather than a spring /// (`Xfade::tick`/`Spinner::draw`'s own standing hazard). Ported from `ui/profiles.rs`'s - /// `step_pin_flash`, `plx_machine::idle::invalidate()` replaced by `Effects::invalidate` — this screen + /// `step_pin_flash`, `plx_machine::motion::report::invalidate()` replaced by `Effects::invalidate` — this screen /// has no `plx_machine::idle` gate to report to; the dispatcher's own `Present` is fed exclusively /// through `Effects`/`fx.note`. fn step_pin_flash(pad: &mut Pad, dt: f32, fx: &mut Effects<'_, H>) { @@ -1771,7 +1771,7 @@ impl Screen for ProfilesScreen { focused_i = Some(i); continue; // draw the focused tile last (ring over neighbours) } - let rect = self.row.draw(p, i, base, Self::avatar_art(u, H::screen_inputs(f.cx).current_server), false, f.measure); + let rect = self.row.draw(p, i, base, Self::avatar_art(u, H::screen_inputs(f.cx).current_server), false, f.measure, &f.press, &plx_machine::machine::FocusKey { entry: self.entry, elem: i as u32 }); Self::draw_name(p, u, cx_, false, f.measure); f.stop( p, @@ -1799,7 +1799,7 @@ impl Screen for ProfilesScreen { ); Self::draw_name(p, u, cx_, true, f.measure); // the click dip folds into the focused avatar's pop (1.0 when idle) - let rect = self.row.draw(p, i, base, Self::avatar_art(u, H::screen_inputs(f.cx).current_server), true, f.measure); + let rect = self.row.draw(p, i, base, Self::avatar_art(u, H::screen_inputs(f.cx).current_server), true, f.measure, &f.press, &plx_machine::machine::FocusKey { entry: self.entry, elem: i as u32 }); f.stop( p, Stop { @@ -1838,7 +1838,7 @@ impl Screen for ProfilesScreen { // controls on its own row: *Back* (what the BACK key does, focused) and *Sign out* // beside it, or *Sign out* alone when BACK would leave the app (`readout_back`). let reason = CString::new(self.error.as_ref()).unwrap_or_default(); - let press = f.press.scale; + let press = f.press; let overlay = readout_overlay(&reason, self.back_resumes) .focus(cur.and_then(|e| self.readout_slot(e))) .scales([0, 1].map(|i| self.footer_pop.scale_with(i, press))); @@ -1855,7 +1855,7 @@ impl Screen for ProfilesScreen { let footer_r = footer_rect(f.measure); Button::new(plx_platform::i18n::msg::settings_account_sign_out_c().as_ptr(), theme::size::BODY, footer_r) .focused(footer_focused) - .scale(self.footer_pop.scale(0)) + .scale(self.footer_pop.scale(0, f.press)) .palette(self.ground.palette()) .draw(&Env::inert(), p); stop(f, FOOTER, footer_r); diff --git a/rust-modules/screens/src/profiles_pin_tests.rs b/rust-modules/screens/src/profiles_pin_tests.rs index b7dc51354e..7e03aa647b 100644 --- a/rust-modules/screens/src/profiles_pin_tests.rs +++ b/rust-modules/screens/src/profiles_pin_tests.rs @@ -92,7 +92,8 @@ fn the_wrong_pin_flash_blinks_at_least_four_times() { #[test] fn a_flash_flip_invalidates_the_present_gate() { let mut present = Present::new(); - present.take(0); // drain the fresh gate's own always-dirty first frame + assert!(present.take(0)); // admit the fresh gate's always-dirty first frame + present.acknowledge(0); // simulate its actual swap let mut pad = Pad { open: true, error_s: PIN_ERR_S, @@ -110,6 +111,7 @@ fn a_flash_flip_invalidates_the_present_gate() { } let now = pin_flash(pad.error_s); let asked = present.take(0); + if asked { present.acknowledge(0); } // simulate only admitted swaps if now != was { assert!( asked, diff --git a/rust-modules/screens/src/registry.rs b/rust-modules/screens/src/registry.rs index 4f78581841..65a9dbec67 100644 --- a/rust-modules/screens/src/registry.rs +++ b/rust-modules/screens/src/registry.rs @@ -270,18 +270,11 @@ pub enum PlayerReq { /// `super::bridge::open_player_overlay` straight from the loop's key ladder; `PlayerScreen` /// may not name that function itself (§2.2), so it asks instead. OpenOverlay(crate::player::overlay::OverlayKind), - /// **A pointer click landed on the transport's own control row** — whichever disc, the Skip - /// pill or the Up Next tile currently occupies it. Arms a tvOS press dip; - /// the loop's commit-frame dispatch - /// (`app/run.rs`'s `Route::Player => activate_player_row(...)`) performs whatever the row - /// decides once the spring-back has played, through the same performer OK reaches by - /// [`Command`](PlayerReq::Command) and [`StandIn`](PlayerReq::StandIn). OK on the row does not - /// ask this: the focus engine presses the control itself. - ArmControlRow, + /// **A press on a control of the discs committed**, after the engine's tvOS dip has played /// (`PressCommit`, [`PlayerScreen`](crate::player::PlayerScreen)): perform this command. The screen resolves the command of the control the /// engine holds, so the app's performer (`app::playback::perform_hud_command`) never reads a - /// cursor. OK on the row is this; a pointer click on the row is still [`ArmControlRow`](PlayerReq::ArmControlRow). + /// cursor. Keyboard and pointer presses use this same commit path. Command(plx_appkit::player_hud::command::HudCommand), /// **A press on a stand-in committed** — the Skip pill, or one of the Up Next pair — after the /// same dip. A stand-in's meaning depends on the segment it offers, which the app resolves on diff --git a/rust-modules/screens/src/search/cards_harness.rs b/rust-modules/screens/src/search/cards_harness.rs index 50d74d85aa..59b6bcf4f2 100644 --- a/rust-modules/screens/src/search/cards_harness.rs +++ b/rust-modules/screens/src/search/cards_harness.rs @@ -80,7 +80,7 @@ impl Harness { fn step(&mut self, ev: ScreenEvent) -> bool { let mut present = Present::new(); let mut out = Vec::new(); - let (_, moving) = plx_machine::idle::scoped_motion(|| { + let (_, moving) = plx_machine::motion::report::scoped_motion(|| { let cx: Cx<'_, SearchHost> = Cx { views: self.snap.view(), tick: Tick { ms: self.ms, dt_us: 16_667 }, measure: &FixtureMeasure, press: PressRead { scale: self.press, ..Default::default() }, focus: FocusRead { current: self.focus, ..Default::default() }, owner: InputOwner::Entry(ENTRY) }; diff --git a/rust-modules/screens/src/search/tests.rs b/rust-modules/screens/src/search/tests.rs index b55271a962..2233240dad 100644 --- a/rust-modules/screens/src/search/tests.rs +++ b/rust-modules/screens/src/search/tests.rs @@ -109,12 +109,16 @@ fn deliver(screen: &mut SearchScreen, fixture: &Fixture, focus: Option::step(screen, &event, &cx, &mut fx) }; - (handled, out, present.take(1)) + let asked = present.take(1); + if asked { present.acknowledge(1); } + (handled, out, asked) } /// One frame: the tick every screen owes, graded on whether it asked the gate for a present. diff --git a/rust-modules/screens/src/settings.rs b/rust-modules/screens/src/settings.rs index 13ed2614f8..b223c72cac 100644 --- a/rust-modules/screens/src/settings.rs +++ b/rust-modules/screens/src/settings.rs @@ -891,7 +891,7 @@ impl Screen for RouteSurface { // opaque ground at rest and what fades out over the host on dismissal let dim = theme::scrim_black(settings_scrim_alpha(a, f.nav_page_alpha)); root.rect(Rect::FULL, 0.0, dim, dim, 0.0); - plx_ui::profile::phase("st.ground", || self.ground.draw_host(root.alpha(a))); + plx_ui::profile::phase("st.ground", || { if self.ground.draw_host(root.alpha(a)) { f.request_frame(); } }); } Family::FirstRunConsent => { self.ground.draw_home(root); @@ -917,6 +917,7 @@ impl Screen for RouteSurface { if let Some(inst) = self.top_mut() { let mut inner = DrawFrame::with_navigation(&icx, f.painter, navigation); inst.screen.draw(&mut inner); + if inner.take_frame_request() { f.request_frame(); } } self.push.route.walked(); } @@ -994,6 +995,7 @@ impl RouteSurface { if let Some(inst) = self.top_mut() { let mut inner = DrawFrame::with_navigation(&icx, entrance, navigation); inst.screen.draw(&mut inner); + if inner.take_frame_request() { f.request_frame(); } stops.extend(inner.into_stops()); } } else { @@ -1002,6 +1004,7 @@ impl RouteSurface { let mut inner = DrawFrame::with_navigation(&icx, parent_p, navigation); inner.push = parent_frame; inst.screen.draw(&mut inner); + if inner.take_frame_request() { f.request_frame(); } stops.extend(inner.into_stops()); } } @@ -1015,6 +1018,7 @@ impl RouteSurface { let mut inner = DrawFrame::with_navigation(&icx, child_p, navigation); inner.push = child_frame; inst.screen.draw(&mut inner); + if inner.take_frame_request() { f.request_frame(); } // a leaving page takes no input: its stops are not registered if !popping { stops.extend(inner.into_stops()); diff --git a/rust-modules/screens/src/settings_draw_and_lifecycle_tests.rs b/rust-modules/screens/src/settings_draw_and_lifecycle_tests.rs index 78b331d532..b641d7f29e 100644 --- a/rust-modules/screens/src/settings_draw_and_lifecycle_tests.rs +++ b/rust-modules/screens/src/settings_draw_and_lifecycle_tests.rs @@ -57,7 +57,7 @@ fn nested_draw_preserves_navigation_at_rest_and_through_push_and_pop() { let seen = Rc::new(RefCell::new(Vec::new())); let instance = |id| Instance { id: InstanceId(id), - screen: Box::new(DrawProbe { id, seen: Rc::clone(&seen) }) as Box>, + screen: Box::new(DrawProbe { id, wake: order.last() == Some(&id), seen: Rc::clone(&seen) }) as Box>, inflight: Vec::new(), staged: false, staged_effects: Vec::new(), @@ -83,6 +83,14 @@ fn nested_draw_preserves_navigation_at_rest_and_through_push_and_pop() { let mut f = DrawFrame::with_navigation(&c, Painter::root(), navigation); let before = LogicalState::hash(&surface); surface.draw_pages(&mut f, Painter::root()); + let mut owner = plx_machine::present::Present::new(); + let mut unrelated = plx_machine::present::Present::new(); + for p in [&mut owner, &mut unrelated] { p.take(0); p.acknowledge(0); } + f.apply_frame_requests(&mut owner); + assert!(owner.peek(1), "{label}: even a leaving child must forward its deferred demand"); + assert!(!unrelated.peek(1)); + assert!(!owner.page_damaged()); + assert!(!owner.page_moving()); assert_eq!(LogicalState::hash(&surface), before, "{label}: draw changed logical state"); actual.push((label, seen.borrow().clone())); expected.push((label, order.iter().map(|&id| (id, navigation)).collect::>())); diff --git a/rust-modules/screens/src/settings_test_support.rs b/rust-modules/screens/src/settings_test_support.rs index c56ce6bd54..0ebd837bea 100644 --- a/rust-modules/screens/src/settings_test_support.rs +++ b/rust-modules/screens/src/settings_test_support.rs @@ -89,6 +89,7 @@ pub fn name(s: &RouteSurface) -> &'static str { pub struct DrawProbe { pub(super) id: u32, + pub(super) wake: bool, pub(super) seen: std::rc::Rc>>, } @@ -116,6 +117,7 @@ impl Screen for DrawProbe { fn crumb(&self, _: &Cx<'_, InnerHost>) -> Option> { None } fn prepare(&mut self, _: &mut Budget, _: &Cx<'_, InnerHost>) {} fn draw(&mut self, f: &mut DrawFrame<'_, '_, InnerHost>) { + if self.wake { f.request_frame(); } self.seen.borrow_mut().push((self.id, plx_ui::screen::NavPresentation { page_alpha: f.page_alpha, chrome_alpha: f.chrome_alpha, diff --git a/rust-modules/screens/src/watchlist/cards_harness.rs b/rust-modules/screens/src/watchlist/cards_harness.rs index 74fa8bed22..e0b566aec8 100644 --- a/rust-modules/screens/src/watchlist/cards_harness.rs +++ b/rust-modules/screens/src/watchlist/cards_harness.rs @@ -246,7 +246,7 @@ impl Harness { pub(crate) fn step_fx(&mut self, ev: ScreenEvent) -> (Vec>, bool) { let mut present = plx_machine::present::Present::new(); let mut out = Vec::new(); - let (_, moving) = plx_machine::idle::scoped_motion(|| { + let (_, moving) = plx_machine::motion::report::scoped_motion(|| { let cx = Cx { views: (), tick: Tick { ms: self.ms, dt_us: 16_667 }, diff --git a/rust-modules/screens/src/watchlist/menu.rs b/rust-modules/screens/src/watchlist/menu.rs index b0073abd88..0311cbc9c5 100644 --- a/rust-modules/screens/src/watchlist/menu.rs +++ b/rust-modules/screens/src/watchlist/menu.rs @@ -216,7 +216,7 @@ impl Screen for WatchlistMenuScreen { /// morph is its own entrance, and the pill above it is the opener lift's. fn draw(&mut self, f: &mut DrawFrame<'_, '_, H>) { let p = f.painter.alpha(f.page_alpha); - self.menu.draw(f.painter, f.underlay, f.measure); + self.menu.draw(f.painter.alpha(f.nav_page_alpha), f.underlay, f.measure); for row in 0..OptionsRow::ALL.len() { let Some(rect) = self.menu.row_frame(row, f.measure) else { continue }; f.stop( diff --git a/rust-modules/screens/src/watchlist/page.rs b/rust-modules/screens/src/watchlist/page.rs index 24b8726e93..2392bd4be9 100644 --- a/rust-modules/screens/src/watchlist/page.rs +++ b/rust-modules/screens/src/watchlist/page.rs @@ -738,7 +738,7 @@ impl StackPage for Page { // stands in while the scroll is still bringing it home (`Handoff::clearance`). let p = p.alpha(self.handoff.head_alpha(r.y)); let row = self.header_row(f.measure); - row.draw(p, r.y, &self.header_capsules, self.header_pop.scale_with(0, f.press.scale), lifted, &self.header_swap.borrow()); + row.draw(p, r.y, &self.header_capsules, self.header_pop.scale_with(0, f.press), lifted, &self.header_swap.borrow()); #[cfg(feature = "devtriggers")] if self.dev_blocked { header::draw_dev_blocked(p, r.y); @@ -950,7 +950,7 @@ impl WatchlistScreen { let row = self.page.header_row(f.measure); let dy = placed.rect.y - row.plate().y; let p = f.painter.alpha(f.page_alpha).alpha(self.page.handoff.head_alpha(dy)); - row.draw_opener(p, dy, self.page.header_pop.scale_with(0, f.press.scale), &self.page.header_swap.borrow()); + row.draw_opener(p, dy, self.page.header_pop.scale_with(0, f.press), &self.page.header_swap.borrow()); } /// The Sort & Filter control as the focused pill draws it, in the page's document space: the diff --git a/rust-modules/session/src/auth/owner.rs b/rust-modules/session/src/auth/owner.rs index 44eba92e9e..d39f53b8c6 100644 --- a/rust-modules/session/src/auth/owner.rs +++ b/rust-modules/session/src/auth/owner.rs @@ -7618,7 +7618,8 @@ mod tests { measure: &plx_machine::machine::BareMeasure, press: Default::default(), focus: Default::default(), owner: InputOwner::Entry(EntryId(0)) }; let mut present = plx_machine::present::Present::new(); - let _ = present.take(0); // the spinner's last frame has been presented + assert!(present.take(0)); // admit the spinner's last frame + present.acknowledge(0); // its simulated swap has completed assert!(!present.peek(0), "rig: nothing is owed before the result lands"); let mut sink = Vec::new(); owner.step(&SessionEvent::Result(envelope), &cx, diff --git a/rust-modules/src/app/account_menu_route_tests.rs b/rust-modules/src/app/account_menu_route_tests.rs index de34eb2e0c..e11d57a168 100644 --- a/rust-modules/src/app/account_menu_route_tests.rs +++ b/rust-modules/src/app/account_menu_route_tests.rs @@ -135,7 +135,7 @@ fn the_morph_begins_and_ends_on_the_chip_as_the_bar_draws_it() { w.land_watchlist(); w.settle(30); let drawn = |w: &World| { - let presented = w.bridge.navigation_presentation().tucked(w.d.top_screen().expect("a page").chrome_tuck()); + let presented = w.bridge.navigation_presentation(&w.d.nav).tucked(w.d.top_screen().expect("a page").chrome_tuck()); w.bridge.bar_member_rect(TAB_KEY_CHIP, presented).expect("the chip is a bar member") }; crate::app::bridge::open_account_menu(&mut w.d); diff --git a/rust-modules/src/app/adapters/backends.rs b/rust-modules/src/app/adapters/backends.rs index a62b8c6125..c22dcdddae 100644 --- a/rust-modules/src/app/adapters/backends.rs +++ b/rust-modules/src/app/adapters/backends.rs @@ -364,7 +364,7 @@ impl MonotonicClock for ProductUriClock { /// global read here, so a test passes its own. The line ends `major= evidence=table|none`: /// `table` when `strata` admitted that major's exported window, `none` otherwise. `none` says only /// that the table admitted nothing, not that the play is Standard: an ACB set reads `none` and -/// still plays URI through `Acb` for a viewer who opted in, while a webOS 5+ release with no entry +/// still plays URI through `Acb` for a viewer who opted in, while a webOS 5+ major with no entry /// reads `none` and plays Standard. The debug override logs its own `evidence=override` line after /// this one. #[cfg(feature = "play-uri")] @@ -663,10 +663,10 @@ mod tests { assert_eq!(uri_product_binding(&sink, &booted(&sink), 11, &[11]), UriBinding::Unbound); } - /// The exported window follows the firmware major through the composition: production's empty - /// table binds no major (a webOS 5+ release without an entry plays Standard), and a table that lists the - /// major binds it, on a display in the exported-window mode only. The URI engine's own handle - /// is not asked for: a 5+ set has none. + /// The exported window follows the firmware major through the composition: production's table + /// binds major 5 (webOS 5.6.2, `docs/uri-mode.md`) and no other (a webOS 5+ release without an + /// entry plays Standard), and a table that lists a major binds it, on a display in the + /// exported-window mode only. The URI engine's own handle is not asked for: a 5+ set has none. #[cfg(feature = "play-uri")] #[test] fn the_exported_window_is_composed_only_for_a_major_the_table_lists() { @@ -674,11 +674,17 @@ mod tests { let exported = UriBinding::Exported { canvas: EXPORTED_CANVAS }; let sink = BootSink::answering(VP_EXPORTED, vec![7, 8]); let owner = booted(&sink); - // Production's table is empty: every release, known or not, composes Unbound on this display. An entry - // lands with its Results row and the change to this test. + // Production's table admits major 5 and nothing else: every other release, known or not, + // composes Unbound on this display. An entry lands with its Results row and the change to + // this test. for major in 0..=30 { - assert_eq!(uri_product_binding(&sink, &owner, major, EXPORTED_STRATA), UriBinding::Unbound, - "major {major}"); + let want = if major == 5 { exported } else { UriBinding::Unbound }; + assert_eq!(uri_product_binding(&sink, &owner, major, EXPORTED_STRATA), want, "major {major}"); + } + // The same display on a set whose mode is not the exported window: major 5 binds nothing there. + for mode in [VP_NONE, plx_platform::tv::sink::VP_ACB] { + let sink = BootSink::answering(mode, vec![7, 8]); + assert_ne!(uri_product_binding(&sink, &booted(&sink), 5, EXPORTED_STRATA), exported, "mode {mode}"); } assert_eq!(uri_product_binding(&sink, &owner, 11, &[11]), exported); assert_eq!(uri_product_binding(&sink, &owner, 10, &[11]), UriBinding::Unbound, "an unlisted major"); @@ -706,6 +712,10 @@ mod tests { let unlisted = line(VP_EXPORTED, 11, &[]); assert!(unlisted.contains("uri: product binding=Unbound mode=2 "), "{unlisted}"); assert!(unlisted.contains(" major=11 evidence=none\n"), "{unlisted}"); + // Production's own table: the webOS 5.6.2 television's boot line reads `major=5 evidence=table`. + let shipped = line(VP_EXPORTED, 5, plx_play_uri::backend::EXPORTED_STRATA); + assert!(shipped.contains("uri: product binding=Exported { canvas: (1920, 1080) } mode=2 "), "{shipped}"); + assert!(shipped.contains(" major=5 evidence=table\n"), "{shipped}"); let acb = line(plx_platform::tv::sink::VP_ACB, 4, &[]); assert!(acb.contains("uri: product binding=Acb ") && acb.contains(" major=4 evidence=none\n"), "{acb}"); } diff --git a/rust-modules/src/app/adapters/hostsim/sim_video.rs b/rust-modules/src/app/adapters/hostsim/sim_video.rs index 075d74b308..2b407da933 100644 --- a/rust-modules/src/app/adapters/hostsim/sim_video.rs +++ b/rust-modules/src/app/adapters/hostsim/sim_video.rs @@ -139,7 +139,7 @@ fn reset(clear_picture: bool) { *SESSION.lock().unwrap_or_else(|e| e.into_inner()) = None; if clear_picture { *LATEST.lock().unwrap_or_else(|e| e.into_inner()) = None; - plx_machine::idle::invalidate(); + } } @@ -220,7 +220,7 @@ fn spawn() -> Option { if frames == 1 { plx_base::eventlog::log("simvideo: first picture decoded"); } - plx_machine::idle::invalidate(); + plx_machine::present::wake_from_worker(); } }); if writer.is_err() || reader.is_err() { diff --git a/rust-modules/src/app/adapters/huds.rs b/rust-modules/src/app/adapters/huds.rs index 428936ed90..2b4ba3b023 100644 --- a/rust-modules/src/app/adapters/huds.rs +++ b/rust-modules/src/app/adapters/huds.rs @@ -6,7 +6,9 @@ //! `appkit::hud_format::admit` (parse, invariants, the app's format range) and returns each result as the //! machine's own addressed event. The effects reach the worker in the order the store pushed them, so //! a `Delete` never overtakes the write it follows. Every answer wakes the frame loop -//! (`idle::invalidate`), because an idle loop does not iterate on its own. +//! through the documented worker scheduling door. UI damage is applied only when the +//! owning HudPage ingests its changed HudList (`Effects::invalidate(Landing(Session))`); +//! the worker never claims page/surface provenance. //! //! **The driver** ([`HudDriver`], owned by the Bridge) steps the store with the answers, executes the //! effects it returns (`Selection` persists the profile's pick, `Notice` is kept for the Settings page) and @@ -367,12 +369,12 @@ impl Executor { match self { Executor::Worker => { let (reply, answer) = std::sync::mpsc::channel(); - if !plx_base::task::spawn_small("hud-fetch", move || { + let _ = plx_base::task::spawn_small("hud-fetch", move || { let _ = reply.send(job()); - plx_machine::idle::invalidate(); - }) { - plx_machine::idle::invalidate(); - } + plx_machine::present::wake_from_worker(); + }); + // Refusal drops the sender. The next runner poll consumes Disconnected + // as its addressed failure; no worker wake or UI damage is fabricated. Slot::Waiting(answer) } #[cfg(test)] @@ -388,7 +390,7 @@ impl Executor { let (reply, answer) = std::sync::mpsc::channel(); let _ = submit_retained(move || { let _ = reply.send(job()); - plx_machine::idle::invalidate(); + plx_machine::present::wake_from_worker(); }); Slot::Waiting(answer) } diff --git a/rust-modules/src/app/adapters/poster.rs b/rust-modules/src/app/adapters/poster.rs index 2821cb3791..9240627611 100644 --- a/rust-modules/src/app/adapters/poster.rs +++ b/rust-modules/src/app/adapters/poster.rs @@ -371,18 +371,16 @@ fn evict_wake_due(s: &Pslot, now: u32) -> bool { s.state == P_EVICTED && s.evict_cooldown_until.is_some_and(|t| now.wrapping_sub(t) < u32::MAX / 2) } -/// Wake the present gate once a scheduled retry's main-thread deadline arrives. The loop calls this -/// even while a settled screen skips draws; the draw it requests is what probes the slot again and -/// moves it back to `P_WANT`. -fn invalidate_due_retries(slots: &mut [Pslot; PT_CAP], now: u32) { +/// Return a typed deadline result once per scheduled retry batch. The runner consumes it +/// through its owned present gate even while a settled screen skips draws; the admitted draw +/// probes the slot again and moves it back to `P_WANT`. +fn invalidate_due_retries(slots: &mut [Pslot; PT_CAP], now: u32) -> Option { let mut due = false; for s in slots.iter_mut().filter(|s| !s.retry_wake_sent && retry_due(s, now)) { s.retry_wake_sent = true; // latch the whole batch; one frame probes every visible slot due = true; } - if due { - plx_machine::idle::invalidate(); - } + due.then_some(ResourceOutcome::RetryDue) } /// The eviction-cooldown twin of [`invalidate_due_retries`], and the fix for the gap the @@ -393,24 +391,22 @@ fn invalidate_due_retries(slots: &mut [Pslot; PT_CAP], now: u32) { /// draws would invalidate every loop iteration forever, undoing the idle behaviour the app depends /// on. The wake only ever asks for one present; it does not itself re-arm anything — re-arming /// stays Draw-only, through `lookup`'s P_EVICTED branch, exactly as before. -fn invalidate_due_evictions(slots: &mut [Pslot; PT_CAP], now: u32) { +fn invalidate_due_evictions(slots: &mut [Pslot; PT_CAP], now: u32) -> Option { let mut due = false; for s in slots.iter_mut().filter(|s| !s.evict_wake_sent && evict_wake_due(s, now)) { s.evict_wake_sent = true; due = true; } - if due { - plx_machine::idle::invalidate(); - } + due.then_some(ResourceOutcome::EvictionDue) } /// Park one transient result and request the draw that assigns its main-thread deadline. -fn park_retry(s: &mut Pslot) { +fn park_retry(s: &mut Pslot) -> ResourceOutcome { s.attempts = s.attempts.saturating_add(1); s.retry_at = None; s.retry_wake_sent = false; s.state = P_RETRY; - plx_machine::idle::invalidate(); + ResourceOutcome::RetryParked } /// Does a failed fetch's outcome deserve another try? Transport failure and the statuses whose @@ -458,8 +454,20 @@ fn sans_token(key: &[u8]) -> &[u8] { } } +/// Actual resource/admission results, consumed by the runner's owned present gate. +/// No worker publishes presentation provenance; deadlines remain main-thread observations. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ResourceOutcome { + AdmissionRefused, + RetryParked, + RetryDue, + EvictionDue, + LoadFailed, +} + struct Store { slots: [Pslot; PT_CAP], + results: Vec, clock: c_uint, frame: c_uint, quit: bool, @@ -469,6 +477,7 @@ impl Store { const fn new() -> Store { Store { slots: [Pslot::ZERO; PT_CAP], + results: Vec::new(), clock: 0, frame: 0, quit: false, @@ -1196,7 +1205,7 @@ fn lookup(srv: ServerId, key_s: &str, touch: Touch) -> (Hit, Warm) { g.slots[i].retry_wake_sent = false; } else if retry_due(&g.slots[i], now) { if decline { - plx_ui::card_motion::deferred(); + g.results.push(ResourceOutcome::AdmissionRefused); #[cfg(feature = "devtriggers")] plx_ui::card_motion_metrics::refused(plx_ui::card_motion_metrics::Refused::Retry); trace::outcome("declined_retry"); @@ -1246,7 +1255,7 @@ fn lookup(srv: ServerId, key_s: &str, touch: Touch) -> (Hit, Warm) { return (None, Warm::Known); } if decline { - plx_ui::card_motion::deferred(); + g.results.push(ResourceOutcome::AdmissionRefused); #[cfg(feature = "devtriggers")] plx_ui::card_motion_metrics::refused(plx_ui::card_motion_metrics::Refused::Evicted); // The same deferral the cooldown just made, for the same reason: the slot @@ -1338,7 +1347,7 @@ fn lookup(srv: ServerId, key_s: &str, touch: Touch) -> (Hit, Warm) { // slow server, which [`victim`] (a stale request is recyclable) and [`next_wanted`] (newest // draw first) bound. if decline { - plx_ui::card_motion::deferred(); + g.results.push(ResourceOutcome::AdmissionRefused); #[cfg(feature = "devtriggers")] plx_ui::card_motion_metrics::refused(plx_ui::card_motion_metrics::Refused::New); trace::outcome("declined_new"); @@ -1601,16 +1610,20 @@ fn store_idle() -> bool { /// checked (see [`log_residency_settled`]'s doc for why THIS seam and not `PosterSource::idle`): /// the slot scan below is the same one [`idle_of`] would run, so this is the store's one /// once-a-frame, screen-agnostic read of whether it is quiet. -pub(crate) fn begin_frame() { +/// Returns actual resource results and newly due deadlines to the owning runner. The runner +/// assigns resource provenance before its present decision; this source never mutates a gate. +pub(crate) fn begin_frame() -> Vec { trace::begin_frame(); let now = crate::app::clock::now(); let mut g = store(); g.frame = g.frame.wrapping_add(1); - invalidate_due_retries(&mut g.slots, now); - invalidate_due_evictions(&mut g.slots, now); + let mut results = std::mem::take(&mut g.results); + results.extend(invalidate_due_retries(&mut g.slots, now)); + results.extend(invalidate_due_evictions(&mut g.slots, now)); let settled = idle_of(&g.slots); drop(g); log_residency_settled(settled); + results } /// MAIN thread, once per frame (§3.3 step 3, the adapter's results): every slot a worker has @@ -1699,13 +1712,8 @@ impl Uploader for GfxUploader { /// under the frame budget — the `Poster` class for an ordinary poster, the solo `Residency` class /// for a backdrop or a hero logo (`ui::tex`'s `RESIDENCY_BYTES`). /// -/// **The frame this runs on has already been decided to present**, because the budget's -/// queued-work term is the second half of that decision (`app/run.rs`, §3.3 step 8). So what -/// `idle::invalidate` marks here is not this frame but the NEXT one, and it is still worth its -/// frame: a landed texture is DISCRETE damage, which is exactly what `idle::present_dirty`'s -/// readers — the glass hosts deciding whether to re-snapshot the page under them — are asking -/// about, and no spring reports it. The cache's own `Provenance::Resource` note is the same -/// statement to the phase-2 `Present` machine. +/// The queued-work budget already admits this frame. The cache reports genuine uploads +/// through the supplied owned `PresentHandle`; no compatibility damage is published. pub(crate) fn prepare( b: &mut plx_ui::frame::Budget, present: &mut plx_machine::machine::PresentHandle<'_>, @@ -1714,7 +1722,7 @@ pub(crate) fn prepare( let n = tex::prepare(b, &mut GfxUploader, present, now_us); if n > 0 { CV.notify_all(); - plx_machine::idle::invalidate(); + } n } @@ -2230,9 +2238,12 @@ fn poster_worker() { true } else { if plx_gfx::dump::armed() { note_dump_failure(key_bytes(s), transient); } - if transient && cache_gen == plx_platform::imgcache::generation() { park_retry(s); } - else { s.state = P_FAILED; } + let outcome = if transient && cache_gen == plx_platform::imgcache::generation() { park_retry(s) } + else { s.state = P_FAILED; ResourceOutcome::LoadFailed }; trace::lost(idx, gen, "failed"); + // Publish the actual result. The runner owns its repaint provenance; this + // mutation-only source does not manufacture a worker/platform wake. + g.results.push(outcome); false } } else { false } @@ -3212,8 +3223,7 @@ mod tests { assert!(store().slots.iter().all(|s| s.state == P_EMPTY), "text prewarming must not start poster work"); for frame in 0..3 { plx_ui::card_motion::begin_frame(frame * 16); - plx_machine::idle::frame_begin(0.016); - plx_machine::idle::take_local_damage(); + store().results.clear(); let painter = plx_ui::Painter::root().translate(if frame == 0 { 0.0 } else { 80.0 }, 0.0); let facts = plx_screens::registry::tile_facts::of(&item); for art in [plx_ui::widgets::Art::Poster(Some(facts)), plx_ui::widgets::Art::Still(Some(facts)), @@ -3224,7 +3234,7 @@ mod tests { // Frame 0 is `Unknown`; frame 1 jumped 80 px in 16 ms (`Moving`, 5000 px/s); frame 2 held. if frame == 0 || enforced && frame == 1 { assert!(store().slots.iter().all(|s| s.state == P_EMPTY), "unknown/moving cards must claim no slots"); - assert!(plx_machine::idle::take_local_damage() > 0, "a refused unknown needs a follow-up present"); + assert_eq!(store().results, vec![ResourceOutcome::AdmissionRefused; 4], "each refused request needs a follow-up present"); } else { assert_eq!(store().slots.iter().filter(|s| s.state == P_WANT).count(), 4, "all four admitted variants must queue art"); } @@ -3251,14 +3261,14 @@ mod tests { } let _enforce = plx_ui::card_motion::enforce_for_test(); let motion = plx_ui::card_motion::Scope::moving_for_test(); - plx_machine::idle::take_local_damage(); + store().results.clear(); assert_eq!(lookup(sid, &path, Touch::Draw).1, Warm::Known, "the future retry must match its existing slot, not take the fresh-miss gate"); - assert_eq!(plx_machine::idle::take_local_damage(), 0, "a future retry must let the present gate rest"); + assert!(store().results.is_empty(), "a future retry must let the present gate rest"); store().slots[0].retry_at = Some(0); assert_eq!(lookup(sid, &path, Touch::Draw).1, Warm::Known, "motion must defer the known due retry"); - assert!(plx_machine::idle::take_local_damage() > 0, "an actually refused rearm needs a follow-up draw"); + assert_eq!(store().results, vec![ResourceOutcome::AdmissionRefused], "an actually refused rearm needs a follow-up draw"); assert_eq!(store().slots[0].state, P_RETRY); drop(motion); assert_eq!(lookup(sid, &path, Touch::Draw).1, Warm::Known, @@ -3824,7 +3834,7 @@ mod tests { #[test] fn a_due_evicted_slot_invalidates_the_frame_gate_exactly_once() { let _g = plx_base::testlock::serial(); - plx_machine::idle::reset_for_test(); + let mut slots = [Pslot::ZERO; PT_CAP]; slots[3] = Pslot { state: P_EVICTED, @@ -3837,24 +3847,21 @@ mod tests { ..Pslot::ZERO }; - invalidate_due_evictions(&mut slots, 1_999); assert_eq!( - plx_machine::idle::take_local_damage(), - 0, + invalidate_due_evictions(&mut slots, 1_999), + None, "a cooling slot must leave the screen settled before its deadline" ); - invalidate_due_evictions(&mut slots, 2_000); assert_eq!( - plx_machine::idle::take_local_damage(), - 1, + invalidate_due_evictions(&mut slots, 2_000), + Some(ResourceOutcome::EvictionDue), "the deadline must wake exactly one draw that can probe the slot again" ); - invalidate_due_evictions(&mut slots, 2_001); assert_eq!( - plx_machine::idle::take_local_damage(), - 0, + invalidate_due_evictions(&mut slots, 2_001), + None, "an off-screen expired slot must not hold the present gate awake - the latch makes \ this ONE redraw request, not a request every frame" ); @@ -4061,7 +4068,7 @@ mod tests { #[test] fn a_due_parked_retry_invalidates_the_frame_gate() { let _g = plx_base::testlock::serial(); - plx_machine::idle::reset_for_test(); + let mut slots = [Pslot::ZERO; PT_CAP]; slots[3] = Pslot { state: P_RETRY, @@ -4074,24 +4081,21 @@ mod tests { ..Pslot::ZERO }; - invalidate_due_retries(&mut slots, 1_999); assert_eq!( - plx_machine::idle::take_local_damage(), - 0, + invalidate_due_retries(&mut slots, 1_999), + None, "a parked retry must leave the screen settled before its deadline" ); - invalidate_due_retries(&mut slots, 2_000); assert_eq!( - plx_machine::idle::take_local_damage(), - 1, + invalidate_due_retries(&mut slots, 2_000), + Some(ResourceOutcome::RetryDue), "the deadline must wake a draw that can re-queue the retry" ); - invalidate_due_retries(&mut slots, 2_001); assert_eq!( - plx_machine::idle::take_local_damage(), - 0, + invalidate_due_retries(&mut slots, 2_001), + None, "an off-screen due slot must not hold the present gate awake" ); } @@ -4102,19 +4106,19 @@ mod tests { #[test] fn a_newly_parked_retry_wakes_the_draw_that_schedules_it() { let _g = plx_base::testlock::serial(); - plx_machine::idle::reset_for_test(); + let mut s = Pslot { state: P_LOADING, attempts: 2, ..Pslot::ZERO }; - park_retry(&mut s); + let outcome = park_retry(&mut s); assert_eq!(s.state, P_RETRY); assert_eq!(s.attempts, 3); assert_eq!(s.retry_at, None, "only a draw may read the loop clock and schedule"); - assert_eq!(plx_machine::idle::take_local_damage(), 1); + assert_eq!(outcome, ResourceOutcome::RetryParked); } /// **The test the whole prefetch rests on.** `Touch::Warm` writes `use_ = 0` and a frame stamp diff --git a/rust-modules/src/app/adapters/session.rs b/rust-modules/src/app/adapters/session.rs index e7cab3c86f..c692fa495d 100644 --- a/rust-modules/src/app/adapters/session.rs +++ b/rust-modules/src/app/adapters/session.rs @@ -635,7 +635,7 @@ impl SessionAdapter { let cancelled = Arc::clone(&pending.cancelled); pending.ticket = plx_base::storage_worker::submit(move || { let result = if cancelled.load(Ordering::Acquire) { Err(()) } else { write_credentials(&plan, &cancelled) }; - plx_machine::idle::wake(); + plx_machine::present::wake_from_worker(); result }).ok(); @@ -889,7 +889,7 @@ impl SessionAdapter { Vec::new() }; if all_local { failures.extend(erasure.preference_failures); } - plx_machine::idle::wake(); + plx_machine::present::wake_from_worker(); EraseWorkerOutcome { complete, failures, kept: erasure.retained } }).ok(); diff --git a/rust-modules/src/app/boot.rs b/rust-modules/src/app/boot.rs index 0463b27c34..ea62d5a489 100644 --- a/rust-modules/src/app/boot.rs +++ b/rust-modules/src/app/boot.rs @@ -2070,7 +2070,7 @@ pub(crate) unsafe fn construct( let mut glass = plx_ui::frame::glass::GlassPlan::new(); if !controlled { crate::dev::scenarios::arm_glassload(&mut glass); - crate::dev::scenarios::arm_navblur(&mut glass); + bridge.blur_dissolve = crate::dev::scenarios::arm_navblur(&mut glass); } // dev: the two OVERDRAW surfaces (`ui::overdraw`, docs/backdrop-blur-profiling.md Part 5). // `plxnative-overdraw` arms the CPU-side per-draw-class ledger — how much screen-visible @@ -2103,8 +2103,8 @@ pub(crate) unsafe fn construct( plx_media::player::seed_dev_track_names(); } if let Some(initial) = &initial { - plx_machine::idle::set_enabled(!plx_base::devtrig::listed(&initial.triggers, "noidle")); - } else { crate::dev::scenarios::arm_noidle(); } + pages.present.set_enabled(!plx_base::devtrig::listed(&initial.triggers, "noidle")); + } else { crate::dev::scenarios::arm_noidle(&mut pages.present); } // dev: /tmp/plxnative-detailosc (read once at boot, like the other triggers) makes the detail scroll // perpetually swing hero<->bottom so the FPS heartbeat samples the transition, not the ends. let detail_osc = !controlled && crate::dev::scenarios::detailosc_armed(); @@ -2328,10 +2328,7 @@ pub(crate) unsafe fn construct( (player, adapters) }; let repause_at = 0i64; - // ui::press click state: a grid-card OK is deferred (press-in on down, activate on the - // spring-back after key-up) so `ok_armed` marks "a press is in flight, commit it from the - // per-frame loop when press::take_commit fires". Only ever set on Home's grid. - let ok_armed = false; + // Which route name was last REPORTED as an event. Not `route` itself: several `Route` // values share one name (every `Route::Player` is "player"), and an overlay // opening is not a screen change. @@ -2495,12 +2492,13 @@ pub(crate) unsafe fn construct( down_sym, modal_repeat, diagnostics: crate::app::diagnostics::Diagnostics::default(), + lab_toast: Default::default(), player, adapters, repause_at, decoder_parked: false, foreground_retry: None, - ok_armed, + last_route_reported, ptr, menu_play_await: None, @@ -2518,11 +2516,11 @@ pub(crate) unsafe fn construct( t0, instr, measure_fault_logged: false, - input: plx_ui::input::Input::new(), + rec: super::recorder::Recplay::Off, boot_initial: initial, telemetry_guard: None, - present: plx_machine::present::Present::new(), + glass, // **The application's page stack runs the route DIP** (§6.2). It ran `Immediate` until // phase 12 while `ui::nav` held a second fader and the loop applied its own route change @@ -2667,7 +2665,7 @@ pub(crate) unsafe fn construct( log(&format!("bootstrap: REFUSED — {reason}")); return Err(1); } - super::run::recorder_end_frame(&mut app.rec, &app.bridge, &app.input.press, + super::run::recorder_end_frame(&mut app.rec, &app.bridge, "home", "", "bootstrap", tree); if let Some(ms) = app.rec.clock_start() { super::clock::set_replay(ms); diff --git a/rust-modules/src/app/bootstrap.rs b/rust-modules/src/app/bootstrap.rs index ea8ce82a0f..8ea763cb31 100644 --- a/rust-modules/src/app/bootstrap.rs +++ b/rust-modules/src/app/bootstrap.rs @@ -279,7 +279,7 @@ impl Initial { use super::recorder::{FP_PRIOR, FP_V6}; match fingerprint { FP_PRIOR => Self::decode(value, expected_hash), - FP_V6 => { + fp if fp == FP_V6 || fp == super::recorder::state_fp() => { let session = value.get_mut("session").ok_or("invalid session codec")?; let envelope = session.as_object_mut().ok_or("invalid session codec")?; if envelope.len() != 2 || envelope.get("codec").and_then(|v| v.as_u64()) != Some(6) { diff --git a/rust-modules/src/app/bootstrap/tests.rs b/rust-modules/src/app/bootstrap/tests.rs index 53baa2fce1..71cac65e38 100644 --- a/rust-modules/src/app/bootstrap/tests.rs +++ b/rust-modules/src/app/bootstrap/tests.rs @@ -11,6 +11,9 @@ fn session_codec_profiles_require_canonical_exact_matching_envelopes() { let current = initial.to_v6_value().unwrap(); let prior = super::super::recorder::FP_PRIOR; let v6 = super::super::recorder::FP_V6; + let owned = super::super::recorder::state_fp(); + assert_eq!(Initial::decode_profile(current.clone(), initial.hash(), owned).unwrap().hash(), initial.hash()); + assert!(Initial::decode_profile(legacy.clone(), initial.hash(), owned).is_err()); assert_eq!(current["session"], serde_json::json!({"codec":6,"boot":legacy["session"]})); assert_eq!(Initial::decode_profile(legacy.clone(), initial.hash(), prior).unwrap().hash(), initial.hash()); assert_eq!(Initial::decode_profile(current.clone(), initial.hash(), v6).unwrap().hash(), initial.hash()); @@ -216,9 +219,8 @@ fn typed_initial_roundtrip_and_hidden_input_hash_are_complete() { changed.consent.errors = true; changed.validate().unwrap(); assert_ne!(changed.hash(), initial.hash(), "automation hides the prompt, not its logical initial decision"); - let press = plx_ui::press::Press::new(); - assert_ne!(super::super::recorder::state_hash(&press,"home","","",0,0,0,initial.hash()), - super::super::recorder::state_hash(&press,"home","","",0,0,0,changed.hash())); + assert_ne!(super::super::recorder::state_hash("home","","",0,0,0,initial.hash()), + super::super::recorder::state_hash("home","","",0,0,0,changed.hash())); assert!(Initial::decode(serde_json::to_value(&changed).unwrap(),initial.hash()).is_err()); let mut unknown = value.clone(); unknown["unrecognized"] = json!(true); assert!(Initial::from_value(unknown).is_err()); @@ -477,7 +479,7 @@ fn controlled_hubs_replays_refusal_retry_and_success() { let mut launches = 0; let sink = plx_ui::rec::MemSink::default(); let bytes = sink.segments.clone(); - let header = plx_ui::rec::Header::new(17,&plx_ui::press::Press::new()); + let header = plx_ui::rec::Header::new(17,&plx_ui::dispatch::press::Press::new()); let mut writer = plx_ui::rec::Writer::open(Box::new(sink),&header,0).unwrap(); for frame in 0..160 { if replay { @@ -594,7 +596,7 @@ fn controlled_discovery_replays_refusal_retry_and_success_with_exact_identity() let mut parked = 0; let sink = plx_ui::rec::MemSink::default(); let bytes = sink.segments.clone(); - let header = plx_ui::rec::Header::new(17, &plx_ui::press::Press::new()); + let header = plx_ui::rec::Header::new(17, &plx_ui::dispatch::press::Press::new()); let mut writer = plx_ui::rec::Writer::open(Box::new(sink), &header, 0).unwrap(); for frame in 0..=602 { if replay { diff --git a/rust-modules/src/app/bridge.rs b/rust-modules/src/app/bridge.rs index 8c8c6c7845..708c7df702 100644 --- a/rust-modules/src/app/bridge.rs +++ b/rust-modules/src/app/bridge.rs @@ -574,6 +574,7 @@ pub(crate) struct Bridge { /// Endpoint refreshes a store step had no room to emit (`EndpointRefreshSet::emit`). endpoint_carry: plx_data::stores::EndpointRefreshSet, session_cache_generation: u64, + plex_visual_inputs: Option, /// The `req` of the last `SessionFx::RefreshCache` this bridge handed its adapter. The frame /// step's reconcile (`land_session_cache`) refuses an in-flight refresh only when it is this /// one: an effect the drain budget carried past the frame has not been begun, so nobody has @@ -659,6 +660,8 @@ pub(crate) struct Bridge { search: plx_data::stores::search::SearchSnapshot, chrome: super::chrome::ChromeSnapshot, chrome_selection: u32, + /// App-owned boot prototype policy; no global navigation readback. + pub(crate) blur_dissolve: bool, /// The shared top bar's render state — the strip's scroll/capsules/chip unfurl and the tab /// track's glass band (restructure phase 12, PX-WIDGETS, review finding 10). `Bridge` is this /// bar's one reachable owner: the only `Rig::draw_chrome` implementation, and the only place @@ -716,6 +719,13 @@ impl Bridge { pub(crate) fn is_controlled_replay(&self) -> bool { self.home_io.as_ref().is_some_and(|io| io.replay) } + + #[cfg(test)] + pub(crate) fn for_visual_inputs_test() -> Self { + let mut bridge = Self::for_test(|| 0); + bridge.home_io = None; // this fixture deliberately observes the test registry, not controlled inputs + bridge + } pub(crate) fn recording_retired_for_erasure(&mut self, failed: bool) { debug_assert!(!self.is_controlled_replay()); self.home_io = None; @@ -892,6 +902,7 @@ impl Bridge { reads: StorePublications, stores: plx_data::stores::Stores, live_screen_inputs: bool) -> Self { let mut bridge = Self { session_cache_generation: plx_plex::plex::session::visible_generation(), + plex_visual_inputs: Default::default(), cache_refresh_begun: None, marker_access: Default::default(), marker_prefs: Default::default(), marker_now: 0, endpoint_carry: Default::default(), @@ -936,6 +947,7 @@ impl Bridge { search: reads.search, chrome: super::chrome::ChromeSnapshot::default(), chrome_selection: 0, + blur_dissolve: false, strip: plx_ui::widgets::StripRender::new(), home_commands: std::collections::VecDeque::new(), library_commands: std::collections::VecDeque::new(), @@ -974,7 +986,8 @@ impl Bridge { let generation = plx_plex::plex::session::visible_generation(); if self.session_cache_generation != generation { self.session_cache_generation = generation; - plx_machine::idle::invalidate(); + d.present.note_in_scope(plx_machine::present::Scope::Page, + plx_machine::present::PresentEvent::Damage(plx_machine::present::Provenance::Landing(MachineId::Session))); } let event = if let Some(req) = self.session.cache_refresh_in_flight() { // The owner is waiting on a refresh. If this bridge began it and the adapter holds no @@ -1420,16 +1433,16 @@ impl Bridge { fetching: self.huds.store().fetching(), package_busy: self.huds.store().busy(), }; - let mut delivered = false; + self.huds_pages.retain_mut(|(page, sent, end)| { if *sent == stamp && *end == end_time { return true } *sent = stamp; *end = end_time; let sent = page.send(list.clone()).is_ok(); - delivered |= sent; + sent }); - if delivered { plx_machine::idle::invalidate(); } + // HudSettings owns damage when Tick ingests the changed list. } /// The rect the next player menu hangs from — see [`AppMounter::player_menu_anchor`]. `None` clears it, @@ -1528,7 +1541,7 @@ impl Bridge { } // The page's own pill: Home's is the first, and a library page's is its library's type. self.chrome_selection = pill_of_arg(route, self.directory.view()).unwrap_or(0) as u32; - let selected = self.navigation_presentation().view_tab.unwrap_or(self.chrome_selection) as i32; + let selected = self.navigation_presentation(&d.nav).view_tab.unwrap_or(self.chrome_selection) as i32; self.publish_strip(d, selected); } else { d.nav.tabs.strip.clear(); @@ -1657,7 +1670,7 @@ impl Bridge { pub(crate) fn update_home_chrome(&mut self, d: &mut Dispatcher, glass: &mut plx_ui::frame::glass::GlassPlan, dt: f32) { - let selected = self.navigation_presentation().view_tab.unwrap_or(self.chrome_selection) as i32; + let selected = self.navigation_presentation(&d.nav).view_tab.unwrap_or(self.chrome_selection) as i32; let focus = Self::home_focus(d); if let Some(idx) = self.chrome.take_pulse() { self.strip.pulse(idx); @@ -1720,7 +1733,7 @@ impl Bridge { let real = &e.inst.as_ref()?.screen; let screen = real.as_any()?; let mut parts = CxParts { tick: Tick { ms: 0, dt_us: 0 }, - press: plx_machine::machine::PressRead { scale: 1.0, is_long: false, held_ms: None, owner: None }, + press: plx_machine::machine::PressRead::default(), focus: plx_machine::machine::FocusRead { current: None , ..Default::default() }, owner: plx_machine::machine::InputOwner::Entry(entry) }; parts.owner = plx_machine::machine::InputOwner::Entry(entry); @@ -2153,10 +2166,10 @@ fn start_jobs(&mut self, jobs: Vec) -> usize { } if watchlist { let profile = Self::seated_profile(); - let stream = self.stores.watchlist.land_stream_results(&self.stores.landgate, &profile); - let write = self.stores.watchlist.land_write_results(&self.stores.landgate, &profile); + self.stores.watchlist.land_stream_results(&self.stores.landgate, &profile); + self.stores.watchlist.land_write_results(&self.stores.landgate, &profile); self.stores.watchlist.land_resolve_refusals(&profile); - if stream || write { plx_machine::idle::invalidate(); } + // Refusals are publications too; the page feed owns their exact visual delta. } started } @@ -2281,22 +2294,21 @@ fn start_jobs(&mut self, jobs: Vec) -> usize { } super::adapters::stores::refill_client_keys(&mut self.client_keys); let endpoints = self.stores.stops_landed(stops, self.directory.view(), &self.client_keys); - plx_machine::idle::invalidate(); + // Store patches are observed by their owning page feeds, not by attempted stops. endpoints } /// The Watchlist store's landing pass, once a frame and route-unconditional: a write burst /// lands, a profile switch resets it, and the page reads its notice through `take_notices`. - pub(crate) fn watchlist_pump(&mut self) { + pub(crate) fn watchlist_pump(&mut self) -> bool { super::adapters::stores::refill_client_keys(&mut self.client_keys); let profile = Self::seated_profile(); let input = self.store_runner.watchlist_snapshot(&self.client_keys, &mut self.watchlist_capture); + let before = self.stores.watchlist.gen(); let changed = { let _step = plx_base::step::StepScope::enter(); self.stores.watchlist.pump_with_snapshot(&self.stores.landgate, &profile, input) }; - if changed { - plx_machine::idle::invalidate(); - } self.start_store_jobs_of(StoreId::Watchlist); + changed || self.stores.watchlist.gen() != before } pub(crate) fn viewstate_pump(&mut self) -> plx_data::stores::EndpointRefreshSet { @@ -2313,28 +2325,27 @@ fn start_jobs(&mut self, jobs: Vec) -> usize { /// goes on, in the same call: an end-of-stream fan-out it queues starts ViewState's next write, /// so both outboxes are drained here (`Stores::RECONCILE_FILLS`); the shared `Stores` call's /// other fan-outs emit no jobs of their own. - pub(crate) fn reconcile_pump(&mut self) -> plx_data::stores::EndpointRefreshSet { + pub(crate) fn reconcile_pump(&mut self) -> plx_data::stores::StoreOutcome { self.capture_store_session(); super::adapters::stores::refill_client_keys(&mut self.client_keys); let mut outcome = self.stores.reconcile_pump(self.directory.view(), &self.client_keys, self.store_session.profile_generation); self.start_store_jobs_in(plx_data::stores::Stores::RECONCILE_FILLS); - if outcome.changed { - plx_machine::idle::invalidate(); - } + if self.stores.network_held() { - return outcome.endpoints; // a membership re-query is a network read + return outcome; // a membership re-query is a network read } let owed = self.stores.browse.borrow().requery_owed(); let requeried = owed.then(|| { super::adapters::stores::refill_client_keys(&mut self.client_keys); let session = self.browse_session(); - self.stores.browse.borrow_mut().pump_with_gate(&self.stores.landgate, &session.input(&self.client_keys)).endpoints + self.stores.browse.borrow_mut().pump_with_gate(&self.stores.landgate, &session.input(&self.client_keys)) }); - if let Some(endpoints) = requeried { - outcome.endpoints.merge(endpoints); + if let Some(publication) = requeried { + outcome.changed |= publication.changed; + outcome.endpoints.merge(publication.endpoints); self.start_store_jobs_of(StoreId::Browse); } - outcome.endpoints + outcome } /// The PMS notification feed's per-frame pass (`stores::notify`), and the mapping of what it @@ -2787,15 +2798,17 @@ impl Bridge { pub(crate) fn marker_preferences(&self) -> plx_appkit::skip_policy::MarkerPrefsView { self.marker_prefs } /// Runner boundary: capture the seated profile and live choices once, then publish values. - pub(crate) fn publish_marker_preferences(&mut self, now: u32) { + pub(crate) fn publish_marker_preferences(&mut self, now: u32) -> bool { self.marker_now = now; if self.home_io.is_some() { - self.marker_prefs = Default::default(); return; + let changed = self.marker_prefs != Default::default(); + self.marker_prefs = Default::default(); return changed; } let view = self.marker_access.poll(&Self::seated_profile(), now, plx_media::route::intro_skip(), plx_media::route::credits_skip()); - if view != self.marker_prefs { plx_machine::idle::invalidate(); } + let changed = view != self.marker_prefs; self.marker_prefs = view; + changed } /// **Publish this frame's calendar date** — see `AppViews::today`. Called once per iteration by @@ -2833,7 +2846,9 @@ impl Bridge { fn deliver_inner(&mut self, to: MachineId, msg: &AppMsg, parts: &CxParts, fx: &mut Effects<'_, AppHost>) -> Handled { if let AppMsg::PersonCommand { from, command } = msg { if to != MachineId::Store(StoreId::Person.ord()) { return Handled::No; } - self.person_run_from(Some(*from), command.clone()); + if self.person_run_from(Some(*from), command.clone()) { + fx.invalidate(plx_machine::present::Provenance::Landing(to)); + } return Handled::Yes; } if let AppMsg::Consent(command) = msg { @@ -2900,7 +2915,9 @@ impl Bridge { AppMsg::Store(StoreCmd::Hubs(cmd)) => { super::adapters::stores::refill_client_keys(&mut self.client_keys); let directory = self.directory.view(); - let due = { let _step = plx_base::step::StepScope::enter(); self.stores.hubs.run_with_directory(cmd.clone(), directory, &self.client_keys) }.endpoints; + let outcome = { let _step = plx_base::step::StepScope::enter(); self.stores.hubs.run_with_directory(cmd.clone(), directory, &self.client_keys) }; + if outcome.changed { fx.invalidate(plx_machine::present::Provenance::Landing(to)); } + let due = outcome.endpoints; Self::admit_home_jobs(&mut self.stores, &mut self.store_runner, io, StoreId::Hubs); return Self::carry(&mut self.endpoint_carry, due); } @@ -2913,6 +2930,7 @@ impl Bridge { // the retained directory visible to Onboard's Tick in this same dispatcher // turn instead of leaving the newly discovered rows one frame behind. if outcome.changed { + fx.invalidate(plx_machine::present::Provenance::Landing(to)); super::adapters::stores::refill_client_keys(&mut self.client_keys); let context = BrowseContext::capture(&self.stores); self.stores.browse.borrow_mut().capture_directory(&mut self.directory, &context.input(&self.client_keys)); @@ -2922,7 +2940,9 @@ impl Bridge { AppMsg::StoreWork(plx_data::stores::StoreWork::Hubs) => { super::adapters::stores::refill_client_keys(&mut self.client_keys); let directory = self.directory.view(); - let due = { let _step = plx_base::step::StepScope::enter(); self.stores.hubs.tick_with_directory(parts.tick.dt(), directory, &self.client_keys) }.endpoints; + let outcome = { let _step = plx_base::step::StepScope::enter(); self.stores.hubs.tick_with_directory(parts.tick.dt(), directory, &self.client_keys) }; + if outcome.changed { fx.invalidate(plx_machine::present::Provenance::Landing(to)); } + let due = outcome.endpoints; Self::admit_home_jobs(&mut self.stores, &mut self.store_runner, io, StoreId::Hubs); return Self::carry(&mut self.endpoint_carry, due); } @@ -2938,27 +2958,30 @@ impl Bridge { } match msg { AppMsg::Store(StoreCmd::Person(command)) => { - self.person_run(command.clone()); + if self.person_run(command.clone()) { fx.invalidate(plx_machine::present::Provenance::Landing(to)); } return Handled::Yes; } AppMsg::Store(StoreCmd::Collection(command)) => { - self.collection_run(command.clone()); + if self.collection_run(command.clone()) { fx.invalidate(plx_machine::present::Provenance::Landing(to)); } return Handled::Yes; } AppMsg::Store(StoreCmd::SubtitleSearch(command)) => { - self.subsearch_run(command.clone()); + if self.subsearch_run(command.clone()) { fx.invalidate(plx_machine::present::Provenance::Landing(to)); } return Handled::Yes; } AppMsg::Store(StoreCmd::ViewState(command)) => { - let due = self.viewstate_run(command.clone()).endpoints; + let outcome = self.viewstate_run(command.clone()); + if outcome.changed { fx.invalidate(plx_machine::present::Provenance::Landing(to)); } + let due = outcome.endpoints; return Self::carry(&mut self.endpoint_carry, due); } AppMsg::Store(StoreCmd::Metadata(command)) => { - self.metadata_run(command.clone()); + if self.metadata_run(command.clone()) { fx.invalidate(plx_machine::present::Provenance::Landing(to)); } return Handled::Yes; } AppMsg::Store(StoreCmd::Browse(command)) => { - self.browse_run(command.clone()); + let changed = self.browse_run(command.clone()); + if changed { fx.invalidate(plx_machine::present::Provenance::Landing(to)); } return Handled::Yes; } _ => {} @@ -2966,13 +2989,15 @@ impl Bridge { let cx = parts.cx::(self.views(), &self.measure); match msg { AppMsg::Store(StoreCmd::Search(c)) => { - self.search_run(c.clone()); + if self.search_run(c.clone()) { fx.invalidate(plx_machine::present::Provenance::Landing(to)); } Handled::Yes } AppMsg::Store(StoreCmd::Hubs(c)) => { super::adapters::stores::refill_client_keys(&mut self.client_keys); let directory = self.directory.view(); - let due = { let _step = plx_base::step::StepScope::enter(); self.stores.hubs.run_with_directory(c.clone(), directory, &self.client_keys) }.endpoints; + let outcome = { let _step = plx_base::step::StepScope::enter(); self.stores.hubs.run_with_directory(c.clone(), directory, &self.client_keys) }; + if outcome.changed { fx.invalidate(plx_machine::present::Provenance::Landing(to)); } + let due = outcome.endpoints; self.start_store_jobs_of(StoreId::Hubs); Self::carry(&mut self.endpoint_carry, due) } @@ -2980,34 +3005,42 @@ impl Bridge { AppMsg::HubsResult(result) => { super::adapters::stores::refill_client_keys(&mut self.client_keys); let directory = self.directory.view(); - let due = { let _step = plx_base::step::StepScope::enter(); self.stores.hubs.land_with_directory(result, directory, &self.client_keys) }.endpoints; + let outcome = { let _step = plx_base::step::StepScope::enter(); self.stores.hubs.land_with_directory(result, directory, &self.client_keys) }; + if outcome.changed { fx.invalidate(plx_machine::present::Provenance::Landing(to)); } + let due = outcome.endpoints; self.start_store_jobs_of(StoreId::Hubs); Self::carry(&mut self.endpoint_carry, due) } AppMsg::StoreWork(plx_data::stores::StoreWork::Hubs) => { super::adapters::stores::refill_client_keys(&mut self.client_keys); let directory = self.directory.view(); - let due = { let _step = plx_base::step::StepScope::enter(); self.stores.hubs.tick_with_directory(parts.tick.dt(), directory, &self.client_keys) }.endpoints; + let outcome = { let _step = plx_base::step::StepScope::enter(); self.stores.hubs.tick_with_directory(parts.tick.dt(), directory, &self.client_keys) }; + if outcome.changed { fx.invalidate(plx_machine::present::Provenance::Landing(to)); } + let due = outcome.endpoints; self.start_store_jobs_of(StoreId::Hubs); Self::carry(&mut self.endpoint_carry, due) } AppMsg::StoreWork(plx_data::stores::StoreWork::BrowseDiscovery) => { - let due = self.browse_discover_pump().endpoints; + let outcome = self.browse_discover_pump(); + if outcome.changed { fx.invalidate(plx_machine::present::Provenance::Landing(to)); } + let due = outcome.endpoints; Self::carry(&mut self.endpoint_carry, due) } AppMsg::StoreWork(plx_data::stores::StoreWork::Browse) => { super::adapters::stores::refill_client_keys(&mut self.client_keys); let session = self.browse_session(); - let due = self.stores.browse.borrow_mut().pump_with_gate(&self.stores.landgate, &session.input(&self.client_keys)).endpoints; + let outcome = self.stores.browse.borrow_mut().pump_with_gate(&self.stores.landgate, &session.input(&self.client_keys)); + if outcome.changed { fx.invalidate(plx_machine::present::Provenance::Landing(to)); } + let due = outcome.endpoints; self.start_store_jobs_of(StoreId::Browse); Self::carry(&mut self.endpoint_carry, due) } AppMsg::StoreWork(plx_data::stores::StoreWork::Search { dt_us }) => { - self.search_pump(*dt_us as f32 / 1_000_000.0); + if self.search_pump(*dt_us as f32 / 1_000_000.0) { fx.invalidate(plx_machine::present::Provenance::Landing(to)); } Handled::Yes } AppMsg::StoreWork(plx_data::stores::StoreWork::SubtitleSearch) => { - self.subsearch_pump(); + if self.subsearch_pump() { fx.invalidate(plx_machine::present::Provenance::Landing(to)); } Handled::Yes } _ => Handled::No, @@ -3023,7 +3056,7 @@ impl Rig for Bridge { let Some(glass) = glass else { return }; let p = plx_ui::Painter::root().alpha(nav.chrome_alpha).translate(0.0, -nav.chrome_lift); let chrome = self.chrome.read(self.strip.chip_expand_pos()); - self.strip.draw(chrome.labels, p, glass.tab_band_mut()); + self.strip.draw(chrome.labels, p, glass.tab_band_mut(), nav); plx_ui::widgets::profile_chip_with( p, chrome.profile, @@ -3049,15 +3082,14 @@ impl Rig for Bridge { let p = plx_ui::Painter::root().alpha(presented.chrome_alpha).translate(0.0, -presented.chrome_lift); plx_ui::widgets::lift_profile_chip(p, chrome.profile, chrome.chip_expand, material, ground); } - fn page_alpha(&self) -> f32 { plx_ui::nav::page_alpha() } - fn navigation_presentation(&self) -> plx_ui::screen::NavPresentation { - plx_ui::screen::NavPresentation { - page_alpha: plx_ui::nav::page_alpha(), - chrome_alpha: plx_ui::nav::chrome_alpha(), - view_tab: u32::try_from(plx_ui::nav::view_tab(-1)).ok(), - blur_amount: plx_ui::nav::blur_amount(), - chrome_lift: 0.0, - } + fn navigation_presentation(&self, nav: &plx_ui::containers::Navigation) -> plx_ui::screen::NavPresentation { + plx_ui::screen::NavPresentation::from_transition( + nav.tabs.stack.page_alpha(), nav.tabs.stack.chrome_alpha(), + nav.tabs.stack.pending_dest() + .and_then(|arg| pill_of_arg(arg, self.directory.view())) + .map(|tab| tab as u32), + self.blur_dissolve, + ) } fn surface_scope(&mut self) -> Option { Some(plx_ui::popover::host::live()) @@ -3209,7 +3241,9 @@ impl Bridge { AppFx::SessionEffect(effect) => self.session_effect(effect, out), AppFx::Preferences(command) => { let profile = Self::seated_profile(); - self.publish_marker_preferences(self.marker_now); + if self.publish_marker_preferences(self.marker_now) { + out.invalidate(plx_machine::present::Provenance::Landing(MachineId::Session)); + } match command { plx_screens::registry::PreferenceCmd::EnsureMarkerAccess => self.marker_access.ensure(&profile, self.marker_now), command @ plx_screens::registry::PreferenceCmd::ChooseMarker { .. } => super::preferences::execute_marker(command, self.marker_prefs), @@ -3592,7 +3626,7 @@ fn frame_ingest( if search_changed && !search_notified { d.store_changed(StoreId::Search.ord(), rig.stores.gen(StoreId::Search)); } - let surface = d.surface_up(); + // A surface's MOTION is not attributed here: this used to wrap the WHOLE dispatcher frame in // `popover::own_motion`, so a PAGE's springs stepped inside it were attributed to the panel and // `idle::page_moving` read false for as long as any surface was up — including a DISMISSED one, where `host_refresh`'s @@ -3613,26 +3647,9 @@ fn frame_ingest( rig.library_page_committed(d, previous, d.nav.top_page().map(|entry| entry.id)); d.prune(&report.unmounted); plx_base::diag::spans::span("dsync", || rig.sync_host(d, tick.dt())); - // On the simulator, a frame the video plane alone presented is not reported as damage: the - // loop's gate presents it on its own video-plane term anyway, and the report would keep the - // settled-capture clock (`plx_machine::idle::last_change_ms`) from ever seeing a paused player at rest - // (`FrameReport::video_only`). The television keeps the unconditional report it always had. - let video_only = cfg!(feature = "hostsim") && report.video_only; - if report.presented && !video_only { - // The dispatcher's gate wants a frame: the loop's gate presents it. While a surface is up - // this bump is the PANEL's — `take_page_damage` subtracts the panel's claims BY COUNT, and - // a page's own landings reach `plx_machine::idle` from the pumps outside this frame (the poster - // adapter, `pms::commit`), where nothing claims them. - let _own = surface.then(plx_machine::idle::OwnScope::open); - plx_machine::idle::invalidate(); - } - // **Publish the transition's presentation** for the readers that draw outside a page's own - // `DrawFrame` (`ui::popover`'s panel and scrim, the profile chip's redraw, the glass track's - // settled test, the navblur prototype). One writer, immediately after the container's own - // frame, from the container's own transition — see `ui::nav`'s module doc. - let tab = d.nav.tabs.stack.pending_dest() - .and_then(|arg| pill_of_arg(arg, rig.directory.view())); - plx_ui::nav::publish(d.nav.tabs.stack.page_alpha(), d.nav.tabs.stack.chrome_alpha(), tab); + // The dispatcher owns the product's one Present. Read its pending events and + // motion in prepare_window; never mirror a verdict into content damage. + // Presentation is derived directly from this stack at each draw boundary; no publication. // **The heartbeat's `route=` word IS the top page's own name** (§15.2). It used to be // `route_word(app.route)` with this line asserting the two agreed every frame; there is one // source now, and the `debug_assert_eq!` that guarded the pair is gone with the pair. @@ -3863,7 +3880,7 @@ fn page_probe(d: &Dispatcher, rig: &Bridge) -> String { let Some(instance) = d.nav.entry(owner).and_then(|e| e.inst.as_ref()) else { return String::new() }; let focus = d.focus(); let parts = CxParts { tick: Tick { ms: 0, dt_us: 0 }, - press: plx_machine::machine::PressRead { scale: 1.0, is_long: false, held_ms: None, owner: None }, + press: plx_machine::machine::PressRead::default(), focus: plx_machine::machine::FocusRead { current: focus , ..Default::default() }, owner: InputOwner::Entry(owner) }; let cx = parts.cx::(rig.views(), &rig.measure); let mut groups = Vec::new(); @@ -5412,6 +5429,13 @@ mod library_collections_arrival_tests; #[path = "strip_home_pill_tests.rs"] mod strip_home_pill_tests; +#[cfg(test)] +#[path = "owned_publication_tests.rs"] +mod owned_publication_tests; + +#[path = "plex_visual_inputs.rs"] +mod plex_visual_inputs; + #[path = "watchlist.rs"] mod watchlist; pub(crate) use watchlist::{hex_of_guid, open_catalog, open_watchlist_menu}; @@ -5688,6 +5712,22 @@ mod screen_input_publication_tests { assert!(bridge.views().inputs.profile.user.is_none()); assert!(bridge.views().inputs.grants.offers.is_empty()); } + + #[test] + fn controlled_visual_observation_never_polls_ambient_plex_state() { + let _serial = plx_base::testlock::serial(); + let initial = crate::app::bootstrap::Initial::synthetic_home(17, 32517, None).unwrap(); + let mt = unsafe { plx_base::task::MainThread::assume() }; + for replay in [false, true] { + let mut bridge = Bridge::controlled_home(|| 0, &initial, &mt, replay); + let mut present = plx_machine::present::Present::new(); + present.take(0); + present.acknowledge(0); + bridge.observe_plex_visual_inputs(&mut present); + assert!(bridge.plex_visual_inputs.is_none(), "controlled modes must not capture ambient domain facts"); + assert!(!present.changed()); + } + } } #[cfg(test)] diff --git a/rust-modules/src/app/bridge_test_support.rs b/rust-modules/src/app/bridge_test_support.rs index b9495f3768..4bfdac1427 100644 --- a/rust-modules/src/app/bridge_test_support.rs +++ b/rust-modules/src/app/bridge_test_support.rs @@ -107,7 +107,7 @@ pub(super) struct Pump { ps: plx_media::route::PlaybackSession, pa: plx_media::player::adapter::PlayerAdapter, menu_play_await: Option, - ok_armed: bool, + } impl Pump { @@ -116,7 +116,7 @@ impl Pump { // under `cfg(test)`, so no player verb is reached. let mt = unsafe { plx_base::task::MainThread::assume() }; Pump { ps: Default::default(), pa: plx_media::player::adapter::PlayerAdapter::new(mt), - menu_play_await: None, ok_armed: false } + menu_play_await: None } } /// One frame's requests, `now` being the frame clock in ms. @@ -158,7 +158,7 @@ fn pump_requests(d: &mut Dispatcher, rig: &mut Bridge, mut item: Option (_, Some((pump, now))) => { // SAFETY: the player seam is this pump's own `NoSink` session. unsafe { - library_page_request(&mut pump.ps, &mut pump.pa, &mut pump.menu_play_await, &mut pump.ok_armed, + library_page_request(&mut pump.ps, &mut pump.pa, &mut pump.menu_play_await, *now, d, rig, instance, entry, request, ret); } seen.push(format!("library:{label}")); @@ -210,8 +210,8 @@ fn pump_requests(d: &mut Dispatcher, rig: &mut Bridge, mut item: Option let label = format!("{request:?}"); seen.push(match (watchlist_navigation(d, rig, &request, ret), item.as_mut()) { (None, _) => format!("watchlist:{label}"), - (Some(ret), Some((pump, _))) => { - watchlist_request(d, rig, entry, request, ret, &mut pump.ok_armed); + (Some(ret), Some(_)) => { + watchlist_request(d, rig, entry, request, ret); format!("watchlist:{label}") } (Some(_), None) => format!("unperformed watchlist:{label}"), @@ -305,7 +305,7 @@ impl DipImage { /// The paint the frame `d` just ran (at `ms`) gets, and `page_image_held` for the next tick. /// `None` when no page is on top. pub(super) fn plan(&mut self, d: &Dispatcher, ms: u32) -> Option { - let quiescent = !plx_machine::idle::page_layout_moving(); + let quiescent = !plx_machine::motion::report::page_layout_moving(); let transition = &d.nav.tabs.stack.transition; let (alpha, flight) = (transition.page_alpha(), transition.in_flight()); let entry = d.nav.top_page().map(|e| e.id)?; @@ -329,6 +329,17 @@ impl Drop for ImageHeld { fn drop(&mut self) { plx_ui::containers::transition::set_page_image_held(false); } } +/// Puts a preview back to Idle when the test ends, however it ends (the machine is process-wide, +/// so a test that panics with one held would leave `preview::occupies()` true for every later test +/// in the binary). Bind it as `let _preview = PreviewReset;` right after `testlock::serial()`. +#[cfg(feature = "play-feed")] +pub(crate) struct PreviewReset; + +#[cfg(feature = "play-feed")] +impl Drop for PreviewReset { + fn drop(&mut self) { plx_media::player::preview::reset_for_test(); } +} + /// How many collections the rig's probe stands in for on every section it seeds (a server the rig /// has no network to ask): enough that the Library header's Collections control is on the row. pub(crate) const RIG_COLLECTIONS: u32 = 4; @@ -650,7 +661,7 @@ impl World { self.frame += 1; if let Some(feed) = self.feed { feed(&mut self.d, &mut self.bridge); } if self.script.is_some() { self.bridge.store_runner.run_held_watchlist_writes(); } - plx_machine::idle::frame_begin(0.016); + plx_machine::motion::report::frame_begin(0.016); super::frame(&mut self.d, &mut self.bridge, tick(self.frame), inputs); let now = self.frame * 16; self.performed.extend(self.pump.run(&mut self.d, &mut self.bridge, now)); diff --git a/rust-modules/src/app/chrome.rs b/rust-modules/src/app/chrome.rs index 7f7e9fdeeb..2b574501d3 100644 --- a/rust-modules/src/app/chrome.rs +++ b/rust-modules/src/app/chrome.rs @@ -93,7 +93,6 @@ impl ChromeSnapshot { /// idle app wakes for it. pub(crate) fn pulse(&mut self, key: u32) { self.pulse = Some(key); - plx_machine::idle::invalidate(); } /// The pending pulse as the strip index of its destination; `None` when nothing is pending or diff --git a/rust-modules/src/app/collections_probe.rs b/rust-modules/src/app/collections_probe.rs index efbec43ec9..7a7001148e 100644 --- a/rust-modules/src/app/collections_probe.rs +++ b/rust-modules/src/app/collections_probe.rs @@ -92,9 +92,7 @@ fn shown(answer: Option) -> Option> { } } -/// Record what a finished probe learned, then ask for a frame: a resting page runs no ticks, so -/// without the wake the header would keep the control off the row after its count landed (or keep -/// a control the answer says to hide) until the next input. +/// Record actual domain state only. The App observer compares visible answers and owns damage. fn land(key: Key, learned: CollectionsCount) { { let mut cache = lock(); @@ -105,7 +103,18 @@ fn land(key: Key, learned: CollectionsCount) { entry.probing = false; } } - plx_machine::idle::invalidate(); + +} + +/// Actual visible answers, retained by the App's Plex observer. Unknown answers and scheduling +/// metadata cannot change the header. Sort by address so insertion order is not visual damage. +pub(super) fn visual_facts() -> Vec<((u16, u32, i64), Option)> { + if plx_data::stores::tape::active() { return Vec::new(); } + let mut facts: Vec<_> = lock().iter().filter_map(|(key, entry)| { + shown(entry.answer).map(|answer| (*key, answer.ok())) + }).collect(); + facts.sort_unstable_by_key(|(key, _)| *key); + facts } /// The cache's answer for `key`, and whether the schedule says the caller now OWNS a probe of it @@ -567,11 +576,28 @@ mod tests { #[test] fn a_landed_answer_wakes_a_frame() { + use plx_machine::present::{Present, Scope}; + let _guard = plx_base::testlock::serial(); let key: Key = (u16::MAX, u32::MAX, -7); lock().push((key, Entry { answer: None, at: None, settled: false, probing: true })); - let _ = plx_machine::idle::take_local_damage(); + let mut bridge = crate::app::bridge::Bridge::for_visual_inputs_test(); + let mut gate = Present::new(); + let mut unrelated = Present::new(); + bridge.observe_plex_visual_inputs(&mut gate); + gate.take(0); + gate.acknowledge(0); + unrelated.take(0); + unrelated.acknowledge(0); land(key, CollectionsCount::Count(4)); - assert!(plx_machine::idle::take_local_damage() > 0, "the landing must request a frame"); + assert!(!gate.take(1), "worker mutation has no presentation authority"); + gate.set_scope(Scope::Surface); + bridge.observe_plex_visual_inputs(&mut gate); + assert!(gate.page_damaged(), "header changes belong to the page beneath a surface"); + assert!(gate.take(1), "the actual owner observes the landed answer"); + gate.acknowledge(1); + bridge.observe_plex_visual_inputs(&mut gate); + assert!(!gate.take(2), "unchanged answers do not repaint"); + assert!(!unrelated.take(2), "no other owned gate is woken"); let mut cache = lock(); let at = cache.iter().position(|(k, _)| *k == key).unwrap(); let entry = cache.remove(at).1; diff --git a/rust-modules/src/app/content.rs b/rust-modules/src/app/content.rs index cbd10292c0..d9252029f0 100644 --- a/rust-modules/src/app/content.rs +++ b/rust-modules/src/app/content.rs @@ -512,8 +512,7 @@ pub(crate) fn content_requests(app: &mut App, fr: &mut Frame) { &mut app.refresh_hubs, &mut app.pages, &mut app.bridge, - &mut app.ok_armed, - &mut app.input.press, + ) }; // …and the item context menu's committed row, for the same reason and at the same moment: it @@ -653,7 +652,7 @@ pub(crate) fn content_requests(app: &mut App, fr: &mut Frame) { // was arranging by hand. if let Some(arg) = app.bridge.content_menu_arg(&app.pages, entry, &ret) { bridge::open_item_menu(&mut app.pages, arg); - app.ok_armed = false; + } } } @@ -736,7 +735,7 @@ fn home_requests(app: &mut App, now: u32) { app.bridge.watchlist_open_if_idle(); arg.watchlist = app.bridge.watchlist_card_face(item); bridge::open_item_menu(&mut app.pages, arg); - app.ok_armed = false; + } } } @@ -801,7 +800,7 @@ fn search_requests(app: &mut App) { app.bridge.watchlist_open_if_idle(); arg.watchlist = app.bridge.watchlist_card_face(&item); bridge::open_item_menu(&mut app.pages, arg); - app.ok_armed = false; + } } } @@ -822,7 +821,7 @@ fn watchlist_requests(app: &mut App) { { continue; } - watchlist_request(&mut app.pages, &mut app.bridge, entry, request, ret, &mut app.ok_armed); + watchlist_request(&mut app.pages, &mut app.bridge, entry, request, ret); } } @@ -832,7 +831,7 @@ fn watchlist_requests(app: &mut App) { /// [`library_navigation`] is: a test that presses OK on the pill sees the menu the TV opens. pub(crate) fn watchlist_request( pages: &mut plx_ui::dispatch::Dispatcher, rig: &mut bridge::Bridge, entry: EntryId, - request: plx_screens::watchlist::page::WatchlistOut, ret: ReturnState, ok_armed: &mut bool, + request: plx_screens::watchlist::page::WatchlistOut, ret: ReturnState, ) { use plx_screens::watchlist::page::WatchlistOut; match request { @@ -852,7 +851,7 @@ pub(crate) fn watchlist_request( WatchlistOut::Hold { guid, state, copy, .. } => { let Some(arg) = rig.watchlist_hold_arg(pages, entry, ret.focus, &guid, state, copy) else { return }; bridge::open_item_menu(pages, arg); - *ok_armed = false; + } // The catalog page of a title no server holds, by the tile's guid (a guid the service // does not form as `plex://movie|show/` has no page to open). @@ -947,7 +946,7 @@ fn library_requests(app: &mut App, now: u32) { let Some(ret) = library_navigation(&mut app.pages, &mut app.bridge, &request, ret) else { continue }; unsafe { library_page_request(&mut app.player.session, &mut app.adapters.player, &mut app.menu_play_await, - &mut app.ok_armed, now, &mut app.pages, &mut app.bridge, instance, entry, request, ret); + now, &mut app.pages, &mut app.bridge, instance, entry, request, ret); } } } @@ -984,7 +983,7 @@ pub(crate) unsafe fn library_page_request( ps: &mut plx_media::route::PlaybackSession, pa: &mut plx_media::player::adapter::PlayerAdapter, menu_play_await: &mut Option, - ok_armed: &mut bool, + now: u32, pages: &mut plx_ui::dispatch::Dispatcher, bridge: &mut bridge::Bridge, @@ -1013,7 +1012,7 @@ pub(crate) unsafe fn library_page_request( bridge.watchlist_open_if_idle(); arg.watchlist = bridge.watchlist_card_face(&item); bridge::open_item_menu(pages, arg); - *ok_armed = false; + } LibraryReq::Detail { sid, ref rk, .. } | LibraryReq::Play { sid, ref rk, .. } => { let Some((mut item, _)) = bridge.library_selection(pages, entry, ret.focus) else { return }; diff --git a/rust-modules/src/app/deeplink_route_tests.rs b/rust-modules/src/app/deeplink_route_tests.rs index 84514444d0..37613fd5d1 100644 --- a/rust-modules/src/app/deeplink_route_tests.rs +++ b/rust-modules/src/app/deeplink_route_tests.rs @@ -5,6 +5,8 @@ use super::*; use super::test_support::{frame, tick, Pms}; +#[cfg(feature = "play-feed")] +use super::test_support::PreviewReset; use crate::app::deeplink::{self, DeepLink}; use crate::app::input; use plx_plex::plex::ServerId; @@ -238,14 +240,6 @@ fn play_payload(rk: &str) -> String { format!(r#"{{"event":"launch","parameters":{{"plex":{{"ratingKey":"{rk}","action":"play"}}}}}}"#) } -/// Puts a preview back to Idle when the test ends, however it ends (the machine is process-wide). -#[cfg(feature = "play-feed")] -struct PreviewReset; -#[cfg(feature = "play-feed")] -impl Drop for PreviewReset { - fn drop(&mut self) { plx_media::player::preview::reset_for_test(); } -} - #[cfg(feature = "play-feed")] impl Rig { /// Frames until the link's item is the loaded detail, then a few more for the wait to act. diff --git a/rust-modules/src/app/diagnostics.rs b/rust-modules/src/app/diagnostics.rs index ecf77d8ab3..ab71ea4609 100644 --- a/rust-modules/src/app/diagnostics.rs +++ b/rust-modules/src/app/diagnostics.rs @@ -206,33 +206,21 @@ pub(crate) fn enabled() -> bool { /// survives a restart is one a user can strand themselves with. pub(crate) fn toggle() { ON.fetch_xor(true, Ordering::Relaxed); - kick(); } /// Force it on for an automated playback run. Unlike [`toggle`], this is idempotent so an already /// visible read-out keeps its sample cadence and does not reset the panel's clock. pub(crate) fn open() { - if !ON.swap(true, Ordering::Relaxed) { - kick(); - } + ON.store(true, Ordering::Relaxed); } /// Force it off. The only caller is the leave-playback ritual — a diagnostics panel that survived /// into the next session would be a bug in the feature built to find bugs. pub(crate) fn close() { ON.store(false, Ordering::Relaxed); - kick(); } -/// A discrete change: the whole-frame present gate has no spring to watch here, so without this -/// the panel would not appear until something else happened to repaint (see `plx_machine::idle`). -/// -/// It used to also force the next sample by writing a static. It does not need to: `Diagnostics` -/// watches [`ON`]'s rising edge itself, which is the same behaviour without a handle the three -/// callers of `toggle`/`open`/`close` do not all have. -fn kick() { - plx_machine::idle::invalidate(); -} +// Toggle callers mutate only ON. The App-owned observer reports visible edges from update. // ---- the snapshot ----------------------------------------------------------------------------- @@ -412,21 +400,23 @@ impl Diagnostics { /// The panel being switched ON is its own re-sample: the rising edge of [`ON`] is what the /// static-era `kick()` expressed by zeroing the deadline from three modules away. pub(crate) fn update(&mut self, ps: &plx_media::route::PlaybackSession, pa: &plx_media::player::adapter::PlayerAdapter, - paused: Option, now: u32) { + paused: Option, now: u32) -> bool { let on = enabled(); + let changed = on != self.was_on; let woke = on && !self.was_on; self.was_on = on; if !on { - return; + return changed; } if !woke && now < self.next_sample { - return; + return false; } self.next_sample = now.wrapping_add(SAMPLE_MS); // The panel is the maintainer's instrument: its own messages are English-only, and the // shared helpers it composes (units, decimals, quality labels) read the UI language, so // the whole sample is taken in English. Nothing sampled here reaches product UI. self.sample(ps, pa, paused, now); + true } /// Take the sample in English (see `update`). The one entry to `resample`. @@ -463,8 +453,19 @@ impl Diagnostics { now, ); self.chart_values = chart_values(&self.history); - // a re-sample changes what is on screen, and no spring is involved — see `plx_machine::idle` - plx_machine::idle::invalidate(); + // The caller owns presentation authority; update reports this sample edge. + } +} + +/// The firmware on the identity line: [`plx_platform::i18n::webos_release_line`] and, when the +/// platform file named one, the API version. A release that only `/usr/lib/os-release` named has +/// no API version, and the line must not end in an `api` label with nothing after it. +fn firmware_head(w: &plx_platform::tv::device::Info) -> String { + let release = plx_platform::i18n::webos_release_line(w); + if w.major == 0 || w.api.is_empty() { + release + } else { + format!("{release} · api {}", w.api) } } @@ -476,12 +477,7 @@ impl Diagnostics { /// firmware where the failure reason should have been. Both facts are now wrapped independently /// and drawn in full, so the array's length remains the semantic contract. fn header(ps: &plx_media::route::PlaybackSession, d: &plx_media::player::Diag, now: u32, paused: Option) -> [String; 2] { - let w = plx_platform::tv::device::info(); - let os = if w.major == 0 { - plx_platform::i18n::msg::browse_diagnostics_unknown_os().to_string() - } else { - format!("webOS {} · api {}", w.release, w.api) - }; + let os = firmware_head(plx_platform::tv::device::info()); let (_, _, vw, vh) = plx_base::surface::viewport(); [ // via `plex::identity`, not a literal + `env!`: that module exists precisely so the @@ -598,9 +594,11 @@ fn device_rows() -> Vec { v.push(Field::new( plx_platform::i18n::msg::browse_diagnostics_field_firmware(), match (i.name.as_str(), i.codename.as_str()) { - // Bare "unknown": the head line above already carries the REASON in this state - // ("webOS unknown — os_info.json unreadable"), and a photograph should not spend two - // of its compact rows on one fact. + // Bare "unknown": with neither file read the head line above already carries the REASON + // ("webOS unknown — os_info.json unreadable"). When `/usr/lib/os-release` named the + // release instead, the head line reads `webOS 6.5.3` and this row is the codename, + // which that file does not carry; a photograph should not spend two of its compact + // rows on one fact. ("", "") => plx_platform::i18n::msg::browse_diagnostics_unknown().to_string(), ("", cn) => cn.to_string(), (n, "") => n.to_string(), @@ -3523,6 +3521,20 @@ mod tests { assert_eq!(mb(3 * 1024 * 1024 * 1024), "3.00 GB"); } + /// The firmware text on the identity line: the release and, only when the platform file named + /// one, the API version. A release that `/usr/lib/os-release` named has no API version, and the + /// line must not end in an `api` label with nothing after it. + #[test] + fn the_firmware_text_names_the_api_only_when_it_is_known() { + use plx_platform::tv::device::Info; + let _g = plx_base::testlock::serial(); + let nyx = Info { release: "4.10.2".into(), api: "4.1.0".into(), major: 4, ..Info::default() }; + assert_eq!(firmware_head(&nyx), "webOS 4.10.2 · api 4.1.0", "the nyx spelling is unchanged"); + let os_release = Info { release: "6.5.3".into(), major: 6, ..Info::default() }; + assert_eq!(firmware_head(&os_release), "webOS 6.5.3"); + assert_eq!(firmware_head(&Info::default()), plx_platform::i18n::msg::browse_diagnostics_unknown_os()); + } + /// An unreadable `os_info.json` must say so rather than print a plausible version — the panel /// exists to identify firmware, so a confident wrong answer is worse than none. (The parse /// itself is pinned in `webos.rs`; this pins the SENTENCE the panel prints.) diff --git a/rust-modules/src/app/events.rs b/rust-modules/src/app/events.rs index 0d8ca7ade4..38ff78200c 100644 --- a/rust-modules/src/app/events.rs +++ b/rust-modules/src/app/events.rs @@ -385,7 +385,7 @@ pub(crate) fn remote_synth_wheel(dy: i32) { } /// Is this SDL event type INPUT — a key, text, pointer or wheel event — as opposed to a lifecycle, -/// window or quit event? The one classification `popover::host::input_scope` rests on: input under +/// window or quit event? The one classification `Dispatcher::input_scope` rests on: input under /// an open modal is the modal's, a lifecycle event is the app's and may change the page beneath. pub(crate) fn is_input_event(et: u32) -> bool { matches!( @@ -446,7 +446,7 @@ mod input_event_tests { } } - /// The boundary `popover::host::input_scope` rests on: every input kind is in, and the + /// The boundary `Dispatcher::input_scope` rests on: every input kind is in, and the /// lifecycle events (background/foreground, `0x103`–`0x106`), window events and quit are out. #[test] fn input_events_are_the_modals_and_lifecycle_events_are_the_apps() { @@ -475,15 +475,10 @@ mod input_event_tests { /// `true` means the token was accepted and injected/requested, not that the screen necessarily /// changed — pressing DOWN at the bottom of a list is still a successfully delivered command. pub(crate) fn dispatch_remote_token(tok: &str, ps: &plx_media::route::PlaybackSession, - pa: &plx_media::player::adapter::PlayerAdapter) -> bool { - // As the SDL loop: a modal's input is its own. NOT for `pat:`, which is not input at all — it - // changes the PAGE's ground directly, and a frozen host must be retaken to show it. - let _own_input = if tok.starts_with("pat:") { - None - } else { - plx_ui::popover::host::input_scope() - }; - plx_machine::idle::invalidate(); // injected input is input like any other + pa: &plx_media::player::adapter::PlayerAdapter, present: &mut plx_machine::present::Present, + scope: plx_machine::present::Scope) -> bool { + let scope = if tok.starts_with("pat:") { plx_machine::present::Scope::Page } else { scope }; + present.note_in_scope(scope, plx_machine::present::PresentEvent::Damage(plx_machine::present::Provenance::Input)); if let Some((kind, x, y)) = remote_token_pointer(tok) { let name = match kind { RemotePointer::Click => "click", diff --git a/rust-modules/src/app/home_chrome_route_tests.rs b/rust-modules/src/app/home_chrome_route_tests.rs index 8a33639c65..b9e5e8d3e2 100644 --- a/rust-modules/src/app/home_chrome_route_tests.rs +++ b/rust-modules/src/app/home_chrome_route_tests.rs @@ -271,9 +271,9 @@ fn long_line(drawn: &Drawn) -> Option<(f32, usize)> { /// Draw the frame, and say whether a marquee is moving in it (past its rest beat). fn draw_and_glides(w: &mut World) -> (Drawn, bool) { - let _ = plx_machine::idle::take_local_damage(); + let _ = plx_machine::motion::report::take_local_motion(); let frame = w.drawn(); - (frame, plx_machine::idle::take_local_damage() > 0) + (frame, plx_machine::motion::report::take_local_motion() > 0) } /// **A held Right along a Home shelf glides the focused caption while the shelf headings stay clear diff --git a/rust-modules/src/app/input.rs b/rust-modules/src/app/input.rs index f74bb3791f..da7f746fc1 100644 --- a/rust-modules/src/app/input.rs +++ b/rust-modules/src/app/input.rs @@ -1181,14 +1181,10 @@ mod item_menu_player_return_tests; // fingerprint each press produces against a recorded table. /// A key-up: the reliable release (this remote sends exactly one per press). Retires this sym from -/// the physically-down slot and springs a deferred grid-card press back. +/// the physically-down slot. Gesture release belongs exclusively to the dispatcher. /// -/// It cleared a second slot — `HeldKey::sym`, the client-side hold-repeat's own — until phase 10 -/// deleted that timer with its last consumer (the item menu). What is left is `down_sym`, which is -/// a fact about the PHYSICAL key rather than about whoever read it, and the press machine's -/// release, which is a fact about the LOOP's own deferred press. **Both are why this still runs -/// unconditionally, above the tree-ownership question**: a key the ladders never saw go down would -/// otherwise look held for as long as a surface was up. +/// This runs unconditionally: physical-key bookkeeping is independent of input ownership. +/// The forwarded event releases the dispatcher press exactly once. /// /// **The scrub half is gone** (restructure phase 12, PX-PLAYER). It ran on /// `PlayerScreen::scrub` — a field of a screen that has owned the whole gesture since it began @@ -1196,45 +1192,17 @@ mod item_menu_player_return_tests; /// `Edge::Up` — so the two together issued TWO seeks for one tap. The commit, the debounce and /// the reveal-cancel are `screens::player::PlayerScreen::key_scrub_release`'s now, and /// the commit reaches `commit_seek` through `PlayerReq::CommitSeek` instead of through here. -pub(crate) fn on_key_up( - sym: c_uint, - ok_armed: bool, - down_sym: &mut u32, - press: &mut plx_ui::press::Press, -) { +pub(crate) fn on_key_up(sym: c_uint, down_sym: &mut u32) { if sym == *down_sym { *down_sym = 0; } - if is_ok(sym) && ok_armed { - // OK released over a grid card: start the spring-back; the deferred - // activation commits from the per-frame loop once the bounce has shown. - press.release(clock::now()); - } } -/// A hardware AUTO-REPEAT (held key). **All that is left of it is the deferred press's liveness -/// beat** — the dropped-key-up net in `ui::press`, which is the loop's own machine and belongs to -/// no screen. -/// -/// The client-side hold-repeat timer went in phase 10: every discrete focus list in the app — the -/// home grid, detail, the Settings family, the player's four panels and, last of them, the item -/// context menu — is an owned screen or a surface on the dispatcher, so a repeat reaching one is -/// an `InputEvent` carrying `Edge::Repeat` handed over before this function is reached, and the -/// cadence is applied THERE (`RepeatGate`, to the DIRECTIONS only). -/// -/// The player's continuous scrub was the last thing this drove directly, and it went the same way -/// in phase 12 (PX-PLAYER): `PlayerScreen::key_scrub_repeat` engages the ramp off its own -/// `Edge::Repeat`, which is the same event one layer down, and the per-frame advance is that -/// screen's `Tick`. Nothing about the gesture is read or written from here any more, which is what -/// makes `PlayerScreen::scrub` a field with ONE owner. -pub(crate) fn on_auto_repeat(sym: c_uint, ok_armed: bool, press: &mut plx_ui::press::Press) { - if ok_armed && is_ok(sym) { - press.note_alive(clock::now()); // OK held: keep the dropped-key-up net honest - } -} +// Auto-repeat liveness, press cancellation and gesture ticks belong to Dispatcher.input. + /// What EVERY fresh press does before the ladder sees it: remember the sym as physically down, -/// un-dismiss the HUD, abort an armed click that a non-OK key slid off, and — the LG pointer +/// un-dismiss the HUD, and — the LG pointer /// convention, global to every screen including the onboarding ones the ladder dispatches first — /// let the first D-pad press dismiss the Magic-Remote cursor and put input in D-pad mode. Pointer /// motion brings it back. @@ -1277,11 +1245,10 @@ pub(crate) unsafe fn begin_fresh_press( down_sym: &mut u32, hud: Option<&mut HudState>, ptr: &mut Pointer, - ok_armed: &mut bool, - press: &mut plx_ui::press::Press, + ) { *down_sym = sym; - note_global_press(ps, sym, wcode, now, viewer_paused, hud, ok_armed, press); + note_global_press(ps, sym, wcode, now, viewer_paused, hud); if matches!( key, Key::Up | Key::Down | Key::Left { alt: false } | Key::Right { alt: false } @@ -1297,7 +1264,7 @@ pub(crate) unsafe fn begin_fresh_press( } } -/// **The two GLOBAL effects of a fresh press, and the guard that decides whether they happen** — +/// **The global HUD wake of a fresh press, and the guard that decides whether it happens** — /// the half of [`begin_fresh_press`] that LG checklist item 40 is about, and its only caller. /// /// Split out for one blunt reason: `begin_fresh_press` calls `hide_cursor`, which acts on whatever @@ -1311,8 +1278,7 @@ pub(crate) fn note_global_press( now: u32, viewer_paused: bool, hud: Option<&mut HudState>, - ok_armed: &mut bool, - press: &mut plx_ui::press::Press, + ) { if !is_bound(sym, wcode) { return; // an unsupported key is not input the app acted on — see `begin_fresh_press` @@ -1323,13 +1289,7 @@ pub(crate) fn note_global_press( if let Some(hud) = hud { hud.note_fresh_press(ps, now, viewer_paused); } - // a fresh non-OK key (navigation / BACK) while a click is armed aborts the press — spring the - // card back to rest WITHOUT activating (you "slid off" the control). A key the app does not - // bind is not sliding off anything: nothing moved, so nothing is abandoned. - if *ok_armed && !is_ok(sym) { - press.cancel(); - *ok_armed = false; - } + // Release and cancellation are owned by the dispatcher's InputMachine. } /// **The unsupported-key invariant, graded.** `tools/keytable.py` grades the other half — that an @@ -1345,28 +1305,24 @@ mod unsupported_key_tests { /// test's own `Press`. fn press(ps: &plx_media::route::PlaybackSession, sym: c_uint, wcode: c_uint) -> (bool, bool) { let mut hud = HudState::IDLE; - let mut ok_armed = true; // a click is in flight, as if OK were still down on a card + hud.dismissed = true; // …and the transport was hidden by hand (UP from the control row) - let mut p = plx_ui::press::Press::new(); + let mut p = plx_ui::dispatch::press::Press::new(); p.begin(1_000); note_global_press(ps, sym, wcode, 1_000, false, - Some(&mut hud), &mut ok_armed, &mut p); - let out = (p.is_active() && ok_armed, hud.dismissed); + Some(&mut hud)); + let out = (p.is_active(), hud.dismissed); p.cancel(); out } - /// A key the app binds behaves exactly as it always has: it un-dismisses the HUD and aborts the - /// click it slid off. BACK is the case to use — it is not OK, so it takes the abort branch. + /// Bound keys wake the HUD; physical bookkeeping leaves all gesture cancellation to input. #[test] - fn a_bound_key_still_wakes_the_hud_and_aborts_the_click() { + fn a_bound_key_still_wakes_the_hud_without_owning_the_press() { let ps = plx_media::route::PlaybackSession::IDLE; let _g = plx_base::testlock::serial(); let (armed, dismissed) = press(&ps, SDLK_ESCAPE, 0); - assert!( - !armed, - "BACK slides off the control — the press is cancelled" - ); + assert!(armed, "physical bookkeeping must leave press ownership to the dispatcher"); assert!(!dismissed, "…and any key un-dismisses the transport"); } @@ -1397,7 +1353,7 @@ mod unsupported_key_tests { let ps = plx_media::route::PlaybackSession::IDLE; let _g = plx_base::testlock::serial(); let (armed, dismissed) = press(&ps, b'5' as c_uint, 34); - assert!(!armed); + assert!(armed, "physical bookkeeping leaves cancellation to the input owner"); assert!(!dismissed); } } diff --git a/rust-modules/src/app/library_back_lift_tests.rs b/rust-modules/src/app/library_back_lift_tests.rs index 69130acc97..b51cff1554 100644 --- a/rust-modules/src/app/library_back_lift_tests.rs +++ b/rust-modules/src/app/library_back_lift_tests.rs @@ -50,7 +50,7 @@ impl Rig { self.frames.push(Frame { phase: self.w.d.nav.tabs.stack.transition.phase_word(), paint, - moving: plx_machine::idle::page_layout_moving(), + moving: plx_machine::motion::report::page_layout_moving(), scale, }); } diff --git a/rust-modules/src/app/library_collections_arrival_tests.rs b/rust-modules/src/app/library_collections_arrival_tests.rs index d3597f1222..492d054a72 100644 --- a/rust-modules/src/app/library_collections_arrival_tests.rs +++ b/rust-modules/src/app/library_collections_arrival_tests.rs @@ -54,7 +54,7 @@ fn trace(frames: usize, land: Option<(usize, usize)>, command: Option<(usize, pl let mut ms = 0u32; let mut step = |d: &mut Dispatcher, rig: &mut Bridge, rows: Option<&mut Vec>| { ms += 16; - plx_machine::idle::frame_begin(0.016); + plx_machine::motion::report::frame_begin(0.016); super::frame(d, rig, Tick { ms, dt_us: 16_000 }, vec![]); let Some(paint) = dip.plan(d, ms) else { return }; if let (Some(rows), Some(content)) = (rows, library_content(d)) { diff --git a/rust-modules/src/app/library_host_freeze_tests.rs b/rust-modules/src/app/library_host_freeze_tests.rs index e8365a1d34..6992ac96bc 100644 --- a/rust-modules/src/app/library_host_freeze_tests.rs +++ b/rust-modules/src/app/library_host_freeze_tests.rs @@ -168,9 +168,9 @@ fn a_host_page_spring_under_an_open_panel_is_host_motion() { // a settled panel over a settled page: nothing moves, and in particular the panel's own // appear spring (`ModalStack::tick`, now in a scope of its own) is not the page's motion - plx_machine::idle::frame_begin(1.0 / 60.0); + plx_machine::motion::report::frame_begin(1.0 / 60.0); frame(&mut d, &mut rig, AppArg::Library, tick(120), vec![]); - assert!(!plx_machine::idle::page_moving(), "a settled host does not move"); + assert!(!plx_machine::motion::report::page_moving(), "a settled host does not move"); // dismiss: input returns to the page while the panel is still visible, and the page is driven d.request(MachineId::Nav, NavOp::Dismiss(menu)); @@ -178,12 +178,12 @@ fn a_host_page_spring_under_an_open_panel_is_host_motion() { Bridge::library_command(&mut d, plx_screens::registry::LibraryCmd::FocusGrid { row: 0, col: 0 }); let mut moved = 0; for i in 122..136u32 { - plx_machine::idle::frame_begin(1.0 / 60.0); + plx_machine::motion::report::frame_begin(1.0 / 60.0); let (_, report) = frame(&mut d, &mut rig, AppArg::Library, tick(i), vec![]); // The panel's own close MORPH is motion too (S11: the menu runs back into its control), in // the panel's scope; it is not the page's. A frame counts here when the page's own spring // moved, and the attribution bug this pins shows as that never happening. - if !plx_machine::idle::page_moving() { + if !plx_machine::motion::report::page_moving() { continue; } moved += 1; @@ -194,7 +194,7 @@ fn a_host_page_spring_under_an_open_panel_is_host_motion() { report.underlay_moving ); assert!( - plx_ui::popover::host_refresh(true, false, plx_machine::idle::page_moving()), + plx_ui::popover::host_refresh(true, false, plx_machine::motion::report::page_moving()), "frame {i}: …so the fading panel's frozen snapshot is re-taken" ); } diff --git a/rust-modules/src/app/library_push_capture_tests.rs b/rust-modules/src/app/library_push_capture_tests.rs index a0a4f9923c..7d8b027d9f 100644 --- a/rust-modules/src/app/library_push_capture_tests.rs +++ b/rust-modules/src/app/library_push_capture_tests.rs @@ -50,7 +50,7 @@ fn push_trace(case: Case) -> Vec { let mut ms = 0u32; let mut step = |d: &mut Dispatcher, rig: &mut Bridge, rows: Option<&mut Vec>| { ms += 16; - plx_machine::idle::frame_begin(0.016); + plx_machine::motion::report::frame_begin(0.016); super::frame(d, rig, Tick { ms, dt_us: 16_000 }, vec![]); use plx_ui::containers::transition::PagePaint; let Some(paint) = dip.plan(d, ms) else { return }; diff --git a/rust-modules/src/app/library_shelf_action_tests.rs b/rust-modules/src/app/library_shelf_action_tests.rs index ffbc059331..d9a0ee870e 100644 --- a/rust-modules/src/app/library_shelf_action_tests.rs +++ b/rust-modules/src/app/library_shelf_action_tests.rs @@ -135,12 +135,7 @@ fn shelf_physical_hold_captures_engine_item_deck_flag_and_bridge_rest_opener() { .unwrap(); let parts = CxParts { tick: tick(n), - press: plx_machine::machine::PressRead { - scale: d.input.press.scale(), - is_long: d.input.press.was_long(), - held_ms: None, - owner: d.input.dip_owner, - }, + press: d.input.press_read(tick(n).ms), focus: d.input.engine.read(InputOwner::Entry(key.entry)), owner: InputOwner::Entry(key.entry), }; diff --git a/rust-modules/src/app/mod.rs b/rust-modules/src/app/mod.rs index de134eb00a..43398d1736 100644 --- a/rust-modules/src/app/mod.rs +++ b/rust-modules/src/app/mod.rs @@ -285,6 +285,7 @@ pub(crate) struct App { /// nine `static mut`s in `ui/stats.rs`. Not a `ModalStack` surface, and `diagnostics.rs`'s /// `Diagnostics` doc says why — the panel takes no keys and draws at two different z-positions. pub(crate) diagnostics: diagnostics::Diagnostics, + pub(crate) lab_toast: crate::lab::ToastObserver, /// **The Player machine** (restructure spec §2.2, phase 9): the playback session that was /// `route::decision::SESSION`, the app-switch lifecycle that was `App.foreground`, and this /// frame's tick. Reached as a parameter from here down — `plx_media::player::machine`'s doc says @@ -302,7 +303,7 @@ pub(crate) struct App { /// DID edge withdraws them), as `(grant revision at the refusal, retries left)`; the frame /// step claims again once the revision moves (`run::retry_refused_foreground`). foreground_retry: Option<(u64, u8)>, - pub(crate) ok_armed: bool, + last_route_reported: &'static str, pub(crate) ptr: Pointer, // (`route`, `play_from`, `trail` and `nav_pending` stood here — four fields that between them @@ -353,17 +354,14 @@ pub(crate) struct App { /// Every dev-trigger arm's own state — oscillator phases, retry latches, boot-time flags /// (formerly `DevFlags`) — gathered on ONE struct (spec: `dev/scenarios.rs`'s module doc). pub(crate) scenarios: crate::dev::scenarios::Scenarios, - /// The Input machine: owner of the press (restructure spec §2.2); the ladders borrow it. - pub(crate) input: plx_ui::input::Input, + /// `text::take_measure_fault` has been reported once (the report is once per process). measure_fault_logged: bool, /// The recorder / replay driver (`plxnative-rec` / `plxnative-recplay`, spec §5.3/§5.5). pub(crate) rec: recorder::Recplay, pub(crate) boot_initial: Option, pub(crate) telemetry_guard: Option, - /// The present gate as a machine (spec §4.4). `plx_machine::idle` is still the product's verdict on - /// this loop; this one receives the render cache's notes and is what `dispatch` takes over. - present: plx_machine::present::Present, + /// The frame plan's GLASS half (spec §8.3): the layer/region source registry, shared chrome /// material and dev load dial. The budget half lives on the `Dispatcher` (§2.2). pub(crate) glass: plx_ui::frame::glass::GlassPlan, @@ -387,6 +385,20 @@ pub(crate) struct App { pub(crate) bridge: bridge::Bridge, } +impl App { + /// Application/runner mutations belong to the page, never an ambient damage queue. + pub(crate) fn note_presentation_damage(&mut self, why: plx_machine::present::Provenance) { + self.pages.present.note_in_scope(plx_machine::present::Scope::Page, + plx_machine::present::PresentEvent::Damage(why)); + } + + pub(crate) fn note_input_damage(&mut self) { + let scope = self.pages.input_scope(); + self.pages.present.note_in_scope(scope, + plx_machine::present::PresentEvent::Damage(plx_machine::present::Provenance::Input)); + } +} + impl App { pub(crate) fn snapshot_init(&self) -> Option { let mut initial = self.boot_initial.clone()?; diff --git a/rust-modules/src/app/owned_publication_tests.rs b/rust-modules/src/app/owned_publication_tests.rs new file mode 100644 index 0000000000..116cf1c2f1 --- /dev/null +++ b/rust-modules/src/app/owned_publication_tests.rs @@ -0,0 +1,39 @@ +//! Owned publication gates are independent; unchanged observations do not repaint. +use super::*; + +#[test] +fn session_cache_landing_damages_only_its_owner_once() { + let _g = plx_base::testlock::serial(); + let mut bridge = Bridge::for_test(|| 0); + let mut owner = Dispatcher::::new(); + let other = Dispatcher::::new(); + let other_epoch = other.present.damage_epoch(); + let other_page = other.present.page_damage_epoch(); + let before = owner.present.damage_epoch(); + let page_before = owner.present.page_damage_epoch(); + owner.present.set_scope(plx_machine::present::Scope::Surface); + bridge.session_cache_generation = plx_plex::plex::session::visible_generation().wrapping_sub(1); + bridge.land_session_cache(&mut owner); + assert_eq!(owner.present.damage_epoch(), before + 1); + assert_eq!(owner.present.page_damage_epoch(), page_before + 1); + bridge.land_session_cache(&mut owner); + assert_eq!(owner.present.damage_epoch(), before + 1, "one visible generation, one landing"); + assert_eq!(other.present.damage_epoch(), other_epoch); + assert_eq!(other.present.page_damage_epoch(), other_page); +} + +#[test] +fn unmounted_watchlist_commands_have_no_page_authority() { + let _g = plx_base::testlock::serial(); + let mut bridge = Bridge::for_test(|| 0); + let mut owner = Dispatcher::::new(); + let other = Dispatcher::::new(); + let before = owner.present.damage_epoch(); + let other_before = other.present.damage_epoch(); + bridge.watchlist_reread(); + bridge.watchlist_feed(&mut owner); + bridge.catalog_feed(&mut owner); + bridge.watchlist_feed(&mut owner); + assert_eq!(owner.present.damage_epoch(), before, "unmounted scalar/store changes publish no page"); + assert_eq!(other.present.damage_epoch(), other_before); +} diff --git a/rust-modules/src/app/page_regions_tests.rs b/rust-modules/src/app/page_regions_tests.rs index c7eb043990..aca15330f1 100644 --- a/rust-modules/src/app/page_regions_tests.rs +++ b/rust-modules/src/app/page_regions_tests.rs @@ -142,7 +142,7 @@ impl Rig { fn step(&mut self, inputs: Vec>) { self.frame += 1; if let Some(feed) = self.feed { feed(&mut self.d, &mut self.bridge); } - plx_machine::idle::frame_begin(0.016); + plx_machine::motion::report::frame_begin(0.016); super::frame(&mut self.d, &mut self.bridge, tick(self.frame), inputs); self.performed.extend(pump_navigation(&mut self.d, &mut self.bridge)); } diff --git a/rust-modules/src/app/playback.rs b/rust-modules/src/app/playback.rs index 56938cafa3..58d3522ca5 100644 --- a/rust-modules/src/app/playback.rs +++ b/rust-modules/src/app/playback.rs @@ -16,7 +16,7 @@ //! `PlayerScreen::step` had been answering the same keys through the dispatcher since the page //! began reporting `FocusSource::Engine`, and these four went on writing that page's `hud`/`scrub` //! from the loop beside it. What is left of the player here is the half a screen may not do — -//! [`commit_seek`], [`exit_player`], [`activate_player_row`], the transport toggle — each reached +//! [`commit_seek`], [`exit_player`], [`activate_stand_in`], the transport toggle — each reached //! through a `PlayerReq`. use super::*; @@ -108,7 +108,7 @@ pub(crate) fn is_started(ps: &plx_media::route::PlaybackSession) -> Option /// Perform what the `…` popover reported. Shared by the OK key and the pointer click, so /// the two paths can never come to disagree about what a row does. -pub(crate) fn apply_more_action(ps: &mut plx_media::route::PlaybackSession, pa: &mut plx_media::player::adapter::PlayerAdapter, bridge: &mut super::bridge::Bridge, a: plx_appkit::more_menu::Action) { +pub(crate) fn apply_more_action(ps: &mut plx_media::route::PlaybackSession, pa: &mut plx_media::player::adapter::PlayerAdapter, bridge: &mut super::bridge::Bridge, a: plx_appkit::more_menu::Action, present: &mut plx_machine::present::Present) { match a { plx_appkit::more_menu::Action::ToggleStats => crate::app::diagnostics::toggle(), // A rung of the playback-quality ladder — a routing POLICY, not a number handed to a @@ -125,7 +125,9 @@ pub(crate) fn apply_more_action(ps: &mut plx_media::route::PlaybackSession, pa: let failed = matches!(plx_media::player::state(ps), plx_media::player::PlaybackState::Error); if failed { plx_media::route::set_quality_for_retry(q); - retry_failed_playback(ps, pa, bridge.metadata_mut(), None, AttemptOrigin::QualityChange); + if retry_failed_playback(ps, pa, bridge.metadata_mut(), None, AttemptOrigin::QualityChange) { + present.note_in_scope(plx_machine::present::Scope::Page, plx_machine::present::PresentEvent::Damage(plx_machine::present::Provenance::Input)); + } } else { plx_media::route::set_quality(ps, q); } @@ -193,7 +195,6 @@ pub(crate) fn retry_failed_playback( return false; } if plx_media::route::retry_current_play(ps, meta, resume_ns, direct_play, origin) { - plx_machine::idle::invalidate(); true } else { log("playback retry: current source cannot be resolved again"); @@ -751,8 +752,7 @@ pub(crate) fn player_requests( refresh_hubs: &mut bool, pages: &mut plx_ui::dispatch::Dispatcher, bridge: &mut super::bridge::Bridge, - ok_armed: &mut bool, - press: &mut plx_ui::press::Press, + ) -> PlayerRequestOutcome { use plx_screens::registry::PlayerReq; let mut performed = PlayerRequestOutcome::default(); @@ -760,7 +760,7 @@ pub(crate) fn player_requests( // Accepted user intent always wins the frame, even if its terminal effect was queued later. let auto_retired = reqs.iter().any(|r| matches!(r, PlayerReq::Exit | PlayerReq::CancelAutoSkip(_))); let auto_blocked = reqs.iter().any(|r| matches!(r, PlayerReq::Exit | PlayerReq::SeekTo(_) - | PlayerReq::Transport(_) | PlayerReq::Command(_) | PlayerReq::ArmControlRow | PlayerReq::StandIn | PlayerReq::CancelAutoSkip(_))); + | PlayerReq::Transport(_) | PlayerReq::Command(_) | PlayerReq::StandIn | PlayerReq::CancelAutoSkip(_))); for req in reqs { match req { PlayerReq::BackCursor { owner, playback, change } => { @@ -769,7 +769,9 @@ pub(crate) fn player_requests( } } PlayerReq::CancelAutoSkip(id) => { - bridge.publish_marker_preferences(now); + if bridge.publish_marker_preferences(now) { + pages.present.note_in_scope(plx_machine::present::Scope::Page, plx_machine::present::PresentEvent::Damage(plx_machine::present::Provenance::Landing(plx_machine::machine::MachineId::Session))); + } if bridge.marker_preferences().scope == id.scope && plx_media::route::playback_trace_generation() == id.playback && super::bridge::player(pages).is_some_and(|screen| screen.auto_skip_entry() == id.entry) { bridge.metadata_run(plx_data::stores::metadata::MetadataCmd::MarkSkipped(id.marker)); @@ -779,7 +781,9 @@ pub(crate) fn player_requests( PlayerReq::AutoSkip { id, reply } => { use plx_appkit::skip_policy::OfferOutcome; let mut outcome = OfferOutcome::Retired; - bridge.publish_marker_preferences(now); + if bridge.publish_marker_preferences(now) { + pages.present.note_in_scope(plx_machine::present::Scope::Page, plx_machine::present::PresentEvent::Damage(plx_machine::present::Provenance::Landing(plx_machine::machine::MachineId::Session))); + } let prefs = bridge.marker_preferences(); let active = bridge.metadata_view().active_marker(plx_data::metadata::Playhead { playing: true, @@ -809,16 +813,20 @@ pub(crate) fn player_requests( plx_screens::registry::AppMsg::AutoSkipResolved { id, outcome })))); } PlayerReq::RetryPlayback => { - retry_failed_playback(&mut player.session, pa, bridge.metadata_mut(), None, AttemptOrigin::UserRetry); + if retry_failed_playback(&mut player.session, pa, bridge.metadata_mut(), None, AttemptOrigin::UserRetry) { + pages.present.note_in_scope(plx_machine::present::Scope::Page, plx_machine::present::PresentEvent::Damage(plx_machine::present::Provenance::Input)); + } } PlayerReq::PlayAutomatically => { - play_automatically(&mut player.session, pa, bridge.metadata_mut()); + if play_automatically(&mut player.session, pa, bridge.metadata_mut()) { + pages.present.note_in_scope(plx_machine::present::Scope::Page, plx_machine::present::PresentEvent::Damage(plx_machine::present::Provenance::Input)); + } } PlayerReq::RepairSandbox => { if player.session.jail_load_blocked { pa.repair_sandbox(&mut player.repair, plx_platform::tv::sandbox::blocks_native_video()); player.session.repair_status = player.repair.state(); - plx_machine::idle::invalidate(); + pages.present.note_in_scope(plx_machine::present::Scope::Page, plx_machine::present::PresentEvent::Damage(plx_machine::present::Provenance::Input)); } } PlayerReq::ExtendHud(ms) => { @@ -834,27 +842,17 @@ pub(crate) fn player_requests( // …and its twin, which does NOT resume: the scrub bar is how a paused film is moved. // The pump keeps the pause across it (see `commit_seek`). PlayerReq::CommitSeek(ns) => commit_seek(&mut player.session, pa, ns), - PlayerReq::More(action) => apply_more_action(&mut player.session, pa, bridge, action), + PlayerReq::More(action) => apply_more_action(&mut player.session, pa, bridge, action, &mut pages.present), PlayerReq::CommitTrack(commit) => commit_track(&mut player.session, pa, bridge.metadata_mut(), commit), // The failure-read-out's recovery escape (`ChooseQuality`) and the Tracks->Timing hand-off, which - // present a panel immediately rather than through the deferred press `ArmControlRow` uses. The + // present a panel immediately rather than through the row's deferred press. The // tabs row is not an asker: it asks `ToggleSection` (Info and Chapters are sections). PlayerReq::OpenOverlay(kind) => { seed_menu_anchor(pages, bridge, kind); super::bridge::open_player_overlay(&mut player.session, bridge.metadata_view(), pages, kind); } - // A pointer click on the control row: dip a tvOS press for the transport's OWN control - // row, not a panel's. The loop's - // existing commit-frame dispatch (`Route::Player => activate_player_row(...)`, below - // in this same call chain) is unchanged and performs whatever the row decides. - PlayerReq::ArmControlRow => { - press.begin_ctl(now); - *ok_armed = true; - } - // The engine's press on the control row, committed on its spring-back: the dip - // already played, so this performs at once (the pointer's `ArmControlRow` above dips - // here and performs from the loop's commit frame, through the same two functions). + // Keyboard and pointer presses both arrive here after the dispatcher's commit. PlayerReq::Command(command) => { perform_hud_command(command, player, pa, repause_at, now, refresh_hubs, pages, bridge) } @@ -1390,8 +1388,8 @@ fn seed_menu_anchor( } /// **THE performer of a [`HudCommand`](plx_appkit::player_hud::command::HudCommand)**: one `match` over the closed vocabulary, which every route to -/// a command ends in. A disc pressed with OK (`PlayerReq::Command`), one clicked -/// ([`activate_player_row`]) and a More-menu row folded from a package (the overlay closes More and asks +/// a command ends in. A disc pressed with a key or pointer (`PlayerReq::Command`) +/// and a More-menu row folded from a package (the overlay closes More and asks /// `PlayerReq::Command`) all end in this function, so a command can never mean one thing from a control and another from a menu. /// /// It performs and does not decide: whether the command is enabled is the caller's, from @@ -1494,40 +1492,7 @@ fn apply_seek_to(ps: &mut plx_media::route::PlaybackSession, resume_if_paused(ps, pa); } -/// Activate the player transport's focused CONTROL ROW item — the deferred half of a pointer -/// click, run from the per-frame loop once the press spring-back has played (OK reaches -/// [`perform_hud_command`] and [`activate_stand_in`] through the engine's own press instead). -/// -/// Two arms: a STAND-IN owns the row (Skip, Up Next) and performs its own action, or the row holds -/// the discs, whose focused item is a [`HudCommand`](plx_appkit::player_hud::command::HudCommand) for the one performer. `ctrl` is re-resolved by -/// the caller on the committing frame rather than captured at the press, so the activation acts on -/// the row that is DRAWN — the slot is resolved once per loop iteration for input, update and draw -/// alike (see the `let ctrl` at the top of the loop), and an offer that arrived mid-press has -/// already changed what the user is looking at. -#[allow(clippy::too_many_arguments)] -pub(crate) unsafe fn activate_player_row( - player: &mut plx_media::player::machine::Player, - pa: &mut plx_media::player::adapter::PlayerAdapter, - repause_at: &mut i64, - ctrl: plx_appkit::player_hud::ControlSlot, - now: u32, - refresh_hubs: &mut bool, - pages: &mut plx_ui::dispatch::Dispatcher, - bridge: &mut super::bridge::Bridge, -) { - // The cursor is the instance's; read the one field this dispatch turns on, so the container - // is borrowed once and the arms below are free to present a panel on it. - let btn = super::bridge::player(pages).map_or(0, |player| player.hud.nav.btn); - if let plx_appkit::player_hud::ControlSlot::Discs(_) = ctrl { - // the command of the control the PACKAGE placed at the cursor's index, as a press of it asks for - let command = super::bridge::player(pages).and_then(|screen| screen.row_command(btn)); - if let Some(command) = command { - perform_hud_command(command, player, pa, repause_at, now, refresh_hubs, pages, bridge); - } - } else { - activate_stand_in(player, pa, repause_at, ctrl, now, refresh_hubs, pages, bridge); - } -} + /// Activate the Skip pill or the Up Next item the cursor is on, then keep the transport up. Same /// value the draw used: the slot is the page's own. (Its `true` answer used to clear the loop's diff --git a/rust-modules/src/app/plex_session_app_tests.rs b/rust-modules/src/app/plex_session_app_tests.rs index 20823d4fa1..7f87f488d8 100644 --- a/rust-modules/src/app/plex_session_app_tests.rs +++ b/rust-modules/src/app/plex_session_app_tests.rs @@ -29,23 +29,26 @@ fn a_visible_session_change_invalidates_the_frame_once_per_landing() { let _session = session::TempSession::new("bridge-session-landing"); struct ResetIdle; impl Drop for ResetIdle { - fn drop(&mut self) { plx_machine::idle::reset_for_test(); } + fn drop(&mut self) { plx_machine::motion::report::reset_for_test(); } } let _idle = ResetIdle; let mut bridge = Bridge::for_test(|| 0); let mut pages = plx_ui::dispatch::Dispatcher::new(); session::save(&signed_in()); - plx_machine::idle::reset_for_test(); + plx_machine::motion::report::reset_for_test(); let _frame = plx_base::task::FrameScope::enter(); + let before = pages.present.damage_epoch(); bridge.land_session_cache(&mut pages); - assert_eq!(plx_machine::idle::take_local_damage(), 1, "a changed session lands on the frame step"); + assert_eq!(pages.present.damage_epoch() - before, 1, "a changed session lands on the frame step"); + let before = pages.present.damage_epoch(); bridge.land_session_cache(&mut pages); - assert_eq!(plx_machine::idle::take_local_damage(), 0, "one invalidation per landing"); + assert_eq!(pages.present.damage_epoch() - before, 0, "one invalidation per landing"); drop(_frame); session::save(&signed_in()); let _frame = plx_base::task::FrameScope::enter(); + let before = pages.present.damage_epoch(); bridge.land_session_cache(&mut pages); - assert_eq!(plx_machine::idle::take_local_damage(), 0, "a save that serves the same content lands nothing"); + assert_eq!(pages.present.damage_epoch() - before, 0, "a save that serves the same content lands nothing"); } /// This thread holds the session's IO lock for the whole run, so a frame that took it — or made any @@ -137,7 +140,7 @@ fn an_unloaded_cache_is_refilled_by_the_owner_within_a_few_frames() { let _session = session::TempSession::new("bridge-cache-refill"); struct ResetIdle; impl Drop for ResetIdle { - fn drop(&mut self) { plx_machine::idle::reset_for_test(); } + fn drop(&mut self) { plx_machine::motion::report::reset_for_test(); } } let _idle = ResetIdle; session::save(&signed_in()); @@ -202,7 +205,7 @@ fn a_refresh_effect_still_queued_is_not_reconciled_as_lost() { let _session = session::TempSession::new("bridge-cache-effect-queued"); struct ResetIdle; impl Drop for ResetIdle { - fn drop(&mut self) { plx_machine::idle::reset_for_test(); } + fn drop(&mut self) { plx_machine::motion::report::reset_for_test(); } } let _idle = ResetIdle; session::save(&signed_in()); diff --git a/rust-modules/src/app/plex_visual_inputs.rs b/rust-modules/src/app/plex_visual_inputs.rs new file mode 100644 index 0000000000..8135f7039f --- /dev/null +++ b/rust-modules/src/app/plex_visual_inputs.rs @@ -0,0 +1,89 @@ +//! IO-boundary observation of addressed Plex/platform facts, never an ambient damage queue. +use plx_machine::present::{Present, PresentEvent, Provenance, Scope}; +use plx_plex::plex::{self, ServerId}; + +#[derive(Debug, PartialEq, Eq)] +struct ServerVisualInput { + id: ServerId, + facts: Option<&'static plex::ServerFacts>, + info: plex::serverinfo::ServerInfoFacts, + probe: Option, + grant_epoch: u32, + token_generation: u32, + link: Option, + ip: Option, +} + +/// Actual domain values: immutable roster descriptions are borrowed, version strings Arc-cloned. +/// No lossy hashes, dirty generations, or worker-owned UI provenance. +#[derive(Debug, PartialEq, Eq)] +pub(super) struct PlexVisualInputs { + current: ServerId, + roster: u32, + facts: u32, + servers: Vec, + preferences: Vec, + collections: Vec<((u16, u32, i64), Option)>, + dv: plx_platform::devcaps::dv::DvProbe, +} + +impl PlexVisualInputs { + fn capture() -> Self { + let servers = plex::server_ids().filter_map(|id| { + let client = plex::client_for(id)?; + Some(ServerVisualInput { + id, facts: plex::server_facts(id), info: plex::serverinfo::facts_of(id), + probe: plex::server_probe_result(id), grant_epoch: client.grant_epoch(), + token_generation: client.token_gen(), link: client.link(), ip: client.ip_version(), + }) + }).collect(); + Self { current: plex::current_server(), roster: plex::server_roster_gen(), + facts: plex::server_facts_gen(), servers, + collections: crate::app::collections_probe::visual_facts(), + preferences: plx_media::route::preference_values(), dv: plx_platform::devcaps::dv::probe() } + } +} + +impl super::Bridge { + /// Called after result/input landings and before shot preparation/admission. These facts can + /// change the host underneath a surface, so their observation always belongs to Page scope. + pub(crate) fn observe_plex_visual_inputs(&mut self, present: &mut Present) { + if self.home_io.is_some() { return; } // controlled inputs must not poll ambient Plex state + let next = PlexVisualInputs::capture(); + if self.plex_visual_inputs.as_ref() != Some(&next) { + present.note_in_scope(Scope::Page, PresentEvent::Damage(Provenance::Lifecycle)); + self.plex_visual_inputs = Some(next); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn addressed_probe_arrivals_damage_only_the_observing_owned_gate() { + let _g = plx_base::testlock::serial(); + plex::reset_servers_for_test(); + let mut bridge = super::super::Bridge::for_visual_inputs_test(); + let mut gate = Present::new(); + bridge.observe_plex_visual_inputs(&mut gate); + gate.take(0); + gate.acknowledge(0); + let id = plex::register_for_test("visual-observer", "127.0.0.1", 32400, "tok", "fixture"); + assert_ne!(id, ServerId::UNSET); + bridge.observe_plex_visual_inputs(&mut gate); + assert!(gate.take(1)); + gate.acknowledge(1); + plex::publish_probe_result(id, plex::probe::Outcome::Unauthorized); + assert!(!gate.take(2), "worker publication alone has no UI authority"); + gate.set_scope(Scope::Surface); + bridge.observe_plex_visual_inputs(&mut gate); + assert!(gate.page_damaged(), "server facts invalidate the host beneath a surface"); + assert!(gate.take(2), "the addressed outcome repaints before keepalive"); + gate.acknowledge(2); + bridge.observe_plex_visual_inputs(&mut gate); + assert!(!gate.take(3), "unchanged inputs do not continuously repaint"); + plex::reset_servers_for_test(); + } +} diff --git a/rust-modules/src/app/preferences.rs b/rust-modules/src/app/preferences.rs index a13999f232..6b0e38240f 100644 --- a/rust-modules/src/app/preferences.rs +++ b/rust-modules/src/app/preferences.rs @@ -46,7 +46,7 @@ pub(super) fn execute(command: PreferenceCmd) { let _ = reply.send(AccountPreferenceReply { request: None, outcome: Err(PreferenceError::Unavailable), }); - plx_machine::idle::invalidate(); + return; }; // A refused spawn drops the reply sender. The screen reports its disconnected @@ -54,14 +54,14 @@ pub(super) fn execute(command: PreferenceCmd) { plx_base::task::spawn_small("acct-prefs", move || { let outcome = request.load(); let _ = reply.send(AccountPreferenceReply { request: Some(request), outcome }); - plx_machine::idle::invalidate(); + plx_machine::present::wake_from_worker(); }); } PreferenceCmd::Save { request, base, update, reply } => { plx_base::task::spawn_small("acct-prefs", move || { let outcome = request.save(&base, update); let _ = reply.send(AccountPreferenceReply { request: Some(request), outcome }); - plx_machine::idle::invalidate(); + plx_machine::present::wake_from_worker(); }); } // Every live setting saves through the one write door, in `choose_setting`. @@ -75,19 +75,19 @@ pub(super) fn execute(command: PreferenceCmd) { (current.auto_sign_in() != on).then(|| current.with_auto_sign_in(on)) }, || plx_plex::plex::session::tenure() == tenure).is_some_and(|write| write.outcome.persisted()); let _ = reply.send(saved); - plx_machine::idle::invalidate(); + plx_machine::present::wake_from_worker(); }); } PreferenceCmd::UiResolution { mode, reply } => { let _ = plx_base::storage_worker::submit_retained(move || { let _ = reply.send(plx_plex::plex::session::set_ui_resolution(mode)); - plx_machine::idle::invalidate(); + plx_machine::present::wake_from_worker(); }); } PreferenceCmd::Language { language, reply } => { let _ = plx_base::storage_worker::submit_retained(move || { let _ = reply.send(plx_plex::plex::session::set_language(language)); - plx_machine::idle::invalidate(); + plx_machine::present::wake_from_worker(); }); } } diff --git a/rust-modules/src/app/preferences/marker_access.rs b/rust-modules/src/app/preferences/marker_access.rs index e93af3ee72..ba4094ceeb 100644 --- a/rust-modules/src/app/preferences/marker_access.rs +++ b/rust-modules/src/app/preferences/marker_access.rs @@ -174,7 +174,7 @@ impl MarkerAccessRunner { let member = !plx_plex::plex::session::peek().active_profile_is_admin(); plx_base::eventlog::log(&outcome_line(member, &result)); let _ = tx.send(result); - plx_machine::idle::invalidate(); + plx_machine::present::wake_from_worker(); }); } } diff --git a/rust-modules/src/app/recorder.rs b/rust-modules/src/app/recorder.rs index 1086bede11..387b1d5688 100644 --- a/rust-modules/src/app/recorder.rs +++ b/rust-modules/src/app/recorder.rs @@ -23,7 +23,7 @@ //! Recorded keys and supplied keys use the same production controlled ingress, retaining the //! original event timestamp and source rather than synthesizing a new SDL timestamp. //! -//! AppFrameV4 combines press/route/overlay/focus/tree with cached Session, physical Consent and typed initial-input +//! AppFrameV5 combines route/overlay/focus/tree with cached Session, physical Consent and typed initial-input //! digests. Private initial/effect data may contain credentials; shareable probes contain no //! raw identity. Only explicit synthetic construction is eligible for fixture import. //! @@ -147,10 +147,10 @@ fn initial_header(app: &AppInit, state: &plx_data::pms::PmsState, adapter: &plx_ /// Pinned by `the_app_shape_census_is_pinned` below, which does NOT move when a screen lands — /// the registry's own pin does that, beside the entry that caused it. const APP_SHAPES: &[&str] = &[ - plx_ui::press::Press::SHAPE, + plx_ui::dispatch::press::Press::SHAPE, plx_ui::input::STATE_SHAPE, "TextInputWire{kind:text,text:str,panel:bool,ms:u32,dt_us:u32,source:{Sdl,RemoteFifo,Script,Replay}}", - "AppFrameV4{route:str,overlay:str,focus:str,tree:u64,session:u64,consent:u64,initial:u64}", + "AppFrameV5{route:str,overlay:str,focus:str,tree:u64,session:u64,consent:u64,initial:u64}", super::bridge::ConsentMachine::SHAPE, plx_ui::containers::STATE_SHAPE, plx_ui::screen::RETURN_STATE_SHAPE, @@ -172,7 +172,9 @@ const RESOLUTION_SHAPE: &str = "ProductResolutionV1{fo:Option<(entry:u32,elem:u3 /// could not distinguish a Session change with otherwise identical visible/tree state. This /// invalidated old recordings. AppFrameV3 additionally bound the complete typed initial-input /// digest; AppFrameV4 adds the physical Consent owner's current decision. The controlled Home -/// boot consumer restores both before work. +/// boot consumer restores both before work. AppFrameV5 removes the shadow App press prefix: +/// the dispatcher tree already includes the single real input press. A bounded key-only V4 +/// profile is graded with frozen idle-prefix bytes; legacy pointer/direct-input profiles are refused. /// /// **`tree:u64` joined it in phase 5b** and the bump was deliberate: the Settings family's state /// left the legacy globals the focus fingerprint reads and became instances on the container tree, @@ -227,6 +229,8 @@ pub(crate) fn state_fp() -> u64 { #[cfg(test)] fn session_app_prior_vector() -> Vec<&'static str> { let mut shapes = APP_SHAPES.to_vec(); + // This test's session-codec census is frozen history, not today's product shape. + shapes[3] = "AppFrameV4{route:str,overlay:str,focus:str,tree:u64,session:u64,consent:u64,initial:u64}"; shapes.push(super::bootstrap::CONTENT_SHAPE); shapes.push(RESOLUTION_SHAPE); shapes.push("CaptureReadinessV2{before_dispatch:pending:bool,text:bool}"); @@ -271,7 +275,10 @@ fn session_app_fingerprint_probe_only() { assert_eq!(prior.iter().zip(&prospective).filter(|(a, b)| a != b).count(), 1); let prospective_fp_v6 = plx_ui::rec::state_fp(&prospective); assert_eq!(prospective_fp_v6, FP_V6); - assert_eq!(state_fp(), prospective_fp_v6); + assert_ne!(state_fp(), prospective_fp_v6, "AppFrameV5 retires the legacy press contribution"); + let manifest = format!(r#"{{"schema":{},"state_fp":{prospective_fp_v6}}}"#, plx_ui::rec::SCHEMA); + assert_eq!(Recording::parse(&manifest, &[], state_fp()).err(), + Some(RecError::StateShape { theirs: prospective_fp_v6, ours: state_fp() })); assert_eq!(frozen["prospective_fp_v6"].as_u64(), Some(FP_V6)); for manifest in [ include_str!("../../../tests/fixtures/replay/1-boot-home-chip-grid/manifest.json"), @@ -293,21 +300,43 @@ fn session_app_fingerprint_probe_only() { /// `session` and `consent` are their owners' cached, side-effect-free subhashes, obtained by /// the common run tail. Only those u64 values are serialized; this neither adds raw secrets nor /// claims all-domain state coverage. -pub(crate) fn state_hash( - press: &plx_ui::press::Press, - route: &str, - overlay: &str, - focus: &str, - tree: u64, - session: u64, - consent: u64, - initial: u64, -) -> u64 { +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum FrameHashProfile { OwnedV5, KeyOnlyV4 } + +/// Only owned key input can prove the retired app press stayed at its boot-time rest. +/// Pointer/direct-token profiles are incompatible and are rejected before startup. +fn recording_hash_profile(recording: &Recording) -> Result { + if recording.header.state_fp == state_fp() { return Ok(FrameHashProfile::OwnedV5); } + if recording.header.state_fp != FP_PRIOR { return Err("incompatible controlled state shape"); } + for input in recording.frames.iter().flat_map(|frame| &frame.inputs) { + if !matches!(decode_input(input).map_err(|_| "unsupported legacy press input")?.kind, + plx_machine::machine::InputKind::Key { .. }) { + return Err("unsupported legacy press input"); + } + } + Ok(FrameHashProfile::KeyOnlyV4) +} + +/// Frozen AppFrameV4 bytes, not a second press machine or mutable compatibility state. +fn write_v4_idle_press(c: &mut Canon) { + c.f32(1.0).f32(0.0).discriminant(0) + .u32(0).u32(0).bool(false).u32(0).u32(0) + .bool(false).bool(false).bool(false).bool(false).bool(true); +} + +pub(crate) fn state_hash_profile(profile: FrameHashProfile, route: &str, overlay: &str, focus: &str, + tree: u64, session: u64, consent: u64, initial: u64) -> u64 { + if profile == FrameHashProfile::OwnedV5 { return state_hash(route, overlay, focus, tree, session, consent, initial); } let mut c = Canon::new(); - press.write(&mut c); + if profile == FrameHashProfile::KeyOnlyV4 { write_v4_idle_press(&mut c); } c.str(route).str(overlay).str(focus).u64(tree).u64(session).u64(consent).u64(initial); c.finish() } +pub(crate) fn state_hash(route: &str, overlay: &str, focus: &str, tree: u64, session: u64, consent: u64, initial: u64) -> u64 { + let mut current = Canon::new(); + current.str(route).str(overlay).str(focus).u64(tree).u64(session).u64(consent).u64(initial); + current.finish() +} pub(crate) struct Rec { w: Writer, @@ -464,6 +493,7 @@ struct ResultEnvelope { /// a live supplier as a fallback; content resources require the typed content initial domain. pub(crate) fn validate_controlled(recording: &Recording, initial: &super::bootstrap::Initial) -> Result<(), &'static str> { + recording_hash_profile(recording)?; if recording.stopped_at.is_some() || recording.frames.is_empty() || recording.header.clock_start_ms != initial.clock_start { return Err("invalid controlled clock"); } @@ -739,6 +769,13 @@ pub(crate) fn machine_name(id: plx_machine::machine::MachineId) -> String { } impl Recplay { + pub(crate) fn frame_hash_profile(&self) -> FrameHashProfile { + match self { + Self::Replaying(replay) if replay.rec.header.state_fp == FP_PRIOR => FrameHashProfile::KeyOnlyV4, + _ => FrameHashProfile::OwnedV5, + } + } + fn resolve_observation(&mut self, identity:(bool,u8,Option), actual:Option) -> Option { match self { Self::Off => actual, @@ -1434,6 +1471,41 @@ mod tests { "startup abort must disarm its own owner gate too"); } + #[test] + fn legacy_profile_loading_cannot_bypass_product_state_shape() { + let initial = super::super::bootstrap::Initial::synthetic_home(1, 32517, Some("root".into())).unwrap(); + let mut header = Header::new(FP_PRIOR, &initial); + header.clock_start_ms = initial.clock_start; + header.features = features(); header.triggers = initial.triggers.clone(); + let mut recording = Recording { header, frames: vec![plx_ui::rec::Frame { + f: 0, tick: Some(Tick::default()), st: Some(0), ..Default::default() + }], metrics: Default::default(), stopped_at: None }; + assert_eq!(recording_hash_profile(&recording), Ok(FrameHashProfile::KeyOnlyV4)); + let key = super::super::bridge::script_edge(plx_machine::machine::Key::Down, + plx_machine::machine::Edge::Down, Tick::default()); + recording.frames[0].inputs.push(super::super::bootstrap::effects::input(&key).unwrap()); + assert_eq!(recording_hash_profile(&recording), Ok(FrameHashProfile::KeyOnlyV4)); + let pointer = super::super::bridge::click_input(0.0, 0.0, Tick::default()); + recording.frames[0].inputs[0] = super::super::bootstrap::effects::input(&pointer).unwrap(); + assert_eq!(recording_hash_profile(&recording), Err("unsupported legacy press input")); + recording.frames[0].inputs.clear(); + recording.header.state_fp = FP_V6; + assert_eq!(validate_controlled(&recording, &initial), Err("incompatible controlled state shape")); + recording.header.state_fp = state_fp(); + assert_eq!(recording_hash_profile(&recording), Ok(FrameHashProfile::OwnedV5)); + assert_eq!(validate_controlled(&recording, &initial), Ok(())); + } + + #[test] + fn legacy_key_grading_uses_the_frozen_rest_prefix_not_a_second_input_owner() { + let mut old = Canon::new(); + plx_ui::dispatch::press::Press::new().write(&mut old); + old.str("home").str("").str("focus").u64(17).u64(21).u64(34).u64(55); + let historical = old.finish(); + assert_eq!(state_hash_profile(FrameHashProfile::KeyOnlyV4, "home", "", "focus", 17, 21, 34, 55), historical); + assert_ne!(state_hash("home", "", "focus", 17, 21, 34, 55), historical); + } + #[test] fn product_pre_resolution_wire_shape_is_refused_before_boot() { let mut before=APP_SHAPES.to_vec(); @@ -2513,7 +2585,8 @@ mod tests { // **A collection shelf's total moves it to this value.** A Home shelf and a hub row carry // the hub's `totalSize` (the linked heading's "· N"), in both the hubs record and the // hubs initial state. - assert_eq!(plx_ui::rec::state_fp(APP_SHAPES), 0x68eb_d05d_f046_ba72); + // AppFrameV5 drops the duplicate legacy press prefix; the tree hashes the real input. + assert_eq!(plx_ui::rec::state_fp(APP_SHAPES), 0xb7b3_fd3a_cc0b_e6b5); } /// The gate at the REAL hubs landing site, through the recording the driver loads: a result @@ -2591,15 +2664,33 @@ mod tests { } } + #[test] + fn the_shadow_press_recording_shape_is_refused() { + let mut shapes = APP_SHAPES.to_vec(); + shapes[3] = "AppFrameV4{route:str,overlay:str,focus:str,tree:u64,session:u64,consent:u64,initial:u64}"; + let initial = shapes.iter_mut().find(|s| **s == super::super::bootstrap::SHAPE).unwrap(); + *initial = super::super::bootstrap::SHAPE_V7; + shapes.push(super::super::bootstrap::CONTENT_SHAPE); + shapes.push(RESOLUTION_SHAPE); + shapes.push("CaptureReadinessV2{before_dispatch:pending:bool,text:bool}"); + shapes.push("MeasurementV1{query:Width(text:bytes,sz:i32,bold:bool)|Cap(sz:i32)|Line(sz:i32),answer:f32bits:u32}"); + shapes.extend_from_slice(plx_screens::registry::SCREEN_SHAPES); + let old = plx_ui::rec::state_fp(&shapes); + assert_ne!(old, state_fp()); + let manifest = format!(r#"{{"schema":{},"state_fp":{old}}}"#, plx_ui::rec::SCHEMA); + assert_eq!(Recording::parse(&manifest, &[], state_fp()).err(), + Some(RecError::StateShape { theirs: old, ours: state_fp() })); + } + #[test] fn the_state_hash_moves_with_the_focus_line_and_the_press() { - let mut press = plx_ui::press::Press::new(); - let a = state_hash(&press, "home", "", "focus route=home sel=0", 0, 0, 0, 0); - let b = state_hash(&press, "home", "", "focus route=home sel=1", 0, 0, 0, 0); + let mut d = plx_ui::dispatch::Dispatcher::::new(); + let a = state_hash("home", "", "focus route=home sel=0", d.state_hash(), 0, 0, 0); + let b = state_hash("home", "", "focus route=home sel=1", d.state_hash(), 0, 0, 0); assert_ne!(a, b); - press.begin(10); - let c = state_hash(&press, "home", "", "focus route=home sel=0", 0, 0, 0, 0); - assert_ne!(a, c); + d.input.press.begin(10); + let c = state_hash("home", "", "focus route=home sel=0", d.state_hash(), 0, 0, 0); + assert_ne!(a, c, "the real dispatcher press is already in the tree digest"); } /// …and with the TREE, which is the half phase 5b added. Every screen in the Settings family @@ -2608,17 +2699,15 @@ mod tests { /// did not, and come back `verdict=SAME`. #[test] fn the_state_hash_moves_with_the_container_tree() { - let press = plx_ui::press::Press::new(); - let a = state_hash(&press, "home", " overlay=settings", "focus route=home", 0x11, 0, 0, 0); - let b = state_hash(&press, "home", " overlay=settings", "focus route=home", 0x12, 0, 0, 0); + let a = state_hash("home", " overlay=settings", "focus route=home", 0x11, 0, 0, 0); + let b = state_hash("home", " overlay=settings", "focus route=home", 0x12, 0, 0, 0); assert_ne!(a, b, "the same page and focus over a different tree is a different state"); } #[test] fn the_state_hash_moves_with_the_physical_consent_owner() { - let press = plx_ui::press::Press::new(); - let denied = state_hash(&press, "home", "", "focus route=home", 0, 0, 0x11, 0); - let allowed = state_hash(&press, "home", "", "focus route=home", 0, 0, 0x12, 0); + let denied = state_hash("home", "", "focus route=home", 0, 0, 0x11, 0); + let allowed = state_hash("home", "", "focus route=home", 0, 0, 0x12, 0); assert_ne!( denied, allowed, "a consent decision changed without moving the canonical application state" @@ -2649,9 +2738,8 @@ mod tests { let mut rec = Recplay::Recording(Rec { w: writer, f: 0, focus: None, events: false, spent_ns: 0, failure: None }); rec.tick(0, 0.016); if let Recplay::Recording(r)=&mut rec { r.events=true; } // force a state grade; this unit exercises no input delivery - let press = plx_ui::press::Press::new(); assert!(!super::super::run::recorder_end_frame( - &mut rec, bridge, &press, "home", "", "fixed synthetic focus", 17, + &mut rec, bridge, "home", "", "fixed synthetic focus", 17, )); let bytes = segments.borrow(); let slices: Vec<_> = bytes.iter().map(Vec::as_slice).collect(); @@ -2696,12 +2784,12 @@ mod tests { present_diffs: 0, result_diffs: 0, land_diffs: 0, result_at: 0, effect_at: 0, input_at: 0, input_diffs: 0, effect_diffs: 0, started: false, failure: None, }); - let press = plx_ui::press::Press::new(); + assert_eq!(plx_ui::dispatch::Tap::::focus_continuation( &mut replay, 0, true, None), Some(None)); plx_ui::dispatch::Tap::::focus(&mut replay, 0, None); assert!(super::super::run::recorder_end_frame( - &mut replay, &other, &press, "home", "", "fixed synthetic focus", 17, + &mut replay, &other, "home", "", "fixed synthetic focus", 17, )); let Recplay::Replaying(result) = replay else { unreachable!() }; assert_eq!(result.graded, 1); @@ -2726,6 +2814,7 @@ mod tests { // `child_count`; they are history, so they keep the record they were computed with. const PRE_CHILD_COUNT_RECORD_SHAPE: &str = "HubsResultV1{gen:u32,seq:u32,sid:u16,client:Option,token_gen:u32,build:Option<{cw:[{last_viewed_at:i64,m:PmsMovie}],shelves:[{title:str,hub_id:str,key:str,items:[PmsMovie]}]}>};PmsMovie{sid:u16,sec:i64,title:str,year:i32,rating:str,dur_ns:i64,part:str,thumb:str,still:str,art:str,summary:str,rk:str,vcodec:str,acodec:str,blur:[[f32bits;3];4],has_blur:bool,kind:i32,resume_ms:i64,show_rk:str,season_index:i32,show_title:str,ep_index:i32,unwatched:bool,watched:bool,aired:str}"; let mut pre_settings = APP_SHAPES.to_vec(); + pre_settings[3] = "AppFrameV4{route:str,overlay:str,focus:str,tree:u64,session:u64,consent:u64,initial:u64}"; let record = pre_settings.iter().position(|shape| *shape == plx_data::pms::record::SHAPE).unwrap(); pre_settings[record] = PRE_CHILD_COUNT_RECORD_SHAPE; // ...and under the hubs initial state before a hub row carried its total. diff --git a/rust-modules/src/app/run.rs b/rust-modules/src/app/run.rs index 2d9bce748f..e28d093f3a 100644 --- a/rust-modules/src/app/run.rs +++ b/rust-modules/src/app/run.rs @@ -38,12 +38,13 @@ //! the same way; see `dev::scenarios`'s own module doc for the full inventory. use super::*; use plx_appkit::player_hud::geometry::{GROUP_ROW, GROUP_TABS}; +use plx_ui::dispatch::Rig as _; /// One lazy product frame-tail hash path for recording and replay grading alike. pub(super) fn recorder_end_frame( rec: &mut super::recorder::Recplay, bridge: &super::bridge::Bridge, - press: &plx_ui::press::Press, + route: &str, overlay: &str, focus: &str, @@ -51,8 +52,9 @@ pub(super) fn recorder_end_frame( ) -> bool { rec.measurements(bridge); rec.content_end(); - rec.end_frame_with_gate(&|| super::recorder::state_hash( - press, route, overlay, focus, tree, bridge.session_subhash(), bridge.consent_subhash(), + let profile = rec.frame_hash_profile(); + rec.end_frame_with_gate(&|| super::recorder::state_hash_profile(profile, + route, overlay, focus, tree, bridge.session_subhash(), bridge.consent_subhash(), bridge.initial_subhash(), ), &|id| bridge.store_gen(id), bridge.landgate()) } @@ -303,7 +305,7 @@ pub(crate) unsafe fn run(app: &mut App) { /// Settle repair and exact native release before publishing this frame's playback facts. fn poll_player_release(app: &mut App) { if app.adapters.player.poll_repair(&mut app.player.repair) { - plx_machine::idle::invalidate(); + app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); } // A timed-out Feed Load and an off-frame Unload get their main-thread tails here. #[cfg(feature = "play-feed")] @@ -366,7 +368,7 @@ fn clock_and_press(app: &mut App, fr: &mut Frame) { let rest_dt = if crate::dev::framedump::active() { crate::dev::framedump::idle_dt(fr.dt) } else { fr.dt }; #[cfg(not(all(feature = "hostsim", feature = "devtriggers")))] let rest_dt = fr.dt; - plx_machine::idle::frame_begin_judging_rest_with(fr.dt, rest_dt); + plx_machine::motion::report::frame_begin_judging_rest_with(fr.dt, rest_dt); // Is a page capture still in flight on the GPU, and is recorded text still warming? Latched // once, before the springs step, so the held appear spring and the present gate below read // the same answer — and, being the machine's speed rather than the inputs, recorded or @@ -377,17 +379,8 @@ fn clock_and_press(app: &mut App, fr: &mut Frame) { plx_gfx::text::latch_surface_text_pending(seen.text); seen.snapshot }); - // ui::press (tvOS click) — advance the dip/spring every frame; when a deferred activation - // commits (the spring-back bounce has played), run it for whichever CARD view armed the - // press. A long-press does NOT commit (`press::tick` clears `want_commit` at `LONG_MS`): - // on Home it opens the item menu below, and anywhere else it just springs back. - let (_, press_moving) = plx_machine::idle::scoped_motion(|| { - app.input.press.tick(fr.now, fr.dt); - }); - // The motion of whatever page is UNDER a popover — Home, the Library or Search, since - // the profile chip is a stop on all three. It was `home_underlay_moving` while only Home - // could be underneath. The account popover's glass re-snapshots off this. - fr.underlay_moving = press_moving; + // Dispatcher::frame alone ticks the owned press and delivers its hold/commit events. + fr.underlay_moving = false; } /// **Make sure the player has a compiled HUD**, on each player frame in `prepare_window` (inside the frame @@ -477,11 +470,20 @@ unsafe fn prepare_window(app: &mut App, fr: &mut Frame) { // tick drain, so on a cold-open frame (~62 ms) every upload was over the ceiling and // only the forward-progress escape let ONE through. A quota of three that was really a // quota of one, on exactly the frames with the most textures waiting. - app.pages.budget.begin_frame(plx_base::diag::heartbeat::now_us()); + // The budget opens with Dispatcher::prepare only after actual admission. // The poster adapter's frame (spec §3.3 step 3's tail): a new frame for the slot LRU and // every decoded image handed to the render cache as owned pixels. No GL here — the // upload is below, on the presenting side of the decision. - super::adapters::poster::begin_frame(); + for outcome in super::adapters::poster::begin_frame() { + match outcome { + super::adapters::poster::ResourceOutcome::RetryDue | super::adapters::poster::ResourceOutcome::EvictionDue => + app.pages.present.note(plx_machine::present::PresentEvent::Wake), + super::adapters::poster::ResourceOutcome::AdmissionRefused + | super::adapters::poster::ResourceOutcome::RetryParked + | super::adapters::poster::ResourceOutcome::LoadFailed => + app.note_presentation_damage(plx_machine::present::Provenance::Resource(plx_machine::present::ResourceKind::Texture)), + } + } super::adapters::poster::drain_decoded(); fr.player = matches!(app.route(), AppArg::Player); @@ -528,7 +530,7 @@ unsafe fn prepare_window(app: &mut App, fr: &mut Frame) { .map(|p| p.clock_fingerprint(&app.player.session, fr.now)); if let Some(fp) = fp { if app.player.note_clock(fp) { - plx_machine::idle::invalidate(); + app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); } } } @@ -576,13 +578,19 @@ unsafe fn prepare_window(app: &mut App, fr: &mut Frame) { // The simulator's settled capture (`PLXNATIVE_SHOT_SETTLE`): once nothing has changed for the // asked-for quiet, invalidate so the NEXT present is the settled frame and `maybe_capture` // takes it. Before the decision below, so that invalidate selects this very frame. + app.bridge.observe_plex_visual_inputs(&mut app.pages.present); + // Settle decisions must include this frame's input, motion and landed content. + plx_machine::motion::report::collect_into(&mut app.pages.present, fr.now); #[cfg(feature = "hostsim")] - crate::shot::tick(fr.now, app.pages.budget.has_queued_work() || plx_gfx::gfx::snapshot_pending() - || app.scenarios.shots.pending()); + if crate::shot::tick(fr.now, app.pages.budget.has_queued_work() || plx_gfx::gfx::snapshot_pending() + || app.scenarios.shots.pending(), app.pages.present.last_change_ms()) { + app.pages.present.note(plx_machine::present::PresentEvent::Wake); + } + // Admission snapshots pending generations but consumes nothing. A lifecycle or + // backbuffer refusal leaves the same work pending, including worker-only wakes. + let demand = app.pages.present.take(fr.now) || app.pages.budget.has_queued_work(); fr.present = !plx_gfx::gfx::snapshot_pending() - && app.window_activity.allow_present( - plx_machine::idle::should_present(fr.now) || app.pages.budget.has_queued_work(), - ); + && app.window_activity.allow_present(demand); // Read-only: was the fence the only thing standing between this iteration and a present? An // inactive window would not have presented either way. (`should_present` is deliberately not // asked: it takes-and-clears the damage the deferred frame still needs.) @@ -595,6 +603,7 @@ unsafe fn prepare_window(app: &mut App, fr: &mut Frame) { app.rec.present(fr.present); if fr.present { app.window_activity.begin_present(fr.player); + app.pages.prepare(&mut app.bridge); } // ---- step 9's UPLOAD, on the presenting side of the decision --------------------- // @@ -614,7 +623,7 @@ unsafe fn prepare_window(app: &mut App, fr: &mut Frame) { // `prepare` (`PanelMotion::prewarm_text`), and uploaded here: `fr.present` already carries the window-activity gate, so a frame that // does not present, or one while the window is backgrounded, uploads nothing. plx_ui::panel_motion::PanelMotion::drain_queued_text(plx_base::diag::heartbeat::now_us); - let mut ph = plx_machine::machine::PresentHandle::of(&mut app.present); + let mut ph = plx_machine::machine::PresentHandle::of(&mut app.pages.present); super::adapters::poster::prepare( &mut app.pages.budget, &mut ph, @@ -723,7 +732,9 @@ fn publish_product_frame(app: &mut App, was_player: bool) { /// Frame-boundary runner inputs, captured before the event pump. fn begin_product_frame(app: &mut App) -> Frame { - app.bridge.publish_marker_preferences(clock::now()); + if app.bridge.publish_marker_preferences(clock::now()) { + app.note_presentation_damage(plx_machine::present::Provenance::Landing(plx_machine::machine::MachineId::Session)); + } let mut frame = Frame::begin(&app.player.session, app.bridge.metadata_view()); frame.ctrl = plx_appkit::player_hud::slot_with_preferences(&app.player.session, app.bridge.metadata_view(), app.bridge.marker_preferences()); @@ -810,7 +821,11 @@ unsafe fn present_and_swap( // A finished underlay-field reduction is read HERE, before framebuffer 0 holds anything // of this frame — a read between the page and the surfaces splits its render pass. plx_gfx::gfx::field_frame_begin(); + #[cfg(feature = "hostsim")] + let shot_last_change = app.pages.present.last_change_ms(); let (_vx, _vy, _vw, _vh) = draw(app, fr); + app.bridge.observe_plex_visual_inputs(&mut app.pages.present); + plx_machine::motion::report::collect_into(&mut app.pages.present, fr.now); app.instr.mark(plx_base::diag::heartbeat::Phase::Draw); // draw // dev capture stream: grab this finished frame before the swap (after the last draw, // so the copy's pass-flush is work the swap would submit anyway). One atomic when idle. @@ -856,7 +871,9 @@ unsafe fn present_and_swap( #[cfg(all(feature = "hostsim", not(feature = "devtriggers")))] let screenshot_seam = true; #[cfg(feature = "hostsim")] - if screenshot_seam && crate::shot::maybe_capture(_vx, _vy, _vw, _vh) { + if screenshot_seam && crate::shot::maybe_capture(fr.now, app.pages.present.changed_after_admission() + || app.pages.budget.has_queued_work() || plx_gfx::gfx::snapshot_pending() + || app.scenarios.shots.pending(), shot_last_change, _vx, _vy, _vw, _vh) { // The headless one-shot is done: finish this frame, then leave through the ordinary // shutdown rather than exiting from inside the frame (see `shot::maybe_capture`). app.running = false; @@ -907,7 +924,8 @@ unsafe fn present_and_swap( plx_gfx::gfx::snapshot_frame_end(); // …and a ground probe's queued copy is read back here, between frames, if it is done. plx_gfx::gfx::ground_probes_frame_end(); - plx_machine::idle::note_present(fr.now); + plx_machine::motion::report::collect_into(&mut app.pages.present, fr.now); + app.pages.present.acknowledge(fr.now); // The swap has returned: this frame's interval, for the visit's slow and frozen counts. app.instr.frame_presented(); // The poster-gate scenes' frame counter, at the same post-swap seam as the present count @@ -935,7 +953,7 @@ unsafe fn present_and_swap( // Device and macOS presented frames block in swap; WSLg/X11 presented frames use the // software budget above. A skipped frame reaches neither path, so sleep here to keep a // settled screen from becoming a CPU spinner. - SDL_Delay(plx_machine::idle::IDLE_POLL_MS); + SDL_Delay(plx_machine::motion::report::IDLE_POLL_MS); } } @@ -992,7 +1010,8 @@ unsafe fn ingress_token(app: &mut App, fr: &mut Frame, token: &str) -> bool { return true; } } - let accepted = dispatch_remote_token(token, &app.player.session, &app.adapters.player); + let scope = app.pages.input_scope(); + let accepted = dispatch_remote_token(token, &app.player.session, &app.adapters.player, &mut app.pages.present, scope); if accepted && token_is_direct(token) { app.rec.input(super::recorder::enc_token(token)); } accepted } @@ -1034,7 +1053,7 @@ fn ingest_text(app: &mut App, text: &str, panel: bool, source: plx_machine::mach } app.inputs.extend(text_inputs(text, panel, at, source)); app.last_input = at.ms; - plx_machine::idle::invalidate(); + app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); } /// Revoke the borrowed SDL window handles on background. `release` answers whether a surface was @@ -1083,22 +1102,9 @@ unsafe fn ingest_sdl_event_with_window(app: &mut App, fr: &mut Frame, } return; } - // INPUT while a popover holds the page frozen is the POPOVER's: every invalidate - // such an event raises — the one below, and whatever its handler adds — is - // attributed to it, so the frozen host is not re-rendered on every key-up - // (`popover::host::input_scope`). Only input: a lifecycle or window event is the - // APP's and may change the page under the panel (backgrounding drops Search's - // editing layout), so its damage stays the page's and the snapshot is retaken. - let _own_input = if is_input_event(et) { - plx_ui::popover::host::input_scope() - } else { - None - }; - // ANY event is a reason to repaint (`plx_machine::idle`): a key changes focus or a label, - // a lifecycle event changes the whole screen. Marked here — once, for every event - // kind — rather than in each of the ~30 arms below, where the next one added would - // silently draw nothing. - plx_machine::idle::invalidate(); + // Attribute only the input repaint to its owner; lifecycle changes remain page damage. + if is_input_event(et) { app.note_input_damage(); } + else { app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); } if et == SDL_KEYDOWN || et == SDL_KEYUP || et == SDL_TEXTINPUT @@ -1207,7 +1213,7 @@ unsafe fn ingest_sdl_event_with_window(app: &mut App, fr: &mut Frame, &mut app.player.session, &mut app.adapters.player, ) { - plx_machine::idle::invalidate(); + app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); } // Playback owns its resolve and Engine before the queued Player page mounts. Page // presence only governs the screen-local cleanup below, never resource suspension. @@ -1268,7 +1274,7 @@ unsafe fn ingest_sdl_event_with_window(app: &mut App, fr: &mut Frame, app.reread.resume(); // Reacquire only on DID foreground, before playback restoration and rendering. restore_window(app.win); - plx_machine::idle::invalidate(); + app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); // A decoder-release park is claimed by this edge like any other park. app.decoder_parked = false; let activation = did_foreground_with_link(app); @@ -1339,7 +1345,7 @@ unsafe fn ingest_sdl_event_with_window(app: &mut App, fr: &mut Frame, // own `TAP_COMMIT_MS` debounce on the very same `Edge::Up` — so one tap of RIGHT // issued two seeks. The publish that followed went with it: nothing here moves a // published field any more. - on_key_up(sym, app.ok_armed, &mut app.down_sym, &mut app.input.press); + on_key_up(sym, &mut app.down_sym); return; } // A repeat is only a repeat if we watched the key go down. See `App::down_sym`: @@ -1363,7 +1369,7 @@ unsafe fn ingest_sdl_event_with_window(app: &mut App, fr: &mut Frame, // All that is left of the legacy repeat path is the deferred press's liveness // beat: the player's continuous scrub, its last direct consumer, engages from // `PlayerScreen`'s own `Edge::Repeat` (phase 12, PX-PLAYER). - on_auto_repeat(sym, app.ok_armed, &mut app.input.press); + return; } // From here down this IS a fresh press, whatever the driver stamped on it. @@ -1400,8 +1406,7 @@ unsafe fn ingest_sdl_event_with_window(app: &mut App, fr: &mut Frame, super::bridge::player_mut(&mut app.pages).map(|player| &mut player.hud) }, &mut app.ptr, - &mut app.ok_armed, - &mut app.input.press, + ); // `note_fresh_press` may have extended the auto-hide deadline; publish it once, here. if let Some(player) = super::bridge::player_mut(&mut app.pages) { @@ -1683,23 +1688,8 @@ unsafe fn ingest_sdl_event_with_window(app: &mut App, fr: &mut Frame, // machine now records about it: motion in that window is a DRAG (§7.5) rather than a // move, and the idle-cursor hide below leaves a held pointer alone. app.ptr.button_down = true; - // A FRESH click supersedes a press still in flight from the previous one — the - // pointer's twin of `begin_fresh_press`'s nav-key abort. Without it, clicking a - // control and then something else inside the ~210 ms commit window let the first - // click's deferred activation fire AFTER the second had already acted (two - // `on_ok`s: the watched toggle flipped twice, each with its own blocking - // refetch). Every arm below re-arms from scratch. - // - // It sits at the TOP of the pointer handler rather than inside one route's arm, - // where it lived while only detail cards armed a press from a click. Every - // control face defers now, so the interleaving it guards is reachable on every - // screen — including across arms, e.g. Home's hero pill pressed and then a tab - // pill clicked, which navigates at once and would otherwise have played the - // hero a moment later on the page it had just left. - if app.ok_armed { - app.input.press.cancel(); - app.ok_armed = false; - } + // The dispatcher owns supersession/cancellation of any previous pointer press. + // A click on NO control is the player's play/pause toggle, so it wakes a paused park // Playing (`wake_input`); a click on a control (the scrub bar, a disc, a tab) is that // control's, which a paused park keeps drawn, so it is only a wake. The OK key a set @@ -1756,17 +1746,9 @@ unsafe fn ingest_sdl_event_with_window(app: &mut App, fr: &mut Frame, app.rec.input(super::recorder::enc_pointer("release", cx as i32, cy as i32)); } } - // a click that armed the tvOS press (a detail card) releases on the button-up, - // the pointer's twin of the OK key-up: without it the dip would sit there until - // press.rs's dropped-key-up ceiling fired. A no-op when no press is in flight. - app.input.press.release(app.last_input); - // …and the same release for the TREE's press machine, which has no pointer-up of - // its own: `dispatch`'s ingest reaches `InputMachine::release` from exactly one - // place, an `Ok` key on the `Up` edge, so that is what a button-up becomes here - // (`bridge::release_input` carries the reasoning and why it is inert everywhere - // else). Unconditional on ownership for `press.release`'s reason above — a - // release with nothing armed is a no-op, and asking `owns_input` would drop the - // release of a press armed on the frame a surface began to close. + // Forward button-up as the dispatcher's OK-up release. Unconditional on ownership: + // querying owns_input here could drop an up while a surface begins closing. + // With nothing armed, InputMachine::release is inert. app.inputs.push(super::bridge::release_input(plx_machine::machine::Tick { ms: app.last_input, dt_us: 0, @@ -1914,7 +1896,7 @@ fn park_on_decoder_release(app: &mut App) { log("player: decoder released by the pipeline — parked until the next press"); park_playback(app); app.decoder_parked = true; - plx_machine::idle::invalidate(); + app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); } /// What the press that wakes a decoder-release park asks of the transport, as far as the restore @@ -1999,7 +1981,7 @@ fn claim_parked_foreground(app: &mut App, input: ForegroundInput) -> bool { if launched { finish_foreground_launch(app); } - plx_machine::idle::invalidate(); + app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); launched } @@ -2169,11 +2151,8 @@ pub(crate) unsafe fn playback_tick(app: &mut App, fr: &mut Frame) { // Everything downstream READS `app.player.video_plane_bound`; nothing recomputes it, and // nothing keys the plane's consequences on the route any more. if let Some(bound) = plx_media::player::observe_video_plane(&mut app.player, &mut app.adapters.player) { - // One edge, three gates. `set_video_plane_bound` has already told the LIVE one - // (`plx_machine::idle`); these are the two §4.4 machines — the one `App` owns and the - // dispatcher's, which is what answers `Rig::opaque_route` at step 9 — plus the rig's - // own copy for the draw-entry call. `PresentEvent::VideoPlane` has no other source. - app.present.note(plx_machine::present::PresentEvent::VideoPlane(bound)); + // One observed edge, one gate recipient. Rendering reads the player's sampled + // plane state; neither the bridge nor a second app gate mirrors this input. app.pages.present.note(plx_machine::present::PresentEvent::VideoPlane(bound)); app.bridge.publish_video_plane(bound); } @@ -2193,7 +2172,7 @@ pub(crate) unsafe fn playback_tick(app: &mut App, fr: &mut Frame) { repause_at: &mut app.repause_at, }, ); - plx_machine::idle::invalidate(); + app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); if matches!(activation, ForegroundActivation::Launched) { finish_foreground_launch(app); } @@ -2463,102 +2442,11 @@ pub(crate) unsafe fn playback_tick(app: &mut App, fr: &mut Frame) { } } -/// Results and requests that land BEFORE nav commit: the OK arm and the press machine, the -/// person / detail open requests, the login and profiles landings (`install_pms`), the glass -/// load, and the nav oscillator. +/// Results and requests that land BEFORE nav commit: person/detail open requests, login and +/// profiles landings (`install_pms`), glass load and the nav oscillator. Press commits are +/// delivered by the dispatcher, never polled here. pub(crate) unsafe fn land_results(app: &mut App, fr: &mut Frame) { - if app.ok_armed { - // PRESS-AND-HOLD → the item context menu, on the latch `press::tick` has always set - // and nothing ever read (`LONG_MS`, `is_long`). It fires while the key is still DOWN, - // which is what makes the menu feel like a hold rather than a delayed tap; the press - // is cancelled so the card springs back, and `ok_armed` is dropped so the eventual - // key-up commits nothing. A SHORT press is untouched on BOTH screens — what it does - // on a Continue Watching tile is `route::deck_press()`'s answer (resume, or open the - // page), and OK on an episode still still plays it, by design; the hold is the other - // half of those interactions either way. Ordered ahead of the commit - // arm (and exclusive with it) so the two can never both run. - // - // `is_long` leads and short-circuits, deliberately: everything after it OPENS a - // menu, so evaluating the arms first would put the popover up on the key-DOWN of - // every tap. - let held_menu = app.input.press.is_long(fr.now) - && match app.route() { - // The detail page has THREE hold surfaces and tries them in turn. Each - // declines by section (`focused_season` answers only on the tab strip, - // `focused_episode` only on the filmstrip, `focused_related` only on the - // Related shelf), so at most one can open and the order between them is not - // a precedence — it is just an order. - // - // The season strip is the newest and the reason is worth keeping: the page - // can mark at three grains and only two of them had a door. An episode has - // its still's hold and the show has the hero's toggle, so "I have seen - // season 3" meant opening eleven menus — a missing control, not a workflow. - // - // The CAST shelf arms the same press and still falls through to the - // ordinary spring-back, deliberately: a headshot is a person, with no - // ratingKey and no watch state, so every row this menu builds would be - // absent and the panel would open empty. - // - // `Route::Search` is deliberately absent (phase 7 Search cutover): its own - // press-and-hold item menu opener is `SearchReq::ItemMenu`, drained by - // `content::search_requests` — an owned screen's press arms and commits - // through the tree's own press machine end to end, so it cannot arrive here - // at all (`app.ok_armed` is armed only by the player's pointer-click - // requests below, neither of which reaches Route::Search any more). - _ => false, - }; - if held_menu { - app.ok_armed = false; - app.input.press.cancel(); - } else if app.input.press.take_commit(fr.now) { - app.ok_armed = false; - // The deferred activation, dispatched by asking the SAME questions the key - // ladder asked when it armed the press, in the SAME order. - // - // **The two family arms that stood at the top of this dispatch are gone** — the - // consent question's answer pill and the first-run editor's action. Both were - // here for one reason: the press was the LOOP's, so the loop had to remember, a - // frame or two later and from nothing but the route, which screen had armed it. - // The tree owns its own press end to end (`InputMachine::arm` records the owner, - // and `PressEvent::Commit` is delivered back to exactly that machine), so an - // owned screen's press cannot arrive here at all — which also retires the - // ordering hazard the old comment recorded, that consent stood OVER a route with - // its own arm below and a match on `route` alone would have committed a consent - // press as a Home activation. - match app.route() { - // `Account { over: Home }` and not every `Account`: the popover can stand on - // three pages now, and a press armed on a Library card must not commit as a - // HOME activation because a panel happened to open over it. (Reaching either - // is near-impossible — a nav key cancels the press — but the arm has to say - // which page it means.) - // Re-ASKED, not remembered, exactly as the Detail arm below does — - // and it has to be asked now that the shelves arm this press too. The - // grid's answer is `Card` (open the page); a SHELF tile's is - // `ShelfCard`, which a section deck turns into a RESUME. Dispatching - // both here rather than calling `open_library_card` unconditionally is - // what stops a held-then-released press on a Continue Watching tile - // opening the detail page the immediate path would have resumed past. - // `Route::Profiles | Route::Search` is deliberately absent (phase 6/7): both - // are owned screens now, so their own press machine arms and commits this - // activation — nothing here ever arms `app.input.press` for either any more - // (see the removed key/pointer arms above), so this deferred commit can never - // see either route. - // the transport's control row (discs or a stand-in) - AppArg::Player => activate_player_row(&mut app.player, - &mut app.adapters.player, - &mut app.repause_at, - fr.ctrl, - fr.now, - &mut app.refresh_hubs, - &mut app.pages, - &mut app.bridge, - ), - _ => {} - } - } else if !app.input.press.is_active() { - app.ok_armed = false; // long-press / cancelled — disarm without activating - } - } + // The ONE consumer of a cast-row person request, drained every frame whatever the // route. `detail::on_ok`'s cast arm raises it, and it is reached from three places @@ -2872,7 +2760,7 @@ pub(crate) unsafe fn update(app: &mut App, fr: &mut Frame) { // Player/Detail frames was pure waste on the A53. Scoped, because the page can be the // one UNDER the account popover and its glass backdrop is refreshed off the // underlay's motion. - let (_, moving) = plx_machine::idle::scoped_motion(|| { + let (_, moving) = plx_machine::motion::report::scoped_motion(|| { app.bridge.update_home_chrome(&mut app.pages, &mut app.glass, fr.dt); }); fr.underlay_moving |= moving; @@ -2923,12 +2811,21 @@ pub(crate) unsafe fn update(app: &mut App, fr: &mut Frame) { // panel is a surface now and the dispatcher ticks it, containers before pages, once per // frame: `PlayerOverlayScreen::step`'s `Tick` arm.) // Re-samples on its own 2 Hz hold; a no-op when the panel is off. - app.diagnostics.update(&app.player.session, &app.adapters.player, - app.adapters.player.backend_viewer_paused(), fr.now); + if app.diagnostics.update(&app.player.session, &app.adapters.player, + app.adapters.player.backend_viewer_paused(), fr.now) { + app.pages.present.note_in_scope(plx_machine::present::Scope::Surface, + plx_machine::present::PresentEvent::Damage(plx_machine::present::Provenance::Lifecycle)); + } // …and the lab upload's toast, which expires on a clock rather than a spring. - crate::lab::update(fr.now); + if crate::lab::update(&mut app.lab_toast, fr.now) { + app.pages.present.note_in_scope(plx_machine::present::Scope::Surface, + plx_machine::present::PresentEvent::Damage(plx_machine::present::Provenance::Lifecycle)); + } #[cfg(feature = "threadcheck")] - plx_ui::runtime_warning::update(app.boot_initial.is_some()); + if plx_ui::runtime_warning::update(app.boot_initial.is_some()) { + app.pages.present.note_in_scope(plx_machine::present::Scope::Surface, + plx_machine::present::PresentEvent::Damage(plx_machine::present::Provenance::Lifecycle)); + } // The Up Next countdown and the control row's focus pop are the PLAYER INSTANCE's and // are stepped from its own `Tick` for the reason `HudMotion::step` gives — the row is // not drawn on every frame of the route, so a spring advanced in the draw would run at a @@ -2966,11 +2863,12 @@ pub(crate) unsafe fn update(app: &mut App, fr: &mut Frame) { // A cold resume's rebuild landed (`player::land_resume`): the Load the pending play // was holding for starts now. if let Some(outcome) = plx_media::player::land_resume(&mut app.player.session, &mut app.adapters.player) { - plx_machine::idle::invalidate(); + app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); finish_landed_play(app, matches!(outcome, plx_media::player::ResumeOutcome::Prepared)); } if let Some(r) = plx_media::route::pump_play(&mut app.player.session, app.bridge.metadata_mut()) { - plx_machine::idle::invalidate(); + app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); + app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); // The resolved URI locator is an owned IO result. Install it against the // route ticket before the common start door chooses a physical backend. #[cfg(feature = "play-uri")] @@ -2991,6 +2889,9 @@ pub(crate) unsafe fn update(app: &mut App, fr: &mut Frame) { // A preview landing nobody is waiting for any more (the page halted it while // the resolve was in flight) must not start an engine: nothing would track // it, so nothing would stop it at its end or hand the engine to a later Play. + // The viewer moved focus; no route failed, so the metric request finishes + // `Cancelled`, never as a handled `PreviewNotDirect` (that kind is only a + // landing the resolve itself refused, which never reaches this branch). #[cfg(feature = "play-feed")] if plx_media::route::is_preview(&app.player.session) && !plx_media::player::preview::expects_landing() @@ -2999,9 +2900,7 @@ pub(crate) unsafe fn update(app: &mut App, fr: &mut Frame) { let _ = plx_media::route::reject_route_start_preparation(transaction); } app.player.session.finish_metric_request( - plx_media::player::attempt_metrics::RequestOutcome::Failed( - plx_media::player::backend::handled_failure( - plx_media::player::FailureKind::PreviewNotDirect))); + plx_media::player::attempt_metrics::RequestOutcome::Cancelled); app.adapters.player.sync_request_metrics(&mut app.player.session); plx_media::player::stop_playback(&mut app.player.session, &mut app.adapters.player); plx_media::route::clear_preview(&mut app.player.session); @@ -3035,7 +2934,7 @@ pub(crate) unsafe fn update(app: &mut App, fr: &mut Frame) { // the same reason as pump_play — play_item_now requests a detail from Home and flips // straight to the player, so a Detail-gated pump would never land it. if app.bridge.metadata_pump_detail() { - plx_machine::idle::invalidate(); // a detail landing rewrites the page under us + app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); // a detail landing rewrites the page under us } // Async season load: install the worker's episode list into CURRENT. Route-unconditional // for the same reason as pump_detail above; see `stores/metadata.rs`'s module doc for why @@ -3045,7 +2944,7 @@ pub(crate) unsafe fn update(app: &mut App, fr: &mut Frame) { // Pumping season first could apply a stale season landing to CURRENT in the one frame // before pump_detail() replaces it. if app.bridge.metadata_pump_season() { - plx_machine::idle::invalidate(); // a season landing rewrites the episode row under us + app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); // a season landing rewrites the episode row under us } // D7: the continuation half of `activate_card`'s show/season Play — see // `App::menu_play_await`/`input::menu_play_tick`'s own doc. Right beside the pump above @@ -3076,7 +2975,11 @@ pub(crate) unsafe fn update(app: &mut App, fr: &mut Frame) { super::bridge::execute_endpoint_outcomes(&mut app.pages, endpoints); // …and the read-back it owes: what the server now says about the item(s) just written, on // every route for the same reason (a refused write is put right here, not by a refetch). - let endpoints = app.bridge.reconcile_pump(); + let outcome = app.bridge.reconcile_pump(); + if outcome.changed { + app.note_presentation_damage(plx_machine::present::Provenance::Landing(plx_machine::machine::MachineId::Store(plx_data::stores::StoreId::ViewReconcile.ord()))); + } + let endpoints = outcome.endpoints; super::bridge::execute_endpoint_outcomes(&mut app.pages, endpoints); // The PMS notification feed (on, for owned servers only: opens nothing until one is described) and // the reads its hints owe the pages on the stack, visible and covered. Route-unconditional @@ -3201,7 +3104,7 @@ pub(crate) unsafe fn draw(app: &mut App, fr: &mut Frame) -> (i32, i32, i32, i32) // is counted in PRESENTS — a loop iteration the gate skipped drew no glass — and // because a step rollover invalidates the snapshot, which must precede every glass // surface drawn by the synthetic dial. - app.glass.prepare_dial(fr.now); + app.glass.prepare_dial(fr.now, &mut app.pages.present); // The authored canvas, scaled UNIFORMLY into the drawable and centred. The shaders // divide every coordinate by `u_screen` (which stays 1920x1080), so this one call // is the entire logical->physical mapping — nothing else in the renderer knows the @@ -3298,10 +3201,11 @@ pub(crate) unsafe fn draw(app: &mut App, fr: &mut Frame) -> (i32, i32, i32, i32) // debug assertion. A popover from this page halts the preview first, so // this frame only skips while the picture is the intended ground. if !(app.player.video_plane_bound && plx_media::route::is_preview(&app.player.session)) { - plx_base::diag::spans::span("host", || plx_ui::popover::host::begin_frame(fr.underlay_moving)); + plx_base::diag::spans::span("host", || plx_ui::popover::host::begin_frame( + fr.underlay_moving, app.pages.present.page_damaged())); } use plx_ui::frame::backdrop::Z; - let layers = app.pages.backdrop_layers(plx_ui::nav::page_alpha()); + let layers = app.pages.backdrop_layers(app.bridge.navigation_presentation(&app.pages.nav).page_alpha); app.glass.sources.borrow_mut().begin(layers); let sources = app.glass.sources.clone(); let _visible_walk = app.glass.walk(Z::ALL); @@ -3374,7 +3278,7 @@ pub(crate) unsafe fn draw(app: &mut App, fr: &mut Frame) -> (i32, i32, i32, i32) // top of everything, and the one thing the tab track (drawn inside the // page) cannot have. drop(_visible_walk); - app.glass.draw_nav_blur(); + app.glass.draw_nav_blur(app.bridge.navigation_presentation(&app.pages.nav)); app.glass.draw_dial(); // The on-screen counter, off the player route (chrome over video). It draws // the last completed `fps=` window — frames actually swapped, not loop @@ -3411,7 +3315,7 @@ pub(crate) unsafe fn draw(app: &mut App, fr: &mut Frame) -> (i32, i32, i32, i32) plx_ui::anim::draw_overlay(); // dev diagnostic overlay (all routes) // The lab upload read-out, over everything, on every route — including the // player, where the two branches above diverge and this one must not. - crate::lab::draw(app.diagnostics.frame_if_shown()); + crate::lab::draw(&app.lab_toast, app.diagnostics.frame_if_shown()); #[cfg(feature = "threadcheck")] plx_ui::runtime_warning::draw(app.boot_initial.is_some()); }); @@ -3587,7 +3491,7 @@ pub(crate) unsafe fn report(app: &mut App, fr: &mut Frame) { }; if crate::focusprobe::armed() { let content = super::bridge::content_probe(&app.pages, &app.bridge); - crate::focusprobe::sample(&app.player.session, fr.rn, probe_screen(app), probe_hud(app), fr.ctrl, &content, app.bridge.metadata_view()); + crate::focusprobe::sample(&app.player.session, fr.rn, probe_screen(app), probe_hud(app), fr.ctrl, &content, app.bridge.metadata_view(), app.pages.input.press.is_active()); } // The recorder's frame tail (spec §5.3): on an event frame the logical-state hash — // the press machine, the route and overlay words, the focus fingerprint and, since phase @@ -3602,13 +3506,12 @@ pub(crate) unsafe fn report(app: &mut App, fr: &mut Frame) { // read lazily by recorder_end_frame for both recording and replay; no raw state is logged. if !matches!(app.rec, super::recorder::Recplay::Off) { let content = super::bridge::content_probe(&app.pages, &app.bridge); - let focus = crate::focusprobe::line(&app.player.session, fr.rn, probe_screen(app), probe_hud(app), fr.ctrl, &content, app.bridge.metadata_view()); + let focus = crate::focusprobe::line(&app.player.session, fr.rn, probe_screen(app), probe_hud(app), fr.ctrl, &content, app.bridge.metadata_view(), app.pages.input.press.is_active()); // The bare WORD, not the heartbeat's ` overlay=` spelling: the prefix is that // line's grammar and has no business in a state hash (phase 10 item 4). let ov = super::words::overlay_word(&app.pages, &app.route()).unwrap_or(""); let tree = app.pages.state_hash(); - let press = &app.input.press; - let done = recorder_end_frame(&mut app.rec, &app.bridge, press, rn, ov, &focus, tree); + let done = recorder_end_frame(&mut app.rec, &app.bridge, rn, ov, &focus, tree); if done { app.running = false; } @@ -3766,7 +3669,7 @@ pub(crate) unsafe fn heartbeat(app: &mut App, fr: &mut Frame) { // a settled screen doing its job, `loop=0` is an app in trouble, and `fps=0` on its // own is not a fault at all. The dev on-screen counter draws this same drained // value, cached below; it never reads a second presentation counter. - let pres = plx_machine::idle::take_presents(); + let pres = app.pages.present.take_presents(); #[cfg(feature = "devtools")] { app.fps_shown = pres.min(i32::MAX as u32) as i32; @@ -3881,7 +3784,7 @@ unsafe fn replay_inject(app: &mut App, fr: &mut Frame, v: &serde_json::Value) { // Same navigation owner as ordinary foreground, with platform and // player restoration kept behind actual SDL lifecycle ingress. super::bridge::foreground(&mut app.pages); - plx_machine::idle::invalidate(); + app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); return; } Err(reason) => { app.rec.refuse(reason); return; } @@ -3907,7 +3810,7 @@ unsafe fn replay_inject(app: &mut App, fr: &mut Frame, v: &serde_json::Value) { log("replay: text has no owned text recipient"); } else if let Some(events) = super::recorder::dec_text(v) { app.inputs.extend(events); - plx_machine::idle::invalidate(); + app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); } else { log("replay: malformed text input"); } } "key" => { @@ -3942,14 +3845,14 @@ unsafe fn controlled_key_input(app: &mut App, event: plx_machine::machine::Input app.ptr.last_motion=event.at.ms; app.ptr.note_cursor_motion(); if matches!(event.kind,InputKind::Click{..}) { app.ptr.button_down=true; } - plx_machine::idle::invalidate(); + app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); app.inputs.push(event); return; } if matches!(event.kind,InputKind::Key { key:Key::Ok,sym:0,wcode:0,edge:Edge::Up,at_edge:false }) && event.source==plx_machine::machine::Source::Sdl { app.last_input=event.at.ms; - app.input.press.release(event.at.ms); + app.ptr.button_down=false; app.inputs.push(event); return; @@ -3962,7 +3865,7 @@ unsafe fn controlled_key_input(app: &mut App, event: plx_machine::machine::Input app.rec.refuse("unsupported controlled key destination"); return; } match edge { - Edge::Up => on_key_up(sym, app.ok_armed, &mut app.down_sym, &mut app.input.press), + Edge::Up => on_key_up(sym, &mut app.down_sym), Edge::Repeat if sym == app.down_sym => { if !app.modal_repeat.ready(event.at.ms) { return; } } @@ -3971,7 +3874,7 @@ unsafe fn controlled_key_input(app: &mut App, event: plx_machine::machine::Input let viewer_paused = viewer_paused_for(&app.player.session, &app.adapters.player); begin_fresh_press(&mut app.player.session, classify(sym, wcode), sym, wcode, event.at.ms, viewer_paused, &mut app.down_sym, - None, &mut app.ptr, &mut app.ok_armed, &mut app.input.press); + None, &mut app.ptr); } } app.inputs.push(event); @@ -4054,6 +3957,7 @@ mod lifecycle_regression_tests { down_sym: Default::default(), modal_repeat: RepeatGate::IDLE, diagnostics: Default::default(), + lab_toast: Default::default(), player: plx_media::player::machine::Player::new(), adapters: Adapters { player: crate::app::adapters::backends::test_adapter(), @@ -4061,7 +3965,7 @@ mod lifecycle_regression_tests { repause_at: -1, decoder_parked: false, foreground_retry: None, - ok_armed: Default::default(), + last_route_reported: Default::default(), ptr: Pointer::IDLE, menu_play_await: Default::default(), @@ -4165,12 +4069,12 @@ mod lifecycle_regression_tests { nobudget: Default::default(), }, }, - input: plx_ui::input::Input::new(), + measure_fault_logged: Default::default(), rec: super::super::recorder::Recplay::Off, boot_initial: Default::default(), telemetry_guard: Default::default(), - present: plx_machine::present::Present::new(), + glass: Default::default(), pages: plx_ui::dispatch::Dispatcher::new(), inputs: Default::default(), @@ -5080,8 +4984,6 @@ mod lifecycle_regression_tests { &mut app.refresh_hubs, &mut app.pages, &mut app.bridge, - &mut app.ok_armed, - &mut app.input.press, ); for later in [232, 248, 264, 280, 296] { frame(&mut app, later); @@ -5259,8 +5161,6 @@ mod lifecycle_regression_tests { &mut app.refresh_hubs, &mut app.pages, &mut app.bridge, - &mut app.ok_armed, - &mut app.input.press, ); for later in [232, 248, 264, 280, 296, 312, 328, 344] { frame(&mut app, later); @@ -7640,16 +7540,9 @@ mod lifecycle_regression_tests { let fr = refuse_restore(&mut rig); player_requests( - &mut rig.app.player, - &mut rig.app.adapters.player, - &mut rig.app.repause_at, - vec![plx_screens::registry::PlayerReq::Exit], - fr.now, - &mut rig.app.refresh_hubs, - &mut rig.app.pages, - &mut rig.app.bridge, - &mut rig.app.ok_armed, - &mut rig.app.input.press, + &mut rig.app.player, &mut rig.app.adapters.player, &mut rig.app.repause_at, + vec![plx_screens::registry::PlayerReq::Exit], fr.now, &mut rig.app.refresh_hubs, + &mut rig.app.pages, &mut rig.app.bridge, ); frame(&mut rig.app, 48); assert!(super::super::bridge::player(&rig.app.pages).is_none()); @@ -7681,8 +7574,6 @@ mod lifecycle_regression_tests { &mut rig.app.refresh_hubs, &mut rig.app.pages, &mut rig.app.bridge, - &mut rig.app.ok_armed, - &mut rig.app.input.press, ); assert!(plx_media::route::play_pending()); rig.accept_start(); @@ -7761,8 +7652,6 @@ mod lifecycle_regression_tests { &mut rig.app.refresh_hubs, &mut rig.app.pages, &mut rig.app.bridge, - &mut rig.app.ok_armed, - &mut rig.app.input.press, ); frame(&mut rig.app, 48); assert!(super::super::bridge::player(&rig.app.pages).is_none()); @@ -9126,6 +9015,69 @@ mod lifecycle_regression_tests { assert!(super::super::bridge::player(&rig.app.pages).is_some(), "premise: the player is on top"); } + /// **A preview the page halted while its resolve was in flight is a cancellation, not a + /// failure.** The viewer moved focus off the hero before the plan landed, so the landing is + /// discarded unstarted ([`plx_media::player::preview::halt`] left the machine Idle). Nothing + /// failed: the request must finish `Cancelled`. It used to finish + /// `Failed(handled_failure(PreviewNotDirect))`, a terminal handled-error effect naming a route + /// problem the preview never had, for a plain focus move. (That effect is a local attempt + /// measurement; the Sentry `PlaybackError` of a preview is `report::tick_preview`'s, keyed on + /// the resolve's own refusal verdict, which a discarded landing never carries.) + #[test] + fn a_preview_halted_before_its_landing_finishes_its_request_cancelled() { + use plx_media::player::attempt_metrics::{Fx, RequestOutcome}; + let _serial = plx_base::testlock::serial(); + // The preview machine is process-wide: put it back to Idle when this test ends, however it + // ends, so a panic between `request_start` and `halt` cannot leave every later test in the + // binary seeing `preview::occupies()`. + let _preview = super::super::bridge::test_support::PreviewReset; + let Some(mut rig) = Rig::new() else { return }; + let mut t = product_transition(&mut rig.app); + settle(&mut rig.app, &mut t); + // The machine and the autoplay switch are process-wide: stand them where a fresh install + // has them, whatever an earlier test in this binary left behind. + plx_media::player::preview::reset_for_test(); + plx_media::player::preview::restore_trailer_autoplay(true); + assert_eq!(plx_media::player::preview::request_start(rig.sid, "1", 0), + plx_media::player::preview::Start::Accepted); + assert!(plx_media::route::request_preview( + &mut rig.app.player.session, + rig.app.bridge.metadata_mut(), + plx_platform::devcaps::caps(), + rig.sid, + "1", + "/library/parts/1/file.mkv", + "h264", + "aac", + "First", + )); + rig.entered.recv_timeout(Duration::from_secs(3)).unwrap(); + let request = rig.app.player.session.metric_request().expect("a preview mints a metric request"); + // The page's focus leaves the hero while the resolve is still parked on the server: with + // no preview session installed yet, `halt` releases the machine so the landing is unwanted. + plx_media::player::preview::halt(&mut rig.app.player.session, &mut rig.app.adapters.player); + assert!(!plx_media::player::preview::occupies(), "premise: nothing waits for the landing any more"); + rig.release.send(()).unwrap(); + poll_until("the halted preview's request never settled", || { + let mut fr = Frame::begin(&rig.app.player.session, rig.app.bridge.metadata_view()); + fr.now = t; + unsafe { update(&mut rig.app, &mut fr); } + rig.app.adapters.player.backend_metrics_snapshot() + .is_some_and(|summary| summary.id == request && summary.outcome.is_some()) + }); + let summary = rig.app.adapters.player.backend_metrics_snapshot().unwrap(); + assert_eq!(summary.outcome, Some(RequestOutcome::Cancelled), + "the viewer left; no route failed, so the request is cancelled, not a handled error"); + assert!(!rig.app.adapters.player.backend_metric_notices().any(|notice| matches!(notice, + plx_media::player::backend::MetricNotice::Measured(Fx::HandledError { .. }))), + "a halted preview raises no handled-error effect"); + assert!(!plx_media::route::is_preview(&rig.app.player.session), + "the discarded landing retired the preview mark"); + assert_ne!(plx_media::player::state(&rig.app.player.session), + plx_media::player::PlaybackState::Error, + "the failure observer reports on the Error transition, which a focus move must never cause"); + } + /// The real app request and landing must reach the backend reducer, including the source /// failure's automatic retry. The fixture serves JSON at the media URL, so both physical /// opens fail and the common owner eventually makes a terminal error decision. @@ -10051,9 +10003,13 @@ mod video_plane_gate_tests { //! writer), the gate (`plx_machine::idle`, the machine layer) and this file's own source (the loop is //! the one consumer a unit test cannot drive). The gate-only half stayed beside the gate: //! `plx_machine::idle`'s `the_present_gate_answers_true_only_while_the_plane_bit_is_set`. - use plx_machine::idle::{ - invalidate, reset_for_test, should_present, take_local_damage, video_plane_bound, - }; + use plx_machine::present::{Present, PresentEvent}; + + fn swap(present: &mut Present, now: u32) -> bool { + let admitted = present.take(now); + if admitted { present.acknowledge(now); } + admitted + } /// **Spec §9, §4.4, §16 risk 10 — the whole-frame gate is turned off by the PLANE'S BIT, not /// by the player route, and both of its edges are carried.** @@ -10079,46 +10035,42 @@ mod video_plane_gate_tests { #[test] fn the_present_gate_answers_true_only_while_the_plane_is_bound() { let _g = plx_base::testlock::serial(); - reset_for_test(); + let mut present = Present::new(); let mut player = plx_media::player::machine::Player::new(); - assert!(!video_plane_bound(), "a fresh machine has no plane"); + assert!(!present.video_plane(), "a fresh machine has no plane"); - invalidate(); - assert!(should_present(0), "the damage just raised selects this frame"); - assert!(!should_present(16), "settled, inside the keepalive: nothing to send"); + assert!(swap(&mut present, 0), "initial damage selects this frame"); + assert!(!swap(&mut present, 16), "settled, inside the keepalive: nothing to send"); // ---- the TRUE edge, and what it buys ---- - player.set_video_plane_bound(true); - assert!(video_plane_bound(), "the machine's edge is the gate's only input"); + assert_eq!(player.set_video_plane_bound(true), Some(true)); + present.note(PresentEvent::VideoPlane(true)); + assert!(present.video_plane(), "the machine's edge is the gate's only input"); for t in [32u32, 48, 64, 80] { assert!( - should_present(t), + swap(&mut present, t), "while the plane is bound every frame presents, unconditionally — nothing about this frame moved", ); } // A LEVEL is not an edge. Writing the same value again must publish nothing: a second // formula term feeding the gate is exactly what risk 10 names. - let _ = take_local_damage(); - player.set_video_plane_bound(true); - assert_eq!( - take_local_damage(), - 0, - "re-asserting the same bit raised damage — the bit is published on EDGES only", - ); + assert_eq!(player.set_video_plane_bound(true), None, + "re-asserting the same bit must publish no edge"); // ---- the FALSE edge, on a frame that would otherwise not present ---- // Nothing else has happened: no input, no landing, no spring, and the keepalive is not due // (LAST_PRESENT is 0 and KEEPALIVE_MS is 2000). Without the edge's own report this frame // is skipped, and the last video frame stays on the panel behind a stale opaque region. - player.set_video_plane_bound(false); - assert!(!video_plane_bound()); + assert_eq!(player.set_video_plane_bound(false), Some(false)); + present.note(PresentEvent::VideoPlane(false)); + assert!(!present.video_plane()); assert!( - should_present(96), + swap(&mut present, 96), "the unbind frame presents even though nothing else about it moved", ); assert!( - !should_present(112), + !swap(&mut present, 112), "…and the frame after it is an ordinary idle frame again, which is the whole point", ); diff --git a/rust-modules/src/app/run_uri_boot_tests.rs b/rust-modules/src/app/run_uri_boot_tests.rs index 58a78cfabd..6f53869b1c 100644 --- a/rust-modules/src/app/run_uri_boot_tests.rs +++ b/rust-modules/src/app/run_uri_boot_tests.rs @@ -252,8 +252,9 @@ mod uri_boot_tests { } /// The port the product composition builds for a viewer who opted in to the URI engine, over the - /// exported-window `Display`: production's binding for it (`Unbound`: the host has no handle, and - /// the product's exported-window table, `EXPORTED_STRATA`, is empty) handed through the debug-only override's + /// exported-window `Display`: the binding of a major the product's exported-window table, + /// `EXPORTED_STRATA`, has not admitted (`Unbound`: the host has no handle and the major is not + /// listed) handed through the debug-only override's /// `compose` (`dev::uri_exported`) as `install_uri_product` does, and the production evidence /// (`unqualified_on` the display's mode, which an opted-in request certifies). #[cfg(feature = "devtriggers")] @@ -953,7 +954,7 @@ mod uri_boot_tests { assert!(plx_media::player::speed_offer(&rig.app.player.session).contains(&1500)); crate::app::playback::apply_more_action(&mut rig.app.player.session, &mut rig.app.adapters.player, &mut rig.app.bridge, - plx_appkit::more_menu::Action::SetSpeed(1500)); + plx_appkit::more_menu::Action::SetSpeed(1500), &mut rig.app.pages.present); assert_eq!(rig.app.player.session.requested_rate_permille(), 1500); assert_eq!(rig.app.player.session.reconfigure_pause_goal(), Some(true)); assert_eq!(rig.app.player.session.attempt_origin(), diff --git a/rust-modules/src/app/surface_navigation_tests.rs b/rust-modules/src/app/surface_navigation_tests.rs index c362fa9cd8..35fc8c8225 100644 --- a/rust-modules/src/app/surface_navigation_tests.rs +++ b/rust-modules/src/app/surface_navigation_tests.rs @@ -911,8 +911,9 @@ fn page_damage_frames_across_a_taken_holds_spring(lift_owns_the_card: bool) -> ( let mut t = 0u32; let run = |d: &mut Dispatcher, rig: &mut Bridge, t: &mut u32| { *t += 1; + let before = d.present.page_damage_epoch(); frame(d, rig, AppArg::Home, tick(*t), vec![]); - let damage = plx_machine::idle::take_page_damage(); + let damage = d.present.page_damage_epoch() != before; damage }; run(&mut d, &mut rig, &mut t); diff --git a/rust-modules/src/app/watchlist.rs b/rust-modules/src/app/watchlist.rs index 625bed5b55..6cbb41fcf0 100644 --- a/rust-modules/src/app/watchlist.rs +++ b/rust-modules/src/app/watchlist.rs @@ -40,6 +40,13 @@ use plx_screens::watchlist::page::{ListState, MatchedFacts, WatchTile, Watchlist use super::*; +/// Publication admission belongs to the observing dispatcher's page, not to a store worker. +fn note_feed_landing(d: &mut Dispatcher, store: StoreId) { + d.present.note_in_scope(plx_machine::present::Scope::Page, + plx_machine::present::PresentEvent::Damage(plx_machine::present::Provenance::Landing( + MachineId::Store(store.ord())))); +} + /// How long after a burst of landed writes the list is read again. const REREAD_DELAY_MS: u32 = 2_000; /// Titles kept in the hold window either side of the focus: three screens of six-wide rows. @@ -243,7 +250,7 @@ impl Bridge { } } if changed { - plx_machine::idle::invalidate(); + note_feed_landing(d, StoreId::Watchlist); } } @@ -269,14 +276,14 @@ impl Bridge { /// A bookmark press (or the hold menu's Remove) on the catalog id `hex`. pub(crate) fn watchlist_press(&mut self, hex: [u8; 12], intent: Intent) { self.stores.watchlist.run(WatchlistCmd::Press { hex, intent }); - plx_machine::idle::invalidate(); + // The feed owns the resulting visual delta, after any menu veil is lifted. } /// Read the list again (and with it the matches): Try again on the unreachable read-out, and /// a resume or a long cover of a live Watchlist page (`reread.rs`). pub(crate) fn watchlist_reread(&mut self) { self.stores.watchlist.run(WatchlistCmd::Reread); - plx_machine::idle::invalidate(); + // A reread with unchanged publication has no visual authority. } /// Try again on the unreachable read-out. @@ -309,7 +316,7 @@ impl Bridge { let (sort, filter) = options.specs(); self.stores.watchlist.run(WatchlistCmd::Sort(sort)); self.stores.watchlist.run(WatchlistCmd::Filter(filter)); - plx_machine::idle::invalidate(); + // Options land through watchlist_feed; a veiled host keeps its existing publication. } /// The menu argument for the Sort & Filter surface over the page `host`: the store's current @@ -422,7 +429,6 @@ impl Bridge { pub(crate) fn watchlist_open_if_idle(&mut self) { if self.stores.watchlist.view().status() == Status::Idle { self.stores.watchlist.run_with_input(WatchlistCmd::Open, &Self::watchlist_input()); - plx_machine::idle::invalidate(); } } @@ -476,9 +482,9 @@ impl Bridge { /// bookmark disc of every Detail page on the stack. pub(crate) fn catalog_feed(&mut self, d: &mut Dispatcher) { use plx_screens::registry::ContentArg; - if self.catalog_pump() { - plx_machine::idle::invalidate(); - } + self.catalog_pump(); + // Pumping is route-unconditional; publication to a veiled host is not. + if plx_ui::containers::modal::page_veiled() { return; } let mut catalog: Option<(EntryId, [u8; 12])> = None; let mut details: Vec = Vec::new(); let mut homes: Vec = Vec::new(); @@ -496,7 +502,8 @@ impl Bridge { .and_then(|i| i.screen.as_any_mut()) .and_then(|a| a.downcast_mut::()) else { continue }; let Some(hex) = screen.watchlist_hex() else { continue }; - screen.set_watchlist(membership_in(&self.stores.watchlist.view(), &hex)); + let changed = screen.set_watchlist(membership_in(&self.stores.watchlist.view(), &hex)); + if changed { note_feed_landing(d, StoreId::Watchlist); } self.watchlist_open_if_idle(); } // The Home hero's bookmark disc, for the title the hero shows now. @@ -533,11 +540,12 @@ impl Bridge { { *status = tile.into(); } - screen.input(plx_screens::catalog::CatalogViewModel { + let mut changed = screen.input(plx_screens::catalog::CatalogViewModel { load, membership: self.stores.catalog.membership(&self.stores.watchlist).into(), }); - screen.set_art_server(self.stores.watchlist.view().art_server()); + changed |= screen.set_art_server(self.stores.watchlist.view().art_server()); + if changed { note_feed_landing(d, StoreId::Catalog); } } /// The catalog page's re-read (`reread.rs`): the list again, which re-matches the title, and diff --git a/rust-modules/src/app/watchlist_wiring_tests.rs b/rust-modules/src/app/watchlist_wiring_tests.rs index a3e3f169ef..acb358aaf8 100644 --- a/rust-modules/src/app/watchlist_wiring_tests.rs +++ b/rust-modules/src/app/watchlist_wiring_tests.rs @@ -305,15 +305,23 @@ fn the_feed_hands_the_page_nothing_while_a_menu_holds_it() { for veil in [1.0, 0.5, CLOSING_GONE * 1.5] { set_veil(veil); rig.watchlist_pump(); - let _ = plx_machine::idle::take_local_damage(); + let before = d.present.damage_epoch(); + let page_before = d.present.page_damage_epoch(); rig.watchlist_feed(&mut d); assert_eq!(guids(&d), vec![guid(1), guid(2), guid(3)], "veil {veil}: the page is as the menu found it"); assert_eq!(page(&d).count(), Some(Count::All(3)), "veil {veil}: and so is its count"); - assert_eq!(plx_machine::idle::take_local_damage(), 0, "veil {veil}: nothing invalidated the host"); + assert_eq!(d.present.damage_epoch() - before, 0, "veil {veil}: nothing invalidated the host"); + assert_eq!(d.present.page_damage_epoch() - page_before, 0, "veil {veil}: no page damage"); } set_veil(CLOSING_GONE * 0.5); rig.watchlist_pump(); + let before = d.present.damage_epoch(); + let page_before = d.present.page_damage_epoch(); rig.watchlist_feed(&mut d); + assert_eq!(d.present.damage_epoch() - before, 1, "one applied publication, one owned landing"); + assert_eq!(d.present.page_damage_epoch() - page_before, 1); + rig.watchlist_feed(&mut d); + assert_eq!(d.present.damage_epoch() - before, 1, "unchanged feed adds no damage"); assert_eq!(guids(&d), vec![guid(1), guid(3)], "the first feed after the menu let go commits the Remove"); set_veil(0.0); } diff --git a/rust-modules/src/dev/framedump.rs b/rust-modules/src/dev/framedump.rs index ae56189f52..e90ed8b496 100644 --- a/rust-modules/src/dev/framedump.rs +++ b/rust-modules/src/dev/framedump.rs @@ -565,7 +565,7 @@ thread_local! { static IDLE_DT: std::cell::Cell = const { std::cell::Cell::new(0.0) }; } -/// The `dt` the idle gate's rest test ([`plx_machine::idle::frame_begin_judging_rest_with`]) uses this iteration. +/// The `dt` the idle gate's rest test ([`plx_machine::motion::report::frame_begin_judging_rest_with`]) uses this iteration. /// /// A spring is "at rest" when its position is near its target AND `velocity * dt` is under the /// rest threshold (`idle::settled`), so a held repeat at `dt == 0` reads every spring that is diff --git a/rust-modules/src/dev/scenarios.rs b/rust-modules/src/dev/scenarios.rs index 21ef251bab..6f6fe62ac2 100644 --- a/rust-modules/src/dev/scenarios.rs +++ b/rust-modules/src/dev/scenarios.rs @@ -283,10 +283,11 @@ pub(crate) fn arm_glassload(glass: &mut plx_ui::frame::glass::GlassPlan) { } /// `/tmp/plxnative-navblur` — the blurred-route-transition prototype. -pub(crate) fn arm_navblur(glass: &mut plx_ui::frame::glass::GlassPlan) { +pub(crate) fn arm_navblur(glass: &mut plx_ui::frame::glass::GlassPlan) -> bool { if let Some(v) = plx_base::devtrig::read("navblur") { glass.configure_navblur(&v); } + glass.blur_dissolve() } /// `/tmp/plxnative-overdraw` — the CPU-side per-draw-class overdraw ledger. @@ -353,9 +354,9 @@ pub(crate) fn arm_cpuprof() { } /// `/tmp/plxnative-noidle` — turn the whole-frame present gate off. -pub(crate) fn arm_noidle() { +pub(crate) fn arm_noidle(present: &mut plx_machine::present::Present) { if plx_base::devtrig::flag("noidle") { - plx_machine::idle::set_enabled(false); + present.set_enabled(false); #[cfg(feature = "devtriggers")] plx_base::eventlog::log("idle: present gate DISABLED by /tmp/plxnative-noidle"); } @@ -1389,7 +1390,7 @@ fn press_arm(app: &mut App, fr: &mut Frame) { } if app.scenarios.press_release_at != 0 && fr.now.wrapping_sub(app.scenarios.press_release_at) < 0x8000_0000 { app.scenarios.press_release_at = 0; - app.input.press.release(fr.now); + app.inputs.push(crate::app::bridge::script_key(Key::Ok, Tick { ms: fr.now, dt_us: 0 })[1].clone()); } @@ -1416,7 +1417,8 @@ fn acct_arm(app: &mut App, fr: &mut Frame) { let Some(rest) = latched(&mut app.scenarios.acct_rest, crate::dev::scenarios::acct_armed) else { return; }; - if screenshot::at_rest(fr.now, rest) && matches!(app.route(), AppArg::Home) && app.pages.top_page().is_some() { + if screenshot::at_rest(fr.now, rest, app.pages.present.last_change_ms(), + app.pages.present.changed() || plx_machine::motion::report::present_moving()) && matches!(app.route(), AppArg::Home) && app.pages.top_page().is_some() { app.scenarios.acct_tried = true; crate::app::bridge::open_account_menu(&mut app.pages); } else if fr.now.wrapping_sub(app.t0) > 12_000 { @@ -1916,7 +1918,7 @@ fn submenuosc_arm(app: &mut App, fr: &mut Frame) { if period == 0 || !matches!(app.route(), AppArg::Player) || fr.now.wrapping_sub(app.t0) < 7000 { return; } - plx_machine::idle::wake(); + app.pages.present.note(plx_machine::present::PresentEvent::Wake); if fr.now.wrapping_sub(app.scenarios.submenu_osc.last) < period { return; } @@ -1963,7 +1965,7 @@ fn moreosc_arm(app: &mut App, fr: &mut Frame) { if period == 0 || !matches!(app.route(), AppArg::Player) || fr.now.wrapping_sub(app.t0) < 7000 { return; } - plx_machine::idle::wake(); + app.pages.present.note(plx_machine::present::PresentEvent::Wake); if fr.now.wrapping_sub(app.scenarios.more_osc.last) < period { return; } @@ -2505,7 +2507,7 @@ pub(crate) fn search_osc_tick(app: &mut App, now: u32) { /// `/tmp/plxnative-acctosc` — drive the profile menu's own TableView. pub(crate) fn account_osc_tick(app: &mut App, now: u32) { if app.scenarios.dev.account_osc && crate::app::bridge::account_menu_up(&app.pages) { - plx_machine::idle::wake(); + app.pages.present.note(plx_machine::present::PresentEvent::Wake); if now.wrapping_sub(app.scenarios.account_osc_last) > 520 { app.scenarios.account_osc_last = now; // The surface's own focus engine moves the selection now, so the oscillator presses a @@ -3089,7 +3091,7 @@ pub(crate) fn alert_tick(app: &mut App, now: u32, dt: f32) { /// `/tmp/plxnative-settingsosc` — hold Settings open under a continuous focus sweep. pub(crate) fn settings_osc_tick(app: &mut App, now: u32, dt: f32) { if app.scenarios.dev.settings_osc && crate::app::bridge::settings_up(&app.pages) { - plx_machine::idle::wake(); + app.pages.present.note(plx_machine::present::PresentEvent::Wake); if now.wrapping_sub(app.scenarios.settings_osc_last) > 520 { app.scenarios.settings_osc_last = now; let key = if app.scenarios.settings_osc_down { Key::Down } else { Key::Up }; @@ -3103,7 +3105,7 @@ pub(crate) fn settings_osc_tick(app: &mut App, now: u32, dt: f32) { /// `/tmp/plxnative-consentosc` — sweep the first-run consent question's focus. pub(crate) fn consent_osc_tick(app: &mut App, now: u32, dt: f32) { if app.scenarios.dev.consent_osc && crate::app::bridge::consent_up(&app.pages) { - plx_machine::idle::invalidate(); + app.note_presentation_damage(plx_machine::present::Provenance::Input); if now.wrapping_sub(app.scenarios.consent_osc_last) > 520 { app.scenarios.consent_osc_last = now; let key = if app.scenarios.consent_osc_down { Key::Down } else { Key::Up }; @@ -3117,7 +3119,7 @@ pub(crate) fn consent_osc_tick(app: &mut App, now: u32, dt: f32) { /// `/tmp/plxnative-onboardosc` — sweep the first-run sources editor's focus. pub(crate) fn onboard_osc_tick(app: &mut App, now: u32, dt: f32) { if app.scenarios.dev.onboard_osc && matches!(app.route(), AppArg::Onboard) { - plx_machine::idle::invalidate(); + app.note_presentation_damage(plx_machine::present::Provenance::Input); if now.wrapping_sub(app.scenarios.onboard_osc_last) > 520 { app.scenarios.onboard_osc_last = now; let key = if app.scenarios.onboard_osc_right { Key::Right } else { Key::Left }; diff --git a/rust-modules/src/dev/scenarios/bench.rs b/rust-modules/src/dev/scenarios/bench.rs index 7572ea905e..332515e024 100644 --- a/rust-modules/src/dev/scenarios/bench.rs +++ b/rust-modules/src/dev/scenarios/bench.rs @@ -751,7 +751,7 @@ mod tests { #[test] fn a_hold_outlasts_the_hold_threshold_and_a_tap_does_not() { - let long = plx_ui::press::LONG_MS; + let long = plx_ui::dispatch::press::LONG_MS; assert!(PressBench::new(1, 1, PressKind::Hold).period_ms > long); assert!(PressBench::new(1, 100_000, PressKind::Tap).period_ms < long); assert_eq!(PressBench::new(1, DEFAULT_HOLD_PERIOD_MS, PressKind::Hold).period_ms, DEFAULT_HOLD_PERIOD_MS); diff --git a/rust-modules/src/dev/scenarios/screenshot.rs b/rust-modules/src/dev/scenarios/screenshot.rs index eb9a0c89cd..0e86e9503b 100644 --- a/rust-modules/src/dev/scenarios/screenshot.rs +++ b/rust-modules/src/dev/scenarios/screenshot.rs @@ -165,14 +165,14 @@ pub(super) fn parse_cell(v: &str) -> Option<(usize, usize)> { /// accept a rest period, and hold the surface back until the page has stopped changing. The signal /// is `plx_machine::idle`'s change clock, which only the simulator keeps; on the television there is none, /// the wait is skipped, and the arm behaves exactly as it did before it took a value. -pub(crate) fn at_rest(now: u32, rest: Option) -> bool { +pub(crate) fn at_rest(now: u32, rest: Option, last_change_ms: u32, current_changed: bool) -> bool { #[cfg(feature = "hostsim")] { - rest.is_none_or(|ms| now.wrapping_sub(plx_machine::idle::last_change_ms()) >= ms) + rest.is_none_or(|ms| !current_changed && now.wrapping_sub(last_change_ms) >= ms) } #[cfg(not(feature = "hostsim"))] { - let _ = (now, rest); + let _ = (now, rest, last_change_ms, current_changed); true } } @@ -379,7 +379,8 @@ pub(crate) fn libmenu_arm(app: &mut App, fr: &Frame) { return; } if on_library_page(app) - && at_rest(fr.now, rest) + && at_rest(fr.now, rest, app.pages.present.last_change_ms(), + app.pages.present.changed() || plx_machine::motion::report::present_moving()) && due(app.scenarios.shots.libmenu_sent, fr.now) { app.scenarios.shots.libmenu_sent = Some(fr.now); diff --git a/rust-modules/src/dev/uri_exported.rs b/rust-modules/src/dev/uri_exported.rs index 218a435ec2..a70fc12c44 100644 --- a/rust-modules/src/dev/uri_exported.rs +++ b/rust-modules/src/dev/uri_exported.rs @@ -1,5 +1,5 @@ //! The exported-window override (`plxnative-uriexported`): the PRODUCTION URI backend, bound to the -//! exported window (`Binding::Exported`) on a webOS 5+ set whose firmware release the evidence +//! exported window (`Binding::Exported`) on a webOS 5+ set whose firmware major the evidence //! table has not admitted. Debug builds only: this file is compiled with `devtriggers` and //! `play-uri` (see `dev.rs`), so a release binary carries none of it, and the read below is //! `false` at compile time there. diff --git a/rust-modules/src/focusprobe.rs b/rust-modules/src/focusprobe.rs index a6b1b89b59..b4d75b478b 100644 --- a/rust-modules/src/focusprobe.rs +++ b/rust-modules/src/focusprobe.rs @@ -192,11 +192,11 @@ plx_base::devtrig::latched_flag!( /// /// Call once per frame, AFTER the frame's input has been handled and the screen drawn, so what is /// recorded is the state a key press has already moved rather than the state it is about to. -pub(crate) fn sample(ps: &plx_media::route::PlaybackSession, route: &str, screen: Screen, hud: Hud, ctrl: ControlSlot, content: &str, meta: plx_data::metadata::MetadataView<'_>) { +pub(crate) fn sample(ps: &plx_media::route::PlaybackSession, route: &str, screen: Screen, hud: Hud, ctrl: ControlSlot, content: &str, meta: plx_data::metadata::MetadataView<'_>, press_active: bool) { if !armed() { return; } - let line = fingerprint_content(ps, route, screen, hud, ctrl, content, meta); + let line = fingerprint_content(ps, route, screen, hud, ctrl, content, meta, press_active); static LAST: Mutex> = Mutex::new(None); let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); if last.as_deref() == Some(line.as_str()) { @@ -214,18 +214,18 @@ pub(crate) fn sample(ps: &plx_media::route::PlaybackSession, route: &str, screen /// one of those screens fingerprints as its route word and nothing else. `app::recorder`'s /// `state_hash` folds `Dispatcher::state_hash` in beside this line for exactly that reason; a /// replay graded on this alone would call a press that opened the wrong family page `SAME`. -pub(crate) fn line(ps: &plx_media::route::PlaybackSession, route: &str, screen: Screen, hud: Hud, ctrl: ControlSlot, content: &str, meta: plx_data::metadata::MetadataView<'_>) -> String { - fingerprint_content(ps, route, screen, hud, ctrl, content, meta) +pub(crate) fn line(ps: &plx_media::route::PlaybackSession, route: &str, screen: Screen, hud: Hud, ctrl: ControlSlot, content: &str, meta: plx_data::metadata::MetadataView<'_>, press_active: bool) -> String { + fingerprint_content(ps, route, screen, hud, ctrl, content, meta, press_active) } /// Build the line. Split out from [`sample`] so its determinism and its grammar are host-testable /// without a log file or a change-detection state. #[cfg(test)] fn fingerprint(ps: &plx_media::route::PlaybackSession, route: &str, screen: Screen, hud: Hud, ctrl: ControlSlot, meta: plx_data::metadata::MetadataView<'_>) -> String { - fingerprint_content(ps, route, screen, hud, ctrl, "", meta) + fingerprint_content(ps, route, screen, hud, ctrl, "", meta, false) } -fn fingerprint_content(ps: &plx_media::route::PlaybackSession, route: &str, screen: Screen, hud: Hud, ctrl: ControlSlot, content: &str, meta: plx_data::metadata::MetadataView<'_>) -> String { +fn fingerprint_content(ps: &plx_media::route::PlaybackSession, route: &str, screen: Screen, hud: Hud, ctrl: ControlSlot, content: &str, meta: plx_data::metadata::MetadataView<'_>, press_active: bool) -> String { let mut s = String::with_capacity(192); s.push_str("focus route="); s.push_str(route); @@ -233,7 +233,7 @@ fn fingerprint_content(ps: &plx_media::route::PlaybackSession, route: &str, scre // The tvOS click, which is route-agnostic: an OK over a card arms a press and the activation // commits from the per-frame loop on the spring-back, so "a press is in flight" is a state the // ladder put the app into and a state the NEXT key cancels. - let _ = write!(s, " press={}", b(plx_ui::press::is_active())); + let _ = write!(s, " press={}", b(press_active)); s } diff --git a/rust-modules/src/lab/mod.rs b/rust-modules/src/lab/mod.rs index 5b4c4662bc..2452002573 100644 --- a/rust-modules/src/lab/mod.rs +++ b/rust-modules/src/lab/mod.rs @@ -150,17 +150,40 @@ pub(crate) fn note_route(_r: &'static str) { upload::note_route(_r); } -/// Expire the toast. Called once per frame from the update block. +/// App-owned retained visible toast. A zero-sized, allocation-free facade without the feature. +#[derive(Default)] +pub(crate) struct ToastObserver { + #[cfg(feature = "lab-diagnostics")] + view: upload::ToastView, +} + +/// Capture coherent IO state plus expiry; the App emits owned Surface/Lifecycle damage if true. #[inline] -pub(crate) fn update(_now: u32) { +pub(crate) fn update(_observer: &mut ToastObserver, _now: u32) -> bool { #[cfg(feature = "lab-diagnostics")] - toast::update(_now); + { + let next = upload::capture(); + if next != _observer.view { + _observer.view = next; + return true; + } + } + false } /// Draw the toast, over everything, on every route. `stats` is the diagnostics read-out's frame /// when it is on screen: the toast sits immediately below it, and neither may cover the other. #[inline] -pub(crate) fn draw(_stats: Option) { +pub(crate) fn draw(_observer: &ToastObserver, _stats: Option) { #[cfg(feature = "lab-diagnostics")] - toast::draw(_stats); + toast::draw(&_observer.view, _stats); +} + +#[cfg(all(test, not(feature = "lab-diagnostics")))] +mod tests { + #[test] + fn disabled_toast_observer_is_zero_sized_and_inert() { + assert_eq!(std::mem::size_of::(), 0); + assert!(!super::update(&mut super::ToastObserver::default(), 0)); + } } diff --git a/rust-modules/src/lab/toast.rs b/rust-modules/src/lab/toast.rs index fc87c3bdf0..362ae59f85 100644 --- a/rust-modules/src/lab/toast.rs +++ b/rust-modules/src/lab/toast.rs @@ -43,16 +43,12 @@ fn frame_for(stats: Option) -> Rect { Rect::new(SCR_W - MARGIN_X - W, y, W, H) } -/// Retire an expired toast. One call per frame from the update block; a no-op when nothing is up. -pub(crate) fn update(now: u32) { - upload::update(now); -} - -pub(crate) fn draw(stats: Option) { - if !upload::showing() { +/// Draw only the App's captured view, never re-read a worker during rendering. +pub(crate) fn draw(view: &upload::ToastView, stats: Option) { + if view.phase == upload::PHASE_IDLE { return; } - let (title, ink) = match upload::phase() { + let (title, ink) = match view.phase { upload::PHASE_SENDING => (plx_platform::i18n::msg::widgets_diagnostics_uploading(), theme::TEXT_PRIMARY), upload::PHASE_OK => (plx_platform::i18n::msg::widgets_diagnostics_uploaded(), theme::TEXT_PRIMARY), _ => (plx_platform::i18n::msg::widgets_diagnostics_failed(), theme::DANGER), @@ -71,9 +67,9 @@ pub(crate) fn draw(stats: Option) { } // The second line is the only variable text: a byte count, or why it failed. Never a URL, a // host or a session secret — `lab::upload::send` composes it and this draws whatever it says. - let detail = upload::detail(); + let detail = &view.detail; if !detail.is_empty() { - if let Ok(cs) = CString::new(detail) { + if let Ok(cs) = CString::new(detail.as_str()) { Label::new(cs.as_ptr(), theme::size::CAPTION, theme::TEXT_SECONDARY) .draw(p, Rect::new(r.x + PAD, r.y + 56.0, r.w - 2.0 * PAD, 28.0)); } diff --git a/rust-modules/src/lab/upload.rs b/rust-modules/src/lab/upload.rs index e9da86377b..ff21c12dbb 100644 --- a/rust-modules/src/lab/upload.rs +++ b/rust-modules/src/lab/upload.rs @@ -21,7 +21,7 @@ //! would answer that by sending four near-identical documents over a link that was already the //! reason nothing appeared to happen. use plx_platform::labcfg::config; -use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU8, Ordering::Relaxed}; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering::Relaxed}; use std::sync::Mutex; /// What the toast is saying. A `u8` because it is written from a worker and read from the render @@ -31,12 +31,21 @@ pub(crate) const PHASE_SENDING: u8 = 1; pub(crate) const PHASE_OK: u8 = 2; pub(crate) const PHASE_FAIL: u8 = 3; -static PHASE: AtomicU8 = AtomicU8::new(PHASE_IDLE); +/// Actual IO result, atomically captured with its text and expiry under one lock. +#[derive(Default, Debug, PartialEq, Eq)] +pub(crate) struct ToastView { + pub(crate) phase: u8, + pub(crate) detail: String, +} +struct ToastState { + view: ToastView, + until_ms: u32, +} +static TOAST: Mutex = Mutex::new(ToastState { + view: ToastView { phase: PHASE_IDLE, detail: String::new() }, until_ms: 0, +}); static INFLIGHT: AtomicBool = AtomicBool::new(false); static SEQ: AtomicU32 = AtomicU32::new(0); -/// ring-clock ms at which the toast stops being drawn; 0 = not showing -static UNTIL_MS: AtomicU32 = AtomicU32::new(0); -static DETAIL: Mutex = Mutex::new(String::new()); /// The route name the app last reported, for the envelope. `&'static str` from `app.rs`'s own /// route table, so this stores a name that already exists rather than allocating one per frame. static ROUTE: Mutex<&'static str> = Mutex::new("home"); @@ -52,46 +61,25 @@ pub(crate) fn note_route(r: &'static str) { *g = r; } -pub(crate) fn phase() -> u8 { - PHASE.load(Relaxed) -} - -/// The toast's second line: a byte count on success, a reason on failure. -pub(crate) fn detail() -> String { - DETAIL.lock().unwrap_or_else(|e| e.into_inner()).clone() -} - -/// Is the toast still within its window? Drives both the draw and the expiry. -pub(crate) fn showing() -> bool { - match phase() { - PHASE_IDLE => false, - PHASE_SENDING => true, - _ => plx_base::eventlog::ring::t_ms() < UNTIL_MS.load(Relaxed), +/// Capture one coherent visible view and retire expired results on the ring clock. +/// No presentation authority crosses this IO boundary. +pub(crate) fn capture() -> ToastView { + let mut state = TOAST.lock().unwrap_or_else(|e| e.into_inner()); + if matches!(state.view.phase, PHASE_OK | PHASE_FAIL) + && plx_base::eventlog::ring::t_ms() >= state.until_ms { + state.view = ToastView::default(); + state.until_ms = 0; } + ToastView { phase: state.view.phase, detail: state.view.detail.clone() } } -/// Retire a finished toast. Called once per frame; the invalidate is what gets the frame that -/// paints its absence — nothing else on screen moved. -pub(crate) fn update(_now: u32) { - if matches!(phase(), PHASE_OK | PHASE_FAIL) && !showing() { - set_phase(PHASE_IDLE, String::new()); - } -} - -fn set_phase(p: u8, detail: String) { - PHASE.store(p, Relaxed); - *DETAIL.lock().unwrap_or_else(|e| e.into_inner()) = detail; - UNTIL_MS.store( - match p { - PHASE_OK | PHASE_FAIL => plx_base::eventlog::ring::t_ms().saturating_add(TOAST_MS), - _ => 0, - }, - Relaxed, - ); - // A toast is a clock-driven overlay, not a spring — `plx_machine::idle::note_spring` cannot see it, and - // an uninvalidated one appears only on the next keypress (the failure mode `Xfade` and - // `Spinner` both shipped with; see `docs/agent-reference.md`'s note on the present gate). - plx_machine::idle::invalidate(); +fn set_phase(phase: u8, detail: String) { + let mut state = TOAST.lock().unwrap_or_else(|e| e.into_inner()); + state.until_ms = match phase { + PHASE_OK | PHASE_FAIL => plx_base::eventlog::ring::t_ms().saturating_add(TOAST_MS), + _ => 0, + }; + state.view = ToastView { phase, detail }; } /// **Main thread.** Sample everything, then hand it to a worker. @@ -195,13 +183,24 @@ mod tests { #[test] fn a_finished_toast_expires_back_to_idle() { let _g = plx_base::testlock::serial(); + let mut observer = crate::lab::ToastObserver::default(); set_phase(PHASE_OK, "12 KB sent".into()); - assert!(showing()); - UNTIL_MS.store(0, Relaxed); // as if TOAST_MS had elapsed - assert!(!showing()); - update(0); - assert_eq!(phase(), PHASE_IDLE); - assert_eq!(detail(), ""); + assert!(crate::lab::update(&mut observer, 0), "success appearance is observed"); + assert!(!crate::lab::update(&mut observer, 0), "held answers do not repaint"); + let view = capture(); + assert_eq!(view.phase, PHASE_OK); + assert_eq!(view.detail, "12 KB sent"); + TOAST.lock().unwrap().until_ms = 0; // as if TOAST_MS had elapsed + assert!(crate::lab::update(&mut observer, 0), "expiry paints the absence"); + assert!(!crate::lab::update(&mut observer, 0)); + let view = capture(); + assert_eq!(view.phase, PHASE_IDLE); + assert_eq!(view.detail, ""); + set_phase(PHASE_FAIL, "receiver said 403".into()); + assert!(crate::lab::update(&mut observer, 0), "failure appearance is observed"); + assert_eq!(observer.view.phase, PHASE_FAIL); + assert_eq!(observer.view.detail, "receiver said 403"); + set_phase(PHASE_IDLE, String::new()); } /// While sending, the toast is up regardless of the clock — an upload over a slow link must @@ -210,10 +209,8 @@ mod tests { fn the_sending_toast_does_not_expire() { let _g = plx_base::testlock::serial(); set_phase(PHASE_SENDING, String::new()); - UNTIL_MS.store(0, Relaxed); - assert!(showing()); - update(0); - assert_eq!(phase(), PHASE_SENDING); + TOAST.lock().unwrap().until_ms = 0; + assert_eq!(capture().phase, PHASE_SENDING); set_phase(PHASE_IDLE, String::new()); } } diff --git a/rust-modules/src/shot.rs b/rust-modules/src/shot.rs index 6d355ec313..66c6e8fa1a 100644 --- a/rust-modules/src/shot.rs +++ b/rust-modules/src/shot.rs @@ -115,17 +115,22 @@ fn settled_due(settle: u32, after: u32, age: u32, quiet: u32, busy: bool) -> boo !busy && age >= after && quiet >= settle } +fn confirm_settled(requested: bool, ready: bool, fired: &AtomicBool) -> bool { + if requested && !ready { fired.store(false, Ordering::Relaxed); } + requested && ready +} + /// Once per loop iteration, BEFORE the present decision (`app::run`): arm the settled capture when /// the screen has been at rest long enough. A settled screen does not present, so this invalidates /// to make the next frame present — and that frame, drawn from unchanged state, is the capture. -pub(crate) fn tick(now: u32, busy: bool) { +pub(crate) fn tick(now: u32, busy: bool, last_change_ms: u32) -> bool { let cfg = cfg(); - let Some(settle) = cfg.settle else { return }; + let Some(settle) = cfg.settle else { return false }; if SETTLE_FIRED.load(Ordering::Relaxed) { - return; + return false; } let first = *FIRST_TICK.get_or_init(|| now); - let quiet = now.wrapping_sub(plx_machine::idle::last_change_ms()); + let quiet = now.wrapping_sub(last_change_ms); if settled_due(settle, cfg.after, now.wrapping_sub(first), quiet, busy) { SETTLE_FIRED.store(true, Ordering::Relaxed); SETTLED.store(true, Ordering::Relaxed); @@ -133,8 +138,9 @@ pub(crate) fn tick(now: u32, busy: bool) { "shot: settled ({quiet} ms at rest, {} ms after the first frame)", now.wrapping_sub(first) )); - plx_machine::idle::invalidate(); + return true; } + false } /// Ask for a capture of the next frame. The remote-FIFO entry point (`app.rs`'s token dispatch). @@ -149,7 +155,6 @@ pub(crate) fn request() { // moving. So a `shot` token sent to a UI that has come to rest — which is exactly when an // agent wants one, after driving and waiting — would set this flag and then wait forever for a // frame that never comes. Observed as a token that logged nothing at all. - plx_machine::idle::invalidate(); } /// `dir/stem-N.ext`, N counting up per on-demand shot within this process. @@ -251,12 +256,16 @@ pub(crate) fn read_flipped(vx: c_int, vy: c_int, vw: c_int, vh: c_int, ch: usize /// loading the CA bundle — SIGSEGV inside libcrypto, captured by `tools/sim-smoke.py --core-dir`. /// Ending the run here lets the app's own shutdown run, and the simulator's `main` then leaves /// without `atexit` teardown (`src/bin/sim.rs`). + #[must_use = "a headless one-shot capture asks the caller to end the run"] -pub(crate) fn maybe_capture(vx: c_int, vy: c_int, vw: c_int, vh: c_int) -> bool { +pub(crate) fn maybe_capture(now: u32, busy: bool, last_change_ms: u32, vx: c_int, vy: c_int, vw: c_int, vh: c_int) -> bool { let n = FRAMES.fetch_add(1, Ordering::Relaxed); let on_demand = ON_DEMAND.swap(false, Ordering::Relaxed); - let settled = SETTLED.swap(false, Ordering::Relaxed); + let requested = SETTLED.swap(false, Ordering::Relaxed); let cfg = cfg(); + let ready = cfg.settle.is_some_and(|settle| settled_due(settle, cfg.after, + now.wrapping_sub(*FIRST_TICK.get_or_init(|| now)), now.wrapping_sub(last_change_ms), busy)); + let settled = confirm_settled(requested, ready, &SETTLE_FIRED); if !on_demand && !settled && cfg.frame != Some(n) { return false; } @@ -306,6 +315,47 @@ mod tests { assert!(!settled_due(800, 0, 9_000, 5_000, true), "not while work is queued"); } + #[test] + fn fresh_input_motion_and_content_restart_the_settle_window() { + use plx_machine::present::{Present, PresentEvent, Provenance}; + use plx_machine::motion::report::FrameReport; + for (event, motion) in [ + (Some(PresentEvent::Damage(Provenance::Input)), false), + (None, true), + (Some(PresentEvent::Damage(Provenance::Landing(plx_machine::machine::MachineId::Cache))), false), + ] { + let mut present = Present::new(); + present.take(0); + present.acknowledge(0); + assert!(settled_due(500, 0, 1500, 1500 - present.last_change_ms(), false)); + if let Some(event) = event { present.note(event); } + present.collect(1500, FrameReport { moving: motion, page_moving: motion, ..Default::default() }); + assert!(!settled_due(500, 0, 1500, 1500 - present.last_change_ms(), false), + "current-frame activity must restart quiet time before the one-shot latch is set"); + } + } + + #[test] + fn a_draw_change_rearms_the_settled_capture_instead_of_exiting() { + use std::sync::atomic::{AtomicBool, Ordering}; + let fired = AtomicBool::new(true); + assert!(!super::confirm_settled(true, false, &fired)); + assert!(!fired.load(Ordering::Relaxed), "the next quiet interval must be allowed to schedule again"); + fired.store(true, Ordering::Relaxed); + assert!(super::confirm_settled(true, true, &fired)); + assert!(fired.load(Ordering::Relaxed)); + } + + #[test] + fn the_loop_collects_current_frame_changes_before_testing_the_settled_shot() { + let source = include_str!("app/run.rs").replace("\r\n", "\n"); + let window = source.split("fn prepare_window(").nth(1).expect("prepare window exists"); + let collect = window.find("plx_machine::motion::report::collect_into(").expect("current frame capture"); + let shot = window.find("crate::shot::tick(").expect("settled screenshot decision"); + let admission = window.find("app.pages.present.take(").expect("present admission"); + assert!(collect < shot && shot < admission, "capture must use fresh change state and schedule before admission"); + } + #[test] fn only_the_automatic_headless_capture_ends_the_run() { assert!(ends_run(true, false)); diff --git a/rust-modules/telemetry/src/telemetry/classes.rs b/rust-modules/telemetry/src/telemetry/classes.rs index 3297dea687..c97d896665 100644 --- a/rust-modules/telemetry/src/telemetry/classes.rs +++ b/rust-modules/telemetry/src/telemetry/classes.rs @@ -957,6 +957,34 @@ impl TerminalStageClass { } } +/// **Why a detail-page trailer preview was refused before it opened** (Sentry PLX-NATIVE-23, on +/// 0.9.0 PLX-NATIVE-1G): the closed domain of `playback.preview_refusal`. A preview takes only a +/// plain direct play, and the resolve checks it in this fixed order, so the FIRST condition that +/// fails is the one named: +/// +/// 1. `no_part`: the item has no media part to play at all; +/// 2. `not_direct`: a direct play was not on offer before Auto quality chose a delivery, so the +/// route was going to be a transcode or a remux. That is the server's decision, but also a link +/// or quality policy that denies direct play and a track the TV cannot play as it is; this +/// domain does not tell those apart; +/// 3. `adaptive`: a direct play WAS on offer, and Auto did not keep the Original. That is Auto's +/// bandwidth probe finding the link too slow, the probe coming back inconclusive, or the link +/// not being classified yet; this domain does not tell those apart. +/// +/// A direct play that was on offer and that Auto kept, then lost to a later demotion (an +/// enhancement's remux), is also named `not_direct`: the fall-through. A route that is still the +/// direct play a preview takes is never refused, so this domain has no "none". It rides a report +/// only when the failure kind is `preview_not_direct`; every value is a code of this enum and +/// nothing the server said. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PreviewRefusal { NotDirect, NoPart, Adaptive } +impl PreviewRefusal { + pub const ALL: [Self; 3] = [Self::NotDirect, Self::NoPart, Self::Adaptive]; + pub const fn code(self) -> &'static str { + match self { Self::NotDirect => "not_direct", Self::NoPart => "no_part", Self::Adaptive => "adaptive" } + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct PlaybackErrorContext { pub backend: ErrorBackendClass, @@ -999,6 +1027,10 @@ pub struct PlaybackErrorContext { pub pipeline_error: i32, /// Only for a refusal the server made at `/decision` — see [`RefusalContext`]. pub refusal: Option, + /// Which condition refused a trailer preview — see [`PreviewRefusal`]. `Some` only for a + /// session whose plan carried the preview verdict; the wire sends it only for the + /// `preview_not_direct` kind. + pub preview_refusal: Option, } /// The video codec, as a CLOSED domain. @@ -1161,9 +1193,9 @@ pub enum FailureClass { } impl FailureClass { - /// Every class, so a test can hold the declared `playback.failed` domain to the enum it is - /// built from. - #[cfg(any(test, feature = "test-support"))] + /// Every class, in declaration order. The consent legend's failure-kind row is built from it + /// (every class reaches the handled report), and a test holds the declared `playback.failed` + /// domain to the enum it is built from. pub const ALL: [Self; 15] = [ Self::DecisionRefused, Self::PlaybackPolicy, diff --git a/rust-modules/telemetry/src/telemetry/crashreport.rs b/rust-modules/telemetry/src/telemetry/crashreport.rs index d726a3972c..27babab4ca 100644 --- a/rust-modules/telemetry/src/telemetry/crashreport.rs +++ b/rust-modules/telemetry/src/telemetry/crashreport.rs @@ -56,7 +56,7 @@ //! may not truncate it. Instead it records how many bytes it has already reported and skips them, //! which means a human and this module can both read the file without either disturbing the other. -use plx_base::task::watchdog::FreezeBucket; +use plx_base::task::watchdog::{FreezeBucket, LoopPhase}; /// The one place a signal number becomes a name. See the module doc: this exists so the name on the /// wire comes from a table this crate owns rather than from bytes in a file. @@ -471,7 +471,8 @@ pub struct PanicReport { /// and probed the thread (`src/crashtrace.c`, `freeze_handler`). **Numbers only, like [`Fault`]**: /// the program counter, the link register, the walked return addresses, the registers, the second /// the probe landed, and a duration BUCKET from [`FreezeBucket`]'s fixed table (never the stall's -/// milliseconds). The process did not die, so there is no signal and no fault address. +/// milliseconds). The one other thing it holds is [`Freeze::leg`], a word from [`LoopPhase`]'s +/// fixed table. The process did not die, so there is no signal and no fault address. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Freeze { /// The n-th probe of the process that wrote it; what a `freeze-end:` line names. @@ -487,6 +488,11 @@ pub struct Freeze { pub crash_time: Option, /// [`FreezeBucket::Unrecovered`] until a `freeze-end:` line of the same process says otherwise. pub bucket: FreezeBucket, + /// The leg of the app's own frame loop the main thread was in when the probe was sent: a fixed + /// word from [`LoopPhase::word`]'s table, from the `freeze-at:` line of the same process and + /// probe number. `None` for a record written before that line existed, or one whose line did + /// not parse. + pub leg: Option, } /// A foreign `exit()`: another part of the television's software (a firmware library on a thread of @@ -646,15 +652,23 @@ fn parse_seeded(log: &str, mut image: Option) -> Vec { // belong to nothing, and without this they would attach to the report above it (`out.last_mut()`), // so a malformed exit could put its thread on a fault that has none. Cleared by the next header. let mut detached = false; + // A `freeze-at:` line that no freeze of this process owns YET. The observer thread writes it + // right after it sends the probe, while the stuck thread's handler writes the `*** FREEZE` + // record, so the two lines come in either order (or interleaved); this holds the earlier one + // until its partner arrives. One slot is enough: a probe is only sent after the one before it + // recovered, so there is never more than one waiting. Cleared at the next process marker. + let mut pending_leg: Option<(u32, LoopPhase)> = None; for l in log.lines() { if l.starts_with("img: ") || l.starts_with("*** ") { detached = false; - } else if detached && !l.starts_with("freeze-end: ") { - // `freeze-end:` names a probe number of its own and is not a line of any record. + } else if detached && !l.starts_with("freeze-end: ") && !l.starts_with("freeze-at: ") { + // `freeze-end:` and `freeze-at:` name a probe number of their own and are not lines of + // any record. continue; } if l.starts_with("img: ") { awaiting_regs = None; + pending_leg = None; process_starts.push(out.len()); // An explicit but unreadable marker is a process boundary too: clear rather than // attributing this process's later crash to the executable that ran before it. @@ -662,7 +676,10 @@ fn parse_seeded(log: &str, mut image: Option) -> Vec { process_start = out.len(); } else if let Some(rest) = l.strip_prefix("*** FREEZE ") { awaiting_regs = None; - if let Some(f) = parse_freeze(rest, l, image.clone()) { + if let Some(mut f) = parse_freeze(rest, l, image.clone()) { + if let Some((_, leg)) = pending_leg.take_if(|(seq, _)| *seq == f.seq) { + f.leg = Some(leg); + } out.push(Report::Freeze(f)); awaiting_regs = Some(out.len() - 1); } @@ -687,6 +704,21 @@ fn parse_seeded(log: &str, mut image: Option) -> Vec { f.bucket = bucket; } } + } else if let Some(rest) = l.strip_prefix("freeze-at: ") { + // Touches no other parse state (`awaiting_regs` included): it may land between a + // freeze header and the `reg:` line that belongs to it. + if let Some((seq, leg)) = parse_freeze_at(rest) { + let open = out[process_start..].iter_mut().rev().find_map(|r| match r { + Report::Freeze(f) if f.seq == seq => Some(f), + _ => None, + }); + match open { + Some(f) => { + f.leg.get_or_insert(leg); + } + None => pending_leg = Some((seq, leg)), + } + } } else if let Some(rest) = l.strip_prefix("*** SIGNAL ") { awaiting_regs = None; let Some(f) = parse_fault(rest, l, image.clone()) else { @@ -903,6 +935,7 @@ fn parse_freeze(rest: &str, whole: &str, image: Option) -> Option modules: Vec::new(), crash_time: None, bucket: FreezeBucket::Unrecovered, + leg: None, }) } @@ -961,6 +994,20 @@ fn parse_freeze_end(rest: &str) -> Option<(u32, FreezeBucket)> { Some((seq.parse().ok()?, FreezeBucket::from_word(bucket)?)) } +/// `seq= leg=` of a `freeze-at:` line: the probe number (decimal digits only) and a word +/// that must be one of [`LoopPhase::word`]'s fixed legs, so what a probe was in can never carry +/// anything but a phase of the app's own frame loop onto the wire. Exactly two fields, in that +/// order: a line with anything else on it is no leg. +fn parse_freeze_at(rest: &str) -> Option<(u32, LoopPhase)> { + let mut it = rest.split_whitespace(); + let seq = it.next()?.strip_prefix("seq=")?; + let leg = it.next()?.strip_prefix("leg=")?; + if it.next().is_some() || seq.is_empty() || seq.len() > 9 || !seq.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + Some((seq.parse().ok()?, LoopPhase::from_word(leg)?)) +} + fn parse_image(line: &str) -> Option { if !line.starts_with("img: ") { return None; @@ -1138,6 +1185,49 @@ fn debug_images( images } +/// The `release` a recovered record may carry, and the honest label when it may not. +/// +/// **A record is filed under the release that ran it, not the one that found it.** Recovery runs +/// on the NEXT launch, so after an upgrade the binary building the body is a newer build than the +/// one that crashed (PLX-NATIVE-26: a 0.9.0 SIGSEGV filed as `plxnative@0.10.0`). That poisons +/// per-release crash counts and Sentry's regression detection right after every release, exactly +/// when they are watched. The record names the executable it ran as, its `img:` line, and +/// `running_build_id` is the build id of the binary recovering it: +/// +/// - the two are equal, the record has no image line (nothing says it is another build), or the +/// running id could not be read (empty): `release` is the running release, as it always was; +/// - they differ: **`release` is omitted** and two tags are added, `crash.uploaded_by` (the running +/// app version) and `crash.build_id` (the crashed build's id, from the record's image line). The +/// record does not carry the crashed build's version (`src/main.c` calls +/// `plx_crash_write_image_marker` before `enter_application`, so before the release is set), and +/// a build id cannot be mapped back to one here, so no `release` is the only claim that is not +/// false. +/// +/// **Why the build id is a tag when `dist` already holds it.** Sentry ignores `dist` on an event +/// that has no `release` (a distribution is a build OF a release), so without the tag the event +/// would name no build at all, and the panic body has no `debug_meta` to name one either: for a +/// panic `dist` was the only carrier. `dist` stays as it was. It names the build; it is not what +/// ties an event to its symbols, which goes through `debug_meta` (`code_id` / `debug_id`) and is +/// untouched here. Both tags are an app version and a binary build id, and the build id was already +/// sent as `dist`, so this adds no new kind of data. +/// +/// `sdk.version` is left alone: it names the binary that BUILT the body, which is true either way. +/// +/// Called last, after the body's `tags` exist, by all four body builders: [`sentry_body`] assigns +/// its whole `tags` object late, which would wipe a tag set earlier. +fn stamp_release(body: &mut serde_json::Value, image: Option<&ImageIdentity>, running_build_id: &str) { + let recorded_by_another_build = image.filter(|i| { + !running_build_id.is_empty() && !i.build_id.eq_ignore_ascii_case(running_build_id) + }); + match recorded_by_another_build { + Some(image) => { + body["tags"]["crash.uploaded_by"] = super::app_version().into(); + body["tags"]["crash.build_id"] = image.build_id.as_str().into(); + } + None => body["release"] = super::release().into(), + } +} + /// The Sentry event body for one fault. /// /// **The title's "address" is not always an address.** `SIGNAL at 0x…` prints `si_addr`, which for @@ -1156,6 +1246,10 @@ fn debug_images( /// left no such record — the tracer is async-signal-safe and writes numbers), attached as /// `user.id` through the one shared [`super::sentry::attach_user`]. Passed in rather than read /// here so the preview can build this exact body with a placeholder. +/// +/// `build_id` is the RUNNING binary's, the fallback for a record with no image line. The record's +/// own image id wins for `dist` and the debug image, and a record from a different build than this +/// one is not filed under this build's `release` ([`stamp_release`]). pub fn sentry_body( f: &Fault, event_id: &str, @@ -1183,7 +1277,6 @@ pub fn sentry_body( "event_id": event_id, "platform": "native", "level": "fatal", - "release": super::release(), "environment": super::sender::ENVIRONMENT, "dist": effective_build_id, "sdk": {"name": "plxnative-fallback", "version": super::app_version()}, @@ -1233,6 +1326,7 @@ pub fn sentry_body( if let Some(fp) = fault_fingerprint(f, &plx_platform::tv::device::info().build, &extra.modules, debug_id) { body["fingerprint"] = serde_json::json!(fp); } + stamp_release(&mut body, f.image.as_ref(), build_id); super::sentry::attach_user(&mut body, errors_id); serde_json::to_vec(&body).unwrap_or_default() } @@ -1250,16 +1344,19 @@ pub fn sentry_body( /// functions, so the same closed `native::{OS,WEBOS,HARDWARE}_FIELDS` vocabulary) and none of the /// fault-only `crash` context. Both are read from the process-wide device snapshot at the time this /// runs, on the next launch, which is the same television the panic was logged on. +/// +/// `build_id` is the RUNNING binary's; a record from another build is not filed under this +/// build's `release` ([`stamp_release`]), the same rule as [`sentry_body`]. pub fn panic_sentry_body( p: &PanicReport, event_id: &str, + build_id: &str, errors_id: Option<&str>, ) -> Vec { let mut body = serde_json::json!({ "event_id": event_id, "platform": "native", "level": "fatal", - "release": super::release(), "environment": super::sender::ENVIRONMENT, "sdk": {"name": "plxnative-fallback", "version": super::app_version()}, "exception": {"values": [{ @@ -1285,6 +1382,7 @@ pub fn panic_sentry_body( // snapshot here takes no lock the panicking thread could have held. super::sentry::attach_os_context(&mut body); super::sentry::attach_hardware_context(&mut body); + stamp_release(&mut body, p.image.as_ref(), build_id); super::sentry::attach_user(&mut body, errors_id); serde_json::to_vec(&body).unwrap_or_default() } @@ -1425,33 +1523,56 @@ fn freeze_stack(f: &Freeze) -> Vec { } /// The second fingerprint component of a freeze: `+0x` of the NEAREST frame inside -/// the app's own image, else of the nearest frame in any recorded mapping, else `unmapped`. +/// the app's own image; else, for a record that carries a loop leg, the basenames of the modules +/// holding `pc` and `lr` (`libfoo.so>libbar.so`, no offsets); else the nearest frame in any +/// recorded mapping as `+0x`; else `unmapped`. /// /// **Why not simply the top frame.** A main thread that is stuck is nearly always parked inside /// libc (`poll`, `futex`, `nanosleep`), so `pc` names the same library offset whatever the app was /// waiting for, and every freeze would land in one issue. The first app frame names the call that /// waited. Never a raw address: an unmapped one reads `unmapped`, since a runtime address is a /// per-boot value that would split one cause into many issues. +/// +/// **With no app frame at all** (the walk found nothing; the report's whole stack is firmware) an +/// offset into a firmware library is the one thing left to name, and it splits one stall into an +/// issue per instruction the thread happened to be parked on. The two modules it sat between do not +/// move, so a record with a leg groups on those. A record WITHOUT a leg predates that rule and keeps +/// the offset, so the issues it already belongs to do not regroup. fn freeze_fingerprint_site(f: &Freeze) -> String { let located: Vec<_> = freeze_stack(f).iter().filter_map(|a| freeze_locate(f, *a)).collect(); + if let Some((file, off, _)) = located.iter().find(|(_, _, app)| *app) { + return format!("{file}+0x{off:x}"); + } + if f.leg.is_some() { + let module = |a: u64| freeze_locate(f, a).map(|(file, _, _)| file); + return match (module(f.pc), module(f.lr)) { + (Some(pc), Some(lr)) => format!("{pc}>{lr}"), + (Some(one), None) | (None, Some(one)) => one, + (None, None) => "unmapped".to_string(), + }; + } located - .iter() - .find(|(_, _, app)| *app) - .or_else(|| located.first()) + .first() .map(|(file, off, _)| format!("{file}+0x{off:x}")) .unwrap_or_else(|| "unmapped".to_string()) } /// The Sentry event body for one main-thread freeze. /// -/// Level `error` (the process survived), tag `freeze` with the duration bucket's word, mechanism -/// `freeze` (`handled` once the loop recovered; an unrecovered one is `handled: false`, since the -/// process died or was killed still stuck). **The fingerprint is explicit**, `["freeze", site]` -/// from [`freeze_fingerprint_site`], and carries neither the bucket nor a signal: the same stall -/// lasting 6 s on one television and 40 s on another is one cause, one issue. +/// Level `error` (the process survived), tag `freeze` with the duration bucket's word, tag +/// `freeze.leg` with the loop leg's fixed word when the record has one, mechanism `freeze` +/// (`handled` once the loop recovered; an unrecovered one is `handled: false`, since the process +/// died or was killed still stuck). **The fingerprint is explicit**, `["freeze", site]` from +/// [`freeze_fingerprint_site`] with the leg's word as a third element when there is one, and +/// carries neither the bucket nor a signal: the same stall lasting 6 s on one television and 40 s +/// on another is one cause, one issue. A record without a leg keeps the two-element form, so the +/// issues it already belongs to do not regroup. /// /// The exception `type` and `value` are built from this crate's own strings and the bucket's fixed /// word, never from the record's text, like [`sentry_body`]'s. +/// +/// `build_id` is the RUNNING binary's; a record from another build is not filed under this +/// build's `release` ([`stamp_release`]), the same rule as [`sentry_body`]. pub fn freeze_sentry_body( f: &Freeze, event_id: &str, @@ -1467,6 +1588,14 @@ pub fn freeze_sentry_body( } else { format!("Main thread frozen for {word}") }; + // The loop leg, when the record has one, is a tag AND the fingerprint's third element: its + // word comes from `LoopPhase`'s fixed table, never from the record's text. + let mut tags = serde_json::json!({"freeze": word}); + let mut fingerprint = vec![serde_json::json!("freeze"), serde_json::json!(freeze_fingerprint_site(f))]; + if let Some(leg) = f.leg { + tags["freeze.leg"] = serde_json::json!(leg.word()); + fingerprint.push(serde_json::json!(leg.word())); + } // Oldest first, which is the order Sentry renders bottom-up: the walk's outermost frame first, // pc (where the thread was parked) last and on top. let frames: Vec<_> = freeze_stack(f) @@ -1485,18 +1614,17 @@ pub fn freeze_sentry_body( "event_id": event_id, "platform": "native", "level": "error", - "release": super::release(), "environment": super::sender::ENVIRONMENT, "dist": effective_build_id, "sdk": {"name": "plxnative-fallback", "version": super::app_version()}, - "tags": {"freeze": word}, + "tags": tags, "exception": {"values": [{ "type": "MainThreadFreeze", "value": value, "mechanism": {"type": "freeze", "handled": f.bucket != FreezeBucket::Unrecovered}, "stacktrace": {"frames": frames}, }]}, - "fingerprint": ["freeze", freeze_fingerprint_site(f)], + "fingerprint": fingerprint, }); if let Some(t) = crash_timestamp(f.crash_time, now_secs()) { body["timestamp"] = serde_json::json!(t); @@ -1511,6 +1639,7 @@ pub fn freeze_sentry_body( } super::sentry::attach_os_context(&mut body); super::sentry::attach_hardware_context(&mut body); + stamp_release(&mut body, f.image.as_ref(), build_id); super::sentry::attach_user(&mut body, errors_id); serde_json::to_vec(&body).unwrap_or_default() } @@ -1539,6 +1668,9 @@ fn exit_site(e: &ExitReport) -> Option<(String, u64, bool)> { /// once more, as it would a return address, and what it symbolicates is the address the fingerprint /// and the `at:` line were derived from. The thread is carried exactly as [`sentry_body`] carries a /// fault's. +/// +/// `build_id` is the RUNNING binary's; a record from another build is not filed under this +/// build's `release` ([`stamp_release`]), the same rule as [`sentry_body`]. pub fn exit_sentry_body( e: &ExitReport, event_id: &str, @@ -1580,7 +1712,6 @@ pub fn exit_sentry_body( "event_id": event_id, "platform": "native", "level": "error", - "release": super::release(), "environment": super::sender::ENVIRONMENT, "dist": effective_build_id, "sdk": {"name": "plxnative-fallback", "version": super::app_version()}, @@ -1614,6 +1745,7 @@ pub fn exit_sentry_body( } super::sentry::attach_os_context(&mut body); super::sentry::attach_hardware_context(&mut body); + stamp_release(&mut body, e.image.as_ref(), build_id); super::sentry::attach_user(&mut body, errors_id); serde_json::to_vec(&body).unwrap_or_default() } @@ -1625,6 +1757,10 @@ const FALLBACK_PROBE_PLACEHOLDER: &str = " Vec<(&'static str, Vec)> { let image = ImageIdentity { build_id: "0".repeat(40), @@ -1742,9 +1878,17 @@ pub fn preview_events() -> Vec<(&'static str, Vec)> { image: Some(image), crash_time: Some(now_secs()), }; + // This sample is the report of a panic that a LATER build recovered (an app update between the + // panic and the next launch), the shape [`stamp_release`] gives a record from another build: + // no `release`, and the two tags instead. It is built that way by handing the serializer a + // running build id that is not the panic's, so the real code path emits the keys; the fault + // sample above is the ordinary shape, with `release`. Together they show every key either + // shape can carry. + let upgraded_build_id = "1".repeat(40); let mut panic_json: serde_json::Value = serde_json::from_slice(&panic_sentry_body( &panic, &"0".repeat(32), + &upgraded_build_id, Some(super::native::PREVIEW_USER_ID), )) .unwrap_or_default(); @@ -1752,6 +1896,16 @@ pub fn preview_events() -> Vec<(&'static str, Vec)> { let source = ""; panic_json["event_id"] = serde_json::json!(""); panic_json["dist"] = serde_json::json!(""); + // Only a tag the serializer really wrote is replaced: indexing would mint one, and a preview + // that shows a key the report does not carry is as wrong as one that hides a key it does. + for (tag, placeholder) in [ + ("crash.uploaded_by", ""), + ("crash.build_id", ""), + ] { + if let Some(value) = panic_json.get_mut("tags").and_then(|tags| tags.get_mut(tag)) { + *value = serde_json::json!(placeholder); + } + } panic_json["timestamp"] = serde_json::json!(""); panic_json["exception"]["values"][0]["value"] = serde_json::json!( "Rust panic at (msg )" @@ -1980,6 +2134,58 @@ fn reconcile(reports: &[Report], natives: &[Option], cu plan } +/// The binary identity a recovered record names, whichever kind of record it is. +fn report_image(r: &Report) -> Option<&ImageIdentity> { + match r { + Report::Fault(f) => f.image.as_ref(), + Report::Panic(p) => p.image.as_ref(), + Report::Freeze(f) => f.image.as_ref(), + Report::Exit(e) => e.image.as_ref(), + } +} + +/// The Sentry body for one recovered record of any kind, as [`recover_pending`] queues it. +/// +/// `running_build_id` is the build id of the binary doing the recovery, NOT the record's: every +/// body compares it with the record's own image to decide whether the report may carry the running +/// release ([`stamp_release`]). It is a separate function from the queueing so a test can drive the +/// exact wiring without a spool. +fn report_body( + r: &Report, + event_id: &str, + running_build_id: &str, + errors_id: Option<&str>, + native_path: NativePath, + read: impl Fn(&ModuleMapping) -> Option>, +) -> Vec { + // The debug id follows the RECORD's image (the symbols of the build that crashed); the bodies + // are handed the running id so they can tell a record from another build. + let did = super::sentry::debug_id(report_image(r).map_or(running_build_id, |x| x.build_id.as_str())); + match r { + Report::Fault(f) => { + let extra = FaultExtra { native_path, modules: module_images(f, read) }; + sentry_body(f, event_id, running_build_id, did.as_deref(), errors_id, &extra) + } + Report::Panic(p) => panic_sentry_body(p, event_id, running_build_id, errors_id), + Report::Freeze(f) => freeze_sentry_body( + f, + event_id, + running_build_id, + did.as_deref(), + errors_id, + &images_of_mappings(&f.modules, read), + ), + Report::Exit(e) => exit_sentry_body( + e, + event_id, + running_build_id, + did.as_deref(), + errors_id, + &images_of_mappings(e.module.as_slice(), read), + ), + } +} + /// The side effects of a recovery pass, behind a seam so their ORDER is testable. trait Recovery { /// Durably queue fresh report `i`. @@ -2144,42 +2350,16 @@ fn recover_pending_at(path: &std::path::Path) -> usize { impl Recovery for Io<'_> { fn queue_report(&mut self, i: usize) -> bool { let r = &self.reports[i]; - let bid = match r { - Report::Fault(f) => f.image.as_ref(), - Report::Panic(p) => p.image.as_ref(), - Report::Freeze(f) => f.image.as_ref(), - Report::Exit(e) => e.image.as_ref(), - } - .map(|x| x.build_id.as_str()) - .unwrap_or(self.current_build_id); - let did = super::sentry::debug_id(bid); + let bid = report_image(r).map_or(self.current_build_id, |x| x.build_id.as_str()); let event_id = event_id_for(bid, self.from + i, r); - let body = match r { - Report::Fault(f) => { - let extra = FaultExtra { - native_path: self.native_path[i].unwrap_or(NativePath::NoEnvelope), - modules: module_images(f, read_module_head), - }; - sentry_body(f, &event_id, bid, did.as_deref(), self.errors_id.as_deref(), &extra) - } - Report::Panic(p) => panic_sentry_body(p, &event_id, self.errors_id.as_deref()), - Report::Freeze(f) => freeze_sentry_body( - f, - &event_id, - bid, - did.as_deref(), - self.errors_id.as_deref(), - &images_of_mappings(&f.modules, read_module_head), - ), - Report::Exit(e) => exit_sentry_body( - e, - &event_id, - bid, - did.as_deref(), - self.errors_id.as_deref(), - &images_of_mappings(e.module.as_slice(), read_module_head), - ), - }; + let body = report_body( + r, + &event_id, + self.current_build_id, + self.errors_id.as_deref(), + self.native_path[i].unwrap_or(NativePath::NoEnvelope), + read_module_head, + ); let ok = super::spool::append(&super::queue::Record { category: super::queue::Category::Errors, dest: super::queue::Dest::Sentry, @@ -2459,14 +2639,14 @@ mod tests { let id = "0123456789abcdef0123456789abcdef"; for body in [ sentry_body(&f, "e", "bid", Some("did"), Some(id), &extra()), - panic_sentry_body(&p, "e", Some(id)), + panic_sentry_body(&p, "e", "bid", Some(id)), ] { let v: serde_json::Value = serde_json::from_slice(&body).unwrap(); assert_eq!(v["user"], serde_json::json!({"id": id})); } for body in [ sentry_body(&f, "e", "bid", Some("did"), None, &extra()), - panic_sentry_body(&p, "e", None), + panic_sentry_body(&p, "e", "bid", None), ] { let v: serde_json::Value = serde_json::from_slice(&body).unwrap(); assert!( @@ -2553,7 +2733,7 @@ mod tests { crash_time: None, }; let panic: serde_json::Value = - serde_json::from_slice(&panic_sentry_body(&p, "e", None)).unwrap(); + serde_json::from_slice(&panic_sentry_body(&p, "e", "bid", None)).unwrap(); let fault: serde_json::Value = serde_json::from_slice(&sentry_body( &only_fault(REC), "e", BUILD, Some("did"), None, &extra(), )) @@ -2676,10 +2856,10 @@ mod tests { let log = format!("*** RUST PANIC [t] at src/a.rs:1: boom\n{}\n", crash_time_record(t)); let Some(Report::Panic(p)) = parse(&log).into_iter().next() else { panic!("a panic") }; assert_eq!(p.crash_time, Some(t)); - let v: serde_json::Value = serde_json::from_slice(&panic_sentry_body(&p, "e", None)).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&panic_sentry_body(&p, "e", "bid", None)).unwrap(); assert_eq!(v["timestamp"], serde_json::json!(t)); let bare = PanicReport { crash_time: None, ..p }; - let v: serde_json::Value = serde_json::from_slice(&panic_sentry_body(&bare, "e", None)).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&panic_sentry_body(&bare, "e", "bid", None)).unwrap(); assert!(v.get("timestamp").is_none()); } @@ -3177,6 +3357,25 @@ mod tests { assert!(panic["contexts"].get("crash").is_none(), "a panic has no native_path"); } + /// The consent screen promises a field added to a schema shows up in front of the person being + /// asked, so the shape a report takes when a LATER build recovers it (no `release`, the + /// `crash.uploaded_by` and `crash.build_id` tags) must be on screen too: the panic sample is + /// that shape, and the fault sample stays the ordinary one. Both tags are placeholders from the + /// consent screen's own translated set, never this build's version or a real id. + #[test] + fn the_panic_preview_shows_the_straddled_shape_and_the_fault_preview_the_ordinary_one() { + let preview = preview_events(); + let fault: serde_json::Value = serde_json::from_slice(&preview[0].1).unwrap(); + let panic: serde_json::Value = serde_json::from_slice(&preview[1].1).unwrap(); + assert_eq!(panic["tags"]["crash.uploaded_by"], ""); + assert_eq!(panic["tags"]["crash.build_id"], ""); + assert!(panic.get("release").is_none(), "the sample is the shape with no release"); + assert_eq!(panic["dist"], ""); + assert_eq!(fault["release"], super::super::release(), "the fault sample is the ordinary shape"); + assert!(fault["tags"].get("crash.uploaded_by").is_none()); + assert!(fault["tags"].get("crash.build_id").is_none()); + } + /// The report belongs to the binary that CRASHED, not to whichever binary happens to read the /// append-only log on the next launch. A deploy between those two moments is ordinary during /// development and makes current-process build identity actively wrong. @@ -3227,6 +3426,102 @@ mod tests { ); } + /// PLX-NATIVE-26: a 0.9.0 process crashed, the next launch was 0.10.0, and the report it queued + /// from 0.9.0's crash log was filed under `plxnative@0.10.0`, which poisons per-release crash + /// counts and regression detection right after every release. The record names the image it ran + /// (its `img:` line); a recovering binary whose own build id differs may not claim the report. + /// + /// Driven through [`report_body`], the function `recover_pending` queues through, with all four + /// kinds of record: the bodies themselves are handed the RECORD's id as their fallback, so a + /// check inside them alone would pass here and do nothing in the field. + fn every_kind_of_record() -> Vec<(&'static str, Report)> { + let fault = parse(REC).remove(0); + assert!(matches!(fault, Report::Fault(_))); + let freeze = Report::Freeze(only_freeze(FRZ)); + let exit = Report::Exit(only_exit(&exit_log())); + let all = vec![("fault", fault), ("panic", panic_report()), ("freeze", freeze), ("exit", exit)]; + for (kind, r) in &all { + assert_eq!(report_image(r).map(|i| i.build_id.as_str()), Some(BUILD), "{kind}: the fixture names its image"); + } + all + } + + fn recovered_body(r: &Report, running_build_id: &str) -> serde_json::Value { + serde_json::from_slice(&report_body( + r, + &"e".repeat(32), + running_build_id, + None, + NativePath::NoEnvelope, + |_| None, + )) + .unwrap() + } + + /// A running build that is not the one the fixtures' records came from (an upgraded install). + const UPGRADED_TO: &str = "e074ee2be074ee2be074ee2be074ee2be074ee2b"; + + #[test] + fn a_record_from_another_build_is_not_filed_under_the_running_release() { + for (kind, r) in every_kind_of_record() { + let body = recovered_body(&r, UPGRADED_TO); + assert!( + body.get("release").is_none(), + "{kind}: a record from build {BUILD} was filed under the running release {}", + body["release"] + ); + assert_eq!(body["dist"], BUILD, "{kind}: dist stays the crashed build's id"); + assert_eq!( + body["tags"]["crash.uploaded_by"], + super::super::app_version(), + "{kind}: the uploader is named instead" + ); + // Sentry ignores `dist` on an event with no `release`, and the panic body has no + // `debug_meta`: without this tag the event would name no build at all. + assert_eq!( + body["tags"]["crash.build_id"], BUILD, + "{kind}: the crashed build is named by a tag, not only by `dist`" + ); + assert_eq!( + body["sdk"]["version"], + super::super::app_version(), + "{kind}: the SDK version still names the binary that built the body" + ); + } + } + + #[test] + fn a_record_from_the_running_build_keeps_the_running_release() { + for (kind, r) in every_kind_of_record() { + // The id compares case-insensitively: an upper-case read of the same ELF is the same build. + for running in [BUILD.to_string(), BUILD.to_ascii_uppercase()] { + let body = recovered_body(&r, &running); + assert_eq!(body["release"], super::super::release(), "{kind}"); + assert!(body["tags"].get("crash.uploaded_by").is_none(), "{kind}: nothing to disclaim"); + assert!(body["tags"].get("crash.build_id").is_none(), "{kind}: `release` and `dist` already name it"); + } + } + } + + /// Where the two cannot be compared the report is stamped as before: no image line in the + /// record, or a running build whose ELF could not be read (`build_id()` is empty then). + #[test] + fn a_record_that_cannot_be_compared_is_stamped_as_before() { + for (kind, r) in every_kind_of_record() { + let body = recovered_body(&r, ""); + assert_eq!(body["release"], super::super::release(), "{kind}: unknown running build"); + assert!(body["tags"].get("crash.uploaded_by").is_none(), "{kind}"); + assert!(body["tags"].get("crash.build_id").is_none(), "{kind}"); + } + let no_image = REC.lines().filter(|l| !l.starts_with("img: ")).collect::>().join("\n"); + let fault = parse(&no_image).remove(0); + assert!(report_image(&fault).is_none()); + let body = recovered_body(&fault, UPGRADED_TO); + assert_eq!(body["release"], super::super::release(), "no image line: nothing says it is another build"); + assert!(body["tags"].get("crash.uploaded_by").is_none()); + assert!(body["tags"].get("crash.build_id").is_none()); + } + /// The image path is a constant, so the report does not say WHICH of the two install prefixes /// this person used — a fact about them rather than about the crash. #[test] @@ -3382,7 +3677,7 @@ mod tests { let Report::Panic(p) = &parse(PANIC_LINE)[0] else { panic!("expected a panic") }; - let body = String::from_utf8(panic_sentry_body(p, &"e".repeat(32), None)).expect("utf-8"); + let body = String::from_utf8(panic_sentry_body(p, &"e".repeat(32), BUILD, None)).expect("utf-8"); assert!(!body.contains("Dune"), "a title reached the wire"); assert!(!body.contains("/media/"), "a path reached the wire"); assert!(!body.contains("unwrap"), "the message reached the wire"); @@ -3926,6 +4221,202 @@ mod tests { assert!(!text.contains("/lib/") && !text.contains("/media"), "only a library's basename may travel"); } + // ---- the loop leg a freeze was probed in (`freeze-at:`) ---- + + const AT_UPDATE: &str = "freeze-at: seq=1 leg=update\n"; + + /// `FRZ` with its `freeze-at:` line in each of the places the two writers can leave it: the + /// observer thread's line may land before the handler's header, between two of the handler's + /// own lines, or after them all. + fn frz_with_leg_at(place: &str) -> String { + match place { + "before the header" => FRZ.replacen("*** FREEZE seq=1", &format!("{AT_UPDATE}*** FREEZE seq=1"), 1), + "between the header and its time" => FRZ.replacen("time: 1750000000", &format!("{AT_UPDATE}time: 1750000000"), 1), + "between its time and its regs" => FRZ.replacen("reg: sp", &format!("{AT_UPDATE}reg: sp"), 1), + "among the mappings" => FRZ.replacen("bin: ", &format!("{AT_UPDATE}bin: "), 1), + "after the recovery" => format!("{FRZ}{AT_UPDATE}"), + other => panic!("{other}"), + } + } + + const LEG_PLACES: [&str; 5] = [ + "before the header", + "between the header and its time", + "between its time and its regs", + "among the mappings", + "after the recovery", + ]; + + #[test] + fn a_freeze_takes_its_leg_from_the_freeze_at_line_wherever_it_landed() { + for place in LEG_PLACES { + let log = frz_with_leg_at(place); + let f = only_freeze(&log); + assert_eq!(f.leg, Some(LoopPhase::Update), "{place}"); + // The line is a neighbour, not a part of the record: everything else reads as before. + assert_eq!(f.registers.r1, Some(0x2a), "{place}"); + assert_eq!(f.frames, vec![0x4b_ccd0, 0x4a_1234, 0xb6f0_1000], "{place}"); + assert_eq!(f.crash_time, Some(1_750_000_000), "{place}"); + assert_eq!(f.bucket, FreezeBucket::Medium, "{place}"); + assert_eq!(f.modules.len(), 1, "{place}"); + assert_eq!(parse(&log).len(), 1, "{place}: a leg line is not a report"); + } + assert_eq!(only_freeze(FRZ).leg, None, "an old record has no leg"); + } + + #[test] + fn a_freeze_leg_is_a_tag_and_a_third_fingerprint_element_only_when_there_is_one() { + for place in LEG_PLACES { + let body = freeze_json(&only_freeze(&frz_with_leg_at(place))); + assert_eq!(body["tags"]["freeze.leg"], "update", "{place}"); + assert_eq!(body["tags"]["freeze"], "10-30s", "{place}"); + assert_eq!(body["fingerprint"], serde_json::json!(["freeze", "plxnative+0x4accd0", "update"]), "{place}"); + } + // An old record, written before the line existed, keeps its tags and its grouping. + let old = freeze_json(&only_freeze(FRZ)); + assert!(old["tags"].get("freeze.leg").is_none()); + assert_eq!(old["fingerprint"], serde_json::json!(["freeze", "plxnative+0x4accd0"])); + } + + #[test] + fn a_freeze_at_line_that_is_not_exactly_a_number_and_a_table_word_is_ignored() { + for bad in [ + "freeze-at: seq=1 leg=SecretMovie\n", + "freeze-at: seq=1 leg=event ingest\n", + "freeze-at: seq=1 leg=update SecretMovie\n", + "freeze-at: seq=1 leg=unlabeled\n", + "freeze-at: seq=1 leg=\n", + "freeze-at: seq=1\n", + "freeze-at: seq=x leg=update\n", + "freeze-at: seq=-1 leg=update\n", + "freeze-at: seq=99999999999 leg=update\n", + "freeze-at: leg=update seq=1\n", + "freeze-at: seq=1 leg=Update\n", + ] { + for place in ["before the header", "after the recovery"] { + let log = frz_with_leg_at(place).replace(AT_UPDATE, bad); + let f = only_freeze(&log); + assert_eq!(f.leg, None, "{bad:?} {place}"); + let body = freeze_json(&f); + assert!(body["tags"].get("freeze.leg").is_none(), "{bad:?} {place}"); + assert_eq!(body["fingerprint"], serde_json::json!(["freeze", "plxnative+0x4accd0"]), "{bad:?} {place}"); + let text = String::from_utf8(freeze_sentry_body(&f, "e", BUILD, Some("did"), None, &[])).unwrap(); + assert!(!text.contains("SecretMovie"), "{bad:?} {place}"); + } + } + } + + #[test] + fn a_freeze_at_line_of_another_probe_number_or_another_process_is_not_this_freezes() { + // Probe 2's line, with no freeze 2: it waits for a freeze 2 that never comes. + let other_probe = "freeze-at: seq=2 leg=update\n"; + for place in ["before the header", "after the recovery"] { + let log = frz_with_leg_at(place).replace(AT_UPDATE, other_probe); + assert_eq!(only_freeze(&log).leg, None, "{place}"); + } + // The earlier process's line, then a later process whose own probe 1 has no line. + let earlier = "\nimg: build_id=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa image_addr=0x10000 image_size=0x5f0000\n"; + let log = format!("{earlier}{AT_UPDATE}{FRZ}"); + assert_eq!(only_freeze(&log).leg, None, "a line waiting from the earlier process is dropped at the next marker"); + // The reverse: the earlier process's freeze 1 never gets the later process's line. + let unrecovered = FRZ.replace("freeze-end: seq=1 bucket=10-30s\n", ""); + let log = format!("{unrecovered}{earlier}{AT_UPDATE}"); + assert_eq!(only_freeze(&log).leg, None, "a leg line closes only a freeze of its own process"); + // And each process keeps its own. + let both = format!("{}{FRZ}", frz_with_leg_at("before the header")); + let legs: Vec<_> = parse(&both) + .into_iter() + .filter_map(|r| match r { + Report::Freeze(f) => Some(f.leg), + _ => None, + }) + .collect(); + assert_eq!(legs, vec![Some(LoopPhase::Update), None]); + } + + #[test] + fn a_freeze_leg_line_survives_a_malformed_exit_header_above_it() { + let log = FRZ.replacen("bin: ", "*** EXIT status=x\nfreeze-at: seq=1 leg=update\nbin: ", 1); + assert_eq!(only_freeze(&log).leg, Some(LoopPhase::Update)); + } + + /// A freeze that has no frame in the app's own image: `pc` in `pc_lib` and `lr` in `lr_lib` + /// (a library basename), at the given offsets, with the given extra line (a `freeze-at:`). + fn firmware_only_freeze(pc_off: u64, lr_off: u64, leg_line: &str) -> Freeze { + let log = format!( + "\nimg: build_id=11223344556677889900aabbccddeeff00112233 image_addr=0x10000 image_size=0x5f0000\n\ + \n*** FREEZE seq=1 pc=0x{:x} lr=0x{:x}\n\ + {leg_line}\ + at: b6f00000-b6f21000 r-xp 00000000 fe:01 1234 /lib/libc.so.6\n\ + at: b6a00000-b6a40000 r-xp 00000000 fe:01 4321 /usr/lib/libgl-firmware.so\n\ + freeze-end: seq=1 bucket=5-10s\n", + 0xb6f0_0000 + pc_off, + 0xb6a0_0000 + lr_off, + ); + only_freeze(&log) + } + + #[test] + fn a_firmware_only_freeze_with_a_leg_fingerprints_on_module_basenames_not_offsets() { + let a = firmware_only_freeze(0x1_0000, 0x2_0000, AT_UPDATE); + let b = firmware_only_freeze(0x1_0aa4, 0x3_1230, AT_UPDATE); + let expect = serde_json::json!(["freeze", "libc.so.6>libgl-firmware.so", "update"]); + assert_eq!(freeze_json(&a)["fingerprint"], expect); + assert_eq!(freeze_json(&b)["fingerprint"], expect, "another instruction in the same libraries is the same issue"); + // Another leg is another issue; so are other libraries. + let other_leg = firmware_only_freeze(0x1_0000, 0x2_0000, "freeze-at: seq=1 leg=present-and-swap\n"); + assert_eq!( + freeze_json(&other_leg)["fingerprint"], + serde_json::json!(["freeze", "libc.so.6>libgl-firmware.so", "present-and-swap"]) + ); + // The stack still shows the exact frames: only the grouping drops the offsets. + let addrs: Vec<_> = freeze_json(&a)["exception"]["values"][0]["stacktrace"]["frames"] + .as_array() + .unwrap() + .iter() + .map(|x| x["instruction_addr"].as_str().unwrap().to_string()) + .collect(); + assert_eq!(addrs, ["0xb6a20000", "0xb6f10000"]); + } + + #[test] + fn the_freeze_basename_site_covers_a_single_module_a_shared_one_and_none() { + let f = firmware_only_freeze(0x1_0000, 0x2_0000, AT_UPDATE); + // lr unlocated: pc's module alone. + let no_lr = Freeze { lr: 0, ..f.clone() }; + assert_eq!(freeze_json(&no_lr)["fingerprint"], serde_json::json!(["freeze", "libc.so.6", "update"])); + // pc unlocated: lr's module alone. + let no_pc = Freeze { pc: 0, ..f.clone() }; + assert_eq!(freeze_json(&no_pc)["fingerprint"], serde_json::json!(["freeze", "libgl-firmware.so", "update"])); + // pc and lr in one module: both ends are named, so it differs from the one-ended shapes. + let same = Freeze { lr: 0xb6f0_5000, ..f.clone() }; + assert_eq!(freeze_json(&same)["fingerprint"], serde_json::json!(["freeze", "libc.so.6>libc.so.6", "update"])); + // Nothing located: the constant word, still with the leg. + let nothing = Freeze { image: None, modules: Vec::new(), ..f }; + assert_eq!(freeze_json(¬hing)["fingerprint"], serde_json::json!(["freeze", "unmapped", "update"])); + } + + #[test] + fn a_firmware_only_freeze_without_a_leg_keeps_its_old_offset_fingerprint() { + // An old record is not regrouped: it names the instruction, as it always did. + let old = firmware_only_freeze(0x1_0000, 0x2_0000, ""); + assert_eq!(old.leg, None); + assert_eq!(freeze_json(&old)["fingerprint"], serde_json::json!(["freeze", "libc.so.6+0x10000"])); + // And an old record with an app frame is untouched, as the test above pins. + assert_eq!(freeze_json(&only_freeze(FRZ))["fingerprint"], serde_json::json!(["freeze", "plxnative+0x4accd0"])); + } + + /// What a freeze report can carry is what `PRIVACY.md` lists: the tag and every word of the + /// fixed table that can reach it. + #[test] + fn privacy_names_the_freeze_leg_tag_and_every_word_it_can_carry() { + let notice = include_str!("../../../../PRIVACY.md"); + assert!(notice.contains("`freeze.leg`"), "PRIVACY.md does not name the tag"); + for leg in LoopPhase::ALL { + assert!(notice.contains(&format!("`{}`", leg.word())), "PRIVACY.md does not name `{}`", leg.word()); + } + } + #[test] fn a_freeze_event_id_is_stable_across_retries_and_ignores_the_bucket() { let f = only_freeze(FRZ); diff --git a/rust-modules/telemetry/src/telemetry/mod.rs b/rust-modules/telemetry/src/telemetry/mod.rs index 409087bb62..c9c16d23c2 100644 --- a/rust-modules/telemetry/src/telemetry/mod.rs +++ b/rust-modules/telemetry/src/telemetry/mod.rs @@ -45,7 +45,9 @@ const RELEASE_PREFIX: &str = "plxnative@"; static RELEASE: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new(); /// Record the release string every outbound report carries (Sentry `release`, the SDK and client -/// version, the usage context's `app_version`). +/// version, the usage context's `app_version`). The one exception to `release` is a crash-log +/// record left by another build than this one, which `crashreport::stamp_release` files under no +/// release rather than this one. /// /// **The application hands it in**: `PLX_VERSION` is published by the application's build script, a /// `cargo:rustc-env` reaches that one crate only, and the rule that derives it is written once diff --git a/rust-modules/telemetry/src/telemetry/playback.rs b/rust-modules/telemetry/src/telemetry/playback.rs index 9c2de25966..705555a221 100644 --- a/rust-modules/telemetry/src/telemetry/playback.rs +++ b/rust-modules/telemetry/src/telemetry/playback.rs @@ -208,6 +208,12 @@ pub fn event_body( }}, "breadcrumbs": {"values": breadcrumbs}, }); + // Which condition refused a trailer preview: one closed tag, and only on the kind it explains + // (the failtest and jail shapes outrank the preview verdict in the kind, and must not carry a + // reason that is no longer the cause). The fingerprint above is untouched: one issue. + if let (FailureClass::PreviewNotDirect, Some(reason)) = (kind, context.preview_refusal) { + body["tags"]["playback.preview_refusal"] = Value::String(reason.code().to_string()); + } if let Some(r) = context.refusal { // Tags so an issue can be searched and grouped on them, a context so one event reads in // one place. Every value is the `code()` of a closed enum; the server's own sentence has @@ -498,8 +504,10 @@ pub fn preview_event() -> Vec { http_status: 404, pipeline_error: 601, // Representative of a `decision_refused` report's extra block, shown here so the - // consent screen's sample carries every key a report can; a real report has it only - // when the server refused the plan. + // consent screen's sample carries every key a report can, bar one: the + // `playback.preview_refusal` tag belongs to a `preview_not_direct` report and is + // listed by `preview_domains` instead. A real report has this block only when the + // server refused the plan. refusal: Some(RefusalContext { general: DecisionCodeClass::C2000, transcode: DecisionCodeClass::C4007, @@ -507,6 +515,8 @@ pub fn preview_event() -> Vec { source_video: VideoCodecClass::Vp9, source_audio: AudioCodecClass::Eac3, }), + // Only a `preview_not_direct` report carries one, and this sample is not that kind. + preview_refusal: None, }, &trace, ) @@ -574,7 +584,8 @@ fn codes(values: &[T], code: fn(T) -> &'static str) -> String { /// Closed value domains for the representative handled-error payload above. Generated from the /// same enum `code()` methods as the serializer, so the consent screen does not imply that its one -/// sample value is the only possible one. +/// sample value is the only possible one. It also names the one key the sample cannot carry, the +/// `playback.preview_refusal` tag of a `preview_not_direct` report. pub fn preview_domains() -> String { use crate::telemetry::classes::{ BufferClass as B, DeliveryClass as D, DeliveryReason as W, ErrorBackendClass as U, @@ -584,25 +595,14 @@ pub fn preview_domains() -> String { DemuxExitClass as E, TransferAgeClass as T, TransportClass as K, }; use crate::telemetry::classes::{AudioCodecClass as Z, DecisionCodeClass as N, VideoCodecClass as V}; - use crate::telemetry::classes::{AttemptOrdinal, AttemptOrigin}; + use crate::telemetry::classes::{AttemptOrdinal, AttemptOrigin, PreviewRefusal}; use FailureClass as F; use plx_platform::i18n::msg; // The labels are the reader's words; the codes after them are the wire values themselves. - let domains: [(&str, String); 27] = [ - (msg::core_preview_domain_failure_kind(), codes( - &[ - F::DecisionRefused, - F::PlaybackPolicy, - F::NoVideoTranscodeTarget, - F::NoVideoTrack, - F::MediaSource, - F::PlaybackInterrupted, - F::TvPipeline, - F::OriginalRollback, - F::Unspecified, - ], - F::code, - )), + let domains: [(&str, String); 28] = [ + // Every class reaches the handled report (`FailureKind::class`), so the row is the whole + // enum: a class added to `FailureClass` appears here without anyone remembering to. + (msg::core_preview_domain_failure_kind(), codes(&F::ALL, F::code)), (msg::core_preview_domain_backend(), codes(&U::ALL, U::code)), (msg::core_preview_domain_terminal_stage(), codes(&S::ALL, S::code)), (msg::core_preview_domain_delivery(), codes(&[D::Unknown, D::Direct, D::Remux, D::Hls, D::Transcode], D::code)), @@ -617,6 +617,10 @@ pub fn preview_domains() -> String { (msg::core_preview_domain_refusal_codes(), codes(&N::ALL, N::code)), (msg::core_preview_domain_source_video(), codes(&V::ALL, V::code)), (msg::core_preview_domain_source_audio(), codes(&Z::ALL, Z::code)), + // The `playback.preview_refusal` tag rides a `preview_not_direct` report only, so the + // sample above (a `playback_interrupted` one) cannot show it; the label says which + // reports carry it, and the list is the enum's own `ALL`. + (msg::core_preview_domain_preview_refusal(), codes(&PreviewRefusal::ALL, PreviewRefusal::code)), (msg::core_preview_domain_quality(), codes( &[ Q::Unknown, @@ -761,6 +765,7 @@ mod tests { http_status: 0, pipeline_error: 0, refusal: None, + preview_refusal: None, } } @@ -1191,6 +1196,50 @@ mod tests { assert_eq!(v["fingerprint"], serde_json::json!(["playback-error", "decision_refused"])); } + /// **Sentry PLX-NATIVE-23.** A refused trailer preview says WHICH condition refused it, as one + /// closed tag, and only on the `preview_not_direct` kind (a failtest or jail shape can outrank + /// the verdict in the kind, and must not carry a stale reason). The issue stays one group. + #[test] + fn a_preview_refusal_is_tagged_only_on_the_preview_not_direct_kind() { + use crate::telemetry::classes::PreviewRefusal; + let body = |kind: FailureClass, reason: Option| -> Value { + let mut ctx = context(); + ctx.attempt_origin = AttemptOrigin::Preview; + ctx.preview_refusal = reason; + serde_json::from_slice(&event_body(&"a".repeat(32), "", None, kind, ctx, &[])).expect("handled event JSON") + }; + for reason in PreviewRefusal::ALL { + let v = body(FailureClass::PreviewNotDirect, Some(reason)); + assert_eq!(v["tags"]["playback.preview_refusal"], reason.code(), "{reason:?}"); + assert_eq!( + v["fingerprint"], + serde_json::json!(["playback-error", "preview", "preview_not_direct"]), + "the reason refines the issue, it never splits its group" + ); + assert!(v["contexts"]["playback"].get("preview_refusal").is_none()); + assert!( + body(FailureClass::TvPipeline, Some(reason))["tags"].get("playback.preview_refusal").is_none(), + "another kind carries no refusal reason: {reason:?}" + ); + } + assert!( + body(FailureClass::PreviewNotDirect, None)["tags"].get("playback.preview_refusal").is_none(), + "no verdict, no tag" + ); + } + + #[test] + fn privacy_names_the_preview_refusal_tag_and_every_value() { + use crate::telemetry::classes::PreviewRefusal; + let privacy = include_str!("../../../../PRIVACY.md"); + assert!(privacy.contains("`preview_refusal`"), "PRIVACY.md omitted the tag"); + let codes: Vec<_> = PreviewRefusal::ALL.iter().map(|r| r.code()).collect(); + assert_eq!(codes, ["not_direct", "no_part", "adaptive"]); + for code in codes { + assert!(privacy.contains(&format!("`{code}`")), "PRIVACY.md omitted {code}"); + } + } + #[test] fn the_consent_sample_carries_every_key_a_refusal_report_can() { let v: Value = serde_json::from_slice(&preview_event()).expect("preview JSON"); @@ -1239,6 +1288,46 @@ mod tests { assert!(privacy.contains("`refusal_recovery`"), "PRIVACY.md omitted the facet rung's reason"); } + /// The values of the legend row headed `label`, read from the one line the legend wrote for it. + /// A code can be a substring of another (`not_direct` of `preview_not_direct`), so a test of a + /// row's domain reads the row it means and never searches the whole legend. + fn legend_row_values(label: &str) -> String { + let prefix = plx_platform::i18n::msg::core_preview_domain_line(label, ""); + let legend = preview_domains(); + let mut rows = legend.lines().filter_map(|line| line.strip_prefix(prefix.as_str())); + let values = rows.next().unwrap_or_else(|| panic!("the legend has no row {label:?}")); + assert!(rows.next().is_none(), "the legend has two rows {label:?}"); + values.to_owned() + } + + /// **Sentry PLX-NATIVE-23.** The consent screen shows every field a report can carry, and + /// `playback.preview_refusal` rides a `preview_not_direct` report, so its closed domain has a + /// row of its own and the failure-kind row names the kind that carries it. The sample event + /// cannot show the key (it is a `playback_interrupted` report), which is why the row's label + /// says which reports have it. + #[test] + fn consent_legend_lists_the_preview_refusal_domain_on_its_own_row() { + use crate::telemetry::classes::PreviewRefusal; + use plx_platform::i18n::msg; + let want: Vec<&str> = PreviewRefusal::ALL.iter().map(|r| r.code()).collect(); + assert_eq!(want, ["not_direct", "no_part", "adaptive"], "the domain is closed at three"); + let row = legend_row_values(msg::core_preview_domain_preview_refusal()); + assert_eq!(row.split(" / ").collect::>(), want, "the whole domain, in the enum's order"); + } + + /// The failure-kind row is the whole `FailureClass` domain, in declaration order: every kind + /// reaches the handled report through `FailureKind::class`, so a kind the row leaves out is a + /// value the person was never shown (`preview_not_direct`, `jail_missing_rtkmem` and the rest + /// were once missing). + #[test] + fn consent_legend_failure_kind_row_lists_every_failure_class() { + use plx_platform::i18n::msg; + let row = legend_row_values(msg::core_preview_domain_failure_kind()); + let want: Vec<&str> = FailureClass::ALL.iter().map(|k| k.code()).collect(); + assert_eq!(row.split(" / ").collect::>(), want); + assert!(want.contains(&"preview_not_direct")); + } + #[test] fn consent_preview_and_privacy_name_the_closed_failure_domains() { let legend = preview_domains(); diff --git a/rust-modules/telemetry/src/telemetry/queue.rs b/rust-modules/telemetry/src/telemetry/queue.rs index aff52222ad..d7270c39b3 100644 --- a/rust-modules/telemetry/src/telemetry/queue.rs +++ b/rust-modules/telemetry/src/telemetry/queue.rs @@ -334,11 +334,15 @@ mod tests { #[test] fn at_the_byte_cap_sessions_are_dropped_before_crash_reports() { let session = rec("sess", Category::Errors, br#"{"attrs":{"release":"r"},"did":"d","sid":"s","started":"t"}"#); - // The largest crash body for which four crash reports fit and no session does. - let mut n = 90_000; - while 4 * encode(&rec("c", Category::Errors, &vec![b'x'; n + 3])).unwrap().len() <= MAX_BYTES { - n += 3; - } + // The largest crash body for which four crash reports fit and no session does. A frame is a + // fixed overhead (header, JSON fields, an empty body) plus four base64 characters per three + // body bytes, so the body is derived from the overhead instead of searched for by framing + // a ~100 KB record thousands of times; the two asserts pin the derivation to `encode`. + let framed = |n: usize| encode(&rec("c", Category::Errors, &vec![b'x'; n])).unwrap().len(); + let overhead = framed(0); + let n = 3 * ((MAX_BYTES / 4 - overhead) / 4); + assert!(4 * framed(n) <= MAX_BYTES, "four crash reports of {n} bytes fit"); + assert!(4 * framed(n + 3) > MAX_BYTES, "and one base64 group more does not"); let crash = |id: &str| rec(id, Category::Errors, &vec![b'x'; n]); let all = vec![crash("c1"), crash("c2"), crash("c3"), crash("c4"), session]; let (kept, dropped) = trim(all); diff --git a/rust-modules/ui/src/CLAUDE.md b/rust-modules/ui/src/CLAUDE.md index 5638e65923..9bdcece484 100644 --- a/rust-modules/ui/src/CLAUDE.md +++ b/rust-modules/ui/src/CLAUDE.md @@ -328,9 +328,13 @@ which the orphan rule forbids. references: `Session` (auth, profile, the one `ProfileScope`), `Consent`, `Input` (press, key-repeat edges, pointer visibility, the double-buffered hit map, and the `FocusEngine` that holds THE current focus — screens keep no copy), `Present` (the gate), `Navigation` (the container tree and -every entry/instance), `Player`, `Stores`, `Adapters`. Ownerships that used to be double are now -single: the press belongs to `Input`, the modal phase to `ModalStack`, the present gate to -`Present`, `ProfileScope` to `Session`. +every entry/instance), `Player`, `Stores`, `Adapters`. Press belongs to `Input`, the modal phase +to `ModalStack`, and `ProfileScope` to `Session`. `Dispatcher::present` is the runtime +frame gate; `App` does not own a second gate. `Input` supplies the explicit `PressRead`, and +`NavStack` supplies `NavPresentation` through `DrawFrame`. Rendering scopes report only +frame-captured motion through `plx_machine::motion::report`. Content damage and its page/surface +attribution are typed effects on the owning `Present`, never an ambient generation or collector. +Admission retains pending work until the loop acknowledges an actual swap. **Navigation is a model, not a route word (§6.2).** `containers/` is the fold: TabContainer → NavStack → ModalStack. A screen is an owned INSTANCE with logical state inside and @@ -351,7 +355,7 @@ Keymanager and LS2 calls. Tests panic (catchably). In developer builds (`threadc `main-thread block: