From 1caf8cb3052d28e09b44b9d1fbdc71b9ad3e7cb8 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 19:46:49 +0300 Subject: [PATCH 1/6] The SDL shell is a crate of its own, plx_shell_sdl, behind the app-private Shell and Surface SDL's bring-up, the window and its GL context, the swap, the event poll and decode, the synthetic events the dev tooling pushes back, and the text-input calls leave the application crate for `rust-modules/shell-sdl`, a mounted module of a new `[shell_sdl]` layer (`uses = base machine os`; the crate names `plx_base` alone). The application keeps what is its own vocabulary: `Shell`, `Surface`, `HostEvent` and `KeyPress` stay app-private (W7a publishes them), and the television's LG half stays in `system.rs` and the webOS platform. The `SDL_SysWMinfo` over-allocation, the opaque region and the LS2 pump do not move, and a pin in the crate fails if it ever names the query that overruns it. `Shell` gains `init` and `open`. `open` returns a `Surface` (window, swap, swap interval, poll, an unsafe quit that `run::shutdown` calls), which `App` owns in place of the raw window pointer. The order boot always had is kept and pinned: SDL_Init and the GL request first, then the stored session is read, then the window. The window's place and size are a value, `OpenAsk { title, placement, high_dpi }`, so the panel's size with its smaller fallback and the desktop fit (hostsim builds only) are the crate's. The two LG steps around SDL_Init, the cursor-sleep hint before and the relaunch tap after, moved into `system.rs` without their `hostsim` gates and are handed to `init` as two hooks by the webOS shell; the cursor hint's SDL_SetHint goes through the crate's `set_hint`. The byte layouts are written down once, in the crate, and both arms of every LG versus stock layout still compile in every build (`cfg!`, not `#[cfg]`). The byte-level tests moved with the code and run in the crate; the HostEvent-level tests stay in the application over re-exports. The source-text pins that read relocated code moved with it, and one new pin holds the application to declaring SDL functions in `system.rs` and `app/clock.rs` only. Three call sites that reach the shell from loop code had no test that would notice the call going missing, and now have one each, each shown to fail with its call deleted: the idle pointer hidden over the video in `playback_tick`, `host_background`'s hand-back of the pointer Back hid, and a controlled pointer input's wake in `controlled_key_input`. Lists that name the layer crates gain the new one: the Makefile's suites and inputs, the CI workflow, the build-budget source list, `check-deps.sh`'s scans, `list-caps.ini` (the five moved cap sites re-keyed, one new), the release-config hook, and the module-layers config. Both read-only certificates are re-sealed over the new manifest set and lock file. The docs follow: the L15e row, the shell_sdl layer paragraph, F14 and the W6 record in the platform plan, and the two points the review of the L15g row left (telemetry's nine arm lines, and the storage-authority part of W8a landing ahead of W7). Co-Authored-By: Claude --- .agents/agents/fw-compat-reviewer.md | 4 +- .agents/skills/ui-sim/SKILL.md | 2 +- .agents/skills/which-tier/SKILL.md | 4 +- .claude/hooks/release-config-check-test.py | 1 + .claude/hooks/release-config-check.py | 2 +- .github/workflows/ci.yml | 4 +- Makefile | 16 +- ci/build-budgets.json | 2 +- ci/check-build-budgets.py | 4 +- ci/check-deps.sh | 26 +- ci/list-caps.ini | 46 +- ci/module-layers.ini | 16 +- ci/proofs/platform-generated-enums.json | 5 +- ci/proofs/serde-json-immutable.json | 5 +- ci/readonly_dependencies.py | 2 +- ci/readonly_generated.py | 2 +- ci/test_build_bench.py | 1 + ci/test_build_not_always_dirty.py | 4 +- ci/test_ci_split.py | 6 +- ci/test_no_host_staticlib.py | 4 +- ci/test_test_fast.py | 4 +- docs/agent-reference.md | 25 +- docs/distribution.md | 2 +- docs/lab-diagnostics.md | 2 +- docs/launch-links.md | 2 +- docs/macos-app.md | 2 +- docs/module-layers.md | 21 +- docs/platform-ports.md | 14 +- docs/search.md | 2 +- rust-modules/Cargo.lock | 8 + rust-modules/Cargo.toml | 23 +- rust-modules/base/src/surface.rs | 2 +- rust-modules/data/src/search.rs | 2 +- rust-modules/shell-sdl/Cargo.toml | 39 ++ rust-modules/shell-sdl/build.rs | 21 + rust-modules/shell-sdl/src/event.rs | 579 ++++++++++++++++++ rust-modules/shell-sdl/src/init.rs | 189 ++++++ rust-modules/shell-sdl/src/inject.rs | 232 ++++++++ rust-modules/shell-sdl/src/lib.rs | 94 +++ rust-modules/shell-sdl/src/sys.rs | 79 +++ rust-modules/shell-sdl/src/testing.rs | 23 + rust-modules/shell-sdl/src/text.rs | 533 +++++++++++++++++ rust-modules/shell-sdl/src/window.rs | 510 ++++++++++++++++ rust-modules/src/app/boot.rs | 653 ++------------------- rust-modules/src/app/deeplink.rs | 2 +- rust-modules/src/app/events.rs | 479 +++------------ rust-modules/src/app/mod.rs | 138 +---- rust-modules/src/app/platform.rs | 166 +++++- rust-modules/src/app/run.rs | 160 +++-- rust-modules/src/platform_desktop.rs | 23 +- rust-modules/src/port.rs | 59 +- rust-modules/src/system.rs | 148 +++++ rust-modules/src/textinput.rs | 484 +-------------- tools/build-bench.py | 4 +- tools/screenshots.py | 2 +- 55 files changed, 3122 insertions(+), 1760 deletions(-) create mode 100644 rust-modules/shell-sdl/Cargo.toml create mode 100644 rust-modules/shell-sdl/build.rs create mode 100644 rust-modules/shell-sdl/src/event.rs create mode 100644 rust-modules/shell-sdl/src/init.rs create mode 100644 rust-modules/shell-sdl/src/inject.rs create mode 100644 rust-modules/shell-sdl/src/lib.rs create mode 100644 rust-modules/shell-sdl/src/sys.rs create mode 100644 rust-modules/shell-sdl/src/testing.rs create mode 100644 rust-modules/shell-sdl/src/text.rs create mode 100644 rust-modules/shell-sdl/src/window.rs diff --git a/.agents/agents/fw-compat-reviewer.md b/.agents/agents/fw-compat-reviewer.md index e703609633..98652f426f 100644 --- a/.agents/agents/fw-compat-reviewer.md +++ b/.agents/agents/fw-compat-reviewer.md @@ -127,8 +127,8 @@ the same SONAME on every release from 2.2.3 to 11.2.0. Moving a library into `dynlib!` **trades link-time symbol checking away** for version tolerance and is only worth it where the version actually varies. If a diff moves a stable library there, push back and ask for the `--inventory` output that justifies it. The precedent for the other direction is -`textinput.rs`: plain `extern "C"`, justified in its module doc by all 14 inventories exporting the -whole `SDL_*TextInput*` family. +`rust-modules/shell-sdl/src/sys.rs`: plain `extern "C"` (the `SDL_*TextInput*` calls among them), +justified in its module doc by all 14 inventories exporting the whole SDL2 family it names. ## WHAT `fwcompat.py` NEEDS BEFORE IT WILL ANSWER — settle this first, not at your third command diff --git a/.agents/skills/ui-sim/SKILL.md b/.agents/skills/ui-sim/SKILL.md index 8d42232b2b..61885cbfab 100644 --- a/.agents/skills/ui-sim/SKILL.md +++ b/.agents/skills/ui-sim/SKILL.md @@ -80,7 +80,7 @@ state. Close other WSL work, run `wsl.exe --shutdown`, and retry; accept the run `use_gfxredir = 1`. **Ask for `SIM_W=1920 SIM_H=1080` on any shot you intend to JUDGE.** The window is otherwise sized -to fit the display (`app::boot::plan_desktop_window`), and on a 1x screen that divisor lands on 2, so +to fit the display (`plx_shell_sdl::window::plan_desktop_window`), and on a 1x screen that divisor lands on 2, so every screenshot comes back 960x540 — half the canvas the UI is authored at. A 1px edge-sheen, a hairline, a snapped glyph and a specular rim are exactly the things that do not survive that halving, which makes a shot at the default size evidence about layout and nothing else. The size is diff --git a/.agents/skills/which-tier/SKILL.md b/.agents/skills/which-tier/SKILL.md index ade82bff39..0273f40d24 100644 --- a/.agents/skills/which-tier/SKILL.md +++ b/.agents/skills/which-tier/SKILL.md @@ -80,7 +80,7 @@ but a photograph could show it (`gfx.rs`, at the `glBlendFuncSeparate` call). ### Tier 1 — `make check` -`cargo +$(RUST_TOOLCHAIN) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_owp`, preceded by `make lint` (three **named** clippy lints — +`cargo +$(RUST_TOOLCHAIN) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp`, preceded by `make lint` (three **named** clippy lints — `ifs_same_cond`, `same_functions_in_if_condition`, `if_same_then_else` — the shadowed-branch gate), and followed by **three** host checks that are easy to forget are in here: `python3 ci/flavor.py --selftest` (the flavour transform, whose central assertion is that the STABLE transform is the @@ -108,7 +108,7 @@ lock.) Do not write a new number here: measure it if you need one — this file Count it yourself if you need the number: ```sh -cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_owp -- --list | grep -c ': test' +cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp -- --list | grep -c ': test' ``` **Run it on the pinned toolchain.** `make check` uses `cargo +$(RUST_TOOLCHAIN)`, the `channel` of diff --git a/.claude/hooks/release-config-check-test.py b/.claude/hooks/release-config-check-test.py index 134742b1a2..c0f51c84e5 100755 --- a/.claude/hooks/release-config-check-test.py +++ b/.claude/hooks/release-config-check-test.py @@ -77,6 +77,7 @@ def edit(path, tool="Edit", key="file_path", **extra): (FIRE, "the media layer crate\\'s source", edit("/repo/rust-modules/media/src/player/mod.rs"), ROOT), (FIRE, "the appkit layer crate\\'s source", edit("/repo/rust-modules/appkit/src/player_hud/mod.rs"), ROOT), (FIRE, "the screens layer crate\\'s source", edit("/repo/rust-modules/screens/src/home/mod.rs"), ROOT), + (FIRE, "the shell_sdl layer crate's source", edit("/repo/rust-modules/shell-sdl/src/window.rs"), ROOT), (FIRE, "MultiEdit", edit("/repo/rust-modules/src/app/run.rs", tool="MultiEdit"), ROOT), (FIRE, "relative to root", edit("rust-modules/src/route.rs"), ROOT), (FIRE, "relative to a subdir", edit("src/plex/client.rs"), "/repo/rust-modules"), diff --git a/.claude/hooks/release-config-check.py b/.claude/hooks/release-config-check.py index 434e61775f..fd86d4c2a4 100755 --- a/.claude/hooks/release-config-check.py +++ b/.claude/hooks/release-config-check.py @@ -273,7 +273,7 @@ def rust_src_target(payload, root, cwd=None): src = os.path.realpath(os.path.join(root, "rust-modules", "src")) # The layer crates split out of `src` (docs/module-layers.md) are compiled by the same # `cargo check --lib` as a dependency, so an edit there is a release-configuration risk too. - layer_srcs = [os.path.realpath(os.path.join(root, "rust-modules", layer, "src")) for layer in ("base", "machine", "net", "os", "gfx", "ui", "plex", "telemetry", "data", "session", "media", "appkit", "screens")] + layer_srcs = [os.path.realpath(os.path.join(root, "rust-modules", layer, "src")) for layer in ("base", "machine", "net", "os", "gfx", "ui", "plex", "telemetry", "data", "session", "media", "appkit", "screens", "shell-sdl")] if not any(path.startswith(s + os.sep) for s in [src] + layer_srcs): return None # `--lib` compiles no bin target, and `sim.rs` needs `hostsim`, which the release set never has. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3e220bbe9d..dddcfbbb35 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -259,7 +259,7 @@ jobs: # (`cargo metadata` resolves; it compiles nothing), plus an informational line count. # The binary-size budget runs in cross-build, where the binary exists. Limits and how to # raise one deliberately: ci/build-budgets.json, docs/agent-reference.md. - run: python3 ci/check-build-budgets.py --graph --src rust-modules/src --src rust-modules/base/src --src rust-modules/machine/src --src rust-modules/net/src --src rust-modules/os/src --src rust-modules/gfx/src --src rust-modules/ui/src --src rust-modules/plex/src --src rust-modules/telemetry/src --src rust-modules/data/src --src rust-modules/session/src --src rust-modules/media/src --src rust-modules/playback-contract/src --src rust-modules/media-codecs/src --src rust-modules/play-feed/src --src rust-modules/play-uri/src --src rust-modules/appkit/src --src rust-modules/screens/src --src rust-modules/owp/src + run: python3 ci/check-build-budgets.py --graph --src rust-modules/src --src rust-modules/base/src --src rust-modules/machine/src --src rust-modules/net/src --src rust-modules/os/src --src rust-modules/gfx/src --src rust-modules/ui/src --src rust-modules/plex/src --src rust-modules/telemetry/src --src rust-modules/data/src --src rust-modules/session/src --src rust-modules/media/src --src rust-modules/playback-contract/src --src rust-modules/media-codecs/src --src rust-modules/play-feed/src --src rust-modules/play-uri/src --src rust-modules/appkit/src --src rust-modules/screens/src --src rust-modules/shell-sdl/src --src rust-modules/owp/src - name: Third-party notices vs the ARM runtime graph # `make check` runs only the OFFLINE half of this (ci/gen-third-party-notices.py --check), which @@ -310,7 +310,7 @@ jobs: # for plxnative-modules both ways), so the `cargo test --lib` below finds everything built # and this step is where the compile happens, not an extra one. The upload below carries it. shell: bash - run: cd rust-modules && cargo "+$RUST_TOOLCHAIN" test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_owp --no-run --timings + run: cd rust-modules && cargo "+$RUST_TOOLCHAIN" test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp --no-run --timings - name: make check-cargo-unit-default # Teed to a file so the size step below can read the `test result:` lines this run already diff --git a/Makefile b/Makefile index c14578a7fd..53d3663235 100644 --- a/Makefile +++ b/Makefile @@ -1050,7 +1050,7 @@ $(FFABI_STAMP): ci/ffabi-assert.c $(FFMPEG_INC)/libavformat/avformat.h Makefile # rule would leave every later `make` linking a library built by the OLD one. Cargo's own # `rerun-if-changed` cannot save that — it is only consulted when make decides to invoke cargo at # all, and this target is an ordinary timestamp comparison. -RUST_INPUTS := $(shell find rust-modules/src rust-modules/base rust-modules/machine rust-modules/net rust-modules/os rust-modules/gfx rust-modules/ui rust-modules/plex rust-modules/telemetry rust-modules/data rust-modules/session rust-modules/media rust-modules/playback-contract rust-modules/play-uri rust-modules/play-feed rust-modules/media-codecs rust-modules/appkit rust-modules/screens rust-modules/build_support locales assets -type f 2>/dev/null) +RUST_INPUTS := $(shell find rust-modules/src rust-modules/base rust-modules/machine rust-modules/net rust-modules/os rust-modules/gfx rust-modules/ui rust-modules/plex rust-modules/telemetry rust-modules/data rust-modules/session rust-modules/media rust-modules/playback-contract rust-modules/play-uri rust-modules/play-feed rust-modules/media-codecs rust-modules/appkit rust-modules/screens rust-modules/shell-sdl rust-modules/build_support locales assets -type f 2>/dev/null) $(RUST_LIB): LICENSE $(RUST_INPUTS) rust-modules/Cargo.toml rust-modules/Cargo.lock rust-modules/build.rs ci/install-identities.json rust-modules/.cargo/config.toml Makefile ci/check-staticlib-artifact.py $(FFABI_STAMP) @# BEFORE the mkdir: the seed is only ever cloned into a target dir that does not exist yet. $(CARGO_SEED) restore $(RUST_TDIR) rust-modules/$(RUST_TDIR) @@ -1717,7 +1717,7 @@ check-cargo-lint: lint @# gate has nothing to reuse a cache for. No `pkg/lab.json` is involved — that file is `make @# LAB=1`'s requirement (a live session secret), not the compiler's. @set -e; cd rust-modules && CARGO_INCREMENTAL=0 PATH="$$HOME/.cargo/bin:$$PATH" \ - cargo +$(RUST_TOOLCHAIN) check --lib --tests -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_owp --features lab-diagnostics + cargo +$(RUST_TOOLCHAIN) check --lib --tests -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp --features lab-diagnostics @# And the demo-video dump build's pixel oracle, `placeholder-sentinel`: in no default set and @# built only by `make site-video-sim`, which no gate runs and which compiles no `plx_ui` tests, so @# this line is what keeps it compiling (its code AND its tests, `--tests`). `plx_ui` is the only @@ -1736,7 +1736,7 @@ check-cargo-lint: lint # `-p` lists in the recipes below (those stay literal because ci/test_ci_split.py greps for them); # 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_os 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 plx_owp +UNIT_SUITE = plxnative-modules plx_base plx_machine plx_os 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 plx_shell_sdl plx_owp # 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 eight that # do not (plx_net, plx_ui, plx_appkit, plx_screens, plx_media_codecs, plx_play_uri, plx_playback_contract, @@ -1748,7 +1748,7 @@ UNIT_SUITE = plxnative-modules plx_base plx_machine plx_os plx_gfx plx_net plx_u # 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_os plx_gfx plx_plex plx_telemetry plx_data plx_session plx_media plx_play_feed +HOSTSIM_SUITE = plxnative-modules plx_base plx_machine plx_os plx_gfx plx_plex plx_telemetry plx_data plx_session plx_media plx_play_feed plx_shell_sdl # The default-feature unit suite and everything that drives cargo through ci/ self-tests. check-cargo-unit-default: @@ -1777,7 +1777,7 @@ check-cargo-unit-default: 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_os -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 -p plx_owp + $(UNIT_RUN) -- cargo +$(RUST_TOOLCHAIN) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp RUST_TOOLCHAIN=$(RUST_TOOLCHAIN) python3 ci/test_storage_service_package.py cd rust-modules && PATH="$$HOME/.cargo/bin:$$PATH" cargo +$(RUST_TOOLCHAIN) test -p plxnative-storage --bin plxnative-storage @# The helper is its own package, so building it compiles no copy of the app library; this reads @@ -1811,7 +1811,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_os -p plx_gfx -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_play_feed --features hostsim + $(UNIT_RUN) -- cargo +$(RUST_TOOLCHAIN) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_play_feed -p plx_shell_sdl --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 @@ -1835,7 +1835,7 @@ test-fast: PATH="$$HOME/.cargo/bin:$$PATH" PLXNATIVE_RUNTIME_DIR="$$d" \ $(TELEMETRY_ENV) \ $(HOST_ENV) \ - $(UNIT_RUN) $(if $(T),--filter '$(T)') -- cargo +$(RUST_TOOLCHAIN) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_owp + $(UNIT_RUN) $(if $(T),--filter '$(T)') -- cargo +$(RUST_TOOLCHAIN) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp # `make test-crate C=plx_ui [T=filter] [DEPS=1]` -- build and run ONLY the named crate's lib tests, in # the same incremental `$(TEST_FAST_TDIR)` tree and with the same flags as `test-fast`, so the two @@ -2471,7 +2471,7 @@ SIM_SHOT ?= $(SIM_DIR)/shot.png # reason BOOT_SH exists for `run`/`run-stream`. # Size of the simulator's DRAWABLE in pixels, 1:1 on any pixel density (the window is ALLOW_HIGHDPI, so # on a Retina display it is half this many points; `fit_window_to_density` does the conversion). -# Empty = fit the display (see `plan_desktop_window`), which on a 1x screen is half the authored +# Empty = fit the display (see `plx_shell_sdl`'s `plan_desktop_window`), which on a 1x screen is half the authored # canvas and therefore half the resolution of every screenshot. Set both to look at the UI the # size it is drawn: # make sim-shot SIM_W=1920 SIM_H=1080 diff --git a/ci/build-budgets.json b/ci/build-budgets.json index d72fb5a550..f6667386e9 100644 --- a/ci/build-budgets.json +++ b/ci/build-budgets.json @@ -48,7 +48,7 @@ "headroom": "+3" }, "source_lines": { - "what": "Lines of Rust under rust-modules/src, rust-modules/base/src, rust-modules/machine/src, rust-modules/net/src, rust-modules/os/src, rust-modules/gfx/src, rust-modules/ui/src, rust-modules/plex/src, rust-modules/telemetry/src, rust-modules/data/src, rust-modules/session/src, rust-modules/media/src, rust-modules/playback-contract/src, rust-modules/media-codecs/src, rust-modules/play-feed/src, rust-modules/play-uri/src, rust-modules/appkit/src, rust-modules/screens/src and rust-modules/owp/src (every .rs file). Informational: exceeding it warns and never fails, because a growing feature is not a build-health defect by itself.", + "what": "Lines of Rust under rust-modules/src, rust-modules/base/src, rust-modules/machine/src, rust-modules/net/src, rust-modules/os/src, rust-modules/gfx/src, rust-modules/ui/src, rust-modules/plex/src, rust-modules/telemetry/src, rust-modules/data/src, rust-modules/session/src, rust-modules/media/src, rust-modules/playback-contract/src, rust-modules/media-codecs/src, rust-modules/play-feed/src, rust-modules/play-uri/src, rust-modules/appkit/src, rust-modules/screens/src, rust-modules/shell-sdl/src and rust-modules/owp/src (every .rs file). Informational: exceeding it warns and never fails, because a growing feature is not a build-health defect by itself.", "unit": "lines", "mode": "warn", "limit": 485000, diff --git a/ci/check-build-budgets.py b/ci/check-build-budgets.py index 6ea4444a9e..b2c2d3fe0e 100755 --- a/ci/check-build-budgets.py +++ b/ci/check-build-budgets.py @@ -15,7 +15,7 @@ * binary_bytes the stripped binary `make ipk` stages (measured in the cross-build job) * packages_* third-party packages the app crate compiles for the ARM target * duplicate_versions_* crate names in more than one version on the normal-edge graph -* source_lines lines of Rust in rust-modules/src and every split-out layer crate (rust-modules/base/src, rust-modules/machine/src, rust-modules/net/src, rust-modules/os/src, rust-modules/gfx/src, rust-modules/ui/src, rust-modules/plex/src, rust-modules/telemetry/src, rust-modules/data/src, rust-modules/session/src, rust-modules/media/src, rust-modules/playback-contract/src, rust-modules/media-codecs/src, rust-modules/play-feed/src, rust-modules/play-uri/src, rust-modules/appkit/src, rust-modules/screens/src, rust-modules/owp/src); mode "warn", never fails +* source_lines lines of Rust in rust-modules/src and every split-out layer crate (rust-modules/base/src, rust-modules/machine/src, rust-modules/net/src, rust-modules/os/src, rust-modules/gfx/src, rust-modules/ui/src, rust-modules/plex/src, rust-modules/telemetry/src, rust-modules/data/src, rust-modules/session/src, rust-modules/media/src, rust-modules/playback-contract/src, rust-modules/media-codecs/src, rust-modules/play-feed/src, rust-modules/play-uri/src, rust-modules/appkit/src, rust-modules/screens/src, rust-modules/shell-sdl/src, rust-modules/owp/src); mode "warn", never fails Exit status: 0 all within budget (warn-mode overruns print ::warning::), 1 a fail-mode budget is exceeded, 2 the budgets file or an input is unusable. @@ -243,7 +243,7 @@ def main(argv=None) -> int: ap.add_argument("--graph", action="store_true") ap.add_argument("--tree-default") ap.add_argument("--tree-no-default") - ap.add_argument("--src", action="append", help="a source directory to count; repeat for each crate (rust-modules/src, rust-modules/base/src, rust-modules/machine/src, rust-modules/net/src, rust-modules/os/src, rust-modules/gfx/src, rust-modules/ui/src, rust-modules/plex/src, rust-modules/telemetry/src, rust-modules/data/src, rust-modules/session/src, rust-modules/media/src, rust-modules/playback-contract/src, rust-modules/media-codecs/src, rust-modules/play-feed/src, rust-modules/play-uri/src, rust-modules/appkit/src, rust-modules/screens/src, rust-modules/owp/src)") + ap.add_argument("--src", action="append", help="a source directory to count; repeat for each crate (rust-modules/src, rust-modules/base/src, rust-modules/machine/src, rust-modules/net/src, rust-modules/os/src, rust-modules/gfx/src, rust-modules/ui/src, rust-modules/plex/src, rust-modules/telemetry/src, rust-modules/data/src, rust-modules/session/src, rust-modules/media/src, rust-modules/playback-contract/src, rust-modules/media-codecs/src, rust-modules/play-feed/src, rust-modules/play-uri/src, rust-modules/appkit/src, rust-modules/screens/src, rust-modules/shell-sdl/src, rust-modules/owp/src)") args = ap.parse_args(argv) try: budgets = load_budgets(Path(args.budgets)) diff --git a/ci/check-deps.sh b/ci/check-deps.sh index 8ebbf38ce1..d52975a4f6 100755 --- a/ci/check-deps.sh +++ b/ci/check-deps.sh @@ -152,6 +152,7 @@ SRC_MEDIA_CODECS=rust-modules/media-codecs/src SRC_APPKIT=rust-modules/appkit/src SRC_SCREENS=rust-modules/screens/src SRC_OWP=rust-modules/owp/src +SRC_SHELL_SDL=rust-modules/shell-sdl/src fails=0 fail() { echo "::error::check-deps: $*"; fails=$((fails+1)); } ok() { echo " ok — $*"; } @@ -353,6 +354,7 @@ wholly_test_files() { python3 ci/rust_test_modules.py "$SRC_APPKIT" python3 ci/rust_test_modules.py "$SRC_SCREENS" python3 ci/rust_test_modules.py "$SRC_OWP" + python3 ci/rust_test_modules.py "$SRC_SHELL_SDL" } # is_wholly_test : the `wholly_test` list as a builtin lookup. Three gates below asked this @@ -720,7 +722,7 @@ fi # metadata-owner # 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_OS" "$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" "$SRC_OWP" \ +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_OS" "$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" "$SRC_OWP" "$SRC_SHELL_SDL" \ | grep -vE '\.log\((&|")' | grep -v "^$SRC_MACHINE/motion.rs:") libm_bad=0 while IFS= read -r line; do @@ -732,7 +734,7 @@ 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 -want ticks && gate ticks 'SDL_GetTicks\(' "$SRC" "$SRC_BASE" "$SRC_OS" "$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" "$SRC_OWP" +want ticks && gate ticks 'SDL_GetTicks\(' "$SRC" "$SRC_BASE" "$SRC_OS" "$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" "$SRC_OWP" "$SRC_SHELL_SDL" # 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 @@ -750,7 +752,7 @@ if [ "$n" -eq 1 ] && [ "$d" -eq 1 ]; then ok "present: one worker door"; else fa fi # present if want effect; then -if [ -n "$(grep_code '\bEffect::' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$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" "$SRC_OWP")" ]; then fail "effect: \`Effect::\` is spelled (use Fx:: / AppFx::)"; else ok "effect"; fi +if [ -n "$(grep_code '\bEffect::' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$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" "$SRC_OWP" "$SRC_SHELL_SDL")" ]; 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 @@ -862,7 +864,7 @@ want nav && gate nav '(crate::ui|plx_ui)::nav::' "$SRC" "$SRC_UI" "$SRC_APPKIT" # 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_OS" "$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" "$SRC_OWP") +ui_owner_hits=$(grep_code '(plx_ui|crate::ui)::press::|(plx_machine|crate)::idle::' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$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" "$SRC_OWP" "$SRC_SHELL_SDL") 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" @@ -962,7 +964,7 @@ want uistorage && gate uistorage '(crate|super|plx_os)::storage::' "$SRC_UI" "$S # 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_OS" "$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" "$SRC_OWP" 2>/dev/null || true) +legacy_hits=$(grep -rn --include='*.rs' 'LegacyPage' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$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" "$SRC_OWP" "$SRC_SHELL_SDL" 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)" @@ -1056,7 +1058,7 @@ fi # textmeasure # 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_OS" "$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" "$SRC_OWP" | grep -v "^$SRC_MACHINE/motion.rs:") +dt_hits=$(grep_code 'idle::dt\(\)|(\+=|-=)\s*dt\b' "$SRC" "$SRC_MACHINE" "$SRC_OS" "$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" "$SRC_OWP" "$SRC_SHELL_SDL" | 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" @@ -1134,7 +1136,7 @@ while IFS= read -r f; do # REMOVES matches, so a file with no raw hit cannot fail this gate — and running its `awk` plus a # `grep` over all 420 files, to reach the two that mention the shape, was the single most expensive # rule in this script (4.8 s of its 17 s). -done < <(grep -rlE --include='*.rs' "$frame_pat" "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$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" "$SRC_OWP" 2>/dev/null | sort) +done < <(grep -rlE --include='*.rs' "$frame_pat" "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$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" "$SRC_OWP" "$SRC_SHELL_SDL" 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 @@ -1159,7 +1161,7 @@ while IFS= read -r line; do case "$p" in "$SRC_MEDIA"/player/*|"$SRC_OS"/tv/*|"$SRC_OS"/tv.rs|"$SRC_OS"/webos/*|"$SRC"/port.rs|"$SRC"/platform_desktop.rs|"$SRC"/app/adapters/backends.rs) continue ;; esac if is_wholly_test "$p"; then continue; fi echo " $line"; sink_bad=$((sink_bad+1)) -done < <(grep_code 'tv::sink::(installed|display_installed)|\b(VideoSink|DisplaySink)\b' "$SRC" "$SRC_OS" "$SRC_UI" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP") +done < <(grep_code 'tv::sink::(installed|display_installed)|\b(VideoSink|DisplaySink)\b' "$SRC" "$SRC_OS" "$SRC_UI" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" "$SRC_SHELL_SDL") if [ "$sink_bad" -eq 0 ]; then ok "sink" else fail "sink: $sink_bad line(s) naming the video sink outside playback execution, port.rs, platform_desktop.rs, tv.rs and tv/"; fi fi # sink @@ -1258,7 +1260,7 @@ while IFS= read -r f; do { print NR":"$0; prev=$0 }' "$f" | grep -E "$pat" | grep -vE '^[0-9]+:\s*//' || true) # ...over the files that spell `spawn(` at all — a superset of both matched spellings, and the `awk` # below only drops `#[cfg(test)] mod` blocks, so the count is unchanged. -done < <(grep -rlE --include='*.rs' '\bspawn\(' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$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" "$SRC_OWP" 2>/dev/null | grep -v "^$SRC_BASE/task.rs\$" | sort) +done < <(grep -rlE --include='*.rs' '\bspawn\(' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$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" "$SRC_OWP" "$SRC_SHELL_SDL" 2>/dev/null | grep -v "^$SRC_BASE/task.rs\$" | sort) 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 @@ -1403,7 +1405,7 @@ EOF_STALE # `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_OS" "$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" "$SRC_OWP" 2>/dev/null \ + grep -rlE --include='*.rs' 'allow_blocking' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$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" "$SRC_OWP" "$SRC_SHELL_SDL" 2>/dev/null \ | grep -v "^$SRC_BASE/task/blocking.rs\$" | sort \ | LG_MODE=call LG_SITE='(^|[^A-Za-z0-9_])allow_blocking\(' LG_DEF='fn[[:space:]]+allow_blocking\(' \ LG_REF='(^|[^A-Za-z0-9_])allow_blocking([^A-Za-z0-9_(]|$)' LG_REEXPORT_FILE="$SRC_BASE/task.rs" \ @@ -1655,7 +1657,7 @@ fi # fxlanes # 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_OS" "$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" "$SRC_OWP" <<'PY' +tmp_hits=$(python3 - "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$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" "$SRC_OWP" "$SRC_SHELL_SDL" <<'PY' import os, sys src = sys.argv[1] @@ -1756,7 +1758,7 @@ fi # tmppath # 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_OS" "$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" "$SRC_OWP" <<'PY' +paging_hits=$(WHOLLY_TEST="$wholly_test" python3 - "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$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" "$SRC_OWP" "$SRC_SHELL_SDL" <<'PY' import os, sys sys.path.insert(0, "ci") from rust_test_modules import close, lex diff --git a/ci/list-caps.ini b/ci/list-caps.ini index 1972afd6ce..c9066e8348 100644 --- a/ci/list-caps.ini +++ b/ci/list-caps.ini @@ -998,6 +998,32 @@ reason = Generations of a PIN-poll supersede counter. class = not-a-list reason = Distinct incident keys a launch remembers; state-growth guard on the closed kind-by-link space. +# ---- shell-sdl ------------------------------------------------------------ + +[shell-sdl/src/event.rs::SYNTH_WINDOW] +class = not-a-list +reason = SYNTH_WINDOW: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. + +[shell-sdl/src/text.rs::TEXT_CAP] +class = not-a-list +reason = TEXT_CAP: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. + +[shell-sdl/src/text.rs::drop_cut_tail] +class = not-a-list +reason = drop_cut_tail: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. + +[shell-sdl/src/window.rs::SDL_WINDOW_ALLOW_HIGHDPI] +class = not-a-list +reason = SDL_WINDOW_ALLOW_HIGHDPI: one window-flag bit of SDL's own (the desktop window asks for the display's pixel density), not a count and not a list the user browses. + +[shell-sdl/src/window.rs::SDL_WINDOW_FLAGS] +class = not-a-list +reason = SDL_WINDOW_FLAGS: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. + +[shell-sdl/src/window.rs::SDL_WINDOW_INPUT_FOCUS] +class = not-a-list +reason = SDL_WINDOW_INPUT_FOCUS: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. + # ---- src ------------------------------------------------------------ [src/app/adapters/poster.rs::AHEAD_MAX] @@ -1060,18 +1086,6 @@ reason = LEFT_ROWS: application/dev tooling bound (scenario period, text input b class = not-a-list reason = RIGHT_ROWS: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. -[src/app/events.rs::SYNTH_WINDOW] -class = not-a-list -reason = SYNTH_WINDOW: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. - -[src/app/mod.rs::SDL_WINDOW_FLAGS] -class = not-a-list -reason = SDL_WINDOW_FLAGS: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. - -[src/app/mod.rs::SDL_WINDOW_INPUT_FOCUS] -class = not-a-list -reason = SDL_WINDOW_INPUT_FOCUS: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. - [src/app/run.rs::log_raw_input_event] class = not-a-list reason = log_raw_input_event: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. @@ -1116,14 +1130,6 @@ reason = MAX_WAIT_MS: application/dev tooling bound (scenario period, text input class = not-a-list reason = MAX_PENDING: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. -[src/textinput.rs::TEXT_CAP] -class = not-a-list -reason = TEXT_CAP: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. - -[src/textinput.rs::drop_cut_tail] -class = not-a-list -reason = drop_cut_tail: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. - # ---- telemetry ------------------------------------------------------------ [telemetry/src/diag/mod.rs::DEFERRED_CAP] diff --git a/ci/module-layers.ini b/ci/module-layers.ini index 00325a7bd3..6a590599ba 100644 --- a/ci/module-layers.ini +++ b/ci/module-layers.ini @@ -73,6 +73,20 @@ members = webos storage keymanager devcaps imgcache i18n labcfg tv playback_trac uses = base machine os members = gfx egl text rtl img svg gpu_timer hwcnt overdraw dump +[shell_sdl] +# EXTRACTED: this layer is the workspace crate `plx_shell_sdl` (rust-modules/shell-sdl/); ci/module_graph.py +# reads it as part of the same module tree through the manifest's `mount = "shell_sdl"` (a path +# `plx_shell_sdl::event::decode` names module `shell_sdl::event`), like `plx_play_uri`. +# The stock-SDL shell the application opens its window through: SDL's init, the window and its GL context, +# the swap, the event queue, the stock layouts of the key, pointer, wheel and text events, and the synthetic +# events pushed back onto the queue. It names no `ui`, no application type and none of [platform webos]; the +# application drives it through its own `Shell` and `Surface` (`app::platform`), and the television's LG half +# (the SysWMinfo handshake, the Wayland surface, the boot hooks around `SDL_Init`) stays in `system`. The crate +# names nothing of `machine` or `os` today, so it depends on `plx_base` only; the ceiling stays (the same +# ruling `[gfx]` records for `os`). +uses = base machine os +members = shell_sdl + [net] # EXTRACTED: this layer is the workspace crate `plx_net` (rust-modules/net/), the fifth split of # docs/module-layers.md; ci/module_graph.py reads it as part of the same module tree (a path @@ -188,7 +202,7 @@ members = screens [app] # The loop, its adapters and every dev/diagnostic surface; lib.rs's own items are the facade. -uses = base machine os gfx net plex telemetry ui data session media appkit screens playback_contract play_uri play_feed media_codecs +uses = base machine os gfx net plex telemetry ui data session media appkit screens shell_sdl playback_contract play_uri play_feed media_codecs members = crate app dev lab capture remote focusprobe hud_cli hud_tools shot coldstart textinput system release_line port platform_desktop diff --git a/ci/proofs/platform-generated-enums.json b/ci/proofs/platform-generated-enums.json index 37bed563b4..07f6a9b69b 100644 --- a/ci/proofs/platform-generated-enums.json +++ b/ci/proofs/platform-generated-enums.json @@ -30,10 +30,10 @@ } }, "include": "include!(concat!(env!(\"OUT_DIR\"), \"/languages.rs\"));", - "lock": "4c8ae319c8db665085f3fe744a30ae925f744feba2e64c3c38de51a94d762b16", + "lock": "800367e4065771c60d1fe5c722e209b2483247a620f382b2248e150bf00b3ad0", "machine_newtype": "reviewed local newtype macro emits pub struct Name(pub u32); doc attributes only", "manifests": { - "Cargo.toml": "1143141629f93032567e2cbf0e119ec0e4381ff32ea84f27f458ae661d715f31", + "Cargo.toml": "29fddc70ec0a893de909e79eea1ea5afc615cf43ccdb1a194bc2cce0094a31e3", "appkit/Cargo.toml": "5cc1214cba7746fe0f2d4cfa5047b599e0d5124abe7bdaebe210381021b88c4a", "base/Cargo.toml": "ebe0b95553bd44f33f422f7d8e22b75ddeb53c7ee81bbe738f675690694568f7", "data/Cargo.toml": "74f79e6240f0965069ec34916ae276b3f7e5f4b944cf16a0846570a6b115afa0", @@ -50,6 +50,7 @@ "plex/Cargo.toml": "5cdb185265b7f7217cff08e54ef683a827735c9b3ae7c50161850f7064667b66", "screens/Cargo.toml": "cd42484a49fac394244ebc7b81f30f7e4f9a31cdf7bc1ace5c3fae21afd6d511", "session/Cargo.toml": "ecb49fc9f44177be6de36715ad70845b8929799cdbeb5ce9d6939be741704db0", + "shell-sdl/Cargo.toml": "357aebbf4a32c5b87154d6b91e3cc1ffb105154e974e536b92c61106b0460c14", "storage/Cargo.toml": "4b8576b04a5877e95d084a49a16b30224c275ae29b4a192c40725ac819500150", "telemetry/Cargo.toml": "9e514e64ae4a35619294621f22534b5e5b109d9dd3b729b94ed20112f47197bf", "ui/Cargo.toml": "7375c6a73cb2558c7c0f62da7b0bd4beb2a5b78f5460ee35e93b1045c0e80eec" diff --git a/ci/proofs/serde-json-immutable.json b/ci/proofs/serde-json-immutable.json index 567f2930e1..507c82a757 100644 --- a/ci/proofs/serde-json-immutable.json +++ b/ci/proofs/serde-json-immutable.json @@ -371,9 +371,9 @@ ".cargo/config": null, ".cargo/config.toml": "82f061c716740e16cfee63a74d87159e0e0dc253e1092b87c54190c603515b14" }, - "lock_sha256": "4c8ae319c8db665085f3fe744a30ae925f744feba2e64c3c38de51a94d762b16", + "lock_sha256": "800367e4065771c60d1fe5c722e209b2483247a620f382b2248e150bf00b3ad0", "manifests": { - "Cargo.toml": "1143141629f93032567e2cbf0e119ec0e4381ff32ea84f27f458ae661d715f31", + "Cargo.toml": "29fddc70ec0a893de909e79eea1ea5afc615cf43ccdb1a194bc2cce0094a31e3", "appkit/Cargo.toml": "5cc1214cba7746fe0f2d4cfa5047b599e0d5124abe7bdaebe210381021b88c4a", "base/Cargo.toml": "ebe0b95553bd44f33f422f7d8e22b75ddeb53c7ee81bbe738f675690694568f7", "data/Cargo.toml": "74f79e6240f0965069ec34916ae276b3f7e5f4b944cf16a0846570a6b115afa0", @@ -390,6 +390,7 @@ "plex/Cargo.toml": "5cdb185265b7f7217cff08e54ef683a827735c9b3ae7c50161850f7064667b66", "screens/Cargo.toml": "cd42484a49fac394244ebc7b81f30f7e4f9a31cdf7bc1ace5c3fae21afd6d511", "session/Cargo.toml": "ecb49fc9f44177be6de36715ad70845b8929799cdbeb5ce9d6939be741704db0", + "shell-sdl/Cargo.toml": "357aebbf4a32c5b87154d6b91e3cc1ffb105154e974e536b92c61106b0460c14", "storage/Cargo.toml": "4b8576b04a5877e95d084a49a16b30224c275ae29b4a192c40725ac819500150", "telemetry/Cargo.toml": "9e514e64ae4a35619294621f22534b5e5b109d9dd3b729b94ed20112f47197bf", "ui/Cargo.toml": "7375c6a73cb2558c7c0f62da7b0bd4beb2a5b78f5460ee35e93b1045c0e80eec" diff --git a/ci/readonly_dependencies.py b/ci/readonly_dependencies.py index ba17d3b914..fe935df6d1 100644 --- a/ci/readonly_dependencies.py +++ b/ci/readonly_dependencies.py @@ -18,7 +18,7 @@ import tarfile CERTIFICATE_PATH = Path(__file__).with_name('proofs') / 'serde-json-immutable.json' -CERTIFICATE_SHA256 = '47228bf8faff2b162797c50c24d9516efb67ba2f2be928be16f0bb722132fec9' +CERTIFICATE_SHA256 = '1e9efc0c1a9f21baed52d0973d76560d4d68a9c5fe6d35322a7b7add95458d8d' 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 a2acdad80a..32097e0897 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 = '55e6b3ace139479c22ac26a81134a934daafd9bff6f1db53beae24c619d7a718' +CERTIFICATE_SHA256 = '0840020f76498e3f973f9523cc4b00ab35dc82837b471f71b1c7efb3449e0c5d' SOURCES = ['os/Cargo.toml', 'os/src/lib.rs', 'os/src/i18n/mod.rs', 'os/build.rs', 'os/build_support/catalog.rs', 'build_support/install_identities.rs', 'machine/src/lib.rs', 'machine/src/machine.rs'] diff --git a/ci/test_build_bench.py b/ci/test_build_bench.py index 054a3f6355..db51bfc9b9 100644 --- a/ci/test_build_bench.py +++ b/ci/test_build_bench.py @@ -108,6 +108,7 @@ def art(pkg_path, name, version): art('/media-codecs', 'plx_media_codecs', '0.0.0') art('/appkit', 'plx_appkit', '0.0.0') art('/screens', 'plx_screens', '0.0.0') + art('/shell-sdl', 'plx_shell_sdl', '0.0.0') art('/owp', 'plx_owp', '0.0.0') art('', 'plxnative-modules', '0.7.0') elif args[0] == "rustc": diff --git a/ci/test_build_not_always_dirty.py b/ci/test_build_not_always_dirty.py index 81012b0934..53aeee5b5e 100644 --- a/ci/test_build_not_always_dirty.py +++ b/ci/test_build_not_always_dirty.py @@ -67,9 +67,9 @@ NIGHTLY = pinned() # the repo's one toolchain (historic name) -# The invocation `make check`'s lab line runs (Makefile, "cargo check --lib --tests -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_owp --features +# The invocation `make check`'s lab line runs (Makefile, "cargo check --lib --tests -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp --features # lab-diagnostics"); identical arguments and CARGO_INCREMENTAL make the first run here a reuse. -LIB_ARGS = ["check", "--lib", "--tests", "-p", "plxnative-modules", "-p", "plx_base", "-p", "plx_machine", "-p", "plx_os", "-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", "-p", "plx_owp", "--features", "lab-diagnostics"] +LIB_ARGS = ["check", "--lib", "--tests", "-p", "plxnative-modules", "-p", "plx_base", "-p", "plx_machine", "-p", "plx_os", "-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", "-p", "plx_shell_sdl", "-p", "plx_owp", "--features", "lab-diagnostics"] def cargo_env(): diff --git a/ci/test_ci_split.py b/ci/test_ci_split.py index 4e20b035b1..173fb1ebd0 100644 --- a/ci/test_ci_split.py +++ b/ci/test_ci_split.py @@ -55,16 +55,16 @@ def rule(target): # Each cargo gate, as a regex over a target's whole (comment-free) recipe, and the one target that # owns it. `lint` is a prerequisite rather than a recipe line, handled separately. GATES = { - "check-cargo-lint": [r"cargo \+\$\(RUST_TOOLCHAIN\) check --lib --tests -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_owp --features lab-diagnostics"], + "check-cargo-lint": [r"cargo \+\$\(RUST_TOOLCHAIN\) check --lib --tests -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp --features lab-diagnostics"], "check-cargo-unit-default": [ - r"cargo \+\$\(RUST_TOOLCHAIN\) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_owp\n", + r"cargo \+\$\(RUST_TOOLCHAIN\) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp\n", r"ci/test_storage_service_package\.py", r"test -p plxnative-storage --bin plxnative-storage", r"ci/test_storage_package_isolated\.py", 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_os -p plx_gfx -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_play_feed --features hostsim"], + "check-cargo-unit-hostsim": [r"cargo \+\$\(RUST_TOOLCHAIN\) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_play_feed -p plx_shell_sdl --features hostsim"], } diff --git a/ci/test_no_host_staticlib.py b/ci/test_no_host_staticlib.py index 4a763bb0c4..3fd00eec24 100644 --- a/ci/test_no_host_staticlib.py +++ b/ci/test_no_host_staticlib.py @@ -37,12 +37,12 @@ CRATE = "plxnative_modules" # The layer crates split out of the app crate (docs/module-layers.md), each a dependency of it and # each held to the same rule: an rlib, never an archive. One archive is linked, and it is the app's. -LAYER_CRATES = ("plx_base", "plx_machine", "plx_net", "plx_os", "plx_gfx", "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") +LAYER_CRATES = ("plx_base", "plx_machine", "plx_net", "plx_os", "plx_gfx", "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", "plx_shell_sdl") TOOLCHAIN = pinned() # the repo's one toolchain # What the workspace needs for cargo to resolve (not compile) the app package: the manifest and # lockfile, the `.cargo/config.toml` that cargo finds from the working directory, and the sources # the manifest names. A mutated copy replaces `Cargo.toml` only. -WORKSPACE_FILES = (".cargo", "Cargo.lock", "build.rs", "build_support", "src", "storage", "base", "machine", "net", "os", "gfx", "ui", "plex", "telemetry", "data", "session", "media", "playback-contract", "play-uri", "play-feed", "media-codecs", "appkit", "screens", "owp") +WORKSPACE_FILES = (".cargo", "Cargo.lock", "build.rs", "build_support", "src", "storage", "base", "machine", "net", "os", "gfx", "ui", "plex", "telemetry", "data", "session", "media", "playback-contract", "play-uri", "play-feed", "media-codecs", "appkit", "screens", "shell-sdl", "owp") def offences(unit_graph=None, metadata=None): diff --git a/ci/test_test_fast.py b/ci/test_test_fast.py index 6f89e3e378..0693cffe7e 100644 --- a/ci/test_test_fast.py +++ b/ci/test_test_fast.py @@ -162,7 +162,7 @@ def test_incremental_in_its_own_target_dir_and_forwards_the_filter(self): self.assertEqual(call["target_dir"], TDIR) self.assertTrue(call["cwd"].endswith("rust-modules"), call["cwd"]) self.assertEqual(call["runtime_dir_set"], "yes") - self.assertRegex(call["args"], r"^\+\S+ test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_owp --no-run --message-format=json-render-diagnostics$") + self.assertRegex(call["args"], r"^\+\S+ test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp --no-run --message-format=json-render-diagnostics$") # The filter goes to each test binary (the runner builds first, then runs), not to cargo. self.assertEqual(len(fake.bin_calls()), call["args"].split().count("-p")) self.assertTrue(all(line.endswith("args=route::") for line in fake.bin_calls()), fake.bin_calls()) @@ -171,7 +171,7 @@ def test_no_filter_runs_the_whole_default_feature_suite(self): with FakeCargoHome() as fake: self.assertEqual(fake.run("test-fast").returncode, 0) (call,) = fake.calls() - self.assertRegex(call["args"], r"^\+\S+ test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_owp --no-run --message-format=json-render-diagnostics$") + self.assertRegex(call["args"], r"^\+\S+ test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp --no-run --message-format=json-render-diagnostics$") self.assertNotIn("--features", call["args"]) self.assertEqual(len(fake.bin_calls()), call["args"].split().count("-p")) self.assertTrue(all(line.endswith("args=") for line in fake.bin_calls()), fake.bin_calls()) diff --git a/docs/agent-reference.md b/docs/agent-reference.md index 70bedc6cb6..5c89b4e93b 100644 --- a/docs/agent-reference.md +++ b/docs/agent-reference.md @@ -221,7 +221,7 @@ the pinned Sentry Native cross-build), and `sshpass` (Homebrew; deploy/run use y what the user can reach, which is the only class that is tracked rather than accepted; `--sites` lists every hit with its class. 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_os -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 -p plx_owp` + `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_os -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 -p plx_shell_sdl -p plx_owp` **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`, `plx_playback_contract` and `plx_owp`, which have no `hostsim` cfg and run the @@ -267,7 +267,7 @@ the pinned Sentry Native cross-build), and `sshpass` (Homebrew; deploy/run use y SDL event loop where no host test can see it. Needs the **clippy component of the pinned toolchain** (`make setup-rust` installs it with `--profile minimal --component clippy`). - `make test-fast [T=filter]` — **opt-in** incremental inner loop: the same default-feature - `cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_owp` as `check-cargo-unit-default` (throwaway runtime root, telemetry env), but + `cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp` as `check-cargo-unit-default` (throwaway runtime root, telemetry env), but with `CARGO_INCREMENTAL=1` in its own `rust-modules/target-fast` (gitignored). `T=route::` is the test-name filter, handed to every one of the per-crate test binaries; each prints its own libtest `test result:` line (the counts are per crate, never one total), followed by the wrapper's summary line. Use it for a long series of @@ -383,12 +383,12 @@ the pinned Sentry Native cross-build), and `sshpass` (Homebrew; deploy/run use y - **CI build health** — four tools keep the build from growing unnoticed, and none of them is a device gate. - *Timings artifact.* `host-unit-default` compiles the test binary in its own step with - `cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_owp --no-run --timings`, then `make check-cargo-unit-default` runs against what that + `cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp --no-run --timings`, then `make check-cargo-unit-default` runs against what that built (`--timings` is not part of cargo's fingerprint: checked 2026-10-02 by building with and without it and getting `Fresh` for `plxnative-modules` both ways, so the step moves the compile rather than adding one). Download `cargo-timings-host-unit-default` from the run page ("Artifacts", kept 14 days) and open `cargo-timing.html`: it names the crates on the critical - path. Locally: `cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_owp --no-run --timings` writes + path. Locally: `cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp --no-run --timings` writes `target/cargo-timings/cargo-timing.html`. - *Trends.* `tools/ci-durations.py [--runs 30] [--recent 5] [--json]` reads the last 30 successful `main` runs of CI and Simulator CI through `gh api` and prints, per job, the median and p90 and @@ -464,7 +464,7 @@ the pinned Sentry Native cross-build), and `sshpass` (Homebrew; deploy/run use y before/after table instead of an ad-hoc scratch-script number. It prints a Markdown table (median / min / max over `--runs`, default 3, the scenarios interleaved round by round) and, with `--json`, a machine-readable document (git sha, `rustc -V` of the pinned toolchain, host, per-run load and swap). Rows: - a **no-op** host test build (`cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_owp --no-run`; it reports from cargo's JSON `fresh` + a **no-op** host test build (`cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp --no-run`; it reports from cargo's JSON `fresh` flag whether the app crate was rebuilt and flags a recompile as UNEXPECTED, the `ci/test_build_not_always_dirty.py` hazard); an **edit-rebuild** after appending a comment to a leaf file of each crate (`plx_base`'s `cbuf.rs`, `plx_machine`'s `landgate.rs`, `plx_os`'s `devcaps.rs`, `plx_gfx`'s `overdraw.rs`, `plx_net`'s `stream_redirect.rs`, `plx_ui`'s `dwell.rs`, `plx_plex`'s `retry.rs`, `plx_telemetry`'s `window.rs`, `plx_data`'s `tape.rs`, `plx_session`'s `scripted.rs`, `plx_media`'s `units.rs`, `plx_appkit`'s `skip_pill.rs`, `plx_screens`'s `clock_readout.rs`, the application's `coldstart.rs`) and to a hub (`plx_ui`'s `lib.rs`), non-incremental (`CARGO_INCREMENTAL=0`, the @@ -943,7 +943,7 @@ the pinned Sentry Native cross-build), and `sshpass` (Homebrew; deploy/run use y rather than the only one — it catches the break before the push, and CI does not run in somebody else's checkout. It type-checks the bare `--no-default-features` set, which drops `play-uri` and `play-feed` too (a build with no playback backend), so it does not replace `make check-nodef`, which passes the Makefile's `RUST_BACKEND_FEATURES`. It type-checks after - every edit to a `rust-modules/src/**.rs` or one of the thirteen layer crates it lists (it does not watch `playback-contract`, `media-codecs`, + every edit to a `rust-modules/src/**.rs` or one of the fourteen layer crates it lists (it does not watch `playback-contract`, `media-codecs`, `play-feed` or `play-uri`, for which `make check-nodef` is the only gate that compiles them in the shipping set, nor `owp`, which the application does not link yet); it costs well under a second warm, because cargo keys fingerprints by feature set and the two configurations coexist in one `target/`. The hazard it guards is hand-written `#[cfg(feature = "devtriggers")]` PAIRS, where a spliced-in function @@ -1144,8 +1144,9 @@ glow, HUD widgets, seven-segment FPS) and a text shader that samples glyph textures (cached by string+size): SDL2_ttf renders every run except Arabic and Hebrew, which libass-plx shapes and rasterizes into the same texture (`gfx/src/rtl.rs`). Critically-damped springs animate focus scale and shelf scroll. -Fonts are the `appfont*.ttf` faces deployed next to the binary, in the fallback chain `gfx/src/text.rs` opens (Inter, CJK, emoji, Arabic, Hebrew; Inter, Arabic and Hebrew with bold cuts; `ci/test_shipped_faces.py` holds every staging list to it), so a missing libass-plx costs Arabic and Hebrew UI text as well as text subtitles; the subtitle renderer additionally loads the per-script Noto faces from `fonts/subs/` (`docs/ass-subtitles.md`, cut by `tools/cut-noto-subs.py`, staged by `SUBS_FONT_FILES` in the Makefile). (Wayland surface setup + -input decoding live in `system.rs` / `app/events.rs` + `app/input.rs`, not the C shim — see the gotchas below.) +Fonts are the `appfont*.ttf` faces deployed next to the binary, in the fallback chain `gfx/src/text.rs` opens (Inter, CJK, emoji, Arabic, Hebrew; Inter, Arabic and Hebrew with bold cuts; `ci/test_shipped_faces.py` holds every staging list to it), so a missing libass-plx costs Arabic and Hebrew UI text as well as text subtitles; the subtitle renderer additionally loads the per-script Noto faces from `fonts/subs/` (`docs/ass-subtitles.md`, cut by `tools/cut-noto-subs.py`, staged by `SUBS_FONT_FILES` in the Makefile). (The SDL window, the event decode and the text-input calls live in +`rust-modules/shell-sdl/` (crate `plx_shell_sdl`), the Wayland surface setup in `system.rs`, and the key ladders in +`app/events.rs` + `app/input.rs`, not the C shim — see the gotchas below.) **Video playback (summary — `rust-modules/media/src/player/CLAUDE.md` is the deep-dive: pipeline, threading model, the Starfish/ACB ABI + bind-order gotchas, seek/PTS rebase. Read it before @@ -1262,7 +1263,7 @@ every thin back-edge with `file:line` (the work list for breaking it up); `--dot `abnormal`, like a freeze's; one made after backgrounding (the PLX-NATIVE-1P shape) finds no open session, because backgrounding already ended it `exited` (`telemetry::session`), so only the `error` event exists. -- `rust-modules/src/` — the app core (Rust): `app/` (`mod.rs` the `run_application` shim + `struct App`, `boot.rs` the bring-up, `run.rs` the frame loop and its phase functions, `events.rs`/`input.rs` the input decode and key ladders, `lifecycle.rs`, `playback.rs`, `content.rs`, `bridge.rs` the seam onto the container and the ONE navigation vocabulary, `words.rs` the heartbeat's `route=`/`overlay=` alphabet — `nav.rs` is gone with `enum Route` since restructure phase 12), `system.rs` (wayland), +- `rust-modules/src/` — the app core (Rust): `app/` (`mod.rs` the `run_application` shim + `struct App`, `boot.rs` the bring-up, `run.rs` the frame loop and its phase functions, `events.rs`/`input.rs` the input decode and key ladders, `lifecycle.rs`, `playback.rs`, `content.rs`, `bridge.rs` the seam onto the container and the ONE navigation vocabulary, `words.rs` the heartbeat's `route=`/`overlay=` alphabet — `nav.rs` is gone with `enum Route` since restructure phase 12), `system.rs` (wayland), `rust-modules/shell-sdl/` (crate `plx_shell_sdl`: `SDL_Init`, the window, the GL swap, the event decode and the text-input calls, which `app/platform.rs`'s `Shell` opens as the app-private `Surface`), and, in the media layer (`rust-modules/media/`, crate `plx_media`, which the application links), `player/` (buffer-feed engine + worker threads — **`rust-modules/media/src/player/CLAUDE.md` is the playback deep-dive; read it before touching playback**), `abr/` and `route/`, and `ff.rs`, which @@ -1622,7 +1623,7 @@ every thin back-edge with `file:line` (the work list for breaking it up); `--dot the same leak by a shorter route. The escape hatch is a prefix on the command, and an agent reaching for it is doing the thing the hook exists to prevent. - **LG's SDL fork has a shifted `SDL_KeyboardEvent`.** `e.key.keysym` is unreliable; the handler - (`app.rs`, via `rd_u32`) reads raw bytes off the event: `+16` = state (u32), `+20` = webOS keycode + (`rust-modules/shell-sdl/src/event.rs`, via `rd_u32`) reads raw bytes off the event: `+16` = state (u32), `+20` = webOS keycode (u32), `+24` = sym (u32). State low byte = pressed(1)/released(0); bit `0x100` = auto-repeat. Magic-Remote buttons are matched by these `wcode`s (e.g. PAUSE=72, PLAY=450, BACK=461/482, stop=413, D-pad L/R alt 412/417; the wcodes live in `ui/consts.rs`, as `WCODE_*` — true of the L/R pair only @@ -1950,7 +1951,7 @@ behaviour; real GL copies, glyphs and presentation still need a device capture w There **is** a host unit suite, and it is not the real gate — both halves matter, and conflating 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_os -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 -p plx_owp` (a bare `cargo test --lib` runs the application crate only and skips every layer crate: `plx_base`, `plx_machine`, `plx_os`, `plx_gfx`, `plx_net`, `plx_ui`, `plx_plex`, `plx_telemetry`, `plx_data`, `plx_session`, `plx_media`, `plx_appkit`, `plx_screens`) runs the whole +**Tier 1 — `make check` (host).** `cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp` (a bare `cargo test --lib` runs the application crate only and skips every layer crate: `plx_base`, `plx_machine`, `plx_os`, `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 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 @@ -1960,7 +1961,7 @@ documented 59 before that, which was five times stale before anyone noticed — of this paragraph was stale within one *commit*, because two agents were adding tests to the same batch that documented it. Three numbers have now rotted here, so do not add a fourth: the only count worth having is the one you take yourself, with -`cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_owp -- --list | grep -c ': test'`. **The per-module counts +`cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp -- --list | grep -c ': test'`. **The per-module counts below have the same disease and are worse**, because a stale one reads as precise rather than round — several were written when the module was a third its present size, and two bullets have now outlived the file they named: `ui/home.rs` (retired to `screens/home/`) and `route.rs` (split in diff --git a/docs/distribution.md b/docs/distribution.md index 5fad25fd6f..3c37180fce 100644 --- a/docs/distribution.md +++ b/docs/distribution.md @@ -753,7 +753,7 @@ world-readable `/tmp` on the TV across many runs. crash log, but the default hook prints the raw message to stderr, so a future `unwrap()` on an `Err` that embeds a URL or token would still land there verbatim. Two things could not be settled without the television: whether LG's SDL logs committed keyboard text at `SDL_LOG_CATEGORY_INPUT` / - `SDL_LOG_PRIORITY_DEBUG`, which `textinput::trace_driver` enables in every build (the five + `SDL_LOG_PRIORITY_DEBUG`, which `plx_shell_sdl::text::trace_driver` (called from `textinput::bind`) enables in every build (the five message formats the driver is documented to print carry a state number, never text), and what the closed TV libraries (libplayerAPIs, libAcbAPI, libpf) write to fd 2. diff --git a/docs/lab-diagnostics.md b/docs/lab-diagnostics.md index d74a00ee2f..f9e331887d 100644 --- a/docs/lab-diagnostics.md +++ b/docs/lab-diagnostics.md @@ -441,7 +441,7 @@ not pretending the old filesystem contract exists. * `make check` is green in both configurations. **Take the counts yourself** — this repository has rotted four written test counts already and the fifth is not going to be this one: - `cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_owp -- --list | grep -c ': test'`, with and without + `cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp -- --list | grep -c ': test'`, with and without `--features lab-diagnostics`. What the feature's own tests cover: the ring's two caps and its `dropped` delta, the `lab.json` parse and each refusal it names, the five scrub rewrites and the outright refusal (including the bare address and the household name the device test found), the diff --git a/docs/launch-links.md b/docs/launch-links.md index d5c9e60f17..72c91b8233 100644 --- a/docs/launch-links.md +++ b/docs/launch-links.md @@ -50,7 +50,7 @@ the window and never reads the parameters. The app cannot hold that subscription on webOS 9.2.2, LG C2: SAM answers an anonymous client `cannot find caller id`, the app-id service name is already taken in the process, and `LSCallFromApplication` is refused as unprivileged). -Instead, `app::boot::tap_relaunch_payloads` wraps the pointer slot LG's SDL reads each reply's +Instead, `system::tap_relaunch_payloads` wraps the pointer slot LG's SDL reads each reply's payload through (`HELPER_HLunaServiceMessage`, exported by its `libSDL2` and filled in `SDL_Init`). A relaunch payload is passed to the link code and returned unchanged, so SDL still raises the window. The link then replaces wherever the app was, with Home underneath. A relaunch without a diff --git a/docs/macos-app.md b/docs/macos-app.md index 735dd796ef..3844984914 100644 --- a/docs/macos-app.md +++ b/docs/macos-app.md @@ -70,7 +70,7 @@ Four things, and three of them were bugs that had been sitting in the tree unrea recipe are untouched. The window changed too, though that is taste rather than a bug: it opens at an exact integer -divisor of the 1920x1080 canvas (`app::boot::plan_desktop_window`) with ALLOW_HIGHDPI, and is not +divisor of the 1920x1080 canvas (`plx_shell_sdl::window::plan_desktop_window`) with ALLOW_HIGHDPI, and is not resizable. The window's pixel density is measured from the window itself (`SDL_GetDisplayDPI` is unreliable on macOS), and the window is then sized in points for the drawable it should give, so a display of any size lands on the same result. On a Retina display that means a 960x540-point window diff --git a/docs/module-layers.md b/docs/module-layers.md index 5ce87d356f..90ef9fa895 100644 --- a/docs/module-layers.md +++ b/docs/module-layers.md @@ -110,6 +110,7 @@ telemetry plex net + os m plex net + os machine base net + os base gfx + os machine base +shell_sdl + os machine base play_feed net playback_contract media_codecs + os base play_uri playback_contract + os base media_codecs playback_contract + base @@ -198,6 +199,18 @@ vendored conformance vectors in `rust-modules/owp/fixtures/`. The WebSocket unde application does not name the crate yet. `ci/check-deps.sh` reads the whole crate for the same IO and clock gates as every other layer, and as machine code. +`shell_sdl` is a twentieth layer, declared the same way. Its crate is `plx_shell_sdl` (`rust-modules/shell-sdl/`); +its layer may use `base`, `machine` and `os` and the crate names `plx_base` alone. It is the SDL half of the shell that the +television and the simulator share: `SDL_Init` and the GL request, the window (the panel's size and its smaller +fallback, and under `hostsim` the desktop fit), the swap and its interval, the event poll and decode (LG's fork layout +on the device, stock SDL2 under `hostsim`), the synthetic key, pointer, wheel and text events the dev tooling pushes back +into the queue, and the text-input calls. The LG half does not move: the `SDL_SysWMinfo` buffer, the `wl_proxy_marshal` +opaque region and the LS2 pump stay in `system.rs`, a member of `[platform webos]`, and a pin in the crate's `lib.rs` fails +if the crate names the query that overruns it. The application reaches it through `app/platform.rs`, whose `Shell` opens a +`Surface` over the crate's `Window`; `Shell`, `Surface` and `HostEvent` stay application-private until W7a. +`ci/check-deps.sh` reads the whole crate for the same clock, statics and thread gates as every other layer, and not as one of the +sans-IO areas: the shell is an IO crate by definition. + The Watchlist adds two data modules and no new edge. `watchlist` (rows, match table, `TileState`, intent ledger, comparator; with `stores::watchlist`) and `catalog` (the Discover-only item page; with `stores::catalog`) name only layers below data, chiefly `plx_plex`: `plex::watchlist`, `Client::find_by_guids`, `plex::session` @@ -334,9 +347,9 @@ proves the references are gone and nothing more; L15b is open. | **L15b** the OS-neutral port — **open** | — | An OS-neutral video sink with the ACB bind sequence behind it and the webOS facts the gate cannot see; the simulator became its own platform in W4. See below. | | **L15c** the platform value and the three contracts — **done** | — | Wave R (the rename that gave this page `os` and `[platform webos]`) landed as #1474; W2 landed (`tv::Port` became `tv::Services`, with four groups of hooks; the shell and the frame probes moved to `app::Platform`), and so did the three contracts, W3a to W3c: who may persist credentials (#1477), what evidence admits a URI player (#1478), who ends the process (#1479). See "L15c to L15h" below. | | **L15d** neutral types and the simulator as its own platform (L15b item 2) — **W3d and W4 landed** | — | W3d landed (the opaque `Backend` tag, `sandbox` to `native_video`, identity publishes a platform name and version, `device::Info` keeps its webOS fields in `WebosDetail`, and `devcaps` reads its files through the platform), and so did W4: `platform_desktop` (`rust-modules/src/platform_desktop.rs`, a second fence section, `[platform desktop]`) is the simulator's and the macOS app's own platform value, which `src/bin/sim.rs` enters through; the `hostsim` terms of the television's fence are gone, so the television's code is compiled into every build and the linker drops it from a desktop executable (`simulators.yml` links the macapp feature set to guard that until W7), and the stand-ins in `webos` and `keymanager` are test seams, compiled for tests and `test-support` (`docs/platform-ports.md`, W4). The desktop platform is the second implementation. | -| **L15e** events, the shell and composition — **W5a to W5c and W6b landed** | — | W5 (`HostEvent` with `Option`) landed in three PRs, lifecycle and quit (W5a, #1484), keys and text (W5b, #1487) and the pointer and wheel (W5c, #1492), and so did W6b (platform-supplied composition in two boot phases, #1489). W6 (`plx_shell_sdl`, a `[shell_sdl]` layer) and W6c (a URI-only and a two-driver composition play an ordinary title) are planned. | -| **L15f** extract the platform crates — **planned** | — | W7: a narrow public `host` module in the application crate, `rust-modules/platform-webos` and `platform-desktop` as crates above `app`, and the gate learning "a platform is a crate above `app`". After L15d, before L15g and L15h. | -| **L15g** the webOS facts and the remaining `hostsim` (L15b item 3) — **W8a started** | — | W8a has begun: the platform states where the account's records live (`tv::Services.storage`, #1488), and telemetry's consent store (#1490) and plex's session persistence (#1491) follow it instead of the `target_arch = "arm"` fence. Still planned: the rest of W8a, one PR per directory (`os`, `src`, `base`, `storage` and `play-feed`), sorting the `target_arch = "arm"` and `target_os = "linux"` sites into "is webOS" (a platform value or runner) and "is 32-bit ARM" or "is Linux" (stays); then W8b, the library name lists, `paths` and the packaging, and W8c, the `feature = "hostsim"` lines left in the tree (none of them in the fence now; `git grep -h 'feature = "hostsim"' -- '*.rs' | wc -l` counts them). | +| **L15e** events, the shell and composition — **W5a to W5c, W6 and W6b landed** | — | W5 (`HostEvent` with `Option`) landed in three PRs, lifecycle and quit (W5a, #1484), keys and text (W5b, #1487) and the pointer and wheel (W5c, #1492), and so did W6b (platform-supplied composition in two boot phases, #1489) and W6 (`plx_shell_sdl`, a `[shell_sdl]` layer: SDL's bring-up, the window, the swap, the event decode and the text-input calls moved out of the application behind its private `Shell` and `Surface`, and the LG half stays in `system.rs`). W6c (a URI-only and a two-driver composition play an ordinary title) is planned. | +| **L15f** extract the platform crates — **planned** | — | W7: a narrow public `host` module in the application crate, `rust-modules/platform-webos` and `platform-desktop` as crates above `app`, and the gate learning "a platform is a crate above `app`". After L15d, before L15g and L15h (the storage-authority part of W8a, #1488, #1490 and #1491, landed ahead of W7; the rest of W8 still follows W7). | +| **L15g** the webOS facts and the remaining `hostsim` (L15b item 3) — **W8a started** | — | W8a has begun: the platform states where the account's records live (`tv::Services.storage`, #1488), and telemetry's consent store (#1490) and plex's session persistence (#1491) follow it instead of the `target_arch = "arm"` fence. Still planned: the rest of W8a, one PR per directory (`os`, `src`, `base`, `storage` and `play-feed`; telemetry's nine `target_arch = "arm"` lines in `telemetry/src/telemetry/native.rs`, the Sentry Native crash capture, are not among them and no step owns them yet, the follow-up for Tizen ARM retail builds that #1490 names), sorting the `target_arch = "arm"` and `target_os = "linux"` sites into "is webOS" (a platform value or runner) and "is 32-bit ARM" or "is Linux" (stays); then W8b, the library name lists, `paths` and the packaging, and W8c, the `feature = "hostsim"` lines left in the tree (none of them in the fence now; `git grep -h 'feature = "hostsim"' -- '*.rs' | wc -l` counts them). | | **L15h** the OS-neutral Feed sink (L15b item 1) — **planned** | — | W11: `plx_acb` (an `[acb]` layer) takes the ACB plane owner and the URI media verbs out of `os`, the Feed-side ACB results become neutral, and the bind sequence moves behind a neutral sink. Needs the television. | ### L15: the webOS port @@ -492,7 +505,7 @@ section is `[platform X]`, and the plan calls its crates `plx_platform_webos`, ` The order is L15c; then L15d and L15e, which overlap (W3d then W4 runs beside W5, and W6b, W6 and W6c wait for both); then L15f; then L15g and L15h. So the extraction (L15f, W7) follows item 2 (L15d, W4), and item 3 (L15g, W8) and item 1 (L15h, W11) come afterwards. The earlier order put the extraction after all of L15b, which would have made W7 -wait for the neutral sink: item 1 needs the television and gates nothing the other platforms need, and W8 follows W7. +wait for the neutral sink: item 1 needs the television and gates nothing the other platforms need, and W8 follows W7 (but the storage-authority part of W8a, #1488, #1490 and #1491, landed ahead of it). The steps are L15b's three items and the moves that serve them: the contracts they rest on (L15c), the events and composition (L15e) and the extraction (L15f). The other workstreams are not steps of this table: W0 (the record of the plan, this amendment), W1 (the `PLATFORM` build axis), W9 (the Tizen platform, which adds `plx_platform_tizen` and a diff --git a/docs/platform-ports.md b/docs/platform-ports.md index 37872e7640..c236b7001c 100644 --- a/docs/platform-ports.md +++ b/docs/platform-ports.md @@ -180,7 +180,10 @@ Citations in this section quote the tree at e9924f0f9 with its old names (see "N - the swap is at `app/run.rs:974` and the poll at `app/run.rs:1066-1069`. Source-text pins search for those calls: tests at `app/boot.rs:705-785` look for `"SDL_Init("` and - `"SDL_CreateWindow("`, and `app/run.rs:11467` looks for `"SDL_GL_SwapWindow(app.win);"`. + `"SDL_CreateWindow("`, and `app/run.rs:11467` looks for `"SDL_GL_SwapWindow(app.win);"`. W6 moved the extern block, + the window, the swap and the poll into `plx_shell_sdl` (`sys.rs`, `window.rs`, `event.rs`); the application crate declares + SDL functions in two files only now, `system.rs` (the `SDL_SysWMinfo` handshake and the GL attribute read) and + `app/clock.rs` (`SDL_GetTicks`), and its swap pin reads `app.surface.swap();`. - F15. SDL is also below `app`: - `base/src/surface.rs:38-39`; - `base/src/diag/heartbeat.rs:30-31`; @@ -1599,6 +1602,15 @@ W3d. Neutral types (L15b item 2 prerequisites; part of item 3). - Test: `make test-hostsim`; a build-bench table; `check-nodef`, the ARM cross-build and fw-compat-reviewer; a TV lease: boot log diff and the video plane still showing through (opaque region); frame claims only via `profile-tv`. Risk: the SysWMinfo overrun (`system.rs:4-5`); that code moves verbatim. +- As landed: `Shell` gained `init` and `open`, and `open` returns the application-private `Surface` (`window`, `swap`, + `set_swap_interval`, `poll` and an unsafe `quit` that `run::shutdown` calls). The bring-up order is kept: `SDL_Init` and the + GL request come before the stored session is read, the window after it. The placement is a value, `OpenAsk { title, + placement, high_dpi }`, so the panel's size with its smaller fallback and the desktop fit (`Placement::Desktop`, `hostsim` + builds only) are the crate's; the webOS shell hands `init` two hooks, the cursor-sleep hint before `SDL_Init` and the + relaunch tap after it (`system::webos3_cursor_sleep_hint` and `system::tap_relaunch_payloads`, moved without their `hostsim` + gates), and the desktop shell none. Text-input state stays in `textinput.rs`; the crate owns the byte layouts and the SDL + calls. The pins moved with their code: the init order into the crate's `init`, the window order into its + `open_order_tests`, and the session-before-window order stays in `app/boot.rs`. ### W6b (N, accepted T). Platform-supplied composition, two phases - Goal: `app::Platform.media` (Target shape 6a). `acb_init` moves behind `early_init` at its present call site diff --git a/docs/search.md b/docs/search.md index 582fc339f7..46b6a102f7 100644 --- a/docs/search.md +++ b/docs/search.md @@ -317,7 +317,7 @@ single hard-coded number ships garbage on one of the two platforms. `SDL_StartTextInput` looks for a window carrying `0x200` (`SDL_video.h` in the SDK sysroot's `usr/include/SDL2/`) before dispatching to the driver hook. Our window is created with -`SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN` and nothing else — `app.rs`'s `SDL_WINDOW_FLAGS` is +`SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN` and nothing else — `plx_shell_sdl`'s `SDL_WINDOW_FLAGS` (`shell-sdl/src/window.rs`) is `0x2 | 0x1` on the device — so it carries neither `SHOWN` nor a focus flag at creation. **If the flag is clear the panel never rises, silently and with no error return.** That is why the boot probe logs the flag rather than trusting it: a keyboard that does not appear and a keyboard that appeared and diff --git a/rust-modules/Cargo.lock b/rust-modules/Cargo.lock index c7e1c8f2a0..d283d70388 100644 --- a/rust-modules/Cargo.lock +++ b/rust-modules/Cargo.lock @@ -971,6 +971,13 @@ dependencies = [ "serde_json", ] +[[package]] +name = "plx_shell_sdl" +version = "0.0.0" +dependencies = [ + "plx_base", +] + [[package]] name = "plx_telemetry" version = "0.0.0" @@ -1019,6 +1026,7 @@ dependencies = [ "plx_plex", "plx_screens", "plx_session", + "plx_shell_sdl", "plx_telemetry", "plx_ui", "serde", diff --git a/rust-modules/Cargo.toml b/rust-modules/Cargo.toml index 5d4f2b25ba..425f154200 100644 --- a/rust-modules/Cargo.toml +++ b/rust-modules/Cargo.toml @@ -1,5 +1,5 @@ # A cargo workspace with this package as its ROOT; the other members are the storage helper and the -# layer crates split out of the application (everything under `rust-modules/*/` with a `[package.metadata.plx] mount`: base/, machine/, net/, os/, gfx/, ui/, plex/, telemetry/, data/, session/, media/, play-feed/, appkit/, screens/, owp/ and the contract and codec crates; +# layer crates split out of the application (everything under `rust-modules/*/` with a `[package.metadata.plx] mount`: base/, machine/, net/, os/, gfx/, ui/, plex/, telemetry/, data/, session/, media/, play-feed/, appkit/, screens/, shell-sdl/, owp/ and the contract and codec crates; # docs/module-layers.md). # The root keeps the literal `version` below (release tooling reads it), `make`/CI run their usual # commands from this directory against this package (a bare `cargo test`/`check`/`build` here still @@ -25,6 +25,7 @@ members = [ "media-codecs", "appkit", "screens", + "shell-sdl", "owp", "storage", ] @@ -173,11 +174,12 @@ placeholder-sentinel = ["plx_ui/placeholder-sentinel"] # a mutually-exclusive partner feature; the television is the DEFAULT, and the simulator opts in. # # What it changes, and nothing else: the media seam (29 symbols that exist only on a television), -# the GL context request (macOS has no GLES2 driver), the window flags, the keyboard event decode -# (LG's SDL fork shifts SDL_KeyboardEvent; stock SDL2 does not), and the wayland/glib calls that -# have no host equivalent. Everything else — all of `ui/`, the whole Plex data layer, the demux -# orchestration — is compiled identically for both. -hostsim = ["dep:xxhash-rust", "plx_base/hostsim", "plx_machine/hostsim", "plx_os/hostsim", "plx_gfx/hostsim", "plx_plex/hostsim", "plx_telemetry/hostsim", "plx_data/hostsim", "plx_session/hostsim", "plx_media/hostsim", "plx_play_feed?/hostsim"] +# the GL context request (macOS has no GLES2 driver), the window flags and the keyboard event decode +# (LG's SDL fork shifts SDL_KeyboardEvent; stock SDL2 does not), the last three now `plx_shell_sdl`'s, +# and, since W4, `platform_desktop` as the platform (the wayland/glib calls are no longer switched +# by this feature: they compile in every build and the desktop never reaches them). Everything else +# — all of `ui/`, the whole Plex data layer, the demux orchestration — is compiled identically for both. +hostsim = ["dep:xxhash-rust", "plx_base/hostsim", "plx_machine/hostsim", "plx_os/hostsim", "plx_gfx/hostsim", "plx_plex/hostsim", "plx_telemetry/hostsim", "plx_data/hostsim", "plx_session/hostsim", "plx_media/hostsim", "plx_play_feed?/hostsim", "plx_shell_sdl/hostsim"] # Warnings are ERRORS, for both workspace packages, in every cargo invocation — build, check, test, clippy, the # ARM cross-build and the simulator alike. The tree reached zero warnings in all four @@ -275,6 +277,13 @@ plx_appkit = { path = "appkit" } # the registry that names them. It links nothing on the television; its build script is for the host # test binary. plx_screens = { path = "screens" } +# The shell_sdl layer (ci/module-layers.ini `[shell_sdl]`): the stock-SDL shell the application opens its +# window through: SDL's init, the window and its GL context, the swap, the event queue, the stock +# layouts of the key, pointer, wheel and text events, and the synthetic events pushed back onto the +# queue. It names no application type and none of the webOS platform (`system`, `port`); the +# application drives it through its own `Shell` and `Surface`. Its `hostsim` feature is forwarded +# above; its build script links SDL2 into a host test binary only. +plx_shell_sdl = { path = "shell-sdl" } # safe pure-Rust JPEG/PNG decoders — replaces vendored stb_image.h (~8k lines C) image = { version = "0.25", default-features = false, features = ["jpeg", "png"] } # raw socket/libc FFI for the stream module (correct constants + struct layouts) @@ -376,3 +385,5 @@ plx_media_codecs = { path = "media-codecs", features = ["test-support"] } plx_appkit = { path = "appkit", features = ["test-support"] } # Likewise the screens layer's seams (`account_menu::overscan_rects`, `registry::every_surface_arg`, ...). plx_screens = { path = "screens", features = ["test-support"] } +# Likewise the shell crate's SDL stubs (`text::start_input` and the rest of the panel calls, which a host test binary must not reach) and its event-subsystem scaffold. +plx_shell_sdl = { path = "shell-sdl", features = ["test-support"] } diff --git a/rust-modules/base/src/surface.rs b/rust-modules/base/src/surface.rs index bbffb8debb..cea941f336 100644 --- a/rust-modules/base/src/surface.rs +++ b/rust-modules/base/src/surface.rs @@ -466,7 +466,7 @@ pub fn probe(win: *mut c_void) { // not the canvas is either a webOS 1-3 owner's smaller Interface resolution (or the debug drawable trigger) or a firmware doing // something no set has been seen to do. On a desktop // it is the ordinary case — the window is an exact divisor of the canvas by design - // (`app::boot::plan_desktop_window`) — and asking a Mac user for their webOS version + // (`plx_shell_sdl::window::plan_desktop_window`) — and asking a Mac user for their webOS version // reads as a malfunction. Same measurement either way; only the sentence differs. let tail = if cfg!(feature = "hostsim") { "This is expected on a desktop: the window is a whole fraction of the canvas." diff --git a/rust-modules/data/src/search.rs b/rust-modules/data/src/search.rs index 3f5837a54e..44c7af0066 100644 --- a/rust-modules/data/src/search.rs +++ b/rust-modules/data/src/search.rs @@ -439,7 +439,7 @@ pub fn terms(q: &str) -> Option<&str> { /// and `CString::new` refuses it at the far end, so the field's run and the empty statement both /// blank over a query the app still believes it is holding. Borrowed when there is nothing to /// remove, which is every keystroke: the television's panel cannot commit one -/// (`textinput::decode_text_at` ends its string AT the NUL) and a remembered term is refused by +/// (`plx_shell_sdl::text`'s `decode_text_at` ends its string AT the NUL) and a remembered term is refused by /// `recents::usable`, so the seed path is the only way one gets in — and that path now enters /// through the STORE rather than through a screen's mount. pub fn sanitize_query(q: &str) -> std::borrow::Cow<'_, str> { diff --git a/rust-modules/shell-sdl/Cargo.toml b/rust-modules/shell-sdl/Cargo.toml new file mode 100644 index 0000000000..ad746acb66 --- /dev/null +++ b/rust-modules/shell-sdl/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "plx_shell_sdl" +version = "0.0.0" +edition = "2021" +license = "GPL-3.0-or-later" +description = "PlxNative stock-SDL shell: SDL bring-up, the window and GL context, the swap, the event drain, the stock key, pointer, wheel and text layouts, and synthetic-event injection." +repository = "https://github.com/GLinnik21/plx-native" +publish = false +build = "build.rs" + +[package.metadata.plx] +mount = "shell_sdl" + +[lib] +name = "plx_shell_sdl" +# An rlib the application crate links, never an archive of its own: the one staticlib is the +# application crate's (ci/test_no_host_staticlib.py holds that line for this crate too). +crate-type = ["rlib"] + +[features] +default = [] +# Forwarded from the application crate, which is the only one that sets it. It selects the +# stock-SDL2 event layouts and the desktop window arithmetic that a simulator runs (the +# television's SDL fork lays its keyboard, text and wheel events out differently), plus the GL +# context request. Both arms of every layout stay compiled either way (`cfg!`). +hostsim = ["plx_base/hostsim"] +# Stubs for the four text-input calls that a host test binary must not reach (no window, no +# panel) and the SDL event-queue guard the application's loop tests drive. Enabled from the +# dependents' `[dev-dependencies]`; never in a shipped build. +test-support = ["plx_base/test-support"] + +[dependencies] +plx_base = { path = "../base" } + +[dev-dependencies] +plx_base = { path = "../base", features = ["test-support"] } + +[lints] +workspace = true diff --git a/rust-modules/shell-sdl/build.rs b/rust-modules/shell-sdl/build.rs new file mode 100644 index 0000000000..fa699ca8cd --- /dev/null +++ b/rust-modules/shell-sdl/build.rs @@ -0,0 +1,21 @@ +//! Host link configuration for the shell-sdl layer's own test binary, and nothing else. +//! +//! `plx_shell_sdl` declares the SDL2 symbols its window, event and text code call. Its `--test` +//! binary is a real executable that can reach them (the event-queue round trips push and poll +//! real SDL events), so on the host it needs the same SDL object the application crate's build +//! script supplies to the application's binaries. The lines are the same ones, from the same file +//! (`../build_support/host_link.rs`), so the crates cannot disagree. +//! +//! On the television this script prints no `rustc-link-*` line at all: the ARM build is a +//! staticlib the Makefile links, and `host_link::emit` returns before emitting anything for +//! `target_arch = "arm"`. No environment variable is read except cargo's own target description, +//! so an ordinary rebuild never re-runs it. + +#[path = "../build_support/host_link.rs"] +mod host_link; + +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-changed=../build_support/host_link.rs"); + host_link::emit(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")); +} diff --git a/rust-modules/shell-sdl/src/event.rs b/rust-modules/shell-sdl/src/event.rs new file mode 100644 index 0000000000..f0e2013af1 --- /dev/null +++ b/rust-modules/shell-sdl/src/event.rs @@ -0,0 +1,579 @@ +//! SDL's events as the application reads them: the event-type codes, the raw-offset readers, the key, +//! pointer, wheel and text layouts of BOTH SDLs this project runs on, and the queue's `poll`/`push`. +//! +//! The decode stops at neutral values ([`Decoded`]): a key is `(state, wcode, sym)`, never an +//! `Action`, because naming one is the application's vocabulary (`ui::consts`) and a shell may not +//! name `ui`. The application maps a [`Decoded`] onto its own `HostEvent`; the tape's format is the +//! SDL code each [`Lifecycle`] edge arrived as ([`Lifecycle::sdl_code`]), so those pairs live here, +//! where the decode table is. +use crate::sys; +use plx_base::surface::to_logical; +use std::os::raw::c_void; + +// event types +pub const SDL_QUIT: u32 = 0x100; +pub const SDL_KEYDOWN: u32 = 0x300; +pub const SDL_KEYUP: u32 = 0x301; +pub const SDL_MOUSEMOTION: u32 = 0x400; +pub const SDL_MOUSEBUTTONDOWN: u32 = 0x401; +pub const SDL_MOUSEBUTTONUP: u32 = 0x402; +pub const SDL_MOUSEWHEEL: u32 = 0x403; +/// The IME's in-progress COMPOSITION. Not acted on — the search field shows what has been +/// committed, so a preedit would put characters on screen the query does not contain — but LOGGED, +/// because the panel's word prediction is a replace and this is where its delete half would arrive +/// if it arrives at all. See the `"edit"` arm in the application's event ladder. +pub const SDL_TEXTEDITING: u32 = 0x302; +/// Text COMMITTED by the system keyboard — the application's `textinput`. +pub const SDL_TEXTINPUT: u32 = 0x303; + +/// SDL's application events (`SDL_APP_*`), the four the loop acts on: the compositor taking the +/// screen (WILL and DID enter background) and giving it back (WILL and DID enter foreground). +pub const SDL_APP_WILLENTERBACKGROUND: u32 = 0x103; +pub const SDL_APP_DIDENTERBACKGROUND: u32 = 0x104; +pub const SDL_APP_WILLENTERFOREGROUND: u32 = 0x105; +pub const SDL_APP_DIDENTERFOREGROUND: u32 = 0x106; + +/// Poll SDL's one process-wide event queue into `ev`. `true` when an event was written. SDL writes +/// at most `sizeof(SDL_Event)` (56 bytes) of the 128 the buffer holds, so the rest is whatever the +/// last, larger event left behind. +pub fn poll(ev: &mut [u8; 128]) -> bool { + unsafe { sys::SDL_PollEvent(ev.as_mut_ptr() as *mut c_void) != 0 } +} + +/// Push one event onto SDL's own queue, so the existing poll loop consumes it as if it had come off +/// the wayland input path. The only caller is `inject.rs`. +pub(crate) fn push(ev: &[u8; 128]) { + unsafe { sys::SDL_PushEvent(ev.as_ptr() as *const c_void) }; +} + +#[inline] +pub fn rd_u32(ev: &[u8], off: usize) -> u32 { + u32::from_ne_bytes([ev[off], ev[off + 1], ev[off + 2], ev[off + 3]]) +} + +#[inline] +pub fn rd_i32(ev: &[u8], off: usize) -> i32 { + i32::from_ne_bytes([ev[off], ev[off + 1], ev[off + 2], ev[off + 3]]) +} + +#[inline] +pub fn rd_f32(ev: &[u8], off: usize) -> f32 { + f32::from_ne_bytes([ev[off], ev[off + 1], ev[off + 2], ev[off + 3]]) +} + +/// A keyboard event's `(state, wcode, sym)`, decoded from the raw event bytes. The `wcode` is +/// `None` only on the host layout, for a press that carries no injected one: stock SDL has no webOS +/// keycode at all, so the application applies its desktop stand-in (`host_wcode`, a `ui` table this +/// crate may not name) exactly where this decode used to. The television's layout always has one. +/// +/// **The two SDLs disagree about this struct, and nothing warns you.** LG's fork writes +/// `state` (u32) at +16, the webOS keycode at +20 and the SDL sym at +24. Stock SDL2 — +/// what the host simulator links — has `SDL_KeyboardEvent { type, timestamp, windowID, +/// state:u8@12, repeat:u8@13, pad, pad, keysym{ scancode:u32@16, sym:i32@20, … } }`, so +/// every field the app reads is at a different offset and there is no webOS keycode at all. +/// Reading the fork's offsets out of a stock event yields the window id as a keystate and +/// a scancode as a sym — plausible-looking garbage rather than a crash. +/// +/// `cfg!` rather than `#[cfg]` deliberately: both arms stay compiled on both platforms, so +/// the one nobody is currently building cannot rot. This is the single site that knows the +/// layout — `rd_u32`'s callers elsewhere read pointer events, whose offsets already agree. +/// +/// **The `wcode` this returns is LG's SCANCODE**, which is worth saying because the name suggests +/// otherwise. Every field measured off the dev set is the SDL scancode of the key beside it — +/// backspace 42, Clear 156, ◀/▶ 80/79, OK 40 — so the fork's shift puts an ordinary +/// `SDL_Keysym { scancode, sym }` at +20/+24 rather than inventing a webOS keycode namespace. That +/// is why the codes above SDL's own range (450 play, 482 back, 505 exit) carry no sym at all: they +/// are LG-private scancodes the keymap has no keycode for. `docs/remote-keys.md` has the account. +/// +/// # The simulator's carrier moved, because the old one was silently DEAD +/// +/// A synthetic press from the remote FIFO has to get its wcode across `SDL_PushEvent`, and on the +/// host that queue is not SDL2's: macOS `libSDL2` is **sdl2-compat forwarding into SDL3**, so every +/// pushed event is converted out and back. Measured 2026-08-23 by dumping the polled bytes of a +/// press whose every spare field carried a distinct value: +/// +/// | field | offset | survives | +/// |------------------------------|--------|----------| +/// | `windowID` | +8 | yes | +/// | `padding2` / `padding3` | +14/15 | no | +/// | `keysym.scancode` | +16 | **no** — comes back 0 | +/// | `keysym.mod` | +24 | yes | +/// | `keysym.unused` | +28 | **no** — comes back 1 | +/// +/// It used to be `unused`, so **every wcode-ONLY token was dead**: `play`, `pause`, `stop`, `ff`, +/// `rew`, `playpause`, `exit`, `chup`, `chdown` all decoded as wcode 1 and did nothing at all, and +/// `tests/keytable.json` recorded three of them as `moved: false` — which reads as "that key does +/// nothing on that screen" and actually meant the press never arrived. An instrument silent by +/// construction: prove it can see the thing before reading its silence. +/// +/// `scancode` would have been the honest home (it is what a wcode IS) and it is the one field the +/// compat layer recomputes. So a synthetic press carries the value in `mod` and a MARKER in +/// `windowID` ([`SYNTH_WINDOW`]) — two fields, because the value alone cannot say whether it is +/// one: a real press puts its modifier bitmask in `mod`, so `mod != 0` means "shift is down" at +/// least as often as it means "injected". The marker restores the priority the `unused` field used +/// to express — **injected first, the desktop stand-in only as a fallback** — which is load-bearing +/// and not a preference: `host_wcode(8)` is BACK, while the `backspace` token is `(8, 42)`, so +/// asking the stand-in first turns the panel's delete key into a navigation. That priority is why +/// this returns the injected wcode or `None` and never a stand-in of its own: the caller's +/// `unwrap_or_else(host_wcode)` can only ever apply to a press that carried none. +/// Clobbering `windowID` is safe here and nowhere else: this arm is `hostsim`-only, the simulator +/// has one window, and nothing in the event loop reads that field. +#[inline] +pub fn decode_key(ev: &[u8]) -> (u32, Option, u32) { + if cfg!(feature = "hostsim") { + let pressed = *ev.get(12).unwrap_or(&0) as u32; + let repeat = *ev.get(13).unwrap_or(&0) as u32; + let sym = rd_u32(ev, 20); + // Rebuild the fork's packed state byte-for-byte: low byte pressed(1)/released(0), + // bit 0x100 auto-repeat. Everything downstream tests exactly those two. + let state = pressed | if repeat != 0 { 0x100 } else { 0 }; + let injected = if rd_u32(ev, 8) == SYNTH_WINDOW { + u32::from(u16::from_ne_bytes([ev[24], ev[25]])) + } else { + 0 // a real desktop press: `mod` there is the modifier bitmask, not a wcode + }; + // The stand-in is the only way a physical Mac keyboard reaches a key the remote has and a + // keyboard does not (space = PAUSE), and it applies to real presses alone. + let wcode = if injected != 0 { Some(injected) } else { None }; + (state, wcode, sym) + } else { + (rd_u32(ev, 16), Some(rd_u32(ev, 20)), rd_u32(ev, 24)) + } +} + +/// The `windowID` a SYNTHETIC key event carries on the host, marking it as one — see [`decode_key`] +/// for why the wcode needs a marker beside it rather than standing on its own. Any value no real +/// window can have; SDL numbers windows from 1. +/// +/// Defined unconditionally, like both halves of [`decode_key`]: the arm that uses it is behind +/// `cfg!` rather than `#[cfg]`, precisely so the configuration nobody is currently building cannot +/// rot. +pub const SYNTH_WINDOW: u32 = 0x504c_584b; // "PLXK" + +/// What a pointer event did. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PointerEdge { + /// `SDL_MOUSEMOTION`. + Move, + /// `SDL_MOUSEBUTTONDOWN`, any button. + Down, + /// `SDL_MOUSEBUTTONUP`, any button. + Up, +} + +/// One edge of the window's visibility. Both background edges park the tree (the second finds +/// nothing left to park); WILL foreground un-parks the tree, and DID foreground alone reacquires the +/// window and restores playback. A platform that sends only DID background is enough on its own +/// (`WindowActivity`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Lifecycle { + WillBackground, + DidBackground, + WillForeground, + DidForeground, +} + +impl Lifecycle { + /// The SDL event type this edge arrives as, and so the code the SDL-coded readers take: the + /// recorder's tape (`enc_lifecycle`, whose recorded codes ARE the tape format), the window gate + /// and telemetry's crash steps and session. The inverse of [`decode`]'s table; the tests pin the + /// four pairs. + pub const fn sdl_code(self) -> u32 { + match self { + Lifecycle::WillBackground => SDL_APP_WILLENTERBACKGROUND, + Lifecycle::DidBackground => SDL_APP_DIDENTERBACKGROUND, + Lifecycle::WillForeground => SDL_APP_WILLENTERFOREGROUND, + Lifecycle::DidForeground => SDL_APP_DIDENTERFOREGROUND, + } + } +} + +/// One SDL event as neutral values. `Key` carries the bytes' own `(state, wcode, sym)` (see +/// [`decode_key`] for the `Option`), and the application turns that into its `KeyPress`. +#[derive(Clone, Debug, PartialEq)] +pub enum Decoded { + /// `SDL_QUIT`. + Quit, + /// One edge of a key: the fork's packed `state` (low byte 1 is down, bit 0x100 is the + /// auto-repeat), the wcode where the bytes carry one, and the sym. + Key { state: u32, wcode: Option, sym: u32 }, + /// One commit from the system keyboard: the decoded string, possibly empty (SDL delivers a + /// commit for the IME's own bookkeeping too, and the loop ignores an empty one). + Text(String), + /// One pointer event at authored 1920x1080 coordinates ([`ptr_xy`]). + Pointer { x: f32, y: f32, edge: PointerEdge }, + /// One tick of the wheel in the signed whole ticks the loop reads ([`decode_wheel_dy`]). + Wheel { dy: i32 }, + /// The window left or came back to the screen. + Lifecycle(Lifecycle), +} + +/// An SDL event decoded: `SDL_QUIT`, the four application lifecycle types, a key edge +/// (`SDL_KEYDOWN`/`SDL_KEYUP`, through [`decode_key`], so both layouts), a text commit +/// (`SDL_TEXTINPUT`, through [`crate::text::decode`]), a pointer event (motion, button down and +/// button up, through [`ptr_xy`]) and a wheel tick (through [`decode_wheel_dy`]). `None` for +/// everything else, which the loop reads raw (the IME's pre-edit, and the SDL events nothing acts +/// on). Beside [`decode_key`], the other place that knows SDL's event bytes. +#[inline] +pub fn decode(ev: &[u8]) -> Option { + Some(match rd_u32(ev, 0) { + SDL_QUIT => Decoded::Quit, + SDL_KEYDOWN | SDL_KEYUP => { + let (state, wcode, sym) = decode_key(ev); + Decoded::Key { state, wcode, sym } + } + SDL_TEXTINPUT => Decoded::Text(crate::text::decode(ev)), + SDL_MOUSEMOTION => pointer_event(ev, PointerEdge::Move), + SDL_MOUSEBUTTONDOWN => pointer_event(ev, PointerEdge::Down), + SDL_MOUSEBUTTONUP => pointer_event(ev, PointerEdge::Up), + SDL_MOUSEWHEEL => Decoded::Wheel { dy: decode_wheel_dy(ev) }, + SDL_APP_WILLENTERBACKGROUND => Decoded::Lifecycle(Lifecycle::WillBackground), + SDL_APP_DIDENTERBACKGROUND => Decoded::Lifecycle(Lifecycle::DidBackground), + SDL_APP_WILLENTERFOREGROUND => Decoded::Lifecycle(Lifecycle::WillForeground), + SDL_APP_DIDENTERFOREGROUND => Decoded::Lifecycle(Lifecycle::DidForeground), + _ => return None, + }) +} + +/// A pointer event's position and edge. The coordinates are read at +20 and +24 in both layouts (the +/// pointer offsets agree, [`ptr_xy`]), and the button at +16 and its state at +17 are not read: the +/// edge is the event type, for any button, as the loop has always taken it. +#[inline] +fn pointer_event(ev: &[u8], edge: PointerEdge) -> Decoded { + let (x, y) = ptr_xy(ev); + Decoded::Pointer { x, y, edge } +} + +/// A wheel event's vertical tick count, in the signed whole ticks the loop reads. +/// +/// **The host reads a DIFFERENT offset, and this one is not the LG-fork +/// shift `decode_key` documents — it is macOS `libSDL2` again being +/// sdl2-compat forwarding into SDL3.** `SDL_MouseWheelEvent` on real SDL2 +/// (what the television runs) carries a plain `Sint32 y` at +20, which is +/// what production code always read. Measured 2026-09-02 by dumping the +/// polled bytes of an injected -40 tick on this host: `+20` came back 0, and +/// -40.0 arrived instead as the FLOAT `preciseY` field at `+32` — SDL2's own +/// struct gained that field in 2.0.18 for fractional trackpad scroll, and +/// sdl2-compat's round trip apparently only forwards it, leaving the legacy +/// integer field zeroed for both a genuine trackpad tick and anything +/// `SDL_PushEvent`d in this shape (item 13's `wheel:` FIFO token hit +/// this the first time anything synthesized a wheel event at all — nothing +/// needed one before). `cfg!`, not `#[cfg]`, so both arms keep compiling. +#[inline] +pub fn decode_wheel_dy(ev: &[u8]) -> i32 { + if cfg!(feature = "hostsim") { + rd_f32(ev, 32).round() as i32 + } else { + rd_i32(ev, 20) + } +} + +/// An SDL pointer event's position, converted from window pixels to the authored 1920x1080 canvas. +/// +/// THE one place event coordinates enter the UI, so the conversion cannot be forgotten at a new +/// call site — there are nine, and patching them individually is how the tenth ends up wrong. +/// `surface::to_logical` is the identity while the drawable is 1920x1080, which it is 1:1 unless +/// a webOS 1-3 owner picks a smaller Interface resolution (or the debug drawable trigger asks for one). +#[inline] +pub fn ptr_xy(ev: &[u8]) -> (f32, f32) { + to_logical(rd_i32(ev, 20) as f32, rd_i32(ev, 24) as f32) +} + +/// 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 `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 fn is_input_event(et: u32) -> bool { + matches!( + et, + SDL_KEYDOWN + | SDL_KEYUP + | SDL_TEXTINPUT + | SDL_TEXTEDITING + | SDL_MOUSEMOTION + | SDL_MOUSEBUTTONDOWN + | SDL_MOUSEBUTTONUP + | SDL_MOUSEWHEEL + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::inject::{encode_key, encode_key_repeat, encode_pointer}; + + fn event_of(code: u32) -> [u8; 128] { + let mut ev = [0u8; 128]; + ev[..4].copy_from_slice(&code.to_ne_bytes()); + ev + } + + /// The wcode a decode reports for an injected one: always on the television, and on the host + /// only when the carrier is set (a wcode of 0 is "no injected wcode" there). + fn carried(wcode: u32) -> Option { + if cfg!(feature = "hostsim") && wcode == 0 { + None + } else { + Some(wcode) + } + } + + /// `encode_key` and `decode_key` must agree, in whichever layout this build compiled. The + /// regression test for a bug that shipped: the two ends disagreed about `SDL_KeyboardEvent`'s + /// field offsets, so every remote-FIFO token was accepted, decoded into nonsense and silently + /// dropped. Nothing in the compiler couples a reader and a writer of raw byte offsets, so this + /// does. `make check` builds the television layout; a hostsim run grades the stock one. + #[test] + fn key_bytes_round_trip() { + // `(8, 42)` is the backspace token and must survive as the pair it is: the application's + // desktop stand-in claims sym 8, so a decode that consulted it first would turn the panel's + // delete key into a navigation. Here that is: the injected wcode is reported as such. + for (sym, wcode) in [ + (0x4000_0051, 0), + (13, 0), + (0, 72), + (8, 482), + (8, 42), + (32, 44), + (112, 19), + (115, 22), + ] { + for down in [true, false] { + let (state, got_wcode, got_sym) = decode_key(&encode_key(sym, wcode, down)); + assert_eq!(got_sym, sym, "sym lost (wcode={wcode}, down={down})"); + assert_eq!(got_wcode, carried(wcode), "wcode lost (sym={sym}, down={down})"); + assert_eq!(state & 0xff, u32::from(down), "press/release lost (sym={sym})"); + assert_eq!(state & 0x100, 0, "a synthetic edge must never look like auto-repeat"); + } + let (state, got_wcode, got_sym) = decode_key(&encode_key_repeat(sym, wcode)); + assert_eq!((got_sym, got_wcode), (sym, carried(wcode))); + assert_eq!(state, 0x101, "a repeat is a DOWN edge with the repeat bit"); + } + } + + /// The key layout, byte for byte and written out a second time rather than through + /// `encode_key`. LG's fork: `state` u32 at +16, wcode at +20, sym at +24. Stock SDL (the + /// simulator): `state` u8 at +12, `repeat` u8 at +13, sym at +20, and a synthetic press carries + /// its wcode in `mod` at +24 under the `SYNTH_WINDOW` marker at +8. + #[test] + fn the_key_layout_is_pinned_byte_for_byte() { + // UP (0x40000052) with no wcode, and PLAY (wcode 450 = 0x1c2) with no sym. + let (up_sym, play_wcode) = ([0x52, 0x00, 0x00, 0x40], [0xc2, 0x01, 0x00, 0x00]); + let mut up = [0u8; 128]; + let mut play = [0u8; 128]; + let mut repeat = [0u8; 128]; + for ev in [&mut up, &mut play, &mut repeat] { + ev[0..4].copy_from_slice(&0x300u32.to_ne_bytes()); + } + if cfg!(feature = "hostsim") { + for ev in [&mut up, &mut play, &mut repeat] { + ev[12] = 1; + ev[8..12].copy_from_slice(&0x504c_584bu32.to_ne_bytes()); + } + up[20..24].copy_from_slice(&up_sym); + play[24..26].copy_from_slice(&450u16.to_ne_bytes()); + repeat[20..24].copy_from_slice(&up_sym); + repeat[13] = 1; + } else { + for ev in [&mut up, &mut play, &mut repeat] { + ev[16] = 1; + } + up[24..28].copy_from_slice(&up_sym); + play[20..24].copy_from_slice(&play_wcode); + repeat[24..28].copy_from_slice(&up_sym); + repeat[17] = 1; // state 0x101 + } + assert_eq!(decode_key(&up), (1, carried(0), 0x4000_0052)); + assert_eq!(decode_key(&play), (1, Some(450), 0)); + assert_eq!(decode_key(&repeat), (0x101, carried(0), 0x4000_0052)); + // a desktop press (no marker) never carries a wcode, whatever `mod` holds + if cfg!(feature = "hostsim") { + let mut real = up; + real[8..12].copy_from_slice(&1u32.to_ne_bytes()); + real[24..26].copy_from_slice(&0x1000u16.to_ne_bytes()); // a modifier bitmask + assert_eq!(decode_key(&real).1, None); + } + } + + /// SDL's quit and application events, decoded. The SDL codes are literals: the table is the + /// contract with SDL and with the tape, so it is not read back from the mapping it grades. + #[test] + fn quit_and_the_four_lifecycle_types_decode_and_the_lifecycle_codes_round_trip() { + for (code, event) in [ + (0x100, Decoded::Quit), + (0x103, Decoded::Lifecycle(Lifecycle::WillBackground)), + (0x104, Decoded::Lifecycle(Lifecycle::DidBackground)), + (0x105, Decoded::Lifecycle(Lifecycle::WillForeground)), + (0x106, Decoded::Lifecycle(Lifecycle::DidForeground)), + ] { + assert_eq!(decode(&event_of(code)), Some(event.clone()), "{code:#x}"); + assert!(!is_input_event(code), "{code:#x}: a window event is never a modal's input"); + if let Decoded::Lifecycle(edge) = event { + assert_eq!(edge.sdl_code(), code, "the code a decoded edge is read back as"); + } + } + } + + /// Everything the loop still reads raw stays raw: the IME's pre-edit (0x302), the SDL events + /// nothing acts on, and the types either side of the pointer and wheel block. + #[test] + fn every_other_event_stays_on_the_raw_path() { + for code in [0, 0x101, 0x102, 0x107, 0x200, 0x302, 0x3ff, 0x404, u32::MAX] { + assert_eq!(decode(&event_of(code)), None, "{code:#x}"); + } + } + + /// The boundary `Dispatcher::input_scope` rests on: every input kind is in, and the lifecycle + /// events, window events and quit are out. + #[test] + fn input_events_are_the_modals_and_lifecycle_events_are_the_apps() { + for et in [ + SDL_KEYDOWN, + SDL_KEYUP, + SDL_TEXTINPUT, + SDL_TEXTEDITING, + SDL_MOUSEMOTION, + SDL_MOUSEBUTTONDOWN, + SDL_MOUSEBUTTONUP, + SDL_MOUSEWHEEL, + ] { + assert!(is_input_event(et), "{et:#x} is input"); + } + for et in [SDL_QUIT, 0x101, 0x103, 0x104, 0x105, 0x106, 0x200] { + assert!(!is_input_event(et), "{et:#x} is the app's, not a modal's"); + } + } + + /// A pointer event as SDL lays it out, written by hand: `type` at +0, the window id at +8, the + /// button at +16 and its state at +17, then `Sint32 x` at +20 and `Sint32 y` at +24. LG's fork + /// and stock SDL2 agree on all of it (the keyboard event is the one that shifts), which is why + /// the decoder has one reading for both. + fn pointer_bytes(code: u32, button: u8, state: u8, x: i32, y: i32) -> [u8; 128] { + let mut ev = [0u8; 128]; + ev[0..4].copy_from_slice(&code.to_ne_bytes()); + ev[8..12].copy_from_slice(&7u32.to_ne_bytes()); + ev[16] = button; + ev[17] = state; + ev[20..24].copy_from_slice(&x.to_ne_bytes()); + ev[24..28].copy_from_slice(&y.to_ne_bytes()); + ev + } + + fn pointer(x: f32, y: f32, edge: PointerEdge) -> Option { + Some(Decoded::Pointer { x, y, edge }) + } + + const POINTERS: [(u32, PointerEdge); 3] = [ + (SDL_MOUSEMOTION, PointerEdge::Move), + (SDL_MOUSEBUTTONDOWN, PointerEdge::Down), + (SDL_MOUSEBUTTONUP, PointerEdge::Up), + ]; + + /// **The decode table.** Each of the three SDL types, at the corners and the middle of the + /// canvas and just outside it (a drag past the edge reports negative and over-large positions), + /// decodes to its edge and its position. The surface is the identity here (1920x1080, the + /// default), so the position is what the bytes say. + #[test] + fn an_sdl_pointer_event_decodes_to_its_edge_and_its_position() { + let _serial = plx_base::testlock::serial(); + for (code, edge) in POINTERS { + for (x, y) in [(0, 0), (960, 540), (1919, 1079), (1400, 870), (-3, 1085), (2000, -1)] { + assert_eq!( + decode(&pointer_bytes(code, 1, 1, x, y)), + pointer(x as f32, y as f32, edge), + "{code:#x} at ({x}, {y})" + ); + } + } + } + + /// **The edge is the event type alone**, for any button and whatever its state byte says: a + /// button-up carrying state 1, a button-down carrying state 0 and a motion with a button byte + /// set are still an up, a down and a move. Bytes the decoder must not read are noise here. + #[test] + fn the_edge_is_the_event_type_whatever_the_button_bytes_say() { + let _serial = plx_base::testlock::serial(); + for button in [0u8, 1, 2, 3, 255] { + for state in [0u8, 1] { + for (code, edge) in POINTERS { + let mut ev = pointer_bytes(code, button, state, 640, 360); + ev[28..64].fill(0xa5); + assert_eq!(decode(&ev), pointer(640.0, 360.0, edge), "{code:#x} button {button} state {state}"); + } + } + } + } + + /// The bytes the synthesis writes (`encode_pointer`) decode to the position and edge they were + /// built from. The encoder and the decoder shipped apart once for keys; this is what couples + /// them for the pointer. + #[test] + fn the_synthesized_pointer_bytes_round_trip() { + let _serial = plx_base::testlock::serial(); + for (code, edge) in POINTERS { + for (x, y) in [(0, 0), (1400, 870), (1919, 1079), (-200, 400)] { + let ev = encode_pointer(code, x, y); + assert_eq!(rd_u32(&ev, 0), code); + assert_eq!(decode(&ev), pointer(x as f32, y as f32, edge), "{code:#x}"); + if code != SDL_MOUSEMOTION { + assert_eq!(ev[16], 1, "the left button survives SDL's event queue"); + assert_eq!(ev[17], u8::from(code == SDL_MOUSEBUTTONDOWN)); + } + } + } + } + + /// A wheel event as the television's SDL2 lays it out: `Sint32 y` at +20. + fn wheel_lg(dy: i32) -> [u8; 128] { + let mut ev = event_of(SDL_MOUSEWHEEL); + ev[20..24].copy_from_slice(&dy.to_ne_bytes()); + ev + } + + /// A wheel event as the simulator's stock SDL2 (sdl2-compat over SDL3) delivers it: the count + /// in the float `preciseY` at +32, with the legacy integer at +20 left at zero. + fn wheel_stock(precise_y: f32) -> [u8; 128] { + let mut ev = event_of(SDL_MOUSEWHEEL); + ev[32..36].copy_from_slice(&precise_y.to_ne_bytes()); + ev + } + + fn wheel(dy: i32) -> Option { + Some(Decoded::Wheel { dy }) + } + + /// **Each layout's wheel, and the one this build does not read.** The television's integer at + /// +20 is the count in the default build and is ignored in the simulator's; the simulator's + /// float at +32 is the count there (rounded to whole ticks) and is ignored on the television. + #[test] + fn a_wheel_tick_is_read_from_the_offset_this_hosts_sdl_carries_it_at() { + for dy in [-40, -3, -1, 1, 2, 120] { + if cfg!(feature = "hostsim") { + assert_eq!(decode(&wheel_stock(dy as f32)), wheel(dy), "stock layout, {dy}"); + assert_eq!(decode(&wheel_lg(dy)), wheel(0), "the television's field is not this host's: {dy}"); + } else { + assert_eq!(decode(&wheel_lg(dy)), wheel(dy), "LG layout, {dy}"); + assert_eq!(decode(&wheel_stock(dy as f32)), wheel(0), "the simulator's field is not read here: {dy}"); + } + } + } + + /// A fractional trackpad tick keeps the sign of what it rounds to, and a half tick or less is + /// no tick (the loop records a zero and ignores it). Only the simulator's layout carries one. + #[cfg(feature = "hostsim")] + #[test] + fn a_fractional_trackpad_tick_rounds_to_whole_ticks() { + for (precise, dy) in [(-0.4, 0), (0.4, 0), (-0.6, -1), (0.6, 1), (-1.4, -1), (2.5, 3), (-40.0, -40)] { + assert_eq!(decode(&wheel_stock(precise)), wheel(dy), "{precise}"); + } + } + + /// A key edge decodes with its packed state and the carrier's wcode, a text commit with this + /// build's offset, and the events nothing reads stay `None`. + #[test] + fn a_key_and_a_text_commit_decode_to_their_neutral_values() { + let key = decode(&encode_key(0x4000_0052, 0, true)); + assert_eq!(key, Some(Decoded::Key { state: 1, wcode: carried(0), sym: 0x4000_0052 })); + assert_eq!(decode(&crate::text::encode_event("star wars")), Some(Decoded::Text("star wars".into()))); + assert_eq!(decode(&event_of(SDL_TEXTEDITING)), None); + } +} diff --git a/rust-modules/shell-sdl/src/init.rs b/rust-modules/shell-sdl/src/init.rs new file mode 100644 index 0000000000..89eb46b4d5 --- /dev/null +++ b/rust-modules/shell-sdl/src/init.rs @@ -0,0 +1,189 @@ +//! SDL's process-level lifecycle: bring-up, the GL context request, the hint door, the idle sleep +//! and the quit. Everything here runs on the SDL main thread, which the caller proves with the +//! `&MainThread` it was handed. +use crate::sys; +use plx_base::eventlog::log; +use plx_base::task::MainThread; +use std::ffi::CStr; +use std::os::raw::c_int; + +/// The two steps a platform runs around `SDL_Init` (`before`: it reads hints SDL consults while it +/// initialises; `after`: it uses what `SDL_Init` set up). Plain function pointers, so the crate +/// names nothing of the platform that supplies them: the television's are LG-fork code, and a +/// desktop's are no-ops ([`InitHooks::NONE`]). +#[derive(Clone, Copy)] +pub struct InitHooks { + pub before: unsafe fn(), + pub after: unsafe fn(), +} + +impl InitHooks { + /// A platform with nothing to do around `SDL_Init`. + pub const NONE: InitHooks = InitHooks { before: noop, after: noop }; +} + +unsafe fn noop() {} + +/// `SDL_Init` refused (the reason is the log line `SDL_Init failed`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InitFailed; + +const SDL_INIT_VIDEO: u32 = 0x20; + +// SDL_GLattr enum +const A_RED: c_int = 0; +const A_GREEN: c_int = 1; +const A_BLUE: c_int = 2; +const A_ALPHA: c_int = 3; +const A_BUFFER_SIZE: c_int = 4; +const A_DEPTH: c_int = 6; +const A_STENCIL: c_int = 7; +const A_CTX_MAJOR: c_int = 17; +const A_CTX_MINOR: c_int = 18; +const A_CTX_PROFILE_MASK: c_int = 21; +const CTX_PROFILE_ES: c_int = 0x0004; +/// `SDL_GL_CONTEXT_PROFILE_CORE` — the simulator's only option on macOS. See [`request_gl`]. +const CTX_PROFILE_CORE: c_int = 0x0001; + +/// Bring SDL's video subsystem up: tell SDL the entry point is ours, state the screensaver intent, +/// run `hooks.before`, `SDL_Init(VIDEO)`, run `hooks.after`, and log the driver it picked. +/// +/// # Safety +/// Once, before any other SDL call (the `&MainThread` is the proof of the thread); and `hooks` +/// must be sound to call on that thread at those two points. +pub unsafe fn init(_mt: &MainThread, hooks: InitHooks) -> Result<(), InitFailed> { + sys::SDL_SetMainReady(); + // DEAD END, measured 2026-07-31 — do not re-try this. The obvious answer to "a parked TV + // should blank itself" is to stop inhibiting the platform screensaver here (and re-allow it + // per route, since webOS BACKGROUNDS the app to run one and `0x103` suspends the + // buffer-feed, so it could never be on during playback). It does not work, for a reason + // upstream of this app: the TV's SDL 2.0.4 fork carries the + // `SDL_VIDEO_ALLOW_SCREENSAVER` hint STRING but implements no wayland idle-inhibit + // (`strings libSDL2-2.0.so.0` finds no `idle_inhibit`/`suspend_screensaver` symbol), so + // this call and `SDL_EnableScreenSaver` are both no-ops. Soaked 34 min on Home with the + // TV's own `screenSaverEnabled: on`: no screensaver, no `LIFECYCLE: background`, CPU flat, + // our UI still at full brightness on the panel. webOS does not blank a foreground native + // app, and nothing reachable from SDL changes that. The line stays because it costs + // nothing and states the intent; it is not what keeps the screensaver away. + sys::SDL_SetHint(c"SDL_VIDEO_ALLOW_SCREENSAVER".as_ptr(), c"0".as_ptr()); + (hooks.before)(); + if sys::SDL_Init(SDL_INIT_VIDEO) != 0 { + log("SDL_Init failed"); + return Err(InitFailed); + } + (hooks.after)(); + { + let d = sys::SDL_GetCurrentVideoDriver(); + if !d.is_null() { + log(&format!( + "video driver: {}", + std::ffi::CStr::from_ptr(d).to_string_lossy() + )); + } + } + Ok(()) +} + +/// Ask SDL for the GL context [`crate::window::Window::open`] will create. It is its own call +/// because the application reads the stored session between the request and the window (the +/// window size is a setting), and that order is pinned. +/// +pub fn request_gl(_mt: &MainThread) { + unsafe { request_gl_attributes() } +} + +unsafe fn request_gl_attributes() { + // The television has a real GLES2 driver (a shim over libmali). macOS has none at all — + // Apple ships desktop GL only, capped at 4.1 core — so asking for ES here fails context + // creation outright. 4.1 core is the closest thing that exists, and it is a superset for + // everything this renderer does: a real VBO (never client arrays) and RGBA/UNSIGNED_BYTE + // textures, both core-profile-legal. The shader sources are adapted at compile time by + // `gfx::glsl_preamble`, which reads the driver's GLSL version rather than assuming. + if cfg!(feature = "hostsim") { + sys::SDL_GL_SetAttribute(A_CTX_PROFILE_MASK, CTX_PROFILE_CORE); + sys::SDL_GL_SetAttribute(A_CTX_MAJOR, 4); + sys::SDL_GL_SetAttribute(A_CTX_MINOR, 1); + } else { + sys::SDL_GL_SetAttribute(A_CTX_PROFILE_MASK, CTX_PROFILE_ES); + sys::SDL_GL_SetAttribute(A_CTX_MAJOR, 2); + sys::SDL_GL_SetAttribute(A_CTX_MINOR, 0); + } + // full 32-bit RGBA so the video plane shows through + sys::SDL_GL_SetAttribute(A_RED, 8); + sys::SDL_GL_SetAttribute(A_GREEN, 8); + sys::SDL_GL_SetAttribute(A_BLUE, 8); + sys::SDL_GL_SetAttribute(A_ALPHA, 8); + sys::SDL_GL_SetAttribute(A_BUFFER_SIZE, 32); + // ...and NO depth or stencil, which SDL would otherwise give us anyway: its defaults are + // 16 bits of depth and 0 of stencil, and asking for neither had simply never been written + // down. **This renderer has no use for either.** There is no `GL_DEPTH_TEST`, no + // `glDepthFunc`, no `glDepthMask` and no `glClear(GL_DEPTH_BUFFER_BIT)` anywhere in the + // crate — every screen is painter's-algorithm 2-D, drawn back to front — and the one + // scissor user (`gfx::clip_set`) is a scissor, not a stencil. + // + // On a TILER this is not merely 4 MB of address space. Midgard allocates the depth buffer + // per tile alongside colour and, unless the driver proves it dead, RESOLVES it to memory at + // end-of-frame: 1920x1080x2 bytes written per presented frame for a buffer nothing ever + // reads. The application's `system.rs` logs what the config actually came back with — a + // request is not a grant, and the only honest confirmation is `FB bits: … depth=0`. + sys::SDL_GL_SetAttribute(A_DEPTH, 0); + sys::SDL_GL_SetAttribute(A_STENCIL, 0); +} + +/// `SDL_SetHint`: the one way a platform's own boot code states a hint to SDL (LG's +/// `SDL_WEBOS_CURSOR_SLEEP_TIME`, read in `SDL_Init`). `true` when SDL took it. +pub fn set_hint(name: &CStr, value: &CStr) -> bool { + unsafe { sys::SDL_SetHint(name.as_ptr(), value.as_ptr()) != 0 } +} + +/// `SDL_Quit`. The caller decides WHEN (the application's `shutdown` skips it while a native +/// worker is still inside firmware): this only does it. +/// +/// # Safety +/// Main thread, after SDL's last use; nothing may call into SDL afterwards. +pub unsafe fn quit() { + sys::SDL_Quit(); +} + +/// `SDL_Delay`: the idle loop's sleep. +pub fn delay_ms(ms: u32) { + unsafe { sys::SDL_Delay(ms) }; +} + +#[cfg(test)] +mod tests { + /// A hostile platform step is the caller's to get right, but the shape the crate promises is + /// that `init` runs `before` ahead of `SDL_Init` and `after` behind it; the source order is the + /// proof, because no host test can run `SDL_Init` on the video subsystem. + #[test] + fn the_before_hook_runs_ahead_of_sdl_init_and_the_after_hook_behind_it() { + let source = include_str!("init.rs"); + let body = source + .split_once(concat!("pub unsafe fn ", "init(")) + .expect("init") + .1 + .split_once(concat!("pub fn ", "request_gl(")) + .expect("the end of init") + .0; + let before = body.find(concat!("(hooks.", "before)()")).expect("init runs the before hook"); + let call = body.find(concat!("sys::SDL_Init(", "SDL_INIT_VIDEO)")).expect("init calls SDL_Init"); + let after = body.find(concat!("(hooks.", "after)()")).expect("init runs the after hook"); + assert!(before < call && call < after, "before < SDL_Init < after"); + assert_eq!(body.matches(concat!("sys::SDL_Init(", "SDL_INIT_VIDEO)")).count(), 1); + } + + /// `SDL_Init` is the only video bring-up this crate makes, and the GL request must not ride + /// inside it: the application reads the stored session between the two. + #[test] + fn the_gl_request_is_not_part_of_init() { + let source = include_str!("init.rs"); + let body = source + .split_once(concat!("pub unsafe fn ", "init(")) + .expect("init") + .1 + .split_once(concat!("pub fn ", "request_gl(")) + .expect("the end of init") + .0; + assert!(!body.contains(concat!("SDL_GL_Set", "Attribute")), "init must not request the GL context"); + } +} diff --git a/rust-modules/shell-sdl/src/inject.rs b/rust-modules/shell-sdl/src/inject.rs new file mode 100644 index 0000000000..b033dfe087 --- /dev/null +++ b/rust-modules/shell-sdl/src/inject.rs @@ -0,0 +1,232 @@ +//! Synthetic input: the bytes of a key, pointer, wheel or lifecycle event in whichever layout +//! [`crate::event`] reads, and the pushes that put them on SDL's own queue so the existing poll loop +//! consumes them as if they had come off the wayland input path. These are the crate's only +//! `SDL_PushEvent` sites. The remote FIFO, Lab Control and the replay driver call them (through the +//! application's token parser, which owns the vocabulary), and so does the production cursor-swap OK. +//! +//! **A synthetic text event is never pushed**: see `text.rs`. `encode_event` builds the bytes and the +//! application's `txt:` token hands them to the decode directly. +//! +//! The encoders are pure and separate from the pushes that consume them, precisely so a host test +//! can run them: a `make check` test binary pushes nothing. +use crate::event::{ + push, rd_u32, SDL_KEYDOWN, SDL_KEYUP, SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP, SDL_MOUSEMOTION, + SDL_MOUSEWHEEL, SYNTH_WINDOW, +}; +use std::os::raw::c_uint; + +/// The bytes a synthetic key event needs, in whichever layout [`crate::event::decode_key`] reads. +/// +/// **The inverse of `decode_key`, and the pair is only correct together.** They already shipped +/// disagreeing once: the simulator accepted every FIFO token and never moved, because this end +/// wrote LG's fork layout while the reading end had been taught stock SDL2's. Nothing in the +/// compiler couples them, so `key_bytes_round_trip` (in `event.rs`) is what does. +/// +/// Pure, and separate from the `SDL_PushEvent` that consumes it, precisely so that test can run on +/// the host — `make check` links no SDL. +pub fn encode_key(sym: c_uint, wcode: c_uint, down: bool) -> [u8; 128] { + let mut ev = [0u8; 128]; + ev[0..4].copy_from_slice(&if down { SDL_KEYDOWN } else { SDL_KEYUP }.to_ne_bytes()); + if cfg!(feature = "hostsim") { + ev[12] = u8::from(down); // state + ev[13] = 0; // repeat + ev[20..24].copy_from_slice(&sym.to_ne_bytes()); + // The wcode rides `SDL_Keysym.mod` (event offset +24, a `Uint16`), under a marker in + // `windowID` that says this press is synthetic at all. Several tokens carry ONLY a wcode + // (`pause` is sym 0, wcode 72), so deriving it from the sym is not an option. + // `decode_key`'s doc has the measurement behind both fields — the short version is that of + // the spare places to put a value, these two are the ones sdl2-compat does not discard. + ev[8..12].copy_from_slice(&SYNTH_WINDOW.to_ne_bytes()); + ev[24..26].copy_from_slice(&(wcode as u16).to_ne_bytes()); + } else { + ev[16..20].copy_from_slice(&if down { 1u32 } else { 0 }.to_ne_bytes()); // state + ev[20..24].copy_from_slice(&wcode.to_ne_bytes()); + ev[24..28].copy_from_slice(&sym.to_ne_bytes()); + } + ev +} + +/// The bytes a synthetic HARDWARE AUTO-REPEAT edge carries — `encode_key`'s down edge with the +/// 0x101 shape (`state & 0x100 != 0`) the loop's repeat arm requires, in whichever layout +/// `decode_key` reads. `encode_key` itself must never produce this (`key_bytes_round_trip` pins +/// that a synthetic EDGE "must never look like auto-repeat"), so it is a second, deliberately +/// separate function rather than a third argument threaded through the first — item 13's +/// `holdrep:` FIFO token is the only caller, and it exists so a script can exercise the +/// `Edge::Repeat` a screen receives without a real remote's own repeat cadence. +pub fn encode_key_repeat(sym: c_uint, wcode: c_uint) -> [u8; 128] { + let mut ev = encode_key(sym, wcode, true); + if cfg!(feature = "hostsim") { + ev[13] = 1; // the `repeat` byte `decode_key`'s hostsim arm folds into `state & 0x100` + } else { + let state = rd_u32(&ev, 16) | 0x100; + ev[16..20].copy_from_slice(&state.to_ne_bytes()); + } + ev +} + +/// SDL pointer bytes shared by clicks, held-pointer FIFO edges and recorded-event replay. +/// The inverse of `ptr_xy`: convert authored coordinates exactly once, including window scaling +/// and letterboxing. Replay may carry a real off-canvas motion, so only the token parser clamps. +/// ABI: SDL's `SDL_events.h` (stock and the NDK's) mouse-event declarations put four +/// Uint32 fields before button@16/state@17 and Sint32 x@20/y@24. ARM32 NDK syntax-only +/// `offsetof` assertions verified these offsets; see `docs/testing-player-pointer.md`. +pub fn encode_pointer(et: u32, x: i32, y: i32) -> [u8; 128] { + let mut ev = [0u8; 128]; + let (px, py) = plx_base::surface::to_physical(x as f32, y as f32); + ev[0..4].copy_from_slice(&et.to_ne_bytes()); + ev[20..24].copy_from_slice(&(px.round() as i32).to_ne_bytes()); + ev[24..28].copy_from_slice(&(py.round() as i32).to_ne_bytes()); + if matches!(et, SDL_MOUSEBUTTONDOWN | SDL_MOUSEBUTTONUP) { + ev[16] = 1; // SDL_BUTTON_LEFT + ev[17] = u8::from(et == SDL_MOUSEBUTTONDOWN); + } + ev +} + +/// The bytes of one app lifecycle event (`0x103`–`0x106`), as the compositor would send it. +pub fn encode_lifecycle(code: u32) -> [u8; 128] { + let mut ev = [0u8; 128]; + ev[0..4].copy_from_slice(&code.to_ne_bytes()); + ev +} + +/// The bytes of one scroll-wheel tick, in the plain, real-SDL2 shape (`Sint32 y` at `+20`) +/// unconditionally: it is the READING side that has to branch by platform now, not this one — see +/// [`crate::event::decode_wheel_dy`] on why `+20` decodes to 0 on this host and where the value +/// actually lands after `SDL_PushEvent` round-trips it. +pub fn encode_wheel(dy: i32) -> [u8; 128] { + let mut ev = [0u8; 128]; + ev[0..4].copy_from_slice(&SDL_MOUSEWHEEL.to_ne_bytes()); + ev[20..24].copy_from_slice(&dy.to_ne_bytes()); + ev +} + +/// Synthesize a Magic-Remote pointer click at authored 1920x1080 coords (the browser +/// remote's click-on-the-stream): two motion events, then button down+up. The first +/// motion is a >=120px jitter so the accumulated pointer distance defeats the +/// D-pad-mode pointer gate (`Pointer::mot_accum < 120` swallows small motions after D-pad use); +/// the second lands on the target. The LG SDL fork's mouse events carry x@20 / y@24 +/// (i32) — the only fields the handlers read. +/// +/// The browser still sends clicks only: forwarding hover moved app focus on every pass of the +/// mouse over the streamed picture. A driver can explicitly send `pm:`/`pd:`/`pu:` instead to +/// separate HUD reveal from a press or to hold a drag across frames. Those edges add no jitter. +pub fn synth_ptr(x: i32, y: i32) { + let jx = if x >= 200 { x - 200 } else { x + 200 }; + synth_pointer(SDL_MOUSEMOTION, jx, y); + synth_pointer(SDL_MOUSEMOTION, x, y); + synth_pointer(SDL_MOUSEBUTTONDOWN, x, y); + synth_pointer(SDL_MOUSEBUTTONUP, x, y); +} + +/// ONE pointer event in authored coordinates, shared by the FIFO and replay. Unlike `ck:`, +/// these primitives add no motion or release: `pd:` stays held until a separate `pu:` arrives. +pub fn synth_pointer(et: u32, x: i32, y: i32) { + push(&encode_pointer(et, x, y)); +} + +/// One app lifecycle event (`0x103`–`0x106`), as the compositor would send it — the replay +/// driver's re-injection of a recorded background/foreground edge. +pub fn synth_lifecycle(code: u32) { + push(&encode_lifecycle(code)); +} + +/// Synthesize a full remote-key press (key-down then key-up) and push both onto SDL's +/// own event queue, so the existing poll loop consumes them as if they came off the +/// wayland input path. The LG SDL fork's `SDL_KeyboardEvent` carries state@16 / +/// wcode@20 / sym@24 (native-endian; the TV is LE), and the handler reads press vs +/// release from `state & 0xff` — so the down carries state=1, the up state=0. Both +/// are required: a grid-card OK arms on down and *commits on release*. +pub fn synth_key(sym: c_uint, wcode: c_uint) { + synth_key_edge(sym, wcode, true); + synth_key_edge(sym, wcode, false); +} + +/// ONE edge of a remote key press. Split out for the `okdown`/`okup` FIFO tokens, because a +/// **press-and-hold** is only expressible as two tokens with real time between them: the item menu +/// opens on `press::is_long`, which measures the interval between the down and the up. The paired +/// [`synth_key`] above is this called twice back to back (a tap). +pub fn synth_key_edge(sym: c_uint, wcode: c_uint, down: bool) { + push(&encode_key(sym, wcode, down)); +} + +/// ONE hardware auto-repeat edge — item 13's `holdrep:` FIFO token, which lets a script +/// exercise a held key's `Edge::Repeat` (the Settings family's paced focus walk, the player +/// scrubber's continuous scrub) without a real remote's own repeat cadence. Only recognised as a +/// repeat by the loop's key arm when `App::down_sym` already equals `sym` — i.e. after a +/// `holddown:` and before its matching `holdup:`, the same split `okdown`/`okup` +/// already uses for a press-and-hold. +pub fn synth_key_repeat(sym: c_uint, wcode: c_uint) { + push(&encode_key_repeat(sym, wcode)); +} + +/// Synthesize one Magic-Remote scroll-wheel tick — item 13's `wheel:` FIFO token, so a script +/// can drive the wheel with no mouse in the room. See [`encode_wheel`] for the layout. +pub fn synth_wheel(dy: i32) { + push(&encode_wheel(dy)); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::event::{decode_wheel_dy, rd_i32, SDL_QUIT}; + + #[test] + fn a_key_event_carries_its_type_and_a_repeat_is_never_a_plain_edge() { + assert_eq!(rd_u32(&encode_key(5, 6, true), 0), SDL_KEYDOWN); + assert_eq!(rd_u32(&encode_key(5, 6, false), 0), SDL_KEYUP); + assert_ne!(encode_key(5, 6, true), encode_key_repeat(5, 6)); + assert_eq!(rd_u32(&encode_key_repeat(5, 6), 0), SDL_KEYDOWN); + } + + /// The `wheel:` token writes the television's shape unconditionally: the count at +20 and the + /// float the simulator's decoder reads left empty, which is why it decodes to zero there. + #[test] + fn the_wheel_bytes_are_the_television_shape_whatever_the_build() { + let ev = encode_wheel(-3); + assert_eq!(rd_u32(&ev, 0), SDL_MOUSEWHEEL); + assert_eq!(rd_i32(&ev, 20), -3); + assert_eq!(decode_wheel_dy(&ev), if cfg!(feature = "hostsim") { 0 } else { -3 }); + } + + #[test] + fn a_lifecycle_event_is_its_code_and_nothing_else() { + let ev = encode_lifecycle(0x104); + assert_eq!(rd_u32(&ev, 0), 0x104); + assert!(ev[4..].iter().all(|&b| b == 0)); + assert_eq!(rd_u32(&encode_lifecycle(SDL_QUIT), 0), SDL_QUIT); + } + + /// **The queue really carries what is pushed.** A click is four events through SDL's own queue: + /// a motion at least 120 px away (it defeats the D-pad-mode pointer gate), the motion onto the + /// target, then the button down and up, in that order. This is the one test that reaches + /// `SDL_PushEvent` and `SDL_PollEvent`, which is what links `sys.rs`'s event externs for real. + #[test] + fn a_click_is_four_events_in_order_through_sdl_s_own_queue() { + use crate::event::{decode, poll, Decoded, PointerEdge}; + let _serial = plx_base::testlock::serial(); + let _events = crate::testing::EventsOnly::init(); + let mut ev = [0u8; 128]; + while poll(&mut ev) {} // whatever an earlier test left behind + synth_ptr(1400, 870); + let mut got = Vec::new(); + while poll(&mut ev) { + got.push(decode(&ev)); + } + let edges: Vec<_> = got + .iter() + .map(|d| match d { + Some(Decoded::Pointer { x, y, edge }) => (*edge, *x, *y), + other => panic!("a click pushes pointer events only, got {other:?}"), + }) + .collect(); + assert_eq!( + edges.iter().map(|e| e.0).collect::>(), + [PointerEdge::Move, PointerEdge::Move, PointerEdge::Down, PointerEdge::Up] + ); + assert!((edges[0].1 - 1400.0).abs() >= 120.0, "the first motion is the jitter: {:?}", edges[0]); + for e in &edges[1..] { + assert_eq!((e.1, e.2), (1400.0, 870.0), "the rest land on the target"); + } + } +} diff --git a/rust-modules/shell-sdl/src/lib.rs b/rust-modules/shell-sdl/src/lib.rs new file mode 100644 index 0000000000..a36cea0cb4 --- /dev/null +++ b/rust-modules/shell-sdl/src/lib.rs @@ -0,0 +1,94 @@ +//! PlxNative's stock-SDL shell: SDL's bring-up and quit, the window and its GL context, the swap, +//! the event queue, the key, pointer, wheel and text layouts of both SDLs this project runs on, and +//! the synthetic events that go back into that queue. +//! +//! This is the half of the platform that is SDL2 and nothing else. The television's LG half (its +//! Wayland handles, the opaque region, the pointer hide, the cursor-sleep hint) is webOS code and +//! stays in the application crate's `system.rs`, reached only through the webOS platform; this +//! crate names none of it, and none of `ui`, `machine`, `os` or any application type. The contract +//! between the two halves is one raw `SDL_Window*` ([`window::Window::raw`]) and the order of calls +//! on one thread. [`init::InitHooks`] is the one place the platform reaches INTO SDL's bring-up, +//! as two plain function pointers the television fills and a desktop leaves empty. +//! +//! The crate is a mounted module of the `shell_sdl` layer (`ci/module-layers.ini`), which may use +//! `base`, `machine` and `os`; the crate names `base` alone. The application's `Shell` and `Surface` traits and its `HostEvent` stay app-private +//! (`docs/platform-ports.md`, Target shapes 1 and 8); [`window::Window`] is the one SDL +//! implementation of that `Surface`, and [`event::Decoded`] is the neutral value the application maps +//! onto its own event type. +//! +//! ## One crate, both SDLs +//! +//! The television's SDL is a fork (LG's, 2.0.5-based) that lays its keyboard, text and wheel events +//! out differently from the stock SDL2 a desktop links. The choice is `cfg!(feature = "hostsim")` +//! and never `#[cfg]`, so both arms of every layout compile in every build and the one nobody is +//! building cannot rot; the `hostsim` feature is forwarded from the application crate, which is the +//! only one that sets it. +//! +//! ## Tests +//! +//! `cfg(test)` does not cross a crate boundary, so the dependents' test builds get the stubs and the +//! event-queue guard through the `test-support` feature ([`testing`]); a shipped build has neither. +pub mod event; +pub mod init; +pub mod inject; +mod sys; +pub mod text; +#[cfg(any(test, feature = "test-support"))] +pub mod testing; +pub mod window; + +pub use init::{set_hint, InitFailed, InitHooks}; +pub use window::{OpenAsk, OpenFailed, Placement, Window}; + +#[cfg(test)] +mod pins { + /// Every source file of this crate, by name, for the tests that read source. A new file that is + /// not listed here is not scanned, which is why the list is checked against the directory. + const SOURCES: [(&str, &str); 8] = [ + ("lib.rs", include_str!("lib.rs")), + ("sys.rs", include_str!("sys.rs")), + ("init.rs", include_str!("init.rs")), + ("window.rs", include_str!("window.rs")), + ("event.rs", include_str!("event.rs")), + ("inject.rs", include_str!("inject.rs")), + ("text.rs", include_str!("text.rs")), + ("testing.rs", include_str!("testing.rs")), + ]; + + #[test] + fn every_source_file_is_scanned() { + let mut on_disk: Vec = std::fs::read_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/src")) + .expect("the crate's src directory") + .map(|e| e.expect("a directory entry").file_name().to_string_lossy().into_owned()) + .collect(); + on_disk.sort(); + let mut listed: Vec<&str> = SOURCES.iter().map(|s| s.0).collect(); + listed.sort(); + assert_eq!(on_disk, listed, "a source file this crate gained is not read by the pins below"); + } + + /// **The television's SDL writes a LARGER `SDL_SysWMinfo` than the headers declare**, so a bare + /// struct on the stack is the "modular-split crash" and the over-allocated buffer with its + /// version handshake lives in the application crate's `system.rs`, beside the rest of the LG + /// half. Nothing in this crate may call it: not for the window, not for a size, not "just to + /// read the display". + #[test] + fn this_crate_never_calls_the_wayland_info_query() { + let needle = concat!("SDL_GetWindow", "WMInfo"); + for (name, text) in SOURCES { + assert!(!text.contains(needle), "{name} names the television's over-writing query"); + } + } + + /// The crate links SDL plainly (`sys.rs`), and it must not grow a Wayland or glib call of its + /// own: those are the television's half and are fenced to the webOS platform by + /// `ci/check-module-layers.py`, which cannot see an `extern` block. + #[test] + fn this_crate_names_no_wayland_or_luna_symbol() { + for needle in [concat!("wl_", "proxy"), concat!("wl_", "display"), concat!("LS", "Register"), concat!("g_main_", "context")] { + for (name, text) in SOURCES { + assert!(!text.contains(needle), "{name} names {needle}"); + } + } + } +} diff --git a/rust-modules/shell-sdl/src/sys.rs b/rust-modules/shell-sdl/src/sys.rs new file mode 100644 index 0000000000..3d2f674c35 --- /dev/null +++ b/rust-modules/shell-sdl/src/sys.rs @@ -0,0 +1,79 @@ +//! Every SDL2 symbol this crate calls, declared once. A PLAIN link, not `dynlib!`: the rule in +//! `plx_base::dynlib` is for libraries whose SONAME moves, and these are stock public SDL2 API that +//! every firmware inventory exports (`tools/fwcompat.py --lib libSDL2-2.0.so.0` finds the whole +//! family on all 14 images), so there is nothing here for a runtime bind to tolerate. +//! +//! The Wayland and `SDL_SysWMinfo` calls are NOT here and never may be: the television's SDL fork +//! writes a larger `SDL_SysWMinfo` than the headers declare, and that over-allocated buffer +//! lives in the application crate's `system.rs` with the rest of the LG half (a pin in `lib.rs` +//! keeps this file from naming it). +#![allow(non_snake_case)] +use std::os::raw::{c_char, c_int, c_void}; + +extern "C" { + pub(crate) fn SDL_SetMainReady(); + pub(crate) fn SDL_SetHint(name: *const c_char, value: *const c_char) -> c_int; + pub(crate) fn SDL_Init(flags: u32) -> c_int; + pub(crate) fn SDL_GetCurrentVideoDriver() -> *const c_char; + pub(crate) fn SDL_GL_SetAttribute(attr: c_int, value: c_int) -> c_int; + pub(crate) fn SDL_CreateWindow( + title: *const c_char, + x: c_int, + y: c_int, + w: c_int, + h: c_int, + flags: u32, + ) -> *mut c_void; + pub(crate) fn SDL_DestroyWindow(win: *mut c_void); + pub(crate) fn SDL_GL_CreateContext(win: *mut c_void) -> *mut c_void; + pub(crate) fn SDL_GL_SetSwapInterval(interval: c_int) -> c_int; + pub(crate) fn SDL_Delay(ms: u32); + pub(crate) fn SDL_PollEvent(event: *mut c_void) -> c_int; + pub(crate) fn SDL_PushEvent(event: *const c_void) -> c_int; + pub(crate) fn SDL_GL_SwapWindow(win: *mut c_void); + pub(crate) fn SDL_Quit(); +} + +// Desktop-only window management. Apart for the mirror-image reason: a television owns the whole +// panel and never asks how big a display is, so on that build these would be dead code — which +// `[workspace.lints.rust] warnings = "deny"` makes a build failure, not a warning. +#[cfg(feature = "hostsim")] +extern "C" { + /// `SDL_GetDisplayUsableBounds` — the display minus the menu bar and the Dock, which is what + /// a window may actually occupy. The out parameter is an `SDL_Rect`: exactly four `c_int`. + pub(crate) fn SDL_GetDisplayUsableBounds(display: c_int, rect: *mut c_int) -> c_int; + /// `SDL_SetWindowSize` / `SDL_SetWindowPosition` — `window::fit_window_to_density` re-sizes + /// and re-centres the window once the display's pixel density has been measured from it. + pub(crate) fn SDL_SetWindowSize(win: *mut c_void, w: c_int, h: c_int); + pub(crate) fn SDL_SetWindowPosition(win: *mut c_void, x: c_int, y: c_int); +} + +// The system on-screen keyboard (`text`). The text-input family is stock public SDL2 API. +// +// Under `cfg(test)` and the `test-support` feature the four calls a host test could reach are +// swapped for `text::stubs`, so these declarations lose their last use there and warn; the +// `allow(dead_code)` is narrower than it looks: a real orphan would be silent in every +// configuration, and these are live on device. +extern "C" { + #[allow(dead_code)] + pub(crate) fn SDL_StartTextInput(); + #[allow(dead_code)] + pub(crate) fn SDL_StopTextInput(); + pub(crate) fn SDL_IsTextInputActive() -> c_int; + #[allow(dead_code)] + pub(crate) fn SDL_HasScreenKeyboardSupport() -> c_int; + /// LG's `WebOSIsScreenKeyboardShown`, the fourth of the four hooks its Wayland driver installs. + /// Exported by all 14 inventories, and **it does not answer the question its name asks** on this + /// firmware — the app's `textinput` note has the measurement and what replaced it. Declared, + /// unused, and kept so the next person finds the finding before they find the symbol. + #[allow(dead_code)] + pub(crate) fn SDL_IsScreenKeyboardShown(w: *mut c_void) -> c_int; + #[allow(dead_code)] + pub(crate) fn SDL_GetWindowFlags(w: *mut c_void) -> u32; + /// Turn the DRIVER's own tracing on for one category. LG's `WebOSShowScreenKeyboard` / + /// `Hide` / `TextModelLeave` / `TextModelInputPanelState` all log through SDL at + /// `SDL_LOG_CATEGORY_INPUT`, which is silent at the default priority — so this is how the + /// keyboard's real lifecycle becomes readable without patching SDL. + #[allow(dead_code)] // test build only — see the note above `SDL_StartTextInput` + pub(crate) fn SDL_LogSetPriority(category: c_int, priority: c_int); +} diff --git a/rust-modules/shell-sdl/src/testing.rs b/rust-modules/shell-sdl/src/testing.rs new file mode 100644 index 0000000000..d033e01ef0 --- /dev/null +++ b/rust-modules/shell-sdl/src/testing.rs @@ -0,0 +1,23 @@ +//! Test scaffolding for the code that polls or pushes SDL events: only SDL's event subsystem, with +//! no window, renderer, boot or device. Compiled for this crate's own tests and, through the +//! `test-support` feature, for the dependents' test builds (the application's loop tests poll SDL +//! when a by-id token drains it first). Never in a shipped build. +use crate::sys; + +/// SDL's event subsystem alone (`SDL_INIT_EVENTS`), brought up for the duration of a test and +/// quit when dropped. A test that holds one serialises on `plx_base::testlock::serial()` first, +/// because SDL's queue is process-wide. +pub struct EventsOnly; + +impl EventsOnly { + pub fn init() -> Self { + assert_eq!(unsafe { sys::SDL_Init(0x4000) }, 0); + Self + } +} + +impl Drop for EventsOnly { + fn drop(&mut self) { + unsafe { sys::SDL_Quit() }; + } +} diff --git a/rust-modules/shell-sdl/src/text.rs b/rust-modules/shell-sdl/src/text.rs new file mode 100644 index 0000000000..5d5d995860 --- /dev/null +++ b/rust-modules/shell-sdl/src/text.rs @@ -0,0 +1,533 @@ +//! The text-input half that is SDL: the bytes of an `SDL_TEXTINPUT` event in this build's layout, +//! and the calls that raise and dismiss the system keyboard. The state a field's editing leaves +//! behind (what the application has asked for, the queue of commits, the focus handshake) is the +//! application's own `textinput` module; this file is only what knows SDL. +//! +//! **Trap 1, the offset.** webOS inserts a `Uint32 inputSource` at `+12` of `SDL_TextInputEvent`, +//! so the UTF-8 text starts at **+16** on the television, not the `+12` that stock SDL 2.0.4's +//! `SDL_events.h` declares and that a desktop's SDL2 really uses. That header lies about the LG +//! build; the NDK sysroot's fork copy is the proof. [`TEXT_OFF`] is that choice, `cfg!` and not +//! `#[cfg]` so both arms stay compiled and the one nobody is building cannot rot, and +//! `decode_text_at` takes the offset as an argument so `make check` grades both layouts. A single +//! hard-coded number ships garbage on one of the two platforms and fails nothing. +//! +//! The calls are stock public SDL2 API, so they are a plain link (`sys.rs`); whether the PANEL rises +//! is a firmware question the application probes at run time ([`has_screen_keyboard`]) rather than +//! assumes. +//! +//! **Do not fake the event with `SDL_PushEvent`** (measured 2026-08-14, recorded in the +//! application's `textinput` module). The Mac's `libSDL2` is sdl2-compat forwarding into SDL3, whose +//! text event carries a `char *text` pointer where SDL2's carries an inline `char text[32]`; the +//! compat layer dereferences it while converting the pushed event and SIGSEGVs inside SDL. So +//! [`encode_event`] builds the bytes and the `txt:` token hands them to the decode directly, and +//! nothing in `inject.rs` ever pushes a text event. +//! +//! Under `cfg(test)` and the `test-support` feature the four calls a host test could reach are +//! replaced by [`host_test_sdl`]'s stubs: a host test has no window and no panel. +use crate::event::SDL_TEXTINPUT; +use crate::sys; +#[cfg(not(any(test, feature = "test-support")))] +use crate::sys::{ + SDL_GetWindowFlags, SDL_HasScreenKeyboardSupport, SDL_StartTextInput, SDL_StopTextInput, +}; +#[cfg(any(test, feature = "test-support"))] +use host_test_sdl::{ + SDL_GetWindowFlags, SDL_HasScreenKeyboardSupport, SDL_StartTextInput, SDL_StopTextInput, +}; +use std::os::raw::c_void; + +/// The four SDL entry points the keyboard calls reach, stubbed for a HOST TEST BINARY. +/// +/// A host test cannot call them: no window exists, and on a desktop `SDL_StartTextInput` would +/// switch text events on for the rest of the process. `cfg(test)` does not cross a crate boundary, +/// so the application's own tests get these stubs through the `test-support` feature, which its +/// `[dev-dependencies]` enable and no shipped build does. +/// +/// **Only a test is stubbed.** `hostsim` links desktop SDL2 and takes the real arm, which is the +/// whole point: the simulator is where the decode path is exercised by typing. +// the stubs carry SDL's own C names ON PURPOSE: `use`d unqualified by the arms above, so the call +// sites read identically in both builds and a signature drift shows up as a type error there +#[allow(non_snake_case)] +#[cfg(any(test, feature = "test-support"))] +mod host_test_sdl { + use std::os::raw::{c_int, c_void}; + /// No window, so no focus bit: the application's `has_focus` answers `Some(false)` under test, + /// the same answer a real television gives when the panel cannot rise. + pub(super) unsafe fn SDL_GetWindowFlags(_w: *mut c_void) -> u32 { + 0 + } + /// No panel on the host, matching what the simulator's own boot probe reports (`support=0`). + pub(super) unsafe fn SDL_HasScreenKeyboardSupport() -> c_int { + 0 + } + pub(super) unsafe fn SDL_StartTextInput() {} + pub(super) unsafe fn SDL_StopTextInput() {} +} + +/// `SDL_TEXTINPUTEVENT_TEXT_SIZE` — `char text[32]`, inline in the event rather than a pointer. +/// Both headers agree on the size; they disagree only about where it starts (trap 1). +pub const TEXT_CAP: usize = 32; + +/// Where that array begins in the raw event bytes. **Trap 1**, and the only number in this file +/// that is wrong on the platform you are not currently building. +/// +/// `cfg!` and not `#[cfg]`, matching [`crate::event::decode_key`]: both arms stay compiled on both +/// platforms, so the one nobody is building cannot rot into a compile error nobody sees for a month. +pub const TEXT_OFF: usize = if cfg!(feature = "hostsim") { 12 } else { 16 }; + +/// `SDL_LOG_CATEGORY_INPUT` / `SDL_LOG_PRIORITY_DEBUG`, from `SDL_log.h`. +#[cfg(not(any(test, feature = "test-support")))] +const SDL_LOG_CATEGORY_INPUT: std::os::raw::c_int = 3; +#[cfg(not(any(test, feature = "test-support")))] +const SDL_LOG_PRIORITY_DEBUG: std::os::raw::c_int = 2; + +/// Ask LG's SDL to narrate its own keyboard lifecycle into stderr (`/tmp/plxnative-stderr.log`). +/// +/// The driver already logs `[WebOSShowScreenKeyboard] called`, `[TextModelLeave] called`, +/// `[TextModelInputPanelState] called - state: %d` and `[WebOSHideScreenKeyboard] called` at +/// `INPUT`/`DEBUG`, which is below the default priority, so none of it prints. One call makes the +/// whole sequence readable without patching SDL. Cheap and permanent: a handful of lines per +/// keyboard session, on a log that is already the primary debugging surface. A no-op under a test. +pub fn trace_driver() { + #[cfg(not(any(test, feature = "test-support")))] + unsafe { + sys::SDL_LogSetPriority(SDL_LOG_CATEGORY_INPUT, SDL_LOG_PRIORITY_DEBUG); + } +} + +/// `SDL_StartTextInput`: raise the system keyboard (the caller keeps its own "have I asked" edge). +pub fn start_input() { + unsafe { SDL_StartTextInput() }; +} + +/// `SDL_StopTextInput`: dismiss it. +pub fn stop_input() { + unsafe { SDL_StopTextInput() }; +} + +/// Does this build/firmware claim a system keyboard? `SDL_HasScreenKeyboardSupport`, which a +/// firmware answers however it likes: the caller probes it, never assumes it. +pub fn has_screen_keyboard() -> bool { + unsafe { SDL_HasScreenKeyboardSupport() != 0 } +} + +/// `SDL_GetWindowFlags` of `win`: the one way to read `SDL_WINDOW_INPUT_FOCUS`, which is what +/// decides whether the panel rises and is never reported as an error. +pub fn window_flags(win: *mut c_void) -> u32 { + unsafe { SDL_GetWindowFlags(win) } +} + +/// What the boot log's `keyboard:` line reports about the system keyboard. The fields are SDL's own +/// numbers, unconverted, so the line keeps printing exactly what it always has. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct KeyboardProbe { + /// `SDL_HasScreenKeyboardSupport()`. + pub support: i32, + /// `SDL_IsTextInputActive()`. + pub active: i32, + /// `SDL_GetWindowFlags(win)`. + pub wflags: u32, +} + +/// Read the three facts the `keyboard:` boot line prints, in one call. +pub fn keyboard_probe(win: *mut c_void) -> KeyboardProbe { + unsafe { + KeyboardProbe { + support: SDL_HasScreenKeyboardSupport(), + active: sys::SDL_IsTextInputActive(), + wflags: SDL_GetWindowFlags(win), + } + } +} + +/// What [`encode_event`]'s inverse reads out of these bytes, at THIS platform's offset. Exposed so a +/// caller can log the decode without duplicating the choice of offset, which is the one thing in +/// this file that must never be written down twice. +pub fn decode(ev: &[u8]) -> String { + decode_text_at(ev, TEXT_OFF) +} + +/// The bytes an `SDL_TEXTINPUT` event carries for `text`, in whichever layout [`decode_text_at`] +/// reads — the inverse of it, and, like [`crate::inject::encode_key`] and +/// [`crate::event::decode_key`], the pair is only ever correct together. Nothing in the compiler +/// couples them; `encode_decode_round_trips` does. +/// +/// It exists so this seam can be DRIVEN, by the application's `txt:` remote token. A real +/// `SDL_TEXTINPUT` needs a human at a keyboard — no trigger raises the panel, and typing into the +/// simulator means somebody physically typing — so without it nothing automated could ever put a +/// character in the search field, on either platform. +/// +/// The bytes are a faithful event in THIS platform's layout, and `txt:` hands them to the decode +/// rather than to `SDL_PushEvent`: pushing a synthetic `SDL_TEXTINPUT` segfaults inside the Mac's +/// SDL, for the reason in the module doc. +pub fn encode_event(text: &str) -> [u8; 128] { + let mut ev = [0u8; 128]; + ev[0..4].copy_from_slice(&SDL_TEXTINPUT.to_ne_bytes()); + // `text[32]` holds at most 31 bytes plus its terminator — and the cut must land on a CHAR + // BOUNDARY. Slicing a codepoint in half would make the decoder answer U+FFFD for text that + // was perfectly valid when it was written, which reads as a decoder bug and is not one. + let mut n = text.len().min(TEXT_CAP - 1); + while n > 0 && !text.is_char_boundary(n) { + n -= 1; + } + ev[TEXT_OFF..TEXT_OFF + n].copy_from_slice(&text.as_bytes()[..n]); + ev +} + +/// The committed text in a raw `SDL_TEXTINPUT` event whose `text[]` begins at `off`. +/// +/// Pure, and offset-parameterised rather than reading [`TEXT_OFF`] itself, so `make check` can +/// grade BOTH platforms' layouts on a host that only ever builds one of them — the same reason +/// `app::decode_key` and `app::encode_key` are pure and tested as a pair. +/// +/// Every failure mode here is a byte string somebody else chose: the panel's own IME writes this +/// field, and the app cannot afford a panic inside the SDL event loop (see `remote.rs`, where +/// exactly that class took the app down). So a short buffer, a missing NUL and invalid UTF-8 are +/// all answers, not faults. +fn decode_text_at(ev: &[u8], off: usize) -> String { + // `min(ev.len())` before the slice, not after: `text[32]` is the LAST field of the event, so a + // truncated or short buffer is the ordinary case at the end of the struct, not a malformed one. + let end = off.saturating_add(TEXT_CAP).min(ev.len()); + let Some(field) = ev.get(off..end) else { + return String::new(); // off past the end — `get` refuses the inverted range rather than panicking + }; + // NUL-terminated INSIDE a fixed array: the terminator is the length, and everything after it + // is whatever the last, longer commit left behind. + let n = field.iter().position(|&b| b == 0).unwrap_or(field.len()); + // The two edges of a codepoint the fixed array may have CUT — see `drop_cut_tail`. The tail + // rule is conditional on the array being FULL (`n == TEXT_CAP`), which is the signature of a + // cut; the head rule is unconditional, because no UTF-8 string may begin with a continuation + // byte under any circumstances. Deliberately NOT `n == field.len()`, which is also true when + // the CALLER's buffer ran out before `text[32]` did — a short buffer is the reader's limit, + // not the panel's, and there is nothing to say the panel cut anything at all. + let text = drop_orphan_head(&field[..n]); + let text = if n == TEXT_CAP { + drop_cut_tail(text) + } else { + text + }; + // Lossy, never `from_utf8`: a single bad byte would otherwise discard the whole commit — and + // an IME that emits one is a keystroke the user typed, not an attack. + String::from_utf8_lossy(text).into_owned() +} + +/// Drop a trailing UTF-8 sequence that is well-formed so far but CUT SHORT by the end of the +/// buffer. Everything else — a lone continuation byte, an overlong or out-of-range lead, a +/// surrogate — is left for `from_utf8_lossy` to answer with U+FFFD, because a replacement character +/// is the only visible signal that something arrived broken and it must not be swallowed. +/// +/// **This is LG checklist row #16** (`docs/lg-self-checklist.md` §2), which asks that the character +/// which arrives be the character that was pressed. `text[32]` is a fixed array, so a commit that +/// fills it is cut at a BYTE, and that cut lands mid-codepoint for any query that is not pure +/// ASCII. Decoded lossily, the surviving half becomes a `` the user never typed, in their search +/// field — exactly the substitution the row is about. Nothing can recover the character (its other +/// half is not in this event), so the honest answer is the text that WAS whole. +/// +/// **The classification is `std`'s, not ours.** `Utf8Error::error_len() == None` is precisely +/// "valid so far, ended mid-sequence", and `valid_up_to()` is where to cut — where a hand-rolled +/// lead-byte width table accepts `0xC0`, `0xF5..=0xF7` and surrogate pairs as merely "incomplete" +/// and deletes real corruption without a trace. Only the LAST sequence is offered to it (walk back +/// at most four bytes to the first non-continuation byte; no sequence is longer), so an interior +/// error earlier in the commit cannot suppress the tail rule. +/// +/// **Belt-and-braces for a case this project has not settled.** Stock SDL2 fills `text[32]` with +/// `SDL_utf8strlcpy`, which truncates on a character boundary and always terminates — so on stock +/// SDL this branch is unreachable, and `encode_event` cuts on a boundary too, which is why nothing +/// the simulator or the `txt:` token can drive reaches it either. Whether **LG's fork** does the +/// same is a question for the television's own `libSDL2`, not for a header or another client: +/// `.agents/skills/decompile-tv-lib/` is how the `+16 inputSource` offset above was settled, and it +/// is how this would be. Until then the branch costs one comparison and cannot make a correct +/// commit wrong. +fn drop_cut_tail(b: &[u8]) -> &[u8] { + for back in 1..=b.len().min(4) { + let i = b.len() - back; + if b[i] & 0xC0 == 0x80 { + continue; // a continuation byte — the sequence it belongs to starts further back + } + return match std::str::from_utf8(&b[i..]) { + Err(e) if e.error_len().is_none() => &b[..i], + _ => b, + }; + } + b // nothing but continuation bytes: garbage, and `from_utf8_lossy`'s to answer +} + +/// The other edge of the same cut: drop a leading run of continuation bytes. +/// +/// If the panel really does split a codepoint at `text[32]`, the half [`drop_cut_tail`] discards +/// arrives at the START of the NEXT commit — orphaned, with its lead byte in the event before it. +/// Left alone those bytes are one U+FFFD each, which is the row-#16 substitution again, one +/// character later; dropping the head is what makes the rule whole rather than one-sided. +/// +/// Unconditional, and safe to be: **no UTF-8 string may begin with a continuation byte**, so this +/// can only ever remove bytes that were already unreadable — never a character the user typed. +fn drop_orphan_head(b: &[u8]) -> &[u8] { + let n = b.iter().take_while(|&&c| c & 0xC0 == 0x80).count(); + &b[n..] +} + +// --------------------------------------------------------------------------------------- +#[cfg(test)] +mod tests { + use super::*; + + /// A synthetic event in one platform's layout: type at +0, the text at `off`, NUL-terminated + /// if it fits. `[u8; 128]` because that is what `app.rs` polls into. + fn ev_with(off: usize, text: &[u8]) -> [u8; 128] { + let mut ev = [0u8; 128]; + ev[0..4].copy_from_slice(&0x303u32.to_ne_bytes()); // SDL_TEXTINPUT + ev[off..off + text.len()].copy_from_slice(text); + ev + } + + /// **The trap this whole file is shaped around.** LG's fork inserts `Uint32 inputSource` at + /// +12, so the text is at +16 on the television and at +12 on a desktop. A single hard-coded + /// offset does not fail loudly on the wrong platform — it reads four bytes of `windowID` (or + /// of the text's own head) and commits plausible garbage into the search field. + #[test] + fn the_text_decodes_at_both_platforms_offsets() { + assert_eq!(decode_text_at(&ev_with(16, b"webos"), 16), "webos"); + assert_eq!(decode_text_at(&ev_with(12, b"desktop"), 12), "desktop"); + // …and reading one layout with the other's offset is exactly the silent corruption above: + // at +16 a stock event is four bytes into the text, and at +12 a fork event is inside + // `inputSource`, which is zero — an empty commit. + assert_eq!(decode_text_at(&ev_with(12, b"desktop"), 16), "top"); + assert_eq!(decode_text_at(&ev_with(16, b"webos"), 12), ""); + } + + /// The ordinary case: a short string in a fixed 32-byte array, terminated by NUL. Everything + /// after the terminator is the tail of some LONGER earlier commit, and must not be returned. + #[test] + fn a_nul_terminates_the_string_inside_the_fixed_array() { + let mut ev = ev_with(16, b"ab\0cdefghijklmnop"); + ev[16 + 31] = b'!'; // …up to and including the last byte of text[32] + assert_eq!(decode_text_at(&ev, 16), "ab"); + } + + /// A commit that fills `text[32]` completely has NO terminator — the array is the length. A + /// decoder that insists on finding a NUL reads past the field into `SDL_Event`'s padding. + #[test] + fn a_full_32_byte_commit_has_no_terminator() { + let text = [b'x'; TEXT_CAP]; + let ev = ev_with(16, &text); + assert_eq!(decode_text_at(&ev, 16), "x".repeat(TEXT_CAP)); + } + + /// Invalid UTF-8 must not panic. This runs inside the SDL event loop, where a panic unwinds + /// out of `plex_run` and takes the app with it — `remote.rs` lost the app exactly this way to + /// a multi-byte whitespace. The bytes come from the television's own IME, so "that cannot + /// happen" is not a thing this file gets to assume. + #[test] + fn invalid_utf8_is_replaced_rather_than_panicking() { + let s = decode_text_at(&ev_with(16, b"a\xffb"), 16); + assert_eq!(s, "a\u{fffd}b"); + // A bad byte in the MIDDLE keeps its replacement whatever surrounds it — it is neither + // edge of a cut, so neither trim rule can claim it. (A LEADING continuation byte is the + // orphan case and IS dropped; `a_commit_orphaned_from_its_lead_byte_is_dropped_rather_ + // than_replaced` owns that, and `\x80` alone belongs to it rather than here.) + assert_eq!(decode_text_at(&ev_with(16, b"x\x80y"), 16), "x\u{fffd}y"); + assert_eq!(decode_text_at(&ev_with(16, b"x\xc0y"), 16), "x\u{fffd}y"); + } + + /// **Row #16: a codepoint the fixed array CUT must not arrive as a character nobody typed.** + /// `text[32]` has no room for the tail of a sequence that starts at its last byte, so a lossy + /// decode puts a `` in the user's query — the exact substitution the checklist row is about. + /// The whole prefix is kept; only the half codepoint goes. + #[test] + fn a_codepoint_cut_by_the_end_of_the_field_is_dropped_not_replaced() { + // Each width of lead byte, cut at every point that leaves it incomplete. + for (lead, whole) in [(0xc3u8, "é"), (0xe5, "千"), (0xf0, "🎬")] { + let need = whole.len(); + for kept in 1..need { + let mut raw = vec![b'y'; TEXT_CAP - kept]; + raw.extend_from_slice(&whole.as_bytes()[..kept]); + assert_eq!(raw.len(), TEXT_CAP); + let got = decode_text_at(&ev_with(16, &raw), 16); + assert_eq!( + got, + "y".repeat(TEXT_CAP - kept), + "lead {lead:#x}, {kept} of {need} bytes" + ); + assert!( + !got.contains('\u{fffd}'), + "a cut must not invent a character" + ); + } + // …and the same codepoint that FITS is untouched, which is what proves the rule cuts + // only what was actually truncated. + let mut raw = vec![b'y'; TEXT_CAP - need]; + raw.extend_from_slice(whole.as_bytes()); + assert_eq!( + decode_text_at(&ev_with(16, &raw), 16), + format!("{}{whole}", "y".repeat(TEXT_CAP - need)) + ); + } + } + + /// A TERMINATED commit is as long as the panel meant it to be, so a malformed tail inside one + /// is genuine garbage and keeps the defensive replacement — the cut rule must not swallow it. + /// Neither may a SHORT BUFFER be read as a cut: that is the caller's limit, not the panel's. + #[test] + fn a_bad_tail_before_a_terminator_still_replaces_rather_than_vanishing() { + // `ab` + a bare 3-byte lead + NUL: nothing cut this, the byte is simply wrong. + assert_eq!(decode_text_at(&ev_with(16, b"ab\xe5\0"), 16), "ab\u{fffd}"); + // …and a buffer that ends mid-codepoint is the READER running out, so the tail rule stays + // off and the bad byte is still reported. + assert_eq!( + decode_text_at(&ev_with(16, "é".as_bytes())[..17], 16), + "\u{fffd}" + ); + } + + /// **A byte no cut could have produced keeps its replacement.** The rule is "valid so far, + /// ended mid-sequence" and nothing looser — a hand-rolled lead-byte width table calls all of + /// these merely incomplete and deletes them, which turns real corruption from the panel's IME + /// into a silent shortening with no signal at all. `std::str::from_utf8` draws the line. + #[test] + fn corruption_that_is_not_a_cut_is_reported_rather_than_deleted() { + for (name, tail) in [ + ("overlong lead", &[0xC0u8][..]), + ("out-of-range lead", &[0xF5][..]), + ("never-a-lead byte", &[0xFF][..]), + ("surrogate half", &[0xED, 0xA0][..]), + ] { + let mut raw = vec![b'y'; TEXT_CAP - tail.len()]; + raw.extend_from_slice(tail); + let got = decode_text_at(&ev_with(16, &raw), 16); + assert!( + got.contains('\u{fffd}'), + "{name} must survive as a replacement, got {got:?}" + ); + } + } + + /// The other edge of the same cut: a commit ORPHANED from its lead byte — the remainder of a + /// codepoint the previous event was cut inside — must not arrive as one U+FFFD per byte, which + /// is the row-#16 substitution again, one character later. + #[test] + fn a_commit_orphaned_from_its_lead_byte_is_dropped_rather_than_replaced() { + // "🎬" is F0 9F 8E AC; cut after F0, the next commit opens with its three tail bytes. + assert_eq!( + decode_text_at(&ev_with(16, b"\x9f\x8e\xacstar"), 16), + "star" + ); + // …and a commit that is nothing BUT an orphaned remainder yields nothing, rather than one + // replacement character per byte. + assert_eq!(decode_text_at(&ev_with(16, b"\x80"), 16), ""); + // …and a commit that legitimately STARTS with a multi-byte character is untouched. + assert_eq!( + decode_text_at(&ev_with(16, "🎬star".as_bytes()), 16), + "🎬star" + ); + } + + /// **Capital and small letters transfer as themselves.** The panel's Shift/Caps is resolved on + /// the television — it commits the CASED character — so the app's whole obligation is to carry + /// the bytes through without touching them, and this is what proves it does. (A decoder that + /// normalised case would be invisible until someone searched for a title that differs only by + /// it.) Deliberately cites no checklist row number: `docs/lg-self-checklist.md` records no such + /// row, and a number this repo cannot corroborate does not belong in a permanent comment. + #[test] + fn letter_case_transfers_exactly_as_the_panel_committed_it() { + for s in [ + "A", "a", "Wallace", "WALLACE", "wallace", "WaLlAcE", "Ç", "ç", "Ä", "ä", + ] { + assert_eq!(decode_text_at(&ev_with(16, s.as_bytes()), 16), s); + assert_eq!(decode_text_at(&encode_event(s), TEXT_OFF), s); + } + } + + /// **Row #16, its own worked example.** The checklist names the full-width `\` (U+FF3C) and + /// asks that it not arrive as a backslash — the substitution a keyboard stack makes when it + /// folds full-width forms to ASCII, and the one a byte-oriented decoder makes when it reads one + /// of the three bytes of a full-width form on its own. + /// + /// The `lookalike` column is not a second assertion (the equality above already implies it); + /// it is the table saying what each row is FOR, so the next reader can tell a deliberate pair + /// from an arbitrary one. The rest are the characters a VKB commonly substitutes or a layer + /// below eats — the shell and URL metacharacters, and the quote pair a keyboard "smartens". + #[test] + fn a_full_width_character_is_not_folded_to_its_ascii_lookalike() { + for (typed, _lookalike) in [ + ("\", "\\"), // U+FF3C FULLWIDTH REVERSE SOLIDUS — the row's own example + ("¥", "\\"), // U+FFE5, the same key on a JP panel, and the same wrong answer + ("/", "/"), + (":", ":"), + (" ", " "), // U+3000 IDEOGRAPHIC SPACE + ("“", "\""), + ("’", "'"), + ("-", "-"), + ] { + let got = decode_text_at(&ev_with(16, typed.as_bytes()), 16); + assert_eq!( + got, typed, + "the character pressed must be the character that arrives" + ); + assert_eq!(decode_text_at(&encode_event(typed), TEXT_OFF), typed); + } + // The ASCII originals still arrive as themselves — nothing here rewrites in either + // direction. `\` is the one the row calls out, and the rest are what a URL layer or a + // shell would eat if anything on the path were not byte-transparent. + for s in [ + "\\", "/", "&", "%", "+", "#", "?", "=", "\"", "'", "<", ">", " ", "\t", + ] { + assert_eq!(decode_text_at(&ev_with(16, s.as_bytes()), 16), s); + } + } + + /// A buffer that ends before (or inside) the text field is an answer, not a fault. `SDL_Event` + /// is a union and nothing guarantees a caller polled into 128 bytes. + #[test] + fn a_short_buffer_yields_an_empty_string() { + assert_eq!(decode_text_at(&[0u8; 8], 16), ""); + assert_eq!(decode_text_at(&[], 16), ""); + // Ending mid-field returns the part that IS there, rather than nothing. + let ev = ev_with(16, b"abcdef"); + assert_eq!(decode_text_at(&ev[..19], 16), "abc"); + } + + /// Multi-byte UTF-8 survives intact — the field is bytes, not characters, and a European or + /// CJK query is the normal case for a media library. + #[test] + fn multibyte_text_round_trips() { + assert_eq!( + decode_text_at(&ev_with(16, "Amélie".as_bytes()), 16), + "Amélie" + ); + assert_eq!( + decode_text_at(&ev_with(16, "千と千尋".as_bytes()), 16), + "千と千尋" + ); + } + + /// The encoder writes what the decoder reads, on whichever platform this is — the pair that + /// nothing but this test couples. `app.rs` already lost the simulator's whole remote FIFO to + /// exactly this: `encode_key` wrote LG's layout while `decode_key` had been taught stock + /// SDL2's, so every token was accepted and nothing moved. + #[test] + fn encode_decode_round_trips() { + for s in ["a", "wallace", "Amélie", "千と千尋", "star wars"] { + assert_eq!(decode_text_at(&encode_event(s), TEXT_OFF), s); + } + } + + /// Over-long text is cut to fit `text[32]`, and the cut lands on a CHAR BOUNDARY — a codepoint + /// sliced in half would come back as U+FFFD and look like a decoder fault. + #[test] + fn an_over_long_commit_is_cut_on_a_char_boundary() { + let long = "x".repeat(100); + assert_eq!( + decode_text_at(&encode_event(&long), TEXT_OFF), + "x".repeat(TEXT_CAP - 1) + ); + // 16 CJK codepoints = 48 bytes: the 31-byte limit falls mid-codepoint, so the cut must + // back up to 30 bytes (10 characters) rather than emit a replacement character. + let cjk = "千".repeat(16); + let got = decode_text_at(&encode_event(&cjk), TEXT_OFF); + assert_eq!(got, "千".repeat(10)); + assert!( + !got.contains('\u{fffd}'), + "the cut must not split a codepoint" + ); + } +} diff --git a/rust-modules/shell-sdl/src/window.rs b/rust-modules/shell-sdl/src/window.rs new file mode 100644 index 0000000000..69047bcf01 --- /dev/null +++ b/rust-modules/shell-sdl/src/window.rs @@ -0,0 +1,510 @@ +//! The window and its GL context: asking SDL for one (with the one retry a stored size needs), the +//! desktop's window arithmetic, the swap, and the swap interval. +//! +//! [`Window`] is the one SDL implementation of the application's `Surface`. It holds the raw +//! `SDL_Window*` and nothing else: it has no destructor, so it never frees or nulls itself when the +//! compositor takes the screen away (the application is leaked at exit and a worker may still hold +//! the handle), and `init::quit` is explicit. The handle is the single contract with the television's +//! Wayland half, which lives in the application crate's `system.rs`: that code receives +//! [`Window::raw`] and the order of calls on one thread, and nothing here ever names the Wayland or +//! `SDL_SysWMinfo` calls (the television's SDL writes a larger info struct than the headers declare; +//! `system.rs` has the buffer that survives that, and a pin in `lib.rs` keeps this crate off it). +use crate::sys; +#[cfg(feature = "hostsim")] +use crate::sys::{SDL_GetDisplayUsableBounds, SDL_SetWindowPosition, SDL_SetWindowSize}; +use plx_base::eventlog::log; +use plx_base::task::MainThread; +use std::ffi::CStr; +use std::os::raw::{c_int, c_void}; + +/// OPENGL | FULLSCREEN on the television, which owns the whole panel. +/// +/// The desktop asks for OPENGL | ALLOW_HIGHDPI — no fullscreen grab (hostile on a laptop) and +/// **not RESIZABLE**: `surface::probe` reads the drawable once, at boot, so a dragged edge would +/// leave the viewport describing a window that no longer exists, and the interface would sit in a +/// 1920x1080-shaped corner of the new one with every pointer hit landing somewhere else. The window +/// opens at an exact divisor of the canvas instead — see `plan_desktop_window`. +/// +/// ALLOW_HIGHDPI is what makes that divisor land on a **1:1 surface** on the Mac people actually +/// have: without it a Retina display gives a drawable equal to the window in POINTS, which the +/// compositor then doubles, so the whole interface is an upscale of a half-size render. With it, +/// `fit_window_to_density` measures the pixels per point once the window exists and sizes +/// it in points for the drawable it should give: 960x540 points for a 1920x1080 drawable on a 2x +/// display, so `surface::scale() == 1.0`, the same 1:1 texel contract the television gets. +pub const SDL_WINDOW_FLAGS: u32 = if cfg!(feature = "hostsim") { + 0x2 | 0x2000 +} else { + 0x2 | 0x1 +}; +/// `SDL_WINDOW_ALLOW_HIGHDPI`, the one bit of [`SDL_WINDOW_FLAGS`] a frame dump clears. +const SDL_WINDOW_ALLOW_HIGHDPI: u32 = 0x2000; +/// `SDL_WINDOW_INPUT_FOCUS`. Note it is NOT among the flags requested above — no window flag can +/// ask for it; SDL sets it when the compositor gives this surface the keyboard. Read, never asked +/// for, and read by exactly one thing: the application's `textinput`, whose panel it silently gates. +pub const SDL_WINDOW_INPUT_FOCUS: u32 = 0x200; + +// The window we ASK SDL for. `surface::probe` then reads back what we actually got. +#[cfg(any(feature = "hostsim", test))] +const SCR_W: c_int = plx_base::surface::LOGICAL_W as c_int; +#[cfg(any(feature = "hostsim", test))] +const SCR_H: c_int = plx_base::surface::LOGICAL_H as c_int; + +/// Where, and how big, to ask for the window. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Placement { + /// The television: placed at 0,0 at exactly `size` and takes the panel. `fallback` is the one + /// size to retry at when the window or its GL context is refused at `size`. + /// + /// **A stored size the set will not give must never brick launch.** If the window or its GL + /// context is refused at a smaller size the owner chose, free whatever was made and retry ONCE + /// at the native canvas; only a refused native window is fatal. + Panel { size: (c_int, c_int), fallback: Option<(c_int, c_int)> }, + /// A desktop: centred at whatever fits the display (`plan_desktop_window`), sized for the + /// display's pixel density once the window exists (`fit_window_to_density`). The request is the + /// desktop's own size, not a setting, so there is no retry here. Only a simulator build has the + /// SDL calls that read a display's size. + #[cfg(feature = "hostsim")] + Desktop, +} + +/// What the application asks for. Plain data: the title the platform chooses, where and how big, and +/// whether the desktop window may be HiDPI. +#[derive(Clone, Copy, Debug)] +pub struct OpenAsk<'a> { + pub title: &'a CStr, + pub placement: Placement, + /// `false` clears `SDL_WINDOW_ALLOW_HIGHDPI`. A frame dump's drawable is exactly the window's + /// size in points: it is the one desktop window that does not ask for it, so its window is the + /// 1920x1080 points of the canonical Linux host on a Retina display too, and + /// `fit_window_to_density` finds nothing to correct. A no-op for the television's flags, which + /// never carry the bit. (Absent from every shipping build.) + pub high_dpi: bool, +} + +/// SDL refused the window or its GL context at the native size (the reason is in the log lines +/// `CreateWindow failed at WxH` / `GL ctx failed at WxH`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct OpenFailed; + +/// An open SDL window, current on this thread's GL context. `!Send`/`!Sync` (it is a raw pointer): +/// the swap, the poll and the interval are the SDL main thread's. +#[derive(Debug)] +pub struct Window { + win: *mut c_void, +} + +impl Window { + /// A window that does not exist: the test rig's and the host shells'. Its swap is + /// `SDL_GL_SwapWindow(NULL)`, which SDL answers with an error and nothing else, exactly as the + /// rig's null handle always has. + pub const DETACHED: Window = Window { win: std::ptr::null_mut() }; + + /// Ask SDL for the window and its GL context, correct it for the display's density where the + /// platform has one to correct, and probe the drawable it actually gave. + /// + /// Called after [`crate::init::init`] and [`crate::init::request_gl`], and after the + /// application has read the stored session, which the placement may depend on: that order is + /// the application's and is pinned there. + pub fn open(_mt: &MainThread, ask: &OpenAsk) -> Result { + // The television is placed at 0,0 at exactly canvas size (unless a webOS 1-3 owner picked a + // smaller Interface resolution) and takes the panel. A desktop window is centred + // (`SDL_WINDOWPOS_CENTERED`) at whatever fits — see `plan_desktop_window`. The density is not + // known until a window exists, so this is the 1x answer; `fit_window_to_density` below + // corrects it on a display where that was wrong. + #[cfg(feature = "hostsim")] + let mut desktop_ask: Option = None; + let (wx, wy, ww_req, wh_req, mut fallback) = match ask.placement { + Placement::Panel { size: (w, h), fallback } => (0, 0, w, h, fallback), + #[cfg(feature = "hostsim")] + Placement::Desktop => { + let planned = desktop_window_ask(); + desktop_ask = Some(planned); + let (w, h) = plan_desktop_window(planned, Density::UNIT); + (WINDOWPOS_CENTERED, WINDOWPOS_CENTERED, w, h, None) + } + }; + let window_flags = if ask.high_dpi { + SDL_WINDOW_FLAGS + } else { + SDL_WINDOW_FLAGS & !SDL_WINDOW_ALLOW_HIGHDPI + }; + let (mut ww_try, mut wh_try) = (ww_req, wh_req); + let win = unsafe { + loop { + let win = + sys::SDL_CreateWindow(ask.title.as_ptr(), wx, wy, ww_try, wh_try, window_flags); + if win.is_null() { + log(&format!("CreateWindow failed at {ww_try}x{wh_try}")); + } else { + let ctx = sys::SDL_GL_CreateContext(win); + if !ctx.is_null() { + break win; + } + log(&format!("GL ctx failed at {ww_try}x{wh_try}")); + sys::SDL_DestroyWindow(win); + } + let Some((w, h)) = fallback.take() else { + return Err(OpenFailed); + }; + log(&format!("surface: retrying the window at the native {w}x{h}")); + (ww_try, wh_try) = (w, h); + } + }; + // Correct the size for the display's density now: `surface::probe` below reads the drawable once. + #[cfg(feature = "hostsim")] + if let Some(desktop_ask) = desktop_ask { + unsafe { fit_window_to_density(win, desktop_ask) }; + } + plx_base::surface::probe(win); + Ok(Window { win }) + } + + /// The raw `SDL_Window*`: the handle the application's `Shell` hands to the television's + /// Wayland half and to `textinput`. Null for [`Window::DETACHED`]. + pub fn raw(&self) -> *mut c_void { + self.win + } + + /// `SDL_GL_SetSwapInterval` for the current context: 1 locks the frame rate to the panel + /// refresh, 0 uncaps it. The caller computes the value (vsync, `/tmp/plxnative-novsync`, a + /// frame dump) because those are application triggers. + pub fn set_swap_interval(&self, interval: i32) { + unsafe { sys::SDL_GL_SetSwapInterval(interval) }; + } + + /// `SDL_GL_SwapWindow`: present the frame. The compositor commit of the opaque-region request + /// the application made just before it is this swap's, not a call of its own. + pub fn swap(&self) { + unsafe { sys::SDL_GL_SwapWindow(self.win) }; + } +} + + +/// What a DESKTOP window is asked to be, before the display's pixel density is known. +#[cfg(any(feature = "hostsim", test))] +#[derive(Clone, Copy)] +enum WindowAsk { + /// `PLXNATIVE_WIN=x`: a DRAWABLE of exactly this many pixels, on any display. + Drawable(c_int, c_int), + /// No override: the largest whole fraction of the canvas whose window fits this usable display + /// area (`SDL_GetDisplayUsableBounds`, in points). + Fit(c_int, c_int), +} + +/// How many drawable pixels a window point is worth on this display, as the integer pair SDL +/// reported for a window that exists: `window_w` points wide, `drawable_w` pixels wide. +/// +/// Integers, never a float multiplied back: 960 points of a 2x window must come out as exactly +/// 1920 pixels, and a ratio that is not a whole number (a 150% Windows display) must round the +/// same way on the way out as on the way in. +#[cfg(any(feature = "hostsim", test))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Density { + window_w: c_int, + drawable_w: c_int, +} + +#[cfg(any(feature = "hostsim", test))] +impl Density { + /// One pixel per point: every 1x display, and what is assumed until a window has been measured. + const UNIT: Density = Density { window_w: 1, drawable_w: 1 }; + + /// The measured pair. A drawable that is not larger than the window (a 1x display) is + /// [`Density::UNIT`]: a drawable never has fewer pixels than points, and a window is never + /// grown to make up for one that seems to. + fn measured(window_w: c_int, drawable_w: c_int) -> Density { + if window_w <= 0 || drawable_w <= window_w { + Density::UNIT + } else { + Density { window_w, drawable_w } + } + } + + /// The window size, in points, whose drawable is `px` pixels: the nearest whole number of + /// points, and one fewer if rounding up would make the drawable LARGER than asked (never + /// larger than the canvas is the contract; a pixel short is a letterbox, a pixel over is not). + fn points(self, px: c_int) -> c_int { + let (w, d) = (i64::from(self.window_w), i64::from(self.drawable_w)); + let pt = ((i64::from(px) * w + d / 2) / d).max(1) as c_int; + if pt > 1 && self.pixels(pt) > px { + pt - 1 + } else { + pt + } + } + + /// The drawable, in pixels, of a window `pt` points wide. + fn pixels(self, pt: c_int) -> c_int { + let (w, d) = (i64::from(self.window_w), i64::from(self.drawable_w)); + ((i64::from(pt) * d + w / 2) / w) as c_int + } +} + +/// `PLXNATIVE_WIN`'s value: `x`, both positive. Anything else is no override. +#[cfg(any(feature = "hostsim", test))] +fn parse_window_override(v: &str) -> Option<(c_int, c_int)> { + let (w, h) = v.split_once(['x', 'X'])?; + match (w.trim().parse::(), h.trim().parse::()) { + (Ok(w), Ok(h)) if w > 0 && h > 0 => Some((w, h)), + _ => None, + } +} + +/// The window a DESKTOP should open at, in points, for a display of this pixel `density`: the +/// pure arithmetic of the size, so the Retina cases are testable without a Retina display. +/// +/// **The drawable is what is sized; the window follows from it.** The UI is authored at a 1920x1080 +/// canvas and every glyph, icon mask and poster is rasterized for 1:1 texels against it +/// (`gfx::snap`, the crispness contract in `theme.rs`), so a drawable LARGER than the canvas is +/// not a sharper picture: it is the same atlas stretched, with every drawable-sized buffer (the +/// page snapshot, the glass sources) four times the television's, which is how a 2x display once +/// breached the render-set ceiling on every frame (`ui/src/frame/render_set.rs`). +/// +/// * `Drawable` is that drawable, exactly. The fit below is chosen for a HUMAN looking at a +/// window, and a screenshot is not that: on a 1x display its divisor lands on 2 and every shot +/// comes back 960x540, half the canvas the UI is authored at, so a shot taken to JUDGE the +/// interface asks for full size (`make sim-shot SIM_W=1920 SIM_H=1080`). Off-screen edges are +/// fine for a headless grab: the drawable is the window's own framebuffer. +/// * `Fit` is **an exact divisor, never a best fit**: the largest of 1/1, 1/2 and 1/3 of the canvas +/// whose window, in points, fits the usable area. `surface::scale` will letterbox any drawable it +/// is given, so an arbitrary size would *work*, but a fractional scale resamples all of the above. +/// The bounds are in points, so the window is `canvas / div / density` of them. +/// +/// The television asks for the canvas itself (1:1) unless the owner picked a smaller Interface +/// resolution in Settings on webOS 1-3 (`requested_drawable`), in which case the compositor fills the panel. +/// A Mac is the case the `surface` doc was written against — 1920x1080 exceeds the usable area of +/// every laptop display Apple ships, so asking for it flatly would put the title bar above the +/// screen and the bottom of the interface under the Dock. +#[cfg(any(feature = "hostsim", test))] +fn plan_desktop_window(ask: WindowAsk, density: Density) -> (c_int, c_int) { + let points = |(w, h): (c_int, c_int)| (density.points(w), density.points(h)); + match ask { + WindowAsk::Drawable(w, h) => points((w, h)), + WindowAsk::Fit(uw, uh) => { + // A little headroom under the usable bounds: a window flush against them reads as a + // fullscreen that went wrong rather than as a deliberate size. + let (max_w, max_h) = ((uw as f32 * 0.95) as c_int, (uh as f32 * 0.95) as c_int); + let fits = |div| { + let (w, h) = points((SCR_W / div, SCR_H / div)); + w <= max_w && h <= max_h + }; + let div = (1..3).find(|&div| fits(div)).unwrap_or(3); + points((SCR_W / div, SCR_H / div)) + } + } +} + +/// `SDL_WINDOWPOS_CENTERED` on display 0. +#[cfg(feature = "hostsim")] +const WINDOWPOS_CENTERED: c_int = 0x2FFF_0000u32 as c_int; + +/// What this process is asked for: `PLXNATIVE_WIN` if it holds a size, else the fit to the display, +/// or the canvas itself if SDL cannot say how big the display is. +#[cfg(feature = "hostsim")] +fn desktop_window_ask() -> WindowAsk { + if let Some((w, h)) = std::env::var_os("PLXNATIVE_WIN").and_then(|v| parse_window_override(&v.to_string_lossy())) { + return WindowAsk::Drawable(w, h); + } + let mut r = [0 as c_int; 4]; // SDL_Rect: x, y, w, h + let ok = unsafe { SDL_GetDisplayUsableBounds(0, r.as_mut_ptr()) } == 0 && r[2] > 0 && r[3] > 0; + if ok { + WindowAsk::Fit(r[2], r[3]) + } else { + WindowAsk::Drawable(SCR_W, SCR_H) + } +} + +/// Size the just-created desktop `win` for the pixel density of the display it opened on. +/// +/// `SDL_GetDisplayDPI` is unreliable on macOS, so the density is MEASURED instead: the window was +/// opened at the 1x answer of [`plan_desktop_window`], and `SDL_GL_GetDrawableSize` over +/// `SDL_GetWindowSize` says how many pixels that bought per point. On a 1x display nothing happens. +/// On a 2x display the window is resized (and put back in the middle of the display, since it was +/// centred at the old size) to the points that give the drawable that was asked for: +/// `PLXNATIVE_WIN=1920x1080` is a 960x540-point window, not a 1920x1080-point one with a 3840x2160 +/// drawable. Called before `surface::probe`, which reads the drawable once and for good. +#[cfg(feature = "hostsim")] +unsafe fn fit_window_to_density(win: *mut c_void, ask: WindowAsk) { + let ((ww, wh), (dw, dh)) = plx_base::surface::window_and_drawable_size(win); + let density = Density::measured(ww, dw); + if density == Density::UNIT { + return; + } + let (pw, ph) = plan_desktop_window(ask, density); + if (pw, ph) == (ww, wh) { + return; + } + SDL_SetWindowSize(win, pw, ph); + SDL_SetWindowPosition(win, WINDOWPOS_CENTERED, WINDOWPOS_CENTERED); + let ((nw, nh), (gw, gh)) = plx_base::surface::window_and_drawable_size(win); + log(&format!( + "surface: {:.3} pixels per point (a {ww}x{wh} point window read back a {dw}x{dh} drawable); \ + resized to {pw}x{ph} points, which now reads {nw}x{nh} points / {gw}x{gh} drawable", + f64::from(dw) / f64::from(ww) + )); +} + +#[cfg(test)] +mod desktop_window_tests { + use super::WindowAsk::{Drawable, Fit}; + use super::{parse_window_override, plan_desktop_window, Density, WindowAsk, SCR_H, SCR_W}; + + /// A window of 1920 points whose drawable reads back 3840 pixels: macOS Retina, the case this + /// module exists for. (macOS always reports a whole backing factor, even in a "scaled" mode.) + fn retina() -> Density { + Density::measured(1920, 3840) + } + + /// The window the planner opens, in points, and the drawable that window gives. + fn plan(ask: WindowAsk, density: Density) -> ((i32, i32), (i32, i32)) { + let points = plan_desktop_window(ask, density); + (points, (density.pixels(points.0), density.pixels(points.1))) + } + + /// `PLXNATIVE_WIN=1920x1080` on a 1x display is the 1920x1080 window it always was. + #[test] + fn a_1x_display_gives_the_override_as_asked() { + assert_eq!(plan(Drawable(1920, 1080), Density::UNIT), ((1920, 1080), (1920, 1080))); + } + + /// THE BUG: `PLXNATIVE_WIN=1920x1080` on a 2x display was a 1920x1080-POINT window, whose + /// drawable is 3840x2160 (`scale=2.000`) and which breached the render-set ceiling on every + /// frame of a Library scroll. The override is the DRAWABLE, so the window is half of it. + #[test] + fn the_override_is_the_drawable_on_a_2x_display() { + assert_eq!(plan(Drawable(1920, 1080), retina()), ((960, 540), (1920, 1080))); + } + + /// A 2x laptop (usable ~1512x945 points): 960x540 points, a 1:1 drawable. What it always got, + /// by the coincidence of div=2 meeting a 2x density; now by arithmetic. + #[test] + fn a_2x_laptop_fits_960x540_points_for_a_1_to_1_drawable() { + assert_eq!(plan(Fit(1512, 945), retina()), ((960, 540), (1920, 1080))); + } + + /// THE SECOND HOLE: a 5K/4K display "looking like 2560x1440" has usable ~2560x1415 points, so + /// the fit in points took div=1 -- a 1920x1080-point window, a 3840x2160 drawable -- with no + /// override at all. The fit is of the DRAWABLE, measured in the points it occupies. + #[test] + fn a_large_2x_display_gives_the_same_1_to_1_drawable_without_any_override() { + assert_eq!(plan(Fit(2560, 1415), retina()), ((960, 540), (1920, 1080))); + } + + /// Nothing changes on a 1x display: the divisor lands where it did, on every size. + #[test] + fn a_1x_display_fits_exactly_as_it_did() { + // a 1080p display's usable area under a menu bar and a Dock: div=2 + assert_eq!(plan(Fit(1920, 1050), Density::UNIT), ((960, 540), (960, 540))); + // a display big enough for the canvas itself (div=1) needs 5% headroom: 1920 / 0.95 = 2021.05 + assert_eq!(plan(Fit(2022, 1140), Density::UNIT), ((1920, 1080), (1920, 1080))); + assert_eq!(plan(Fit(2020, 1140), Density::UNIT), ((960, 540), (960, 540))); + // a small one: div=3 + assert_eq!(plan(Fit(100, 100), Density::UNIT), ((640, 360), (640, 360))); + } + + /// A density that is not a whole number (a 150% Windows display, a fractional Wayland scale): + /// the window is the drawable over the ratio, exactly where that is exact. + #[test] + fn a_fractional_density_is_divided_out_too() { + let d150 = Density::measured(1280, 1920); + assert_eq!(plan(Drawable(1920, 1080), d150), ((1280, 720), (1920, 1080))); + // 1280x720 points is over 95% of a 1280x800 display, so the half (960x540 px) wins + assert_eq!(plan(Fit(1280, 800), d150), ((640, 360), (960, 540))); + } + + /// Whatever the ratio, the window never gives a drawable LARGER than the one asked for: a + /// pixel short is a letterbox, a pixel over is a texture that is not the canvas. + #[test] + fn the_drawable_is_never_larger_than_asked_on_any_density() { + for (window_w, drawable_w) in [(1000, 1100), (1000, 1250), (1000, 1333), (1000, 1750), (1000, 2000), (1000, 2500), (1000, 3000), (1920, 2880), (1366, 2049)] { + let d = Density::measured(window_w, drawable_w); + for (w, h) in [(1920, 1080), (960, 540), (640, 360), (1280, 720)] { + let (_, got) = plan(Drawable(w, h), d); + assert!(got.0 <= w && got.1 <= h, "{window_w}->{drawable_w} asked {w}x{h}: {got:?}"); + // and no more than a point short of it, in either axis + let point = (drawable_w + window_w - 1) / window_w; + assert!(w - got.0 < point && h - got.1 < point, "{window_w}->{drawable_w} asked {w}x{h}: {got:?}"); + } + for (uw, uh) in [(1280, 720), (1512, 945), (1920, 1050), (2560, 1415), (3840, 2100)] { + let (_, got) = plan(Fit(uw, uh), d); + assert!(got.0 <= SCR_W && got.1 <= SCR_H, "{window_w}->{drawable_w} usable {uw}x{uh}: {got:?}"); + } + } + } + + /// A drawable that is not larger than the window is no HiDPI at all, however it got that way: + /// a window is never grown to cover for a measurement that failed. + #[test] + fn a_drawable_no_larger_than_the_window_is_unit_density() { + assert_eq!(Density::measured(1920, 1920), Density::UNIT); + assert_eq!(Density::measured(0, 1920), Density::UNIT); + assert_eq!(Density::measured(1920, 960), Density::UNIT); + } + + #[test] + fn the_override_parses_a_positive_size_and_nothing_else() { + assert_eq!(parse_window_override("1920x1080"), Some((1920, 1080))); + assert_eq!(parse_window_override(" 640X360 "), Some((640, 360))); + assert_eq!(parse_window_override("1920 x 1080"), Some((1920, 1080))); + for bad in ["", "1920", "x", "0x1080", "1920x0", "-1x5", "axb", "1920x1080x2"] { + assert_eq!(parse_window_override(bad), None, "{bad:?}"); + } + } +} + +/// The order `Window::open` does its work in, and the one thing this file must never grow. Each +/// test reads the source, because no host test can open a window; the needles are split with +/// `concat!` so this module's own text, which `include_str!` reads too, can never be what they match. +#[cfg(test)] +mod open_order_tests { + fn source() -> &'static str { + include_str!("window.rs") + } + + /// The body of `Window::open`, from its signature to the next method. + fn open_body() -> &'static str { + source() + .split_once(concat!("pub fn ", "open(")) + .expect("Window::open") + .1 + .split_once(concat!("pub fn ", "raw(")) + .expect("the method after open") + .0 + } + + /// `surface::probe` reads the drawable once, at boot, for good: the desktop window has to be + /// sized for the display's pixel density BEFORE it, or a 2x display keeps the 3840x2160 + /// drawable the 1x size gave it. + #[test] + fn the_desktop_window_is_fitted_to_the_density_before_the_drawable_is_probed() { + let body = open_body(); + let create = body.find(concat!("sys::SDL_CreateWindow", "(")).expect("creates the window"); + let fit = body.find(concat!("fit_window_to_", "density(win")).expect("fits the window to the density"); + let probe = body.find(concat!("surface::", "probe(win)")).expect("probes the drawable"); + assert!(create < fit && fit < probe, "create the window, fit it to the density, then probe the drawable"); + assert_eq!(body.matches(concat!("surface::", "probe(")).count(), 1, "one probe"); + } + + /// `open` frees a half-made window before it retries (a leaked one would keep the display), and + /// does it inside the creation loop, ahead of the probe. + #[test] + fn open_destroys_a_half_made_window_before_the_retry() { + let body = open_body(); + let create = body.find(concat!("sys::SDL_CreateWindow", "(")).expect("creates the window"); + let context = body.find(concat!("sys::SDL_GL_CreateContext", "(")).expect("creates the context"); + let destroy = body.find(concat!("sys::SDL_DestroyWindow", "(win)")).expect("destroys a half-made window"); + let retry = body.find(concat!("fallback.", "take()")).expect("takes the one fallback size"); + let probe = body.find(concat!("surface::", "probe(win)")).expect("probes the drawable"); + assert!(create < context && context < destroy && destroy < retry && retry < probe, + "create, context, destroy the half-made window, retry at the fallback, then probe"); + } + + /// **`Window` has no destructor.** The application is leaked at exit and a worker may still hold + /// the handle, so a window that destroyed itself (or nulled itself when the compositor took the + /// screen) would free a surface under a live reader. `init::quit` is the explicit end. + #[test] + fn window_has_no_destructor() { + assert!(!source().contains(concat!("impl Dr", "op for Window")), "a Window must never free itself"); + assert!(!source().contains(concat!("fn dr", "op(&mut self)")), "no destructor of any shape"); + } +} diff --git a/rust-modules/src/app/boot.rs b/rust-modules/src/app/boot.rs index d8436dd07b..a4da245509 100644 --- a/rust-modules/src/app/boot.rs +++ b/rust-modules/src/app/boot.rs @@ -1,281 +1,11 @@ -//! Boot-time helpers of the app core: the desktop window size, the panic logger, the replay -//! budget, the direct-server trigger, the cursor and the loop-rate tick. Moved out of `app.rs` -//! verbatim in phase 1a of the UI restructure (a pure move; `pub(crate)` widening only). +//! Boot-time helpers of the app core: the panic logger, the window a stored setting asks for, the +//! replay budget, the direct-server trigger and the loop-rate tick. Moved out of `app.rs` +//! verbatim in phase 1a of the UI restructure (a pure move; `pub(crate)` widening only). The SDL +//! shell's own steps (the window, the GL context, the display's density) moved on to +//! `plx_shell_sdl`, and the LG SDL's two boot hooks to `system`. use super::*; -use super::platform::Platform; - -/// What a DESKTOP window is asked to be, before the display's pixel density is known. -#[cfg(any(feature = "hostsim", test))] -#[derive(Clone, Copy)] -enum WindowAsk { - /// `PLXNATIVE_WIN=x`: a DRAWABLE of exactly this many pixels, on any display. - Drawable(c_int, c_int), - /// No override: the largest whole fraction of the canvas whose window fits this usable display - /// area (`SDL_GetDisplayUsableBounds`, in points). - Fit(c_int, c_int), -} - -/// How many drawable pixels a window point is worth on this display, as the integer pair SDL -/// reported for a window that exists: `window_w` points wide, `drawable_w` pixels wide. -/// -/// Integers, never a float multiplied back: 960 points of a 2x window must come out as exactly -/// 1920 pixels, and a ratio that is not a whole number (a 150% Windows display) must round the -/// same way on the way out as on the way in. -#[cfg(any(feature = "hostsim", test))] -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct Density { - window_w: c_int, - drawable_w: c_int, -} - -#[cfg(any(feature = "hostsim", test))] -impl Density { - /// One pixel per point: every 1x display, and what is assumed until a window has been measured. - const UNIT: Density = Density { window_w: 1, drawable_w: 1 }; - - /// The measured pair. A drawable that is not larger than the window (a 1x display) is - /// [`Density::UNIT`]: a drawable never has fewer pixels than points, and a window is never - /// grown to make up for one that seems to. - fn measured(window_w: c_int, drawable_w: c_int) -> Density { - if window_w <= 0 || drawable_w <= window_w { - Density::UNIT - } else { - Density { window_w, drawable_w } - } - } - - /// The window size, in points, whose drawable is `px` pixels: the nearest whole number of - /// points, and one fewer if rounding up would make the drawable LARGER than asked (never - /// larger than the canvas is the contract; a pixel short is a letterbox, a pixel over is not). - fn points(self, px: c_int) -> c_int { - let (w, d) = (i64::from(self.window_w), i64::from(self.drawable_w)); - let pt = ((i64::from(px) * w + d / 2) / d).max(1) as c_int; - if pt > 1 && self.pixels(pt) > px { - pt - 1 - } else { - pt - } - } - - /// The drawable, in pixels, of a window `pt` points wide. - fn pixels(self, pt: c_int) -> c_int { - let (w, d) = (i64::from(self.window_w), i64::from(self.drawable_w)); - ((i64::from(pt) * d + w / 2) / w) as c_int - } -} - -/// `PLXNATIVE_WIN`'s value: `x`, both positive. Anything else is no override. -#[cfg(any(feature = "hostsim", test))] -fn parse_window_override(v: &str) -> Option<(c_int, c_int)> { - let (w, h) = v.split_once(['x', 'X'])?; - match (w.trim().parse::(), h.trim().parse::()) { - (Ok(w), Ok(h)) if w > 0 && h > 0 => Some((w, h)), - _ => None, - } -} - -/// The window a DESKTOP should open at, in points, for a display of this pixel `density`: the -/// pure arithmetic of the size, so the Retina cases are testable without a Retina display. -/// -/// **The drawable is what is sized; the window follows from it.** The UI is authored at a 1920x1080 -/// canvas and every glyph, icon mask and poster is rasterized for 1:1 texels against it -/// (`gfx::snap`, the crispness contract in `theme.rs`), so a drawable LARGER than the canvas is -/// not a sharper picture: it is the same atlas stretched, with every drawable-sized buffer (the -/// page snapshot, the glass sources) four times the television's, which is how a 2x display once -/// breached the render-set ceiling on every frame (`ui/src/frame/render_set.rs`). -/// -/// * `Drawable` is that drawable, exactly. The fit below is chosen for a HUMAN looking at a -/// window, and a screenshot is not that: on a 1x display its divisor lands on 2 and every shot -/// comes back 960x540, half the canvas the UI is authored at, so a shot taken to JUDGE the -/// interface asks for full size (`make sim-shot SIM_W=1920 SIM_H=1080`). Off-screen edges are -/// fine for a headless grab: the drawable is the window's own framebuffer. -/// * `Fit` is **an exact divisor, never a best fit**: the largest of 1/1, 1/2 and 1/3 of the canvas -/// whose window, in points, fits the usable area. `surface::scale` will letterbox any drawable it -/// is given, so an arbitrary size would *work*, but a fractional scale resamples all of the above. -/// The bounds are in points, so the window is `canvas / div / density` of them. -/// -/// The television asks for the canvas itself (1:1) unless the owner picked a smaller Interface -/// resolution in Settings on webOS 1-3 (`requested_drawable`), in which case the compositor fills the panel. -/// A Mac is the case the `surface` doc was written against — 1920x1080 exceeds the usable area of -/// every laptop display Apple ships, so asking for it flatly would put the title bar above the -/// screen and the bottom of the interface under the Dock. -#[cfg(any(feature = "hostsim", test))] -fn plan_desktop_window(ask: WindowAsk, density: Density) -> (c_int, c_int) { - let points = |(w, h): (c_int, c_int)| (density.points(w), density.points(h)); - match ask { - WindowAsk::Drawable(w, h) => points((w, h)), - WindowAsk::Fit(uw, uh) => { - // A little headroom under the usable bounds: a window flush against them reads as a - // fullscreen that went wrong rather than as a deliberate size. - let (max_w, max_h) = ((uw as f32 * 0.95) as c_int, (uh as f32 * 0.95) as c_int); - let fits = |div| { - let (w, h) = points((SCR_W / div, SCR_H / div)); - w <= max_w && h <= max_h - }; - let div = (1..3).find(|&div| fits(div)).unwrap_or(3); - points((SCR_W / div, SCR_H / div)) - } - } -} - -/// `SDL_WINDOWPOS_CENTERED` on display 0. -#[cfg(feature = "hostsim")] -const WINDOWPOS_CENTERED: c_int = 0x2FFF_0000u32 as c_int; - -/// What this process is asked for: `PLXNATIVE_WIN` if it holds a size, else the fit to the display, -/// or the canvas itself if SDL cannot say how big the display is. -#[cfg(feature = "hostsim")] -fn desktop_window_ask() -> WindowAsk { - if let Some((w, h)) = std::env::var_os("PLXNATIVE_WIN").and_then(|v| parse_window_override(&v.to_string_lossy())) { - return WindowAsk::Drawable(w, h); - } - let mut r = [0 as c_int; 4]; // SDL_Rect: x, y, w, h - let ok = unsafe { SDL_GetDisplayUsableBounds(0, r.as_mut_ptr()) } == 0 && r[2] > 0 && r[3] > 0; - if ok { - WindowAsk::Fit(r[2], r[3]) - } else { - WindowAsk::Drawable(SCR_W, SCR_H) - } -} - -/// Size the just-created desktop `win` for the pixel density of the display it opened on. -/// -/// `SDL_GetDisplayDPI` is unreliable on macOS, so the density is MEASURED instead: the window was -/// opened at the 1x answer of [`plan_desktop_window`], and `SDL_GL_GetDrawableSize` over -/// `SDL_GetWindowSize` says how many pixels that bought per point. On a 1x display nothing happens. -/// On a 2x display the window is resized (and put back in the middle of the display, since it was -/// centred at the old size) to the points that give the drawable that was asked for: -/// `PLXNATIVE_WIN=1920x1080` is a 960x540-point window, not a 1920x1080-point one with a 3840x2160 -/// drawable. Called before `surface::probe`, which reads the drawable once and for good. -#[cfg(feature = "hostsim")] -unsafe fn fit_window_to_density(win: *mut c_void, ask: WindowAsk) { - let ((ww, wh), (dw, dh)) = plx_base::surface::window_and_drawable_size(win); - let density = Density::measured(ww, dw); - if density == Density::UNIT { - return; - } - let (pw, ph) = plan_desktop_window(ask, density); - if (pw, ph) == (ww, wh) { - return; - } - SDL_SetWindowSize(win, pw, ph); - SDL_SetWindowPosition(win, WINDOWPOS_CENTERED, WINDOWPOS_CENTERED); - let ((nw, nh), (gw, gh)) = plx_base::surface::window_and_drawable_size(win); - log(&format!( - "surface: {:.3} pixels per point (a {ww}x{wh} point window read back a {dw}x{dh} drawable); \ - resized to {pw}x{ph} points, which now reads {nw}x{nh} points / {gw}x{gh} drawable", - f64::from(dw) / f64::from(ww) - )); -} - -#[cfg(test)] -mod desktop_window_tests { - use super::WindowAsk::{Drawable, Fit}; - use super::{parse_window_override, plan_desktop_window, Density, WindowAsk, SCR_H, SCR_W}; - - /// A window of 1920 points whose drawable reads back 3840 pixels: macOS Retina, the case this - /// module exists for. (macOS always reports a whole backing factor, even in a "scaled" mode.) - fn retina() -> Density { - Density::measured(1920, 3840) - } - - /// The window the planner opens, in points, and the drawable that window gives. - fn plan(ask: WindowAsk, density: Density) -> ((i32, i32), (i32, i32)) { - let points = plan_desktop_window(ask, density); - (points, (density.pixels(points.0), density.pixels(points.1))) - } - - /// `PLXNATIVE_WIN=1920x1080` on a 1x display is the 1920x1080 window it always was. - #[test] - fn a_1x_display_gives_the_override_as_asked() { - assert_eq!(plan(Drawable(1920, 1080), Density::UNIT), ((1920, 1080), (1920, 1080))); - } - - /// THE BUG: `PLXNATIVE_WIN=1920x1080` on a 2x display was a 1920x1080-POINT window, whose - /// drawable is 3840x2160 (`scale=2.000`) and which breached the render-set ceiling on every - /// frame of a Library scroll. The override is the DRAWABLE, so the window is half of it. - #[test] - fn the_override_is_the_drawable_on_a_2x_display() { - assert_eq!(plan(Drawable(1920, 1080), retina()), ((960, 540), (1920, 1080))); - } - - /// A 2x laptop (usable ~1512x945 points): 960x540 points, a 1:1 drawable. What it always got, - /// by the coincidence of div=2 meeting a 2x density; now by arithmetic. - #[test] - fn a_2x_laptop_fits_960x540_points_for_a_1_to_1_drawable() { - assert_eq!(plan(Fit(1512, 945), retina()), ((960, 540), (1920, 1080))); - } - - /// THE SECOND HOLE: a 5K/4K display "looking like 2560x1440" has usable ~2560x1415 points, so - /// the fit in points took div=1 -- a 1920x1080-point window, a 3840x2160 drawable -- with no - /// override at all. The fit is of the DRAWABLE, measured in the points it occupies. - #[test] - fn a_large_2x_display_gives_the_same_1_to_1_drawable_without_any_override() { - assert_eq!(plan(Fit(2560, 1415), retina()), ((960, 540), (1920, 1080))); - } - - /// Nothing changes on a 1x display: the divisor lands where it did, on every size. - #[test] - fn a_1x_display_fits_exactly_as_it_did() { - // a 1080p display's usable area under a menu bar and a Dock: div=2 - assert_eq!(plan(Fit(1920, 1050), Density::UNIT), ((960, 540), (960, 540))); - // a display big enough for the canvas itself (div=1) needs 5% headroom: 1920 / 0.95 = 2021.05 - assert_eq!(plan(Fit(2022, 1140), Density::UNIT), ((1920, 1080), (1920, 1080))); - assert_eq!(plan(Fit(2020, 1140), Density::UNIT), ((960, 540), (960, 540))); - // a small one: div=3 - assert_eq!(plan(Fit(100, 100), Density::UNIT), ((640, 360), (640, 360))); - } - - /// A density that is not a whole number (a 150% Windows display, a fractional Wayland scale): - /// the window is the drawable over the ratio, exactly where that is exact. - #[test] - fn a_fractional_density_is_divided_out_too() { - let d150 = Density::measured(1280, 1920); - assert_eq!(plan(Drawable(1920, 1080), d150), ((1280, 720), (1920, 1080))); - // 1280x720 points is over 95% of a 1280x800 display, so the half (960x540 px) wins - assert_eq!(plan(Fit(1280, 800), d150), ((640, 360), (960, 540))); - } - - /// Whatever the ratio, the window never gives a drawable LARGER than the one asked for: a - /// pixel short is a letterbox, a pixel over is a texture that is not the canvas. - #[test] - fn the_drawable_is_never_larger_than_asked_on_any_density() { - for (window_w, drawable_w) in [(1000, 1100), (1000, 1250), (1000, 1333), (1000, 1750), (1000, 2000), (1000, 2500), (1000, 3000), (1920, 2880), (1366, 2049)] { - let d = Density::measured(window_w, drawable_w); - for (w, h) in [(1920, 1080), (960, 540), (640, 360), (1280, 720)] { - let (_, got) = plan(Drawable(w, h), d); - assert!(got.0 <= w && got.1 <= h, "{window_w}->{drawable_w} asked {w}x{h}: {got:?}"); - // and no more than a point short of it, in either axis - let point = (drawable_w + window_w - 1) / window_w; - assert!(w - got.0 < point && h - got.1 < point, "{window_w}->{drawable_w} asked {w}x{h}: {got:?}"); - } - for (uw, uh) in [(1280, 720), (1512, 945), (1920, 1050), (2560, 1415), (3840, 2100)] { - let (_, got) = plan(Fit(uw, uh), d); - assert!(got.0 <= SCR_W && got.1 <= SCR_H, "{window_w}->{drawable_w} usable {uw}x{uh}: {got:?}"); - } - } - } - - /// A drawable that is not larger than the window is no HiDPI at all, however it got that way: - /// a window is never grown to cover for a measurement that failed. - #[test] - fn a_drawable_no_larger_than_the_window_is_unit_density() { - assert_eq!(Density::measured(1920, 1920), Density::UNIT); - assert_eq!(Density::measured(0, 1920), Density::UNIT); - assert_eq!(Density::measured(1920, 960), Density::UNIT); - } - - #[test] - fn the_override_parses_a_positive_size_and_nothing_else() { - assert_eq!(parse_window_override("1920x1080"), Some((1920, 1080))); - assert_eq!(parse_window_override(" 640X360 "), Some((640, 360))); - assert_eq!(parse_window_override("1920 x 1080"), Some((1920, 1080))); - for bad in ["", "1920", "x", "0x1080", "1920x0", "-1x5", "axb", "1920x1080x2"] { - assert_eq!(parse_window_override(bad), None, "{bad:?}"); - } - } -} +use super::platform::{OpenAsk, Placement, Platform}; /// Log every Rust panic (message + source location + thread) to the event log AND the /// persistent crash log BEFORE it unwinds. A panic that crosses an extern "C" boundary @@ -441,27 +171,6 @@ pub(crate) fn install_plex_seams() { plx_plex::plex::session::install_account_clear_cleanup(plx_telemetry::telemetry::cleanup_after_account_clear); } -#[cfg(test)] -mod relaunch_tap_tests { - use super::slot_holds; - - #[test] - fn relaunch_slot_must_hold_libhelpers() { - assert!(slot_holds(0x1000, Some(0x1000)), "the slot holds libhelpers' function"); - assert!(!slot_holds(0x1000, Some(0x1001)), "a different value, even by the Thumb bit"); - assert!(!slot_holds(0x1000, None), "libhelpers is not mapped or lacks the symbol"); - assert!(!slot_holds(0, None)); - } - - #[test] - fn the_slot_must_be_word_aligned() { - use super::slot_aligned; - let word = core::mem::align_of::(); - assert!(slot_aligned(0x1000) && slot_aligned(word)); - assert!(!slot_aligned(0x1000 + 1) && !slot_aligned(word + word / 2)); - } -} - #[cfg(test)] mod seam_order_tests { /// `plx_plex` reports the version it is handed (`plex::identity::set_version`) and, in a @@ -623,25 +332,11 @@ mod seam_order_tests { assert!(user_agent < init, "set_user_agent must come before net::global_init"); } - /// SDL reads `SDL_WEBOS_CURSOR_SLEEP_TIME` in `SDL_Init`, so the hint set after it does nothing. - #[test] - fn the_cursor_sleep_hint_is_set_before_sdl_init() { - // Split with `concat!` for the reason the test above gives. - let source = include_str!("boot.rs"); - let body = source - .split_once(concat!("pub(crate) unsafe fn ", "construct(")) - .expect("construct") - .1; - let hint = body - .find(concat!("webos3_cursor_", "sleep_hint()")) - .expect("construct must set the cursor sleep hint"); - let init = body.find(concat!("SDL_Init(", "SDL_INIT_VIDEO)")).expect("construct's SDL_Init"); - assert!(hint < init, "the cursor sleep hint must come before SDL_Init"); - } - /// The Interface resolution is read from the stored session, so the session has to be read - /// BEFORE `SDL_CreateWindow` (the one place the window size is applied) and the window request - /// has to come from it. Reads the source for the reason the tests above give. + /// BEFORE the window is created (`Shell::open`, the one place the window size is applied) and the + /// window request has to come from it. SDL itself comes up before the session is read, as it always + /// has (`plx_shell_sdl::init` pins the order of its own steps). Reads the source for the reason the + /// tests above give. #[test] fn the_stored_session_is_read_before_the_window_is_created() { let source = include_str!("boot.rs"); @@ -655,8 +350,10 @@ mod seam_order_tests { let request = body .find(concat!("requested_drawable(", "&session)")) .expect("the window request is derived from the session"); - let window = body.find(concat!("SDL_CreateWindow(", "title")).expect("construct creates the window"); - assert!(load < request && request < window, "session read, then request, then SDL_CreateWindow"); + let window = body.find(concat!("shell.", "open(")).expect("construct opens the window"); + assert!(load < request && request < window, "session read, then request, then Shell::open"); + let init = body.find(concat!("shell.", "init(")).expect("construct brings the platform's SDL up"); + assert!(init < load, "SDL comes up before the session is read, the order boot has always had"); } /// Automatic is the native canvas on every set and asks for no smaller window. The other @@ -697,30 +394,18 @@ mod seam_order_tests { assert_eq!(super::window_fallback((super::SCR_W, super::SCR_H)), None, "the native canvas has no fallback"); } - /// `surface::probe` reads the drawable once, at boot, for good: the desktop window has to be - /// sized for the display's pixel density BEFORE it, or a 2x display keeps the 3840x2160 - /// drawable the 1x size gave it. Reads the source for the reason the tests above give. - #[test] - fn the_desktop_window_is_fitted_to_the_density_before_the_drawable_is_probed() { - let source = include_str!("boot.rs"); - let body = source.split_once(concat!("pub(crate) unsafe fn ", "construct(")).expect("construct").1; - let create = body.find(concat!("SDL_CreateWindow(", "title")).expect("creates the window"); - let fit = body.find(concat!("fit_window_to_", "density(win")).expect("fits the window to the density"); - let probe = body.find(concat!("surface::", "probe(win)")).expect("probes the drawable"); - assert!(create < fit && fit < probe, "create the window, fit it to the density, then probe the drawable"); - } - - /// `construct` frees a half-made window before it retries (a leaked one would keep the display). + /// The smaller-window retry is armed before the first window is asked for, from the size that + /// request carries: `construct` evaluates `window_fallback(` as part of the placement it hands + /// `Shell::open`. The retry loop itself, the destroy of a half-made window before it, and the + /// density fit before the drawable probe are the shell crate's (`plx_shell_sdl::Window::open`, + /// which pins their order). Reads the source for the reason the tests above give. #[test] - fn construct_destroys_a_half_made_window_before_the_retry() { + fn the_smaller_window_fallback_is_armed_before_the_window_is_opened() { let source = include_str!("boot.rs"); let body = source.split_once(concat!("pub(crate) unsafe fn ", "construct(")).expect("construct").1; - let create = body.find(concat!("SDL_CreateWindow(", "title")).expect("creates the window"); - let destroy = body.find(concat!("SDL_DestroyWindow(", "win)")).expect("destroys a half-made window"); - let retry = body.find(concat!("window_fallback(", "(ww_req")).expect("asks for the fallback size"); - assert!(create < destroy && destroy < body[create..].find("probe(win)").map(|i| i + create).unwrap(), - "the half-made window is destroyed inside the creation loop, before `surface::probe`"); - assert!(retry < create, "the retry is armed before the first attempt"); + let retry = body.find(concat!("window_fallback(", "size)")).expect("asks for the fallback size"); + let open = body.find(concat!("shell.", "open(")).expect("opens the window"); + assert!(retry < open, "the retry is armed before the first attempt"); } } @@ -772,145 +457,6 @@ fn drawable_for_setting(major: u32, chosen: plx_plex::plex::session::UiResolutio if plx_os::tv::device::offers_ui_resolution(major) { chosen.size() } else { None } } - -/// **webOS 3.x: shorten LG's own idle hide from about five minutes to five seconds.** Without -/// LG's extension, LG's SDL hides its pointer by itself after `SDL_WEBOS_CURSOR_SLEEP_TIME` of -/// stillness, and its default is about five minutes (timed on a 3.9.3 set, issue #642), where -/// every other app on that television hides it within seconds. Measured on the same set: the value -/// is milliseconds, `5000` hides a still pointer after about five seconds, and a deliberate -/// movement brings it back. Set only where `SDL_webOSCursorVisibility` is absent, so webOS 4+ -/// keeps its SDL's own behaviour. Must run before `SDL_Init`, which reads the hint. -#[cfg(not(feature = "hostsim"))] -unsafe fn webos3_cursor_sleep_hint() { - if let Some(ms) = cursor_sleep_hint(self_sym("SDL_webOSCursorVisibility").is_some()) { - SDL_SetHint(c"SDL_WEBOS_CURSOR_SLEEP_TIME".as_ptr(), ms.as_ptr()); - log("cursor: SDL_WEBOS_CURSOR_SLEEP_TIME=5000 (no SDL_webOS* in this SDL)"); - } -} -#[cfg(feature = "hostsim")] -unsafe fn webos3_cursor_sleep_hint() {} - -/// The idle-hide time to ask SDL for, in milliseconds as a string; `None` where LG's extension is -/// present and its SDL keeps its own behaviour. -#[cfg(not(feature = "hostsim"))] -fn cursor_sleep_hint(has_lg_extension: bool) -> Option<&'static std::ffi::CStr> { - (!has_lg_extension).then_some(c"5000") -} - -/// A symbol of the running process (the system SDL), resolved at runtime; `None` if absent or NULL. -#[cfg(not(feature = "hostsim"))] -fn self_sym(name: &str) -> Option<*mut std::ffi::c_void> { - plx_base::dynlib::Handle::self_handle().sym(name).filter(|p| !p.is_null()) -} - -/// **A warm launch's parameters, read where LG's SDL reads its `registerApp` replies.** SAM sends a -/// relaunch's parameters only to the `registerApp` subscriber, which is LG's SDL; its handler -/// (`callback_RegistNativeApp`) raises the window and never reads `parameters`. It fetches every -/// reply's payload through `HELPER_HLunaServiceMessage`, an exported pointer slot that -/// `LoadWEBOSBASELibrary` fills from `libhelpers.so.2` inside `SDL_Init` and that the handler -/// reloads on every call. Wrapping that slot hands a relaunch payload to `tv::launch` and returns -/// it unchanged, so SDL still raises the window. No new Luna registration: SAM refuses the app's -/// own (`tv::launch`). The firmware inventories have the slot from webOS 7.4 on; where it is missing -/// or empty (webOS 4.x to 6.x), nothing changes and callers keep closing the app first. -/// The tap installs only when the slot holds the address `libhelpers.so.2` (already mapped, -/// `RTLD_NOLOAD`) exports as `HLunaServiceMessage` ([`slot_holds`]); any other value is left alone. -#[cfg(not(feature = "hostsim"))] -unsafe fn tap_relaunch_payloads() { - use std::sync::atomic::{AtomicUsize, Ordering}; - let Some(slot) = self_sym("HELPER_HLunaServiceMessage") else { - log("relaunch tap: no HELPER_HLunaServiceMessage in this SDL"); - return; - }; - // An atomic reference to a misaligned address is undefined behaviour: refuse a symbol that is - // not a word-aligned slot before forming it. - if !slot_aligned(slot as usize) { - log("relaunch tap: slot misaligned \u{2014} not installed"); - return; - } - // SDL's Luna thread may read the slot while it is replaced: store it atomically, after the - // function it forwards to is published. - let slot = &*(slot as *const AtomicUsize); - let wrapped = wrapped_message as *const () as usize; - let current = slot.load(Ordering::Acquire); - if current == 0 || current == wrapped { - log(if current == 0 { "relaunch tap: HELPER_HLunaServiceMessage is empty" } - else { "relaunch tap: already installed" }); - return; - } - // The slot is only ours to wrap while it holds libhelpers' own `HLunaServiceMessage`: another - // value (a different SDL build, a slot of some other type) would be called as a function - // pointer it is not. - let expected = plx_base::dynlib::Handle::open_loaded(&["libhelpers.so.2"]) - .and_then(|(h, _)| h.sym("HLunaServiceMessage")) - .filter(|p| !p.is_null()) - .map(|p| p as usize); - if !slot_holds(current, expected) { - log("relaunch tap: slot does not hold libhelpers' HLunaServiceMessage \u{2014} not installed"); - return; - } - REAL_MESSAGE.store(current, Ordering::Release); - MAIN_THREAD.store(libc::pthread_self() as usize, Ordering::Relaxed); - slot.store(wrapped, Ordering::Release); - log("relaunch tap: installed"); -} -#[cfg(feature = "hostsim")] -unsafe fn tap_relaunch_payloads() {} - -/// Does the SDL slot hold exactly the function `libhelpers.so.2` exports as `HLunaServiceMessage`? -/// The Thumb bit is compared as `dlsym` and the slot both carry it. `expected` is `None` when -/// libhelpers is not mapped or lacks the symbol, and then nothing holds. -#[cfg(any(test, not(feature = "hostsim")))] -fn slot_holds(current: usize, expected: Option) -> bool { - expected == Some(current) -} - -/// Is `addr` aligned for the `AtomicUsize` the slot is read and written as? -#[cfg(any(test, not(feature = "hostsim")))] -fn slot_aligned(addr: usize) -> bool { - addr % core::mem::align_of::() == 0 -} - -#[cfg(not(feature = "hostsim"))] -type LunaMessageFn = unsafe extern "C" fn(*mut std::ffi::c_void) -> *const std::ffi::c_char; -#[cfg(not(feature = "hostsim"))] -static REAL_MESSAGE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -#[cfg(not(feature = "hostsim"))] -static MAIN_THREAD: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - -/// SDL's payload read, passed through. Every Luna reply SDL subscribed to comes through here, so -/// anything that is not a relaunch costs one substring scan and nothing else. -#[cfg(not(feature = "hostsim"))] -unsafe extern "C" fn wrapped_message(msg: *mut std::ffi::c_void) -> *const std::ffi::c_char { - let real = REAL_MESSAGE.load(std::sync::atomic::Ordering::Acquire); - if real == 0 { - return std::ptr::null(); - } - let real: LunaMessageFn = std::mem::transmute(real); - let p = real(msg); - if !p.is_null() { - let payload = std::ffi::CStr::from_ptr(p).to_string_lossy(); - if payload.contains("\"relaunch\"") { - let main = libc::pthread_self() as usize == MAIN_THREAD.load(std::sync::atomic::Ordering::Relaxed); - log(&format!("relaunch tap: {} bytes on the {} thread, parameters={}", - payload.len(), if main { "main" } else { "other" }, payload.contains("\"parameters\""))); - plx_os::tv::launch::offer(&payload); - } - } - p -} - -#[cfg(all(test, not(feature = "hostsim")))] -mod cursor_sleep_hint_tests { - use super::*; - - #[test] - fn the_idle_hide_hint_is_asked_for_only_where_lgs_extension_is_absent() { - assert_eq!(cursor_sleep_hint(false), Some(c"5000")); - assert_eq!(cursor_sleep_hint(true), None); - } -} - - /// Advance the once-per-second LOOP-RATE window: bump `iters_ct` and, when a full second has /// elapsed, recompute `loop_shown`, reset the window, and return `true` so the caller logs the /// heartbeat with its own route/overlay tag. Shared by the player and home/detail draw paths. @@ -1208,73 +754,13 @@ pub(crate) unsafe fn construct( initial.home.restore(&mt).map_err(|_| Exit::refused(1))?; plx_plex::plex::Client::restore_generation_seed(initial.primary_client).map_err(|_| Exit::refused(1))?; } - SDL_SetMainReady(); - // DEAD END, measured 2026-07-31 — do not re-try this. The obvious answer to "a parked TV - // should blank itself" is to stop inhibiting the platform screensaver here (and re-allow it - // per route, since webOS BACKGROUNDS the app to run one and `0x103` suspends the - // buffer-feed, so it could never be on during playback). It does not work, for a reason - // upstream of this app: the TV's SDL 2.0.4 fork carries the - // `SDL_VIDEO_ALLOW_SCREENSAVER` hint STRING but implements no wayland idle-inhibit - // (`strings libSDL2-2.0.so.0` finds no `idle_inhibit`/`suspend_screensaver` symbol), so - // this call and `SDL_EnableScreenSaver` are both no-ops. Soaked 34 min on Home with the - // TV's own `screenSaverEnabled: on`: no screensaver, no `LIFECYCLE: background`, CPU flat, - // our UI still at full brightness on the panel. webOS does not blank a foreground native - // app, and nothing reachable from SDL changes that. The line stays because it costs - // nothing and states the intent; it is not what keeps the screensaver away. - SDL_SetHint(c"SDL_VIDEO_ALLOW_SCREENSAVER".as_ptr(), c"0".as_ptr()); - webos3_cursor_sleep_hint(); - if SDL_Init(SDL_INIT_VIDEO) != 0 { - log("SDL_Init failed"); - return Err(Exit::refused(1)); - } - tap_relaunch_payloads(); - { - let d = SDL_GetCurrentVideoDriver(); - if !d.is_null() { - log(&format!( - "video driver: {}", - std::ffi::CStr::from_ptr(d).to_string_lossy() - )); - } - } - // The television has a real GLES2 driver (a shim over libmali). macOS has none at all — - // Apple ships desktop GL only, capped at 4.1 core — so asking for ES here fails context - // creation outright. 4.1 core is the closest thing that exists, and it is a superset for - // everything this renderer does: a real VBO (never client arrays) and RGBA/UNSIGNED_BYTE - // textures, both core-profile-legal. The shader sources are adapted at compile time by - // `gfx::glsl_preamble`, which reads the driver's GLSL version rather than assuming. - if cfg!(feature = "hostsim") { - SDL_GL_SetAttribute(A_CTX_PROFILE_MASK, CTX_PROFILE_CORE); - SDL_GL_SetAttribute(A_CTX_MAJOR, 4); - SDL_GL_SetAttribute(A_CTX_MINOR, 1); - } else { - SDL_GL_SetAttribute(A_CTX_PROFILE_MASK, CTX_PROFILE_ES); - SDL_GL_SetAttribute(A_CTX_MAJOR, 2); - SDL_GL_SetAttribute(A_CTX_MINOR, 0); - } - // full 32-bit RGBA so the video plane shows through - SDL_GL_SetAttribute(A_RED, 8); - SDL_GL_SetAttribute(A_GREEN, 8); - SDL_GL_SetAttribute(A_BLUE, 8); - SDL_GL_SetAttribute(A_ALPHA, 8); - SDL_GL_SetAttribute(A_BUFFER_SIZE, 32); - // ...and NO depth or stencil, which SDL would otherwise give us anyway: its defaults are - // 16 bits of depth and 0 of stencil, and asking for neither had simply never been written - // down. **This renderer has no use for either.** There is no `GL_DEPTH_TEST`, no - // `glDepthFunc`, no `glDepthMask` and no `glClear(GL_DEPTH_BUFFER_BIT)` anywhere in the - // crate — every screen is painter's-algorithm 2-D, drawn back to front — and the one - // scissor user (`gfx::clip_set`) is a scissor, not a stencil. - // - // On a TILER this is not merely 4 MB of address space. Midgard allocates the depth buffer - // per tile alongside colour and, unless the driver proves it dead, RESOLVES it to memory at - // end-of-frame: 1920x1080x2 bytes written per presented frame for a buffer nothing ever - // reads. `system.rs` logs what the config actually came back with — a request is not a - // grant, and the only honest confirmation is `FB bits: … depth=0`. - SDL_GL_SetAttribute(A_DEPTH, 0); - SDL_GL_SetAttribute(A_STENCIL, 0); + // SDL up: the screensaver hint, the platform's two steps around `SDL_Init`, the GL context request. + // The platform's (`Shell::init`; `plx_shell_sdl::init` is the one SDL implementation, and it pins the + // order inside it) and FIRST: before the stored session is read and before the window exists. + platform.shell.init(&mt)?; // **The stored session is read HERE, before the window.** The window size is a setting // (Settings > System > Interface resolution, install-wide: `Session::ui_resolution`), and - // `SDL_CreateWindow` below is the only moment it can be applied, so the record has to be read + // the window's creation (`Shell::open`) is the only moment it can be applied, so the record has to be read // first. `peek_settled` would not do: it only reads the cache, which the session owner fills // after boot, so its first call answers "not yet". The seams `load` consults (`install_plex_seams`) are installed by // `enter_application`, before `boot`. A replay or captured boot brings its own session. @@ -1283,21 +769,19 @@ pub(crate) unsafe fn construct( None => plx_plex::plex::session::load(), }; // The television is placed at 0,0 at exactly canvas size (unless a webOS 1-3 owner picked a smaller - // Interface resolution, `requested_drawable`) and takes the panel. A desktop - // window is centred (`SDL_WINDOWPOS_CENTERED`) at whatever fits — see `plan_desktop_window`. - // The density is not known until a window exists, so this is the 1x answer; `fit_window_to_density` - // below corrects it on a display where that was wrong. - #[cfg(feature = "hostsim")] - let desktop_ask = desktop_window_ask(); + // Interface resolution, `requested_drawable`) and takes the panel. A desktop window is centred at + // whatever fits the display: `Placement::Desktop`, which the shell plans and corrects for the + // display's pixel density once a window exists (`plx_shell_sdl::window`). + // **A stored size the set will not give must never brick launch.** If the window or its GL + // context is refused at a smaller size the owner chose, the shell frees whatever was made and + // retries ONCE at the native canvas (`fallback`); only a refused native window is fatal. On a + // desktop the request is the desktop's own size, not a setting, so there is no retry there. #[cfg(feature = "hostsim")] - let (wx, wy, ww_req, wh_req) = { - let (w, h) = plan_desktop_window(desktop_ask, Density::UNIT); - (WINDOWPOS_CENTERED, WINDOWPOS_CENTERED, w, h) - }; + let placement = Placement::Desktop; #[cfg(not(feature = "hostsim"))] - let (wx, wy, ww_req, wh_req) = { - let (w, h) = requested_drawable(&session).unwrap_or((SCR_W, SCR_H)); - (0, 0, w, h) + let placement = { + let size = requested_drawable(&session).unwrap_or((SCR_W, SCR_H)); + Placement::Panel { size, fallback: window_fallback(size) } }; // The title is furniture a television never draws (no window manager, no decoration) and // the first thing a desktop shows, so the two builds spell it differently: the device keeps @@ -1307,42 +791,18 @@ pub(crate) unsafe fn construct( #[cfg(not(feature = "hostsim"))] let title = c"plxnative"; // A frame dump's drawable is exactly the window's size in points: it is the one desktop window - // that does not ask for ALLOW_HIGHDPI (0x2000), so its window is the 1920x1080 points of the - // canonical Linux host on a Retina display too, and `fit_window_to_density` finds nothing to - // correct. (Absent from every shipping build.) + // that does not ask for ALLOW_HIGHDPI, so its window is the 1920x1080 points of the canonical + // Linux host on a Retina display too, and the shell's density fit finds nothing to correct. + // (Absent from every shipping build.) #[cfg(all(feature = "hostsim", feature = "devtriggers"))] - let window_flags = if crate::dev::framedump::requested() { SDL_WINDOW_FLAGS & !0x2000 } else { SDL_WINDOW_FLAGS }; + let high_dpi = !crate::dev::framedump::requested(); #[cfg(not(all(feature = "hostsim", feature = "devtriggers")))] - let window_flags = SDL_WINDOW_FLAGS; - // **A stored size the set will not give must never brick launch.** If the window or its GL - // context is refused at a smaller size the owner chose, free whatever was made and retry ONCE - // at the native canvas; only a refused native window is fatal. On a desktop the request is the - // desktop's own size, not a setting, so there is no retry there. - #[cfg(not(feature = "hostsim"))] - let mut fallback = window_fallback((ww_req, wh_req)); - #[cfg(feature = "hostsim")] - let mut fallback: Option<(c_int, c_int)> = None; - let (mut ww_try, mut wh_try) = (ww_req, wh_req); - let win = loop { - let win = SDL_CreateWindow(title.as_ptr(), wx, wy, ww_try, wh_try, window_flags); - if win.is_null() { - log(&format!("CreateWindow failed at {ww_try}x{wh_try}")); - } else { - let ctx = SDL_GL_CreateContext(win); - if !ctx.is_null() { - break win; - } - log(&format!("GL ctx failed at {ww_try}x{wh_try}")); - SDL_DestroyWindow(win); - } - let Some((w, h)) = fallback.take() else { return Err(Exit::refused(1)); }; - log(&format!("surface: retrying the window at the native {w}x{h}")); - (ww_try, wh_try) = (w, h); - }; - // Correct the size for the display's density now: `surface::probe` below reads the drawable once. - #[cfg(feature = "hostsim")] - fit_window_to_density(win, desktop_ask); - plx_base::surface::probe(win); + let high_dpi = true; + // The window and its GL context: created (with the retry above), corrected for the display's + // density, and its drawable probed (`surface::probe` reads it once, for good). The `Surface` it + // returns is the `App`'s for the rest of the process. + let surface = platform.shell.open(&mt, &OpenAsk { title, placement, high_dpi })?; + let win = surface.window(); // vsync on → the frame rate locks to the panel refresh. `/tmp/plxnative-novsync` uncaps it so // `fps=` reports the true GPU render rate. WSLg's X11/GLX swap accepts interval 1 without // blocking, so the software budget in `run` follows the same switch. @@ -1353,7 +813,7 @@ pub(crate) unsafe fn construct( #[cfg(not(all(feature = "hostsim", feature = "devtriggers")))] let dumping = false; let vsync_enabled = !dumping && (controlled || !crate::dev::scenarios::novsync_armed()); - SDL_GL_SetSwapInterval(if vsync_enabled { 1 } else { 0 }); + surface.set_swap_interval(if vsync_enabled { 1 } else { 0 }); #[cfg(all(feature = "hostsim", target_os = "linux"))] let wslg_frame_pacing = vsync_enabled && std::env::var_os("WSL_DISTRO_NAME").is_some() @@ -1393,12 +853,13 @@ pub(crate) unsafe fn construct( // …and the same handshake for the ROOT press: `tv::home::go_home`'s fallback leg minimizes // this window, and the window is created here, a long way from where BACK is decided. platform.shell.bind_window(win); - let wflags = SDL_GetWindowFlags(win); + let keyboard = plx_shell_sdl::text::keyboard_probe(win); log(&format!( - "keyboard: support={} active={} focus={} winflags=0x{wflags:x}", - SDL_HasScreenKeyboardSupport(), - SDL_IsTextInputActive(), - i32::from(wflags & SDL_WINDOW_INPUT_FOCUS != 0) + "keyboard: support={} active={} focus={} winflags=0x{:x}", + keyboard.support, + keyboard.active, + i32::from(keyboard.wflags & SDL_WINDOW_INPUT_FOCUS != 0), + keyboard.wflags )); platform.shell.grab_surface(win); @@ -2191,7 +1652,7 @@ pub(crate) unsafe fn construct( reread: Default::default(), ev, remote, - win, + surface, #[cfg(all(feature = "hostsim", target_os = "linux"))] wslg_frame_pacing, t0, diff --git a/rust-modules/src/app/deeplink.rs b/rust-modules/src/app/deeplink.rs index 6a1843bef9..d1810bf159 100644 --- a/rust-modules/src/app/deeplink.rs +++ b/rust-modules/src/app/deeplink.rs @@ -13,7 +13,7 @@ //! where Resume would. Anything else is `open`. //! - Unknown keys are ignored. No `plex` object at all is an ordinary launch. //! - A launch while the app runs carries the link too, where LG's SDL lets the app read relaunch -//! payloads (`app::boot::tap_relaunch_payloads`, webOS 7.4 on); the page then replaces wherever +//! payloads (`system::tap_relaunch_payloads`, webOS 7.4 on); the page then replaces wherever //! the app was. Elsewhere (webOS 4.x to 6.x) only a cold launch does, and a caller closes the app first //! (`com.webos.applicationManager/closeByAppId`), then launches. //! diff --git a/rust-modules/src/app/events.rs b/rust-modules/src/app/events.rs index 949ceec4cc..ff455dcbea 100644 --- a/rust-modules/src/app/events.rs +++ b/rust-modules/src/app/events.rs @@ -1,6 +1,7 @@ -//! SDL event decoding and the remote-FIFO token synthesis — the raw-offset reads of LG's shifted -//! `SDL_KeyboardEvent`, the synthetic key/pointer/wheel events, and `dispatch_remote_token`. -//! Moved out of `app.rs` verbatim in phase 1a (a pure move; `pub(crate)` widening only). +//! What the loop reads of SDL's events, and the remote-FIFO token synthesis: the `HostEvent` a decoded +//! SDL event becomes, the `KeyPress` constructor, the token parser and `dispatch_remote_token`. The bytes +//! themselves (the raw-offset reads of LG's shifted `SDL_KeyboardEvent`, the synthetic key, pointer and +//! wheel events) are `plx_shell_sdl`'s, re-exported below. //! //! The one decode that yields a platform-neutral value is [`decode_host_event`]: SDL's quit, //! application-lifecycle, key, text, pointer and wheel events become a [`HostEvent`], which the loop @@ -23,99 +24,38 @@ pub(crate) fn text_inputs(text: &str, panel: bool, at: plx_machine::machine::Tic events } -#[inline] -pub(crate) fn rd_u32(ev: &[u8], off: usize) -> u32 { - u32::from_ne_bytes([ev[off], ev[off + 1], ev[off + 2], ev[off + 3]]) -} +// What SDL's bytes are, and how they are written back, is the stock-SDL shell's (`plx_shell_sdl`): the +// raw-offset readers and both layouts of the key, pointer, wheel and text events, the lifecycle codes +// the tape is written in, and the synthetic events pushed onto SDL's queue. The application keeps what +// needs its own vocabulary: the `HostEvent` the loop consumes, the `KeyPress` constructor, the desktop's +// key stand-in, and the token parser. Re-exported here so the `remote_synth_*` names every call site +// (the loop, the FIFO, the replay driver, the cursor-swap click) already uses stay what they are. +pub(crate) use plx_shell_sdl::event::{is_input_event, rd_u32, Decoded, Lifecycle, PointerEdge}; +pub(crate) use plx_shell_sdl::inject::{ + synth_key as remote_synth_key, synth_key_edge as remote_synth_key_edge, + synth_key_repeat as remote_synth_key_repeat, synth_lifecycle as remote_synth_lifecycle, + synth_pointer as remote_synth_pointer, synth_ptr as remote_synth_ptr, synth_wheel as remote_synth_wheel, +}; +// The byte writers and two readers are the loop tests' (they write the bytes a platform would deliver). +#[cfg(test)] +pub(crate) use plx_shell_sdl::event::{rd_f32, rd_i32}; +#[cfg(test)] +pub(crate) use plx_shell_sdl::inject::{encode_key, encode_key_repeat, encode_pointer}; -/// A keyboard event's `(state, wcode, sym)`, decoded from the raw event bytes. -/// -/// **The two SDLs disagree about this struct, and nothing warns you.** LG's fork writes -/// `state` (u32) at +16, the webOS keycode at +20 and the SDL sym at +24. Stock SDL2 — -/// what the host simulator links — has `SDL_KeyboardEvent { type, timestamp, windowID, -/// state:u8@12, repeat:u8@13, pad, pad, keysym{ scancode:u32@16, sym:i32@20, … } }`, so -/// every field the app reads is at a different offset and there is no webOS keycode at all. -/// Reading the fork's offsets out of a stock event yields the window id as a keystate and -/// a scancode as a sym — plausible-looking garbage rather than a crash. -/// -/// `cfg!` rather than `#[cfg]` deliberately: both arms stay compiled on both platforms, so -/// the one nobody is currently building cannot rot. This is the single site that knows the -/// layout — `rd_u32`'s callers elsewhere read pointer events, whose offsets already agree. +/// The wcode a key press is read as: the one its bytes carried, else the desktop's stand-in for it. /// -/// **The `wcode` this returns is LG's SCANCODE**, which is worth saying because the name suggests -/// otherwise. Every field measured off the dev set is the SDL scancode of the key beside it — -/// backspace 42, Clear 156, ◀/▶ 80/79, OK 40 — so the fork's shift puts an ordinary -/// `SDL_Keysym { scancode, sym }` at +20/+24 rather than inventing a webOS keycode namespace. That -/// is why the codes above SDL's own range (450 play, 482 back, 505 exit) carry no sym at all: they -/// are LG-private scancodes the keymap has no keycode for. `docs/remote-keys.md` has the account. -/// -/// # The simulator's carrier moved, because the old one was silently DEAD -/// -/// A synthetic press from the remote FIFO has to get its wcode across `SDL_PushEvent`, and on the -/// host that queue is not SDL2's: macOS `libSDL2` is **sdl2-compat forwarding into SDL3**, so every -/// pushed event is converted out and back. Measured 2026-08-23 by dumping the polled bytes of a -/// press whose every spare field carried a distinct value: -/// -/// | field | offset | survives | -/// |------------------------------|--------|----------| -/// | `windowID` | +8 | yes | -/// | `padding2` / `padding3` | +14/15 | no | -/// | `keysym.scancode` | +16 | **no** — comes back 0 | -/// | `keysym.mod` | +24 | yes | -/// | `keysym.unused` | +28 | **no** — comes back 1 | -/// -/// It used to be `unused`, so **every wcode-ONLY token was dead**: `play`, `pause`, `stop`, `ff`, -/// `rew`, `playpause`, `exit`, `chup`, `chdown` all decoded as wcode 1 and did nothing at all, and -/// `tests/keytable.json` recorded three of them as `moved: false` — which reads as "that key does -/// nothing on that screen" and actually meant the press never arrived. An instrument silent by -/// construction: prove it can see the thing before reading its silence. -/// -/// `scancode` would have been the honest home (it is what a wcode IS) and it is the one field the -/// compat layer recomputes. So a synthetic press carries the value in `mod` and a MARKER in -/// `windowID` ([`SYNTH_WINDOW`]) — two fields, because the value alone cannot say whether it is -/// one: a real press puts its modifier bitmask in `mod`, so `mod != 0` means "shift is down" at -/// least as often as it means "injected". The marker restores the priority the `unused` field used -/// to express — **injected first, the desktop stand-in only as a fallback** — which is load-bearing -/// and not a preference: `host_wcode(8)` is BACK, while `remote_token_key`'s `backspace` token is -/// `(8, 42)`, so asking the stand-in first turns the panel's delete key into a navigation. -/// Clobbering `windowID` is safe here and nowhere else: this arm is `hostsim`-only, the simulator -/// has one window, and nothing in the event loop reads that field. +/// The shell reports `None` only for a stock-SDL press that carries no injected wcode (the television's +/// layout always has one), and the stand-in is the only way a physical Mac keyboard reaches a key the +/// remote has and a keyboard does not (space = PAUSE). **Injected first, the stand-in only as a +/// fallback** is load-bearing and not a preference: `host_wcode(8)` is BACK, while the `backspace` token +/// is `(8, 42)`, so asking the stand-in first turns the panel's delete key into a navigation +/// (`plx_shell_sdl::event::decode_key` has the measurement behind the carrier). It lives here and not in +/// the shell because `host_wcode` is a `ui` table the shell may not name. #[inline] -pub(crate) fn decode_key(ev: &[u8]) -> (u32, u32, u32) { - if cfg!(feature = "hostsim") { - let pressed = *ev.get(12).unwrap_or(&0) as u32; - let repeat = *ev.get(13).unwrap_or(&0) as u32; - let sym = rd_u32(ev, 20); - // Rebuild the fork's packed state byte-for-byte: low byte pressed(1)/released(0), - // bit 0x100 auto-repeat. Everything downstream tests exactly those two. - let state = pressed | if repeat != 0 { 0x100 } else { 0 }; - let injected = if rd_u32(ev, 8) == SYNTH_WINDOW { - u32::from(u16::from_ne_bytes([ev[24], ev[25]])) - } else { - 0 // a real desktop press: `mod` there is the modifier bitmask, not a wcode - }; - // The stand-in is the only way a physical Mac keyboard reaches a key the remote has and a - // keyboard does not (space = PAUSE), and it applies to real presses alone. - let wcode = if injected != 0 { - injected - } else { - host_wcode(sym) - }; - (state, wcode, sym) - } else { - (rd_u32(ev, 16), rd_u32(ev, 20), rd_u32(ev, 24)) - } +fn wcode_of(carried: Option, sym: u32) -> u32 { + carried.unwrap_or_else(|| host_wcode(sym)) } -/// The `windowID` a SYNTHETIC key event carries on the host, marking it as one — see [`decode_key`] -/// for why the wcode needs a marker beside it rather than standing on its own. Any value no real -/// window can have; SDL numbers windows from 1. -/// -/// Defined unconditionally, like both halves of [`decode_key`]: the arm that uses it is behind -/// `cfg!` rather than `#[cfg]`, precisely so the configuration nobody is currently building cannot -/// rot. -pub(crate) const SYNTH_WINDOW: u32 = 0x504c_584b; // "PLXK" - /// The Magic Remote button a desktop keyboard stands in for, or 0. /// /// Only the keys with NO sym equivalent need this. Navigation and OK/BACK already work on a @@ -133,13 +73,6 @@ pub(crate) fn host_wcode(sym: u32) -> u32 { } } -/// SDL's application events (`SDL_APP_*`), the four the loop acts on: the compositor taking the -/// screen (WILL and DID enter background) and giving it back (WILL and DID enter foreground). -const SDL_APP_WILLENTERBACKGROUND: u32 = 0x103; -const SDL_APP_DIDENTERBACKGROUND: u32 = 0x104; -const SDL_APP_WILLENTERFOREGROUND: u32 = 0x105; -const SDL_APP_DIDENTERFOREGROUND: u32 = 0x106; - /// What the platform tells the loop: a key press, a text commit, the pointer, the wheel, the window /// leaving or returning to the screen, and the host asking the application to end. App-private, like /// [`Shell`](super::platform::Shell): no platform reaches it by a type of its own until the @@ -167,9 +100,9 @@ pub(crate) enum HostEvent { /// One commit from the platform's text input (the television's own keyboard): the decoded /// string, possibly empty (SDL delivers a commit for the IME's own bookkeeping too, and the /// loop ignores an empty one as it always has). The platform's own text layout is decoded - /// before it gets here (`textinput::decode`, the one place that knows the offsets). + /// before it gets here (`plx_shell_sdl::text::decode`, the one place that knows the offsets). Text(String), - /// One pointer event, at authored 1920x1080 coordinates ([`ptr_xy`]: the window's pixels + /// One pointer event, at authored 1920x1080 coordinates (`plx_shell_sdl::event::ptr_xy`: the window's pixels /// converted exactly once, the identity while the drawable is the canvas). `edge` is what it did: /// moved, went down or came up. It is the event TYPE alone, for any button, as the loop has always /// read it. The plan's `buttons` and `shown` members are not carried, because today's SDL events @@ -180,21 +113,10 @@ pub(crate) enum HostEvent { /// One tick of the wheel: its vertical count in the signed whole ticks the loop reads (a /// fractional trackpad tick that rounds to nothing is `0`, which the loop records and then /// ignores, as it always has). Decoded from whichever offset this host carries it at - /// ([`decode_wheel_dy`]). + /// (`plx_shell_sdl::event::decode_wheel_dy`). Wheel { dy: i32 }, } -/// What a [`HostEvent::Pointer`] did. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum PointerEdge { - /// `SDL_MOUSEMOTION`. - Move, - /// `SDL_MOUSEBUTTONDOWN`, any button. - Down, - /// `SDL_MOUSEBUTTONUP`, any button. - Up, -} - impl HostEvent { /// Is this the viewer's INPUT (a key, text, pointer or wheel event), as opposed to the window's /// (a lifecycle edge, quit)? The loop's activity bookkeeping asks it: input keeps a release-health @@ -264,11 +186,12 @@ impl KeyPress { Some(KeyPress { action, edge, raw }) } - /// The press an SDL key event is: the raw pair as `decode_key` reads it, its action, and the - /// edge the fork's packed `state` names (low byte 1 is down, bit 0x100 is the auto-repeat; the - /// same reading `bridge::key_input` makes of it). A key-up never carries the repeat bit here. - pub(crate) fn from_sdl(ev: &[u8]) -> Option { - let (state, wcode, sym) = decode_key(ev); + /// The press a decoded SDL key edge is: the raw pair (the carried wcode, else the desktop stand-in, + /// [`wcode_of`]), its action, and the edge the fork's packed `state` names (low byte 1 is down, bit + /// 0x100 is the auto-repeat; the same reading `bridge::key_input` makes of it). A key-up never + /// carries the repeat bit here. + fn from_decoded(state: u32, wcode: Option, sym: u32) -> Option { + let wcode = wcode_of(wcode, sym); let edge = if (state & 0xff) != 1 { Edge::Up } else if state & 0x100 != 0 { @@ -306,137 +229,27 @@ impl KeyPress { } } -/// One edge of the window's visibility. Both background edges park the tree (the second finds -/// nothing left to park); WILL foreground un-parks the tree, and DID foreground alone reacquires the -/// window and restores playback. A platform that sends only DID background is enough on its own -/// (`WindowActivity`). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Lifecycle { - WillBackground, - DidBackground, - WillForeground, - DidForeground, -} - -impl Lifecycle { - /// The SDL event type this edge arrives as, and so the code the SDL-coded readers take: the - /// recorder's tape (`enc_lifecycle`, whose recorded codes ARE the tape format), the window gate - /// and telemetry's crash steps and session. The inverse of [`decode_host_event`]'s table; - /// `host_event_tests` pins the four pairs. - pub(crate) const fn sdl_code(self) -> u32 { - match self { - Lifecycle::WillBackground => SDL_APP_WILLENTERBACKGROUND, - Lifecycle::DidBackground => SDL_APP_DIDENTERBACKGROUND, - Lifecycle::WillForeground => SDL_APP_WILLENTERFOREGROUND, - Lifecycle::DidForeground => SDL_APP_DIDENTERFOREGROUND, - } - } -} - -/// An SDL event decoded into a [`HostEvent`]: `SDL_QUIT`, the four application lifecycle types, a -/// key edge (`SDL_KEYDOWN`/`SDL_KEYUP`, through [`decode_key`], so both layouts), a text commit -/// (`SDL_TEXTINPUT`, through `textinput::decode`), a pointer event (motion, button down and button up, -/// through [`ptr_xy`]) and a wheel tick (through [`decode_wheel_dy`]). `None` for everything else, -/// which the loop reads raw (the IME's pre-edit, and the SDL events nothing acts on). Beside -/// [`decode_key`], the other place that knows SDL's event bytes. +/// An SDL event decoded into a [`HostEvent`]: the shell's decode of the bytes (both layouts of every +/// event, `plx_shell_sdl::event::decode`) mapped onto the vocabulary the loop reads. `None` for +/// everything the shell leaves raw (the IME's pre-edit, and the SDL events nothing acts on), which the +/// loop reads raw. #[inline] pub(crate) fn decode_host_event(ev: &[u8]) -> Option { - Some(match rd_u32(ev, 0) { - SDL_QUIT => HostEvent::Quit, - SDL_KEYDOWN | SDL_KEYUP => HostEvent::Key(KeyPress::from_sdl(ev)?), - SDL_TEXTINPUT => HostEvent::Text(crate::textinput::decode(ev)), - SDL_MOUSEMOTION => pointer_event(ev, PointerEdge::Move), - SDL_MOUSEBUTTONDOWN => pointer_event(ev, PointerEdge::Down), - SDL_MOUSEBUTTONUP => pointer_event(ev, PointerEdge::Up), - SDL_MOUSEWHEEL => HostEvent::Wheel { dy: decode_wheel_dy(ev) }, - SDL_APP_WILLENTERBACKGROUND => HostEvent::Lifecycle(Lifecycle::WillBackground), - SDL_APP_DIDENTERBACKGROUND => HostEvent::Lifecycle(Lifecycle::DidBackground), - SDL_APP_WILLENTERFOREGROUND => HostEvent::Lifecycle(Lifecycle::WillForeground), - SDL_APP_DIDENTERFOREGROUND => HostEvent::Lifecycle(Lifecycle::DidForeground), - _ => return None, - }) -} - -/// A pointer event's position and edge. The coordinates are read at +20 and +24 in both layouts (the -/// pointer offsets agree, [`ptr_xy`]), and the button at +16 and its state at +17 are not read: the -/// edge is the event type, for any button, as the loop has always taken it. -#[inline] -fn pointer_event(ev: &[u8], edge: PointerEdge) -> HostEvent { - let (x, y) = ptr_xy(ev); - HostEvent::Pointer { x, y, edge } -} - -/// A wheel event's vertical tick count, in the signed whole ticks the loop reads. -/// -/// **The host reads a DIFFERENT offset, and this one is not the LG-fork -/// shift `decode_key` documents — it is macOS `libSDL2` again being -/// sdl2-compat forwarding into SDL3.** `SDL_MouseWheelEvent` on real SDL2 -/// (what the television runs) carries a plain `Sint32 y` at +20, which is -/// what production code always read. Measured 2026-09-02 by dumping the -/// polled bytes of an injected -40 tick on this host: `+20` came back 0, and -/// -40.0 arrived instead as the FLOAT `preciseY` field at `+32` — SDL2's own -/// struct gained that field in 2.0.18 for fractional trackpad scroll, and -/// sdl2-compat's round trip apparently only forwards it, leaving the legacy -/// integer field zeroed for both a genuine trackpad tick and anything -/// `SDL_PushEvent`d in this shape (item 13's `wheel:` FIFO token hit -/// this the first time anything synthesized a wheel event at all — nothing -/// needed one before). `cfg!`, not `#[cfg]`, so both arms keep compiling. -#[inline] -fn decode_wheel_dy(ev: &[u8]) -> i32 { - if cfg!(feature = "hostsim") { - rd_f32(ev, 32).round() as i32 - } else { - rd_i32(ev, 20) - } + host_event(plx_shell_sdl::event::decode(ev)?) } -/// The bytes a synthetic key event needs, in whichever layout [`decode_key`] reads. -/// -/// **The inverse of `decode_key`, and the pair is only correct together.** They already shipped -/// disagreeing once: the simulator accepted every FIFO token and never moved, because this end -/// wrote LG's fork layout while the reading end had been taught stock SDL2's. Nothing in the -/// compiler couples them, so `key_bytes_round_trip` below is what does. -/// -/// Pure, and separate from the `SDL_PushEvent` that consumes it, precisely so that test can run on -/// the host — `make check` links no SDL. -pub(crate) fn encode_key(sym: c_uint, wcode: c_uint, down: bool) -> [u8; 128] { - let mut ev = [0u8; 128]; - ev[0..4].copy_from_slice(&if down { SDL_KEYDOWN } else { SDL_KEYUP }.to_ne_bytes()); - if cfg!(feature = "hostsim") { - ev[12] = u8::from(down); // state - ev[13] = 0; // repeat - ev[20..24].copy_from_slice(&sym.to_ne_bytes()); - // The wcode rides `SDL_Keysym.mod` (event offset +24, a `Uint16`), under a marker in - // `windowID` that says this press is synthetic at all. Several tokens carry ONLY a wcode - // (`pause` is sym 0, wcode 72), so deriving it from the sym is not an option. - // `decode_key`'s doc has the measurement behind both fields — the short version is that of - // the spare places to put a value, these two are the ones sdl2-compat does not discard. - ev[8..12].copy_from_slice(&SYNTH_WINDOW.to_ne_bytes()); - ev[24..26].copy_from_slice(&(wcode as u16).to_ne_bytes()); - } else { - ev[16..20].copy_from_slice(&if down { 1u32 } else { 0 }.to_ne_bytes()); // state - ev[20..24].copy_from_slice(&wcode.to_ne_bytes()); - ev[24..28].copy_from_slice(&sym.to_ne_bytes()); - } - ev -} - -/// The bytes a synthetic HARDWARE AUTO-REPEAT edge carries — `encode_key`'s down edge with the -/// 0x101 shape (`state & 0x100 != 0`) the loop's repeat arm requires, in whichever layout -/// `decode_key` reads. `encode_key` itself must never produce this (`key_bytes_round_trip` pins -/// that a synthetic EDGE "must never look like auto-repeat"), so it is a second, deliberately -/// separate function rather than a third argument threaded through the first — item 13's -/// `holdrep:` FIFO token is the only caller, and it exists so a script can exercise the -/// `Edge::Repeat` a screen receives without a real remote's own repeat cadence. -pub(crate) fn encode_key_repeat(sym: c_uint, wcode: c_uint) -> [u8; 128] { - let mut ev = encode_key(sym, wcode, true); - if cfg!(feature = "hostsim") { - ev[13] = 1; // the `repeat` byte `decode_key`'s hostsim arm folds into `state & 0x100` - } else { - let state = rd_u32(&ev, 16) | 0x100; - ev[16..20].copy_from_slice(&state.to_ne_bytes()); - } - ev +/// One decoded SDL event as a [`HostEvent`]. The only place a [`Decoded`] becomes the application's own +/// type, so the next platform's events arrive through a sibling of this function and not through SDL's +/// bytes (`docs/platform-ports.md`, Target shape 8). +fn host_event(decoded: Decoded) -> Option { + Some(match decoded { + Decoded::Quit => HostEvent::Quit, + Decoded::Key { state, wcode, sym } => HostEvent::Key(KeyPress::from_decoded(state, wcode, sym)?), + Decoded::Text(text) => HostEvent::Text(text), + Decoded::Pointer { x, y, edge } => HostEvent::Pointer { x, y, edge }, + Decoded::Wheel { dy } => HostEvent::Wheel { dy }, + Decoded::Lifecycle(edge) => HostEvent::Lifecycle(edge), + }) } /// **One native key edge as the loop hands it to the tree**, for the effect-level guards (W5b): the @@ -454,25 +267,6 @@ pub(crate) fn native_key_input(sym: c_uint, wcode: c_uint, down: bool, at: plx_m (press, super::bridge::key_input(sym, wcode, press.state(), at, plx_machine::machine::Source::Sdl)) } -#[inline] -/// An SDL pointer event's position, converted from window pixels to the authored 1920x1080 canvas. -/// -/// THE one place event coordinates enter the UI, so the conversion cannot be forgotten at a new -/// call site — there are nine, and patching them individually is how the tenth ends up wrong. -/// `surface::to_logical` is the identity while the drawable is 1920x1080, which it is 1:1 unless -/// a webOS 1-3 owner picks a smaller Interface resolution (or the debug drawable trigger asks for one). -pub(crate) fn ptr_xy(ev: &[u8]) -> (f32, f32) { - plx_base::surface::to_logical(rd_i32(ev, 20) as f32, rd_i32(ev, 24) as f32) -} - -pub(crate) fn rd_i32(ev: &[u8], off: usize) -> i32 { - i32::from_ne_bytes([ev[off], ev[off + 1], ev[off + 2], ev[off + 3]]) -} - -pub(crate) fn rd_f32(ev: &[u8], off: usize) -> f32 { - f32::from_ne_bytes([ev[off], ev[off + 1], ev[off + 2], ev[off + 3]]) -} - /// Map a remote-control token (from the `crate::remote` FIFO) to the `(sym, wcode)` a /// real Magic-Remote press would carry — the pair the ONE key handler already matches /// (see `ui::consts`). Returns None for an unknown token. Kept deliberately small: the @@ -598,57 +392,6 @@ fn remote_token_pointer(tok: &str) -> Option<(RemotePointer, i32, i32)> { y.parse::().ok()?.clamp(0, plx_base::surface::LOGICAL_H as i32 - 1))) } -/// SDL pointer bytes shared by clicks, held-pointer FIFO edges and recorded-event replay. -/// The inverse of `ptr_xy`: convert authored coordinates exactly once, including window scaling -/// and letterboxing. Replay may carry a real off-canvas motion, so only the token parser clamps. -/// ABI: SDL's `SDL_events.h` (stock and the NDK's) mouse-event declarations put four -/// Uint32 fields before button@16/state@17 and Sint32 x@20/y@24. ARM32 NDK syntax-only -/// `offsetof` assertions verified these offsets; see `docs/testing-player-pointer.md`. -fn encode_pointer(et: u32, x: i32, y: i32) -> [u8; 128] { - let mut ev = [0u8; 128]; - let (px, py) = plx_base::surface::to_physical(x as f32, y as f32); - ev[0..4].copy_from_slice(&et.to_ne_bytes()); - ev[20..24].copy_from_slice(&(px.round() as i32).to_ne_bytes()); - ev[24..28].copy_from_slice(&(py.round() as i32).to_ne_bytes()); - if matches!(et, SDL_MOUSEBUTTONDOWN | SDL_MOUSEBUTTONUP) { - ev[16] = 1; // SDL_BUTTON_LEFT - ev[17] = u8::from(et == SDL_MOUSEBUTTONDOWN); - } - ev -} - -/// Synthesize a Magic-Remote pointer click at authored 1920x1080 coords (the browser -/// remote's click-on-the-stream): two motion events, then button down+up. The first -/// motion is a >=120px jitter so the accumulated pointer distance defeats the -/// D-pad-mode pointer gate (`Pointer::mot_accum < 120` swallows small motions after D-pad use); -/// the second lands on the target. The LG SDL fork's mouse events carry x@20 / y@24 -/// (i32) — the only fields the handlers read. -/// -/// The browser still sends clicks only: forwarding hover moved app focus on every pass of the -/// mouse over the streamed picture. A driver can explicitly send `pm:`/`pd:`/`pu:` instead to -/// separate HUD reveal from a press or to hold a drag across frames. Those edges add no jitter. -pub(crate) fn remote_synth_ptr(x: i32, y: i32) { - let jx = if x >= 200 { x - 200 } else { x + 200 }; - remote_synth_pointer(SDL_MOUSEMOTION, jx, y); - remote_synth_pointer(SDL_MOUSEMOTION, x, y); - remote_synth_pointer(SDL_MOUSEBUTTONDOWN, x, y); - remote_synth_pointer(SDL_MOUSEBUTTONUP, x, y); -} - -/// ONE pointer event in authored coordinates, shared by the FIFO and replay. Unlike `ck:`, -/// these primitives add no motion or release: `pd:` stays held until a separate `pu:` arrives. -pub(crate) fn remote_synth_pointer(et: u32, x: i32, y: i32) { - let ev = encode_pointer(et, x, y); - unsafe { SDL_PushEvent(ev.as_ptr() as *const c_void) }; -} - -/// One app lifecycle event (`0x103`–`0x106`), as the compositor would send it — the replay -/// driver's re-injection of a recorded background/foreground edge. -pub(crate) fn remote_synth_lifecycle(code: u32) { - let mut ev = [0u8; 128]; - ev[0..4].copy_from_slice(&code.to_ne_bytes()); - unsafe { SDL_PushEvent(ev.as_ptr() as *const c_void) }; -} /// A remote token that acts DIRECTLY rather than by pushing SDL events — the recorder writes /// these as `token` records, and the replay driver re-dispatches them. It is one of four fates: @@ -669,66 +412,6 @@ pub(crate) fn token_is_direct(tok: &str) -> bool { || tok.starts_with("txt:") } -/// Synthesize a full remote-key press (key-down then key-up) and push both onto SDL's -/// own event queue, so the existing poll loop consumes them as if they came off the -/// wayland input path. The LG SDL fork's `SDL_KeyboardEvent` carries state@16 / -/// wcode@20 / sym@24 (native-endian; the TV is LE), and the handler reads press vs -/// release from `state & 0xff` — so the down carries state=1, the up state=0. Both -/// are required: a grid-card OK arms on down and *commits on release*. -pub(crate) fn remote_synth_key(sym: c_uint, wcode: c_uint) { - remote_synth_key_edge(sym, wcode, true); - remote_synth_key_edge(sym, wcode, false); -} - -/// ONE edge of a remote key press. Split out for the `okdown`/`okup` FIFO tokens, because a -/// **press-and-hold** is only expressible as two tokens with real time between them: the item menu -/// opens on `press::is_long`, which measures the interval between the down and the up. The paired -/// `remote_synth_key` above is this called twice back to back (a tap). -pub(crate) fn remote_synth_key_edge(sym: c_uint, wcode: c_uint, down: bool) { - let ev = encode_key(sym, wcode, down); - unsafe { SDL_PushEvent(ev.as_ptr() as *const c_void) }; -} - -/// ONE hardware auto-repeat edge — item 13's `holdrep:` FIFO token, which lets a script -/// exercise a held key's `Edge::Repeat` (the Settings family's paced focus walk, the player -/// scrubber's continuous scrub) without a real remote's own repeat cadence. Only recognised as a -/// repeat by the loop's key arm when `App::down_sym` already equals `sym` — i.e. after a -/// `holddown:` and before its matching `holdup:`, the same split `okdown`/`okup` -/// already uses for a press-and-hold. -pub(crate) fn remote_synth_key_repeat(sym: c_uint, wcode: c_uint) { - let ev = encode_key_repeat(sym, wcode); - unsafe { SDL_PushEvent(ev.as_ptr() as *const c_void) }; -} - -/// Synthesize one Magic-Remote scroll-wheel tick — item 13's `wheel:` FIFO token, so a script -/// can drive the wheel with no mouse in the room. Encoded in the plain, real-SDL2 shape -/// (`Sint32 y` at `+20`) unconditionally: it is the READING side that has to branch by platform -/// now, not this one — see [`decode_wheel_dy`] on why `+20` decodes to 0 on this host and -/// where the value actually lands after `SDL_PushEvent` round-trips it. -pub(crate) fn remote_synth_wheel(dy: i32) { - let mut ev = [0u8; 128]; - ev[0..4].copy_from_slice(&SDL_MOUSEWHEEL.to_ne_bytes()); - ev[20..24].copy_from_slice(&dy.to_ne_bytes()); - unsafe { SDL_PushEvent(ev.as_ptr() as *const c_void) }; -} - -/// 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 `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!( - et, - SDL_KEYDOWN - | SDL_KEYUP - | SDL_TEXTINPUT - | SDL_TEXTEDITING - | SDL_MOUSEMOTION - | SDL_MOUSEBUTTONDOWN - | SDL_MOUSEBUTTONUP - | SDL_MOUSEWHEEL - ) -} - #[cfg(test)] mod input_event_tests { use super::*; @@ -747,22 +430,6 @@ mod input_event_tests { assert_eq!(remote_token_pointer("pointer:1,2"), None); } - #[test] - fn pointer_bytes_round_trip_through_the_common_coordinate_decoder() { - let _serial = plx_base::testlock::serial(); - for et in [SDL_MOUSEMOTION, SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP] { - for (x, y) in [(0, 0), (1400, 870), (1919, 1079), (-200, 400)] { - let ev = encode_pointer(et, x, y); - assert_eq!(rd_u32(&ev, 0), et); - assert_eq!(ptr_xy(&ev), (x as f32, y as f32)); - if et != SDL_MOUSEMOTION { - assert_eq!(ev[16], 1, "the left button survives SDL's event queue"); - assert_eq!(ev[17], u8::from(et == SDL_MOUSEBUTTONDOWN)); - } - } - } - } - #[cfg(feature = "devtriggers")] #[test] fn hang_probes_are_direct_recorder_tokens() { @@ -800,27 +467,6 @@ mod input_event_tests { // a by-id input is recorded as an input at its tap, never as a direct recorder token assert!(!token_is_direct("focus:home.row.2") && !token_is_direct("press:home.row.2")); } - - /// 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() { - for et in [ - SDL_KEYDOWN, - SDL_KEYUP, - SDL_TEXTINPUT, - SDL_TEXTEDITING, - SDL_MOUSEMOTION, - SDL_MOUSEBUTTONDOWN, - SDL_MOUSEBUTTONUP, - SDL_MOUSEWHEEL, - ] { - assert!(is_input_event(et), "{et:#x} is input"); - } - for et in [SDL_QUIT, 0x101, 0x103, 0x104, 0x105, 0x106, 0x200] { - assert!(!is_input_event(et), "{et:#x} is the app's, not a modal's"); - } - } } /// Dispatch one synthetic-input token. Shared by the SSH-only development FIFO and Lab Control's @@ -939,9 +585,18 @@ pub(crate) fn dispatch_remote_token(tok: &str, ps: &plx_media::route::PlaybackSe #[cfg(test)] mod key_layout_tests { - use super::{decode_key, encode_key, encode_key_repeat}; + use super::{encode_key, encode_key_repeat, wcode_of}; use plx_ui::consts::{SDLK_DOWN, SDLK_RETURN, WCODE_BACK, WCODE_PAUSE}; + /// What the loop reads a key's bytes as: the shell's decode with this application's desktop + /// stand-in applied where the bytes carry no wcode, the way `KeyPress::from_decoded` reads it. + /// The shell's own tests grade the byte layout; these grade the pair that reaches the loop, + /// stand-in priority included. + fn decode_key(ev: &[u8]) -> (u32, u32, u32) { + let (state, wcode, sym) = plx_shell_sdl::event::decode_key(ev); + (state, wcode_of(wcode, sym), sym) + } + /// `encode_key` and `decode_key` must agree, in whichever layout this build compiled. /// /// This is the regression test for a bug that shipped: the two ends disagreed about diff --git a/rust-modules/src/app/mod.rs b/rust-modules/src/app/mod.rs index 7210ad9e3d..761e150d12 100644 --- a/rust-modules/src/app/mod.rs +++ b/rust-modules/src/app/mod.rs @@ -19,7 +19,6 @@ use std::os::raw::{c_char, c_int, c_uint, c_void}; use std::sync::atomic::Ordering::Relaxed; // ---- constants (SDL 2.0.4 + GLES2 + app) ---- -const SDL_INIT_VIDEO: u32 = 0x20; /// Appended to every heartbeat on a simulator build, and empty on a television. /// /// The heartbeat is the app's perf surface: `tests/run.py --fps` grades `loop=` and `fps=` from it, @@ -33,61 +32,16 @@ const SIM_TAG: &str = if cfg!(feature = "hostsim") { "" }; -/// OPENGL | FULLSCREEN on the television, which owns the whole panel. -/// -/// The desktop asks for OPENGL | ALLOW_HIGHDPI — no fullscreen grab (hostile on a laptop) and -/// **not RESIZABLE**: `surface::probe` reads the drawable once, at boot, so a dragged edge would -/// leave the viewport describing a window that no longer exists, and the interface would sit in a -/// 1920x1080-shaped corner of the new one with every pointer hit landing somewhere else. The window -/// opens at an exact divisor of the canvas instead — see `boot::plan_desktop_window`. -/// -/// ALLOW_HIGHDPI is what makes that divisor land on a **1:1 surface** on the Mac people actually -/// have: without it a Retina display gives a drawable equal to the window in POINTS, which the -/// compositor then doubles, so the whole interface is an upscale of a half-size render. With it, -/// `boot::fit_window_to_density` measures the pixels per point once the window exists and sizes -/// it in points for the drawable it should give: 960x540 points for a 1920x1080 drawable on a 2x -/// display, so `surface::scale() == 1.0`, the same 1:1 texel contract the television gets. -const SDL_WINDOW_FLAGS: u32 = if cfg!(feature = "hostsim") { - 0x2 | 0x2000 -} else { - 0x2 | 0x1 -}; -/// `SDL_WINDOW_INPUT_FOCUS`. Note it is NOT among the flags requested above — no window flag can -/// ask for it; SDL sets it when the compositor gives this surface the keyboard. Read, never asked -/// for, and read by exactly one thing: `crate::textinput`, whose panel it silently gates. -pub(crate) const SDL_WINDOW_INPUT_FOCUS: u32 = 0x200; const GL_COLOR_BUFFER_BIT: c_uint = 0x0000_4000; const GL_RENDERER: c_uint = 0x1F01; const GL_VERSION: c_uint = 0x1F02; -// SDL_GLattr enum -const A_RED: c_int = 0; -const A_GREEN: c_int = 1; -const A_BLUE: c_int = 2; -const A_ALPHA: c_int = 3; -const A_BUFFER_SIZE: c_int = 4; -const A_DEPTH: c_int = 6; -const A_STENCIL: c_int = 7; -const A_CTX_MAJOR: c_int = 17; -const A_CTX_MINOR: c_int = 18; -const A_CTX_PROFILE_MASK: c_int = 21; -const CTX_PROFILE_ES: c_int = 0x0004; -/// `SDL_GL_CONTEXT_PROFILE_CORE` — the simulator's only option on macOS. See the context request. -const CTX_PROFILE_CORE: c_int = 0x0001; -// event types -const SDL_QUIT: u32 = 0x100; -const SDL_KEYDOWN: u32 = 0x300; -const SDL_KEYUP: u32 = 0x301; -const SDL_MOUSEMOTION: u32 = 0x400; -const SDL_MOUSEBUTTONDOWN: u32 = 0x401; -const SDL_MOUSEBUTTONUP: u32 = 0x402; -const SDL_MOUSEWHEEL: u32 = 0x403; -/// The IME's in-progress COMPOSITION. Not acted on — the search field shows what has been -/// committed, so a preedit would put characters on screen the query does not contain — but LOGGED, -/// because the panel's word prediction is a replace and this is where its delete half would arrive -/// if it arrives at all. See the `"edit"` arm in the event ladder. -const SDL_TEXTEDITING: u32 = 0x302; -/// Text COMMITTED by the system keyboard — `crate::textinput`. -pub(crate) const SDL_TEXTINPUT: u32 = 0x303; +// SDL's event-type codes the ladder and the loop tests read, and the one window flag `textinput` reads, +// are the stock-SDL shell's (`plx_shell_sdl`); they are re-exported here so every `use super::*` chain +// below keeps resolving them by the names it always has. +pub(crate) use plx_shell_sdl::event::{ + SDL_KEYDOWN, SDL_KEYUP, SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP, SDL_MOUSEMOTION, SDL_TEXTEDITING, SDL_TEXTINPUT, +}; +pub(crate) use plx_shell_sdl::window::SDL_WINDOW_INPUT_FOCUS; // keysyms, the OK/BACK predicates and `classify` — the key VOCABULARY the ladder below dispatches // on — live in ui::consts (the single keycode home) use plx_ui::consts::{ @@ -99,20 +53,6 @@ const SCR_W: c_int = plx_base::surface::LOGICAL_W as c_int; const SCR_H: c_int = plx_base::surface::LOGICAL_H as c_int; pub(crate) const COLS: c_int = 10; -// Desktop-only window management. Apart for the mirror-image reason: a television owns the whole -// panel and never asks how big a display is, so on that build these would be dead code — which -// `[workspace.lints.rust] warnings = "deny"` makes a build failure, not a warning. -#[cfg(feature = "hostsim")] -extern "C" { - /// `SDL_GetDisplayUsableBounds` — the display minus the menu bar and the Dock, which is what - /// a window may actually occupy. The out parameter is an `SDL_Rect`: exactly four `c_int`. - fn SDL_GetDisplayUsableBounds(display: c_int, rect: *mut c_int) -> c_int; - /// `SDL_SetWindowSize` / `SDL_SetWindowPosition` — `app::boot::fit_window_to_density` re-sizes - /// and re-centres the window once the display's pixel density has been measured from it. - fn SDL_SetWindowSize(win: *mut c_void, w: c_int, h: c_int); - fn SDL_SetWindowPosition(win: *mut c_void, x: c_int, y: c_int); -} - // Phase 1a of the UI restructure split this file: everything above `run_application` moved into // the submodules below as a PURE move (`pub(crate)` widening only), glob-imported here so the // loop body reads exactly as before. `run_application` itself is phase 1b. @@ -156,59 +96,6 @@ use self::input::*; use self::content::*; extern "C" { - fn SDL_SetMainReady(); - fn SDL_SetHint(name: *const c_char, value: *const c_char) -> c_int; - fn SDL_Init(flags: u32) -> c_int; - fn SDL_GetCurrentVideoDriver() -> *const c_char; - fn SDL_GL_SetAttribute(attr: c_int, value: c_int) -> c_int; - fn SDL_CreateWindow( - title: *const c_char, - x: c_int, - y: c_int, - w: c_int, - h: c_int, - flags: u32, - ) -> *mut c_void; - fn SDL_DestroyWindow(win: *mut c_void); - fn SDL_GL_CreateContext(win: *mut c_void) -> *mut c_void; - fn SDL_GL_SetSwapInterval(interval: c_int) -> c_int; - fn SDL_Delay(ms: u32); - fn SDL_PollEvent(event: *mut c_void) -> c_int; - fn SDL_PushEvent(event: *const c_void) -> c_int; - fn SDL_GL_SwapWindow(win: *mut c_void); - fn SDL_Quit(); - // The system on-screen keyboard. A PLAIN link, not `dynlib!`, and the rule in `dynlib.rs` is - // why: that module is for libraries whose SONAME moves, and this is stock public SDL2 API — - // `tools/fwcompat.py --lib libSDL2-2.0.so.0 --grep TextInput` finds the whole family exported - // by all 14 firmware inventories, so there is nothing here for a runtime bind to tolerate. - // - // `pub(crate)` on these five alone because `crate::textinput` owns this seam and is the only - // caller; the declarations stay here with the rest of SDL rather than being duplicated into a - // second `extern` block, where a signature could drift from this one unnoticed. - // - // The `allow(dead_code)` below is a consequence of that ownership: under `cfg(test)` the only - // caller swaps itself for `textinput::host_test_sdl`'s stubs, so these three lose their last - // use in the TEST build alone and warn there. The allow is narrower than it looks — a real - // orphan would be silent in every configuration, and these are live on device. - #[allow(dead_code)] - pub(crate) fn SDL_StartTextInput(); - #[allow(dead_code)] - pub(crate) fn SDL_StopTextInput(); - pub(crate) fn SDL_IsTextInputActive() -> c_int; - pub(crate) fn SDL_HasScreenKeyboardSupport() -> c_int; - /// LG's `WebOSIsScreenKeyboardShown`, the fourth of the four hooks its Wayland driver installs. - /// Exported by all 14 inventories, and **it does not answer the question its name asks** on this - /// firmware — `textinput`'s note has the measurement and what replaced it. Declared, unused, and - /// kept so the next person finds the finding before they find the symbol. - #[allow(dead_code)] - pub(crate) fn SDL_IsScreenKeyboardShown(w: *mut c_void) -> c_int; - pub(crate) fn SDL_GetWindowFlags(w: *mut c_void) -> u32; - /// Turn the DRIVER's own tracing on for one category. LG's `WebOSShowScreenKeyboard` / - /// `Hide` / `TextModelLeave` / `TextModelInputPanelState` all log through SDL at - /// `SDL_LOG_CATEGORY_INPUT`, which is silent at the default priority — so this is how the - /// keyboard's real lifecycle becomes readable without patching SDL. - #[allow(dead_code)] // test build only — see the note above `SDL_StartTextInput` - pub(crate) fn SDL_LogSetPriority(category: c_int, priority: c_int); fn glGetString(name: c_uint) -> *const c_char; fn glViewport(x: c_int, y: c_int, w: c_int, h: c_int); fn glClear(mask: c_uint); @@ -346,10 +233,12 @@ pub(crate) struct App { /// The re-read of covered pages and of the visible one on resume, stepped once per loop /// iteration beside the view-state pumps (`app/reread.rs`). pub(crate) reread: reread::Reread, + /// The buffer [`platform::Surface::poll`] fills, one event at a time. ev: [u8; 128], remote: Option, - /// The SDL window (`SDL_CreateWindow`), for the swap. - win: *mut c_void, + /// The window and its GL context (`Shell::open`): the swap, the event poll, the raw handle the + /// shell's per-window calls take, and the process's SDL quit. Thread-affine, like the loop. + surface: Box, /// WSLg accepts swap interval 1 on X11/GLX without pacing the compositor. This boot-scoped /// flag enables the host-only software frame budget while leaving native Linux and macOS on /// their driver swap behavior. @@ -588,7 +477,7 @@ unsafe fn run_and_shutdown(app: &mut App) -> Exit { let failed = finish_recording(&mut app.rec, bridge.landgate()) || bridge.controlled_failure().is_some(); app.glass.sources.borrow_mut().clear(); - let release = run::shutdown(&mut app.player.session, &mut app.adapters.player); + let release = run::shutdown(&mut app.player.session, &mut app.adapters.player, &*app.surface); // The crash-channel guard is the one `Drop` that persists something (it closes the capture // backend and removes its database), so it runs here explicitly: nothing drops the `App`. drop(app.telemetry_guard.take()); @@ -678,7 +567,8 @@ pub(crate) fn run_application(platform: &'static platform::Platform, pms_host: * // the origin an `EntryId` on the mounted player screen, so the same questions are asked of a // real container, beside `playback::enter_player`/`exit_player` — including two the description // could not reach: the spot the page comes back at, and an origin that is really gone. -// * `key_layout_tests` — beside `events::decode_key`/`encode_key`, whose byte offsets it pins. +// * `key_layout_tests` — beside `events`' `encode_key`, round-tripped through `plx_shell_sdl::event::decode_key`, +// whose byte offsets it pins. // * `route_tests` — split in two, each half beside its subject: the direct-screen server rule is // `boot::resolve_direct_server`'s, and the profile chip's alphabet is `ScreenArg::chrome`'s, in // `screens::registry`. diff --git a/rust-modules/src/app/platform.rs b/rust-modules/src/app/platform.rs index cb89b04963..7ff3228b10 100644 --- a/rust-modules/src/app/platform.rs +++ b/rust-modules/src/app/platform.rs @@ -7,10 +7,11 @@ //! accessors (identity, the secure store, Home and the toast, the legacy webOS media verbs). //! `run_application` installs it into `tv` once, and nothing else in the app reads it. //! - `shell`: the window, the bus and the pointer's visibility, [`Shell`]. Its consumers are boot -//! (`app::boot` brings the window up with the platform it was handed), the loop (`app::run` drives -//! it every frame, through `App::platform`) and the bridge, which holds the shell for the -//! dispatcher's two opaque-region hooks and lends it to the pointer's own callers (`input`, -//! `playback`), which hide and show the Magic Remote's pointer through it. +//! (`app::boot` brings the window up with the platform it was handed: `init`, then `open`, which +//! returns the [`Surface`] the `App` owns from then on), the loop (`app::run` drives it every +//! frame, through `App::platform`, and presents and polls through the surface) and the bridge, which +//! holds the shell for the dispatcher's two opaque-region hooks and lends it to the pointer's own +//! callers (`input`, `playback`), which hide and show the Magic Remote's pointer through it. //! - `diag`: the six frame probes, [`FrameProbe`], read by the loop. The renderer's clear hook takes //! plain functions, so the platform's entry installs it (`gfx::install_clear_probe`). //! - `media`: [`MediaBoot`], the platform's two boot-time playback steps. `early_init` runs once before @@ -19,10 +20,11 @@ //! platform composed through [`publish_composition`], the one function that does, so the set of //! installed drivers and the resolver the planner reads cannot disagree. //! -//! `Shell`, `FrameProbe` and `Platform` are app-private on purpose: no type a platform's shell has +//! `Shell`, `Surface`, `FrameProbe` and `Platform` are app-private on purpose: no type a platform's shell has //! to match leaves the application crate until the platform contract is settled. The webOS value is //! built by `port.rs`; `ci/check-deps.sh`'s `frame` gate pins the call text of the three //! privileged calls (`pump_bus`, `opaque_route`, `clear_opaque_region`) to `app/run.rs`. +use super::Exit; use plx_base::task::MainThread; use plx_media::player::adapter::PlayerAdapter; use plx_media::route::uri_preflight::ResolvePort; @@ -30,11 +32,30 @@ use plx_media::route::PlaybackSession; use plx_os::tv::Services; use std::os::raw::c_void; +/// What a platform's boot asks of SDL, as plain data: [`InitHooks`] (the two steps a platform runs +/// around `SDL_Init`), and [`OpenAsk`] with its [`Placement`] (the window's title, place and size). The +/// shell crate's own types, re-exported rather than copied: they hold no SDL type, and W7a, which +/// publishes `Shell` and `Surface`, is where a platform-neutral spelling of them is decided. +pub(crate) use plx_shell_sdl::{InitHooks, OpenAsk, Placement}; + /// The platform's window, bus and pointer, as the application drives them: the SDL window and its /// surface, the opaque-region hint, the platform bus pump, and the visibility of the Magic Remote's /// pointer. Every call runs on the loop thread, and every hook is required: a platform with nothing /// to do states a no-op, as the desktop and the test-only host platform do. +/// +/// `init` and `open` are the two steps that bring the surface up, and they are two because the +/// application reads the stored session between them (the window size is a setting): SDL and the GL +/// request first, the session read, then the window. That is the order boot has always had, and +/// `app::boot` pins it. A platform whose surface is not SDL's states its own pair; every SDL one is the +/// shell crate's (`plx_shell_sdl`), reached through [`sdl_init`] and [`sdl_open`]. pub(crate) trait Shell: Sync { + /// Bring the platform's windowing up and ask for the GL context, once, FIRST: before the stored + /// session is read and before [`open`](Shell::open). A refusal ends the boot with that `Exit`. + fn init(&self, mt: &MainThread) -> Result<(), Exit>; + /// Open the window and its GL context at `ask`, make the context current on this thread and + /// probe the drawable it gave. The [`Surface`] it returns is the application's for the rest of the + /// process. A refusal ends the boot with that `Exit`. + fn open(&self, mt: &MainThread, ask: &OpenAsk) -> Result, Exit>; /// Hand the platform the SDL window, once, at boot: the window is created deep inside boot and /// the platform needs it a long way from there (`textinput::bind`'s shape and its reason). fn bind_window(&self, win: *mut c_void); @@ -66,6 +87,82 @@ pub(crate) trait Shell: Sync { fn hide_is_cursor_swap(&self) -> bool; } +/// The window the application presents to and reads events from, owned by `App` for the rest of the +/// process. App-private and thread-affine (not `Sync`) like [`Shell`], and for the same reason: no +/// type a platform has to match leaves the application crate until the platform contract is settled +/// (`docs/platform-ports.md`, Target shapes 1 and 8, which W7a publishes as `host`). +/// +/// `window` is the raw handle the [`Shell`]'s per-window calls still take (`bind_window`, +/// `grab_surface`, and `textinput`'s focus read), so every call site the `frame` gate pins stays where +/// it is; W7a folds those into this trait. `poll` is SDL-shaped bytes until the platform's own event +/// sink replaces it. There is no destructor: the `App` is leaked at exit and a worker may still hold +/// the handle, so the end is the explicit, decided [`quit`](Surface::quit). +pub(crate) trait Surface { + /// The raw window handle, null for a surface that has none (the rig's). + fn window(&self) -> *mut c_void; + /// Present the frame. The compositor commit of the opaque-region request just made is this call's. + fn swap(&self); + /// 1 locks the frame rate to the panel's refresh, 0 uncaps it; the application computes which. + fn set_swap_interval(&self, interval: i32); + /// Take the next event off the platform's queue into `ev`; `false` when there is none. + fn poll(&self, ev: &mut [u8; 128]) -> bool; + /// End the platform's windowing for the process. + /// + /// # Safety + /// After the loop's last use of it, on the loop thread; nothing may touch the platform's + /// windowing afterwards. The caller decides WHEN (`run::quits_sdl`): a worker still inside + /// firmware means the display must not be torn down under it. + unsafe fn quit(&self); +} + +/// SDL's window is a [`Surface`] by delegation: the one SDL implementation, for the television and a +/// desktop alike. The trait is local, so the orphan rule has nothing to say. +impl Surface for plx_shell_sdl::Window { + fn window(&self) -> *mut c_void { + self.raw() + } + fn swap(&self) { + plx_shell_sdl::Window::swap(self) + } + fn set_swap_interval(&self, interval: i32) { + plx_shell_sdl::Window::set_swap_interval(self, interval) + } + fn poll(&self, ev: &mut [u8; 128]) -> bool { + plx_shell_sdl::event::poll(ev) + } + unsafe fn quit(&self) { + plx_shell_sdl::init::quit() + } +} + +/// [`Shell::init`] for an SDL platform: SDL up with the platform's two steps around `SDL_Init`, then the +/// GL context request. `SDL_Init` refused ends the boot (`Exit::refused(1)`, the status it always had). +/// +/// # Safety +/// `hooks` must be sound to call on the SDL main thread (`mt` is the proof of the thread) at the two +/// points `plx_shell_sdl::init::init` calls them. +pub(crate) unsafe fn sdl_init(mt: &MainThread, hooks: InitHooks) -> Result<(), Exit> { + plx_shell_sdl::init::init(mt, hooks).map_err(|_| Exit::refused(1))?; + plx_shell_sdl::init::request_gl(mt); + Ok(()) +} + +/// [`Shell::open`] for an SDL platform: the window and its GL context. Refused at the native size, the +/// boot ends with `Exit::refused(1)`, the status it always had. +pub(crate) fn sdl_open(mt: &MainThread, ask: &OpenAsk) -> Result, Exit> { + plx_shell_sdl::Window::open(mt, ask) + .map(|window| Box::new(window) as Box) + .map_err(|_| Exit::refused(1)) +} + +/// A surface with no window, for the shells of a process that owns none: a host test, and the loop's +/// rig. Its swap is `SDL_GL_SwapWindow(NULL)` and its poll is SDL's real process-global queue, which is +/// what the rig's null handle and the tests that push events have always had. Test builds only. +#[cfg(test)] +pub(crate) fn detached_surface() -> Box { + Box::new(plx_shell_sdl::Window::DETACHED) +} + /// The dev frame probe (`/tmp/plxnative-framecb`): the platform's presentation-callback clock, read /// by the loop and by the renderer's clear hook. Unarmed, every call is a latched flag read. pub(crate) trait FrameProbe: Sync { @@ -169,6 +266,12 @@ struct HostShell; #[cfg(test)] impl Shell for HostShell { + fn init(&self, _mt: &MainThread) -> Result<(), Exit> { + Ok(()) + } + fn open(&self, _mt: &MainThread, _ask: &OpenAsk) -> Result, Exit> { + Ok(detached_surface()) + } fn bind_window(&self, _win: *mut c_void) {} fn grab_surface(&self, _win: *mut c_void) {} fn release_surface(&self) -> bool { @@ -212,6 +315,12 @@ pub(crate) struct SwapShell { #[cfg(test)] impl Shell for SwapShell { + fn init(&self, _mt: &MainThread) -> Result<(), Exit> { + Ok(()) + } + fn open(&self, _mt: &MainThread, _ask: &OpenAsk) -> Result, Exit> { + Ok(detached_surface()) + } fn bind_window(&self, _win: *mut c_void) {} fn grab_surface(&self, _win: *mut c_void) {} fn release_surface(&self) -> bool { @@ -287,6 +396,17 @@ mod tests { "the services are the host-test services (`tv`'s own tests pin each answer)" ); + // SAFETY: a host test owns the one thread it runs the shell's bring-up on. + let mt = unsafe { MainThread::assume() }; + assert_eq!(s.init(&mt), Ok(()), "there is no windowing to bring up"); + let ask = OpenAsk { + title: c"PlxNative", + placement: Placement::Panel { size: (1920, 1080), fallback: None }, + high_dpi: false, + }; + let surface = s.open(&mt, &ask).expect("a process with no platform opens a windowless surface"); + assert!(surface.window().is_null(), "and the surface it hands back has no window"); + let window = std::ptr::null_mut(); s.bind_window(window); s.grab_surface(window); @@ -307,8 +427,7 @@ mod tests { p.acquired(); assert_eq!(p.fields(), "", "an unarmed probe has nothing to log"); - // SAFETY: a host test owns the one thread it runs the media boot on. - let mt = unsafe { MainThread::assume() }; + // The same thread, the same proof: the media boot runs on it too. (media.early_init)(&mt); let mut adapter = PlayerAdapter::new(mt); let composed = (media.compose)(&mut adapter, false); @@ -349,4 +468,37 @@ mod tests { "another platform's counts are its own"); assert!(!other.shell.release_surface(), "the rest of the shell answers as the host-test one does"); } + + /// **The SDL calls the application still declares are the two that stay.** Everything SDL-shaped + /// that is the stock shell's (the window, the GL context, the queue, the text-input panel) is + /// `plx_shell_sdl`'s; what remains is `system.rs`'s `SDL_GetWindowWMInfo` handshake (the television's + /// SDL writes a larger `SDL_SysWMinfo` than the headers declare, so the buffer and the version query + /// are LG's and stay verbatim) and `clock.rs`'s `SDL_GetTicks`, the `ticks` gate's one door. A third + /// declaration here is a second SDL seam beside the shell crate's. Reads the sources, like + /// `port.rs`'s tests, because no host test can see a declaration. + #[test] + fn the_application_declares_no_sdl_function_but_the_two_that_stay() { + fn walk(dir: &std::path::Path, src: &std::path::Path, hits: &mut Vec) { + for entry in std::fs::read_dir(dir).expect("read a source directory") { + let path = entry.expect("a directory entry").path(); + if path.is_dir() { + walk(&path, src, hits); + } else if path.extension().is_some_and(|ext| ext == "rs") { + let rel = path.strip_prefix(src).expect("under src").to_string_lossy().replace('\\', "/"); + if rel == "system.rs" || rel == "app/clock.rs" { + continue; + } + let text = std::fs::read_to_string(&path).expect("read a source file"); + // Split with `concat!`, so this file's own text is never what it matches. + if text.contains(concat!("fn ", "SDL_")) { + hits.push(rel); + } + } + } + } + let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut hits = Vec::new(); + walk(&src, &src, &mut hits); + assert!(hits.is_empty(), "an SDL function is declared outside `system.rs` and `app/clock.rs`: {hits:?}"); + } } diff --git a/rust-modules/src/app/run.rs b/rust-modules/src/app/run.rs index dbd88d74d4..a7a2b17b91 100644 --- a/rust-modules/src/app/run.rs +++ b/rust-modules/src/app/run.rs @@ -975,7 +975,7 @@ unsafe fn present_and_swap( // dev (`/tmp/plxnative-framecb`): this frame's compositor callback, requested before // the swap that commits it. One latched bool unarmed. app.platform.diag.request(); - SDL_GL_SwapWindow(app.win); + app.surface.swap(); } app.window_activity.presented(fr.player); // dev diagnostic, OFF unless `/tmp/plxnative-eglage` was present at boot: re-ask EGL for @@ -1036,7 +1036,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::motion::report::IDLE_POLL_MS); + plx_shell_sdl::init::delay_ms(plx_machine::motion::report::IDLE_POLL_MS); } } @@ -1068,7 +1068,7 @@ pub(crate) unsafe fn ingest(app: &mut App, fr: &mut Frame) { } unsafe fn drain_sdl(app: &mut App, fr: &mut Frame) { - while SDL_PollEvent(app.ev.as_mut_ptr() as *mut c_void) != 0 { + while app.surface.poll(&mut app.ev) { ingest_sdl_event(app, fr); } } @@ -1207,7 +1207,7 @@ unsafe fn ingest_host_event(app: &mut App, fr: &mut Frame, event: HostEvent, // Only its DID foreground reacquires native handles. Recorded notifications // below never reacquire them, revoke grants or resume a native player. match event { - HostEvent::Lifecycle(Lifecycle::DidForeground) => restore_window(app.win), + HostEvent::Lifecycle(Lifecycle::DidForeground) => restore_window(app.surface.window()), HostEvent::Quit | HostEvent::Lifecycle(Lifecycle::WillBackground | Lifecycle::DidBackground) => { app.rec.refuse("live window exit interrupted controlled replay"); @@ -1378,7 +1378,7 @@ unsafe fn host_foreground(app: &mut App, edge: Lifecycle, playing: bool, // The television may have been away long enough for every page to be stale. app.reread.resume(); // Reacquire only on DID foreground, before playback restoration and rendering. - restore_window(app.win); + restore_window(app.surface.window()); 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; @@ -3810,11 +3810,13 @@ pub(crate) fn quits_sdl(native_exit: plx_media::player::NativeExit) -> bool { /// Teardown after the loop: abandon the pending report, stop the active backend, wait for the stop /// scrobble, close the capture stream and the poster workers, quit SDL (unless a worker is still -/// in firmware). Answers what it released: the caller (`app::run_and_shutdown`) returns it in the -/// `Exit`, and the executable entry then ends the process with `_exit`. +/// in firmware: `surface.quit()` is the platform's, and WHETHER it runs is this function's). Answers +/// what it released: the caller (`app::run_and_shutdown`) returns it in the `Exit`, and the executable +/// entry then ends the process with `_exit`. pub(crate) unsafe fn shutdown( ps: &mut plx_media::route::PlaybackSession, pa: &mut plx_media::player::adapter::PlayerAdapter, + surface: &dyn super::platform::Surface, ) -> Release { ps.finish_metric_request(plx_media::player::attempt_metrics::RequestOutcome::Cancelled); pa.sync_request_metrics(ps); @@ -3839,7 +3841,7 @@ pub(crate) unsafe fn shutdown( // anywhere above leaves its state for the next boot to classify as crashed or abnormal. plx_telemetry::telemetry::session::shutdown(); if quits_sdl(native_exit) { - SDL_Quit(); + surface.quit(); } else { log("shutdown: a native worker is still inside firmware; SDL_Quit skipped, exiting without unwinding"); } @@ -4115,7 +4117,7 @@ pub(in crate::app) mod lifecycle_regression_tests { reread: Default::default(), ev: [0; 128], remote: Default::default(), - win: Default::default(), + surface: crate::app::platform::detached_surface(), #[cfg(target_os = "linux")] wslg_frame_pacing: false, t0: Default::default(), @@ -5293,6 +5295,96 @@ pub(in crate::app) mod lifecycle_regression_tests { } } + // ---- W6: the loop's other calls on the platform's shell ------------------------------------- + // + // Three call sites reach `Shell` from the loop outside the key and pointer arms the tests above + // count, and none of them had a test that would notice the call going missing: the idle pointer + // over the video (`playback_tick`), the hand-back of Back's hidden pointer on backgrounding + // (`host_background`), and a controlled pointer input's wake (`controlled_key_input`). Each is + // counted on a `SwapShell`, the platform's shell as the loop holds it. + + /// **An idle pointer over the video is hidden through the platform's shell**, once, after more + /// than three seconds without motion on a mounted player: not at three seconds, not again on the + /// next frame, and not while a button is held. + #[test] + fn an_idle_pointer_over_the_video_is_hidden_through_the_platforms_shell_after_three_seconds() { + use std::sync::atomic::Ordering::Relaxed; + fn tick(app: &mut App, now: u32) { + let mut fr = Frame::begin(&app.player.session, app.runtime.metadata_view()); + fr.now = now; + unsafe { playback_tick(app, &mut fr) }; + } + let _serial = plx_base::testlock::serial(); + let (platform, shell) = crate::app::platform::SwapShell::platform(); + clock::set_replay(100); + let mut app = app_on(platform); + super::super::bridge::show_page(&mut app.pages, AppArg::Player); + frame(&mut app, 0); + assert!(matches!(app.route(), AppArg::Player), "premise: the player is mounted"); + app.ptr.last_motion = 1_000; + tick(&mut app, 4_000); + assert_eq!((shell.hides.load(Relaxed), app.ptr.cur_hidden), (0, false), "three seconds is not more than three seconds"); + app.ptr.button_down = true; + tick(&mut app, 4_001); + assert_eq!((shell.hides.load(Relaxed), app.ptr.cur_hidden), (0, false), "a held button keeps the pointer"); + app.ptr.button_down = false; + tick(&mut app, 4_001); + assert_eq!((shell.hides.load(Relaxed), app.ptr.cur_hidden), (1, true), "more than three seconds idle hides it, through the shell"); + tick(&mut app, 9_000); + assert_eq!(shell.hides.load(Relaxed), 1, "...once"); + } + + /// **Backgrounding hands back the pointer Back hid, through the platform's shell**: the OS took + /// the screen, so the cursor Back's hold made transparent is shown again (nothing else would + /// until a motion), whether the edge arrives as SDL's bytes or as the host's `Lifecycle`. + #[test] + fn backgrounding_hands_back_the_pointer_back_hid_through_the_platforms_shell() { + use plx_machine::machine::{InstanceId, MachineId}; + use plx_screens::registry::BackCursorChange; + use std::sync::atomic::Ordering::Relaxed; + let _serial = plx_base::testlock::serial(); + for hosted in [false, true] { + let (platform, shell) = crate::app::platform::SwapShell::platform(); + let mut app = app_on(platform); + let mut fr = Frame::begin(&app.player.session, app.runtime.metadata_view()); + let target = (MachineId::Instance(InstanceId(1)), 7); + app.ptr.sync_back_cursor(app.platform.shell, Some(target), Some((target, BackCursorChange::Hide))); + assert!(app.ptr.back_cursor_active() && app.ptr.cur_hidden, "premise: Back holds a hidden pointer"); + assert_eq!((shell.hides.load(Relaxed), shell.shows.load(Relaxed)), (1, 0), "premise: it hid it through the shell"); + deliver(&mut app, &mut fr, hosted, HostEvent::Lifecycle(Lifecycle::WillBackground)); + assert!(!app.ptr.back_cursor_active() && !app.ptr.cur_hidden, "backgrounding ends Back's hold (hosted {hosted})"); + assert_eq!(shell.shows.load(Relaxed), 1, "...and shows the pointer again, through the shell (hosted {hosted})"); + } + } + + /// **A controlled pointer input wakes a hidden pointer through the platform's shell**, as the + /// SDL pointer path does: a recorded or scripted pointer, click or drag is the viewer moving the + /// pointer, so the pointer the D-pad hid comes back, once (`controlled_key_input`). + #[test] + fn a_controlled_pointer_input_shows_a_hidden_pointer_through_the_platforms_shell() { + use plx_machine::machine::{InputEvent, InputKind, Source, Tick}; + use std::sync::atomic::Ordering::Relaxed; + let _serial = plx_base::testlock::serial(); + let kinds = [ + InputKind::::Pointer { x: 400.0, y: 300.0, hit: None }, + InputKind::Click { x: 400.0, y: 300.0, hit: None }, + InputKind::Drag { x: 400.0, y: 300.0, hit: None }, + ]; + for kind in kinds { + let (platform, shell) = crate::app::platform::SwapShell::platform(); + let mut app = app_on(platform); + app.ptr.cur_hidden = true; + let event = InputEvent { at: Tick { ms: 500, dt_us: 0 }, source: Source::Sdl, kind }; + unsafe { controlled_key_input(&mut app, event) }; + assert_eq!(shell.shows.load(Relaxed), 1, "the controlled pointer input shows the hidden pointer, through the shell"); + assert!(!app.ptr.cur_hidden && app.ptr.last_motion == 500); + let again = InputEvent { at: Tick { ms: 516, dt_us: 0 }, source: Source::Sdl, + kind: InputKind::Pointer { x: 410.0, y: 300.0, hit: None } }; + unsafe { controlled_key_input(&mut app, again) }; + assert_eq!(shell.shows.load(Relaxed), 1, "...once"); + } + } + /// **The tape is the same whichever way a pointer event or a wheel tick arrives**, and it is /// today's: one `pointer`, `click` or `release` row per event at its authored position, and the /// wheel's `wheel` row (its count in `y`) at the debounce's pace, before the zero-tick return. @@ -5383,8 +5475,8 @@ pub(in crate::app) mod lifecycle_regression_tests { let (mut app, mut fr) = settings_app(); clock::set_replay(1_000); remote_synth_wheel(-2); - let polled = unsafe { SDL_PollEvent(app.ev.as_mut_ptr() as *mut c_void) }; - assert_eq!(polled, 1, "SDL handed the pushed wheel event back"); + let polled = plx_shell_sdl::event::poll(&mut app.ev); + assert!(polled, "SDL handed the pushed wheel event back"); let precise = rd_f32(&app.ev, 32); assert!(rd_i32(&app.ev, 20) == -2 || precise == -2.0, "premise: the tick survived SDL's round trip in one field"); unsafe { ingest_sdl_event(&mut app, &mut fr) }; @@ -5836,18 +5928,9 @@ pub(in crate::app) mod lifecycle_regression_tests { assert!(recording.frames.iter().all(|frame| frame.inputs.is_empty()), "a read-back is not recorded"); } - /// Only SDL's event subsystem, for the tests that poll SDL (a by-id token drains it first): no - /// window, renderer, boot or device. Quits when dropped. - struct SdlEvents; - impl SdlEvents { - fn init() -> Self { - assert_eq!(unsafe { SDL_Init(0x4000) }, 0); - Self - } - } - impl Drop for SdlEvents { - fn drop(&mut self) { unsafe { SDL_Quit(); } } - } + // Only SDL's event subsystem, for the tests that poll SDL (a by-id token drains it first): no + // window, renderer, boot or device. Quits when dropped (`plx_shell_sdl::testing`). + use plx_shell_sdl::testing::EventsOnly as SdlEvents; fn by_id_tags(inputs: &[plx_machine::machine::InputEvent]) -> Vec { use plx_machine::machine::InputKind; @@ -6086,12 +6169,7 @@ pub(in crate::app) mod lifecycle_regression_tests { fn hang_probe_dispatch_preserves_key_order() { let _serial = plx_base::testlock::serial(); // Only SDL's event subsystem: no window, renderer, boot or device. - assert_eq!(unsafe { SDL_Init(0x4000) }, 0); - struct Events; - impl Drop for Events { - fn drop(&mut self) { unsafe { SDL_Quit(); } } - } - let _events = Events; + let _events = plx_shell_sdl::testing::EventsOnly::init(); for fifo in [true, false] { let mut app = app(); super::super::bridge::show_page(&mut app.pages, @@ -6208,12 +6286,7 @@ pub(in crate::app) mod lifecycle_regression_tests { const ADDRESS: &str = "https://example.com/hud.plxhud"; let _serial = plx_base::testlock::serial(); // SDL's event subsystem only: no window, renderer, native playback or device. - assert_eq!(unsafe { SDL_Init(0x4000) }, 0); - struct Events; - impl Drop for Events { - fn drop(&mut self) { unsafe { SDL_Quit(); } } - } - let _events = Events; + let _events = plx_shell_sdl::testing::EventsOnly::init(); // Three doors: the FIFO's token, the television's keyboard as the SDL bytes the drain decodes, // and the same commit as the `HostEvent::Text` a platform with no SDL hands the loop (W5b). for (fifo, hosted) in [(true, false), (false, false), (false, true)] { @@ -6266,12 +6339,7 @@ pub(in crate::app) mod lifecycle_regression_tests { } let _serial = plx_base::testlock::serial(); // SDL's event subsystem only: no window, renderer, native playback or device. - assert_eq!(unsafe { SDL_Init(0x4000) }, 0); - struct Events; - impl Drop for Events { - fn drop(&mut self) { unsafe { SDL_Quit(); } } - } - let _events = Events; + let _events = plx_shell_sdl::testing::EventsOnly::init(); let dir = HudDir::new("close-then-text"); let (mut app, mut fr, mut now) = hud_address_field_up(&dir.0, dial); @@ -6300,12 +6368,7 @@ pub(in crate::app) mod lifecycle_regression_tests { use plx_machine::machine::{Edge, InputKind, Key}; let _serial = plx_base::testlock::serial(); // SDL's event subsystem only: no window, renderer, native playback or device. - assert_eq!(unsafe { SDL_Init(0x4000) }, 0); - struct Events; - impl Drop for Events { - fn drop(&mut self) { unsafe { SDL_Quit(); } } - } - let _events = Events; + let _events = plx_shell_sdl::testing::EventsOnly::init(); let mut app = app(); super::super::bridge::show_page(&mut app.pages, AppArg::Player); frame(&mut app, 0); @@ -12762,7 +12825,8 @@ mod straighten_wiring_tests { let compositor = at("composite_plane_under();\n }"); let dump = at("crate::dev::framedump::after_draw("); let shot = at("crate::shot::maybe_capture("); - let swap = at("SDL_GL_SwapWindow(app.win);"); + let swap = at("app.surface.swap();"); + assert_eq!(src.matches("app.surface.swap();").count(), 1, "one swap closes the frame"); assert!(begin < draw, "the ledger opens before the frame draws"); assert!(draw < capture && capture < pass, "the capture stream reads before the pass"); assert!(pass < compositor, "the simulator's compositor runs after the pass it models"); diff --git a/rust-modules/src/platform_desktop.rs b/rust-modules/src/platform_desktop.rs index 33d7aaa591..10e0e16d56 100644 --- a/rust-modules/src/platform_desktop.rs +++ b/rust-modules/src/platform_desktop.rs @@ -14,8 +14,10 @@ //! - the video sink is the Feed backend's host sink (`HOST_SINK`) when the build has one, else the //! refusing `NoSink`. //! -//! The shell and the frame probe are plain no-ops: SDL owns the window and its event loop, there is -//! no compositor to hint, no bus to pump and no remote pointer to hide. The secure store is +//! The shell's hooks and the frame probe are plain no-ops, bar the two that bring SDL up and open its +//! window (`init` and `open`, the shell crate's, with nothing around `SDL_Init`): SDL owns the window +//! and its event loop, there is no compositor to hint, no bus to pump and no remote pointer to hide. +//! The secure store is //! `SecureHooks::NONE`: nothing seals, so a session is the 0600 plaintext file the session layer //! writes itself, which the simulator's harnesses plant and read. //! The storage group is `StorageHooks::NONE`: there is no storage helper, so the account's records @@ -27,7 +29,8 @@ //! made one of them reachable would fail to link for want of libwayland, glib or luna-service2, on //! a Mac and on Linux alike. `simulators.yml` links the shapes the simulator ships in to guard that //! until the platform crates split (`docs/platform-ports.md`, W7). -use crate::app::platform::{Composition, FrameProbe, MediaBoot, Platform, Shell}; +use crate::app::platform::{sdl_init, sdl_open, Composition, FrameProbe, InitHooks, MediaBoot, OpenAsk, Platform, Shell, Surface}; +use crate::app::Exit; use plx_os::devcaps::dv::{self, DvCapability, DvProbe, ProbeSource}; use plx_os::tv::toast::{Identity, Outcome, Sent}; use plx_os::tv::{IdentityHooks, LegacyWebosMedia, SecureHooks, Services, StorageHooks, SystemHooks}; @@ -98,12 +101,20 @@ fn deliver_toast(_message: &str, identity: Identity) -> Sent { Sent { reply: None, outcome: Outcome::NoBus } } -/// The desktop shell: SDL owns the window and its event loop, so nothing is bound, grabbed, hinted -/// or pumped, and no surface is ever held. The pointer is a mouse the application does not hide, so -/// hiding and showing it do nothing, and a click is always a real one (the hide is not a cursor swap). +/// The desktop shell: SDL owns the window and its event loop (`init` and `open` are the shell crate's, +/// with no hook around `SDL_Init`), so nothing is bound, grabbed, hinted or pumped, and no surface is +/// ever held. The pointer is a mouse the application does not hide, so hiding and showing it do +/// nothing, and a click is always a real one (the hide is not a cursor swap). struct DesktopShell; impl Shell for DesktopShell { + fn init(&self, mt: &plx_base::task::MainThread) -> Result<(), Exit> { + // SAFETY: `InitHooks::NONE` calls nothing. + unsafe { sdl_init(mt, InitHooks::NONE) } + } + fn open(&self, mt: &plx_base::task::MainThread, ask: &OpenAsk) -> Result, Exit> { + sdl_open(mt, ask) + } fn bind_window(&self, _win: *mut c_void) {} fn grab_surface(&self, _win: *mut c_void) {} fn release_surface(&self) -> bool { diff --git a/rust-modules/src/port.rs b/rust-modules/src/port.rs index 8ce5310957..bef2c7fbe7 100644 --- a/rust-modules/src/port.rs +++ b/rust-modules/src/port.rs @@ -7,7 +7,9 @@ //! platform (`platform_desktop`), which never names this module, so a desktop build compiles the //! television's code and the linker drops it. use crate::app::adapters::backends; -use crate::app::platform::{FrameProbe, MediaBoot, Platform, Shell}; +use crate::app::platform::{sdl_init, sdl_open, FrameProbe, InitHooks, MediaBoot, OpenAsk, Platform, Shell, Surface}; +use crate::app::Exit; +use plx_base::task::MainThread; use std::os::raw::{c_char, c_int, c_void}; #[cfg(all(not(test), feature = "play-feed"))] @@ -53,10 +55,28 @@ static SERVICES: plx_os::tv::Services = plx_os::tv::Services { /// The webOS shell: the SDL window's Wayland surface, the opaque-region hint, the LS2 bus pump and the /// Magic Remote's pointer. The bodies stay in `crate::system` (and `webos::bind_window`); this is the -/// table over them. +/// table over them. SDL itself, and the window it opens, are the shell crate's (`plx_shell_sdl`), which +/// this platform brings up with LG's two boot hooks around `SDL_Init`. struct WebosShell; impl Shell for WebosShell { + fn init(&self, mt: &MainThread) -> Result<(), Exit> { + // SAFETY: both hooks are LG's SDL boot steps (`crate::system`), run on the SDL main thread `mt` + // proves, at the two points `plx_shell_sdl::init::init` calls them: the cursor hint before + // `SDL_Init`, which reads it, and the relaunch tap after, once LG's SDL has filled its slot. + unsafe { + sdl_init( + mt, + InitHooks { + before: crate::system::webos3_cursor_sleep_hint, + after: crate::system::tap_relaunch_payloads, + }, + ) + } + } + fn open(&self, mt: &MainThread, ask: &OpenAsk) -> Result, Exit> { + sdl_open(mt, ask) + } fn bind_window(&self, win: *mut c_void) { plx_os::webos::bind_window(win); } @@ -183,6 +203,41 @@ mod tests { assert_eq!(SERVICES.secure.mode, plx_os::tv::secure::StoreMode::Durable); } + /// **The two LG hooks are the webOS shell's `init`, handed in the order SDL needs.** The shell crate + /// pins the order inside `plx_shell_sdl::init::init` (`before`, then `SDL_Init`, then `after`) and + /// cannot name the hooks; this pins that the webOS shell hands exactly them, the cursor hint as the + /// step BEFORE (SDL reads it in `SDL_Init`, so a hint set after does nothing) and the relaunch tap as + /// the step AFTER (LG's SDL fills the slot it wraps inside `SDL_Init`), once each, and that nothing + /// else in this file names them. Reads the source, like the tests below, because no host test can + /// run LG's SDL. + #[test] + fn the_webos_shell_binds_the_cursor_hint_before_and_the_relaunch_tap_after_sdl_init() { + // The needles are split with `concat!` so this test's own text, which `include_str!` reads too, + // can never be what they match. + let source = include_str!("port.rs"); + let init = source + .split_once(concat!("impl Shell for ", "WebosShell {")) + .expect("the webOS shell") + .1 + .split_once(" fn init(") + .expect("its init") + .1 + .split_once("\n }\n") + .expect("the end of its init") + .0; + let before = concat!("before: crate::system::", "webos3_cursor_sleep_hint,"); + let after = concat!("after: crate::system::", "tap_relaunch_payloads,"); + assert_eq!(init.matches(before).count(), 1, "the cursor hint is `init`'s `before`"); + assert_eq!(init.matches(after).count(), 1, "the relaunch tap is `init`'s `after`"); + assert!(init.find(before) < init.find(after), "`before` is stated first, as it runs first"); + for hook in [ + concat!("crate::system::", "webos3_cursor_sleep_hint"), + concat!("crate::system::", "tap_relaunch_payloads"), + ] { + assert_eq!(source.matches(hook).count(), 1, "{hook} is named by `WebosShell::init` and nowhere else"); + } + } + /// Every `.rs` file under the application crate's `src`, as text. fn crate_sources() -> Vec { fn walk(dir: &std::path::Path, out: &mut Vec) { diff --git a/rust-modules/src/system.rs b/rust-modules/src/system.rs index 48854b2031..b4d6ea14b0 100644 --- a/rust-modules/src/system.rs +++ b/rust-modules/src/system.rs @@ -918,6 +918,154 @@ fn cursor_door() -> CursorDoor { }) } +// ---- The LG SDL's boot hooks (moved from `app::boot`, W6) ------------------------------------------- +// +// The two steps a webOS platform runs around `SDL_Init`, which the shell crate (`plx_shell_sdl::init`) +// calls in the order it pins: [`webos3_cursor_sleep_hint`] before it and [`tap_relaunch_payloads`] after +// it. They name LG's SDL fork (its `SDL_webOSCursorVisibility`, its `HELPER_HLunaServiceMessage` slot), +// so they are the webOS platform's and not the stock-SDL shell's; `WebosShell::init` (`port.rs`) is the +// only caller. They compile in every build, a desktop one included, where nothing calls them and the +// linker drops them, like the rest of this file. + +/// **webOS 3.x: shorten LG's own idle hide from about five minutes to five seconds.** Without +/// LG's extension, LG's SDL hides its pointer by itself after `SDL_WEBOS_CURSOR_SLEEP_TIME` of +/// stillness, and its default is about five minutes (timed on a 3.9.3 set, issue #642), where +/// every other app on that television hides it within seconds. Measured on the same set: the value +/// is milliseconds, `5000` hides a still pointer after about five seconds, and a deliberate +/// movement brings it back. Set only where `SDL_webOSCursorVisibility` is absent, so webOS 4+ +/// keeps its SDL's own behaviour. Must run before `SDL_Init`, which reads the hint. +pub(crate) unsafe fn webos3_cursor_sleep_hint() { + if let Some(ms) = cursor_sleep_hint(self_sym("SDL_webOSCursorVisibility").is_some()) { + plx_shell_sdl::set_hint(c"SDL_WEBOS_CURSOR_SLEEP_TIME", ms); + log("cursor: SDL_WEBOS_CURSOR_SLEEP_TIME=5000 (no SDL_webOS* in this SDL)"); + } +} + +/// The idle-hide time to ask SDL for, in milliseconds as a string; `None` where LG's extension is +/// present and its SDL keeps its own behaviour. +fn cursor_sleep_hint(has_lg_extension: bool) -> Option<&'static std::ffi::CStr> { + (!has_lg_extension).then_some(c"5000") +} + +/// **A warm launch's parameters, read where LG's SDL reads its `registerApp` replies.** SAM sends a +/// relaunch's parameters only to the `registerApp` subscriber, which is LG's SDL; its handler +/// (`callback_RegistNativeApp`) raises the window and never reads `parameters`. It fetches every +/// reply's payload through `HELPER_HLunaServiceMessage`, an exported pointer slot that +/// `LoadWEBOSBASELibrary` fills from `libhelpers.so.2` inside `SDL_Init` and that the handler +/// reloads on every call. Wrapping that slot hands a relaunch payload to `tv::launch` and returns +/// it unchanged, so SDL still raises the window. No new Luna registration: SAM refuses the app's +/// own (`tv::launch`). The firmware inventories have the slot from webOS 7.4 on; where it is missing +/// or empty (webOS 4.x to 6.x), nothing changes and callers keep closing the app first. +/// The tap installs only when the slot holds the address `libhelpers.so.2` (already mapped, +/// `RTLD_NOLOAD`) exports as `HLunaServiceMessage` ([`slot_holds`]); any other value is left alone. +pub(crate) unsafe fn tap_relaunch_payloads() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let Some(slot) = self_sym("HELPER_HLunaServiceMessage") else { + log("relaunch tap: no HELPER_HLunaServiceMessage in this SDL"); + return; + }; + // An atomic reference to a misaligned address is undefined behaviour: refuse a symbol that is + // not a word-aligned slot before forming it. + if !slot_aligned(slot as usize) { + log("relaunch tap: slot misaligned \u{2014} not installed"); + return; + } + // SDL's Luna thread may read the slot while it is replaced: store it atomically, after the + // function it forwards to is published. + let slot = &*(slot as *const AtomicUsize); + let wrapped = wrapped_message as *const () as usize; + let current = slot.load(Ordering::Acquire); + if current == 0 || current == wrapped { + log(if current == 0 { "relaunch tap: HELPER_HLunaServiceMessage is empty" } + else { "relaunch tap: already installed" }); + return; + } + // The slot is only ours to wrap while it holds libhelpers' own `HLunaServiceMessage`: another + // value (a different SDL build, a slot of some other type) would be called as a function + // pointer it is not. + let expected = plx_base::dynlib::Handle::open_loaded(&["libhelpers.so.2"]) + .and_then(|(h, _)| h.sym("HLunaServiceMessage")) + .filter(|p| !p.is_null()) + .map(|p| p as usize); + if !slot_holds(current, expected) { + log("relaunch tap: slot does not hold libhelpers' HLunaServiceMessage \u{2014} not installed"); + return; + } + REAL_MESSAGE.store(current, Ordering::Release); + MAIN_THREAD.store(libc::pthread_self() as usize, Ordering::Relaxed); + slot.store(wrapped, Ordering::Release); + log("relaunch tap: installed"); +} + +/// Does the SDL slot hold exactly the function `libhelpers.so.2` exports as `HLunaServiceMessage`? +/// The Thumb bit is compared as `dlsym` and the slot both carry it. `expected` is `None` when +/// libhelpers is not mapped or lacks the symbol, and then nothing holds. +fn slot_holds(current: usize, expected: Option) -> bool { + expected == Some(current) +} + +/// Is `addr` aligned for the `AtomicUsize` the slot is read and written as? +fn slot_aligned(addr: usize) -> bool { + addr % core::mem::align_of::() == 0 +} + +type LunaMessageFn = unsafe extern "C" fn(*mut std::ffi::c_void) -> *const std::ffi::c_char; +static REAL_MESSAGE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static MAIN_THREAD: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// SDL's payload read, passed through. Every Luna reply SDL subscribed to comes through here, so +/// anything that is not a relaunch costs one substring scan and nothing else. +unsafe extern "C" fn wrapped_message(msg: *mut std::ffi::c_void) -> *const std::ffi::c_char { + let real = REAL_MESSAGE.load(std::sync::atomic::Ordering::Acquire); + if real == 0 { + return std::ptr::null(); + } + let real: LunaMessageFn = std::mem::transmute(real); + let p = real(msg); + if !p.is_null() { + let payload = std::ffi::CStr::from_ptr(p).to_string_lossy(); + if payload.contains("\"relaunch\"") { + let main = libc::pthread_self() as usize == MAIN_THREAD.load(std::sync::atomic::Ordering::Relaxed); + log(&format!("relaunch tap: {} bytes on the {} thread, parameters={}", + payload.len(), if main { "main" } else { "other" }, payload.contains("\"parameters\""))); + plx_os::tv::launch::offer(&payload); + } + } + p +} + +#[cfg(test)] +mod relaunch_tap_tests { + use super::slot_holds; + + #[test] + fn relaunch_slot_must_hold_libhelpers() { + assert!(slot_holds(0x1000, Some(0x1000)), "the slot holds libhelpers' function"); + assert!(!slot_holds(0x1000, Some(0x1001)), "a different value, even by the Thumb bit"); + assert!(!slot_holds(0x1000, None), "libhelpers is not mapped or lacks the symbol"); + assert!(!slot_holds(0, None)); + } + + #[test] + fn the_slot_must_be_word_aligned() { + use super::slot_aligned; + let word = core::mem::align_of::(); + assert!(slot_aligned(0x1000) && slot_aligned(word)); + assert!(!slot_aligned(0x1000 + 1) && !slot_aligned(word + word / 2)); + } +} + +#[cfg(test)] +mod cursor_sleep_hint_tests { + use super::*; + + #[test] + fn the_idle_hide_hint_is_asked_for_only_where_lgs_extension_is_absent() { + assert_eq!(cursor_sleep_hint(false), Some(c"5000")); + assert_eq!(cursor_sleep_hint(true), None); + } +} + #[cfg(test)] mod wayland_tests { use super::*; diff --git a/rust-modules/src/textinput.rs b/rust-modules/src/textinput.rs index 20b4f58fff..3008c8e651 100644 --- a/rust-modules/src/textinput.rs +++ b/rust-modules/src/textinput.rs @@ -15,8 +15,8 @@ //! comes back as an ordinary `SDL_TEXTINPUT` event, so `app.rs`'s existing `SDL_PollEvent` loop //! already sees it. moonlight-tv 1.5.8 shipped exactly this against the TV's own SDL. //! -//! Linking is the plain `extern "C"` case, not `dynlib!`: all 14 firmware images in -//! `tools/fwcompat.py`'s inventories export the whole `SDL_*TextInput*` family. That says nothing +//! Linking is the plain `extern "C"` case (declared in `plx_shell_sdl`'s `sys.rs`), not `dynlib!`: all 14 +//! firmware images in `tools/fwcompat.py`'s inventories export the whole `SDL_*TextInput*` family. That says nothing //! about whether the PANEL rises, though — those are stock public API in every SDL2 build — so //! [`available`] probes at runtime rather than assuming. //! @@ -26,8 +26,10 @@ //! starts at **+16**, not the `+12` that stock SDL 2.0.4's `SDL_events.h` declares. That //! header lies about this build; the NDK sysroot's fork copy is the proof. //! Under `hostsim` the offset really is `+12` — desktop SDL2 is stock — so this is a `cfg`, and -//! a single hard-coded number ships garbage on one of the two platforms. [`TEXT_OFF`] is that -//! `cfg`; `decode_text_at` takes the offset as an argument so `make check` grades both. +//! a single hard-coded number ships garbage on one of the two platforms. `plx_shell_sdl::text::TEXT_OFF` +//! is that `cfg`, and the decoder next to it takes the offset as an argument so `make check` grades +//! both: the byte layout is the shell crate's, and [`decode`] and [`encode_event`] are re-exported +//! from it. //! 2. **`SDL_WINDOW_INPUT_FOCUS` is a precondition.** `SDL_StartTextInput` shows the panel only //! `if (SDL_GetKeyboardFocus())` — the window carrying `0x200` — and our window is created //! `OPENGL | FULLSCREEN` with neither `SHOWN` nor a focus flag. If it is clear, SDL still @@ -84,58 +86,17 @@ #![allow(dead_code)] use crate::app::SDL_WINDOW_INPUT_FOCUS; -#[cfg(not(test))] -use crate::app::{ - SDL_GetWindowFlags, SDL_HasScreenKeyboardSupport, SDL_StartTextInput, SDL_StopTextInput, -}; -#[cfg(test)] -use host_test_sdl::{ - SDL_GetWindowFlags, SDL_HasScreenKeyboardSupport, SDL_StartTextInput, SDL_StopTextInput, -}; - -/// The four SDL entry points this module calls, stubbed for the HOST TEST BINARY only. -/// -/// `cargo test --lib` links a Mach-O binary against no SDL at all, and unlike every other SDL user -/// in this crate these calls are reachable from ordinary `pub(crate)` functions that a test can -/// touch — `available()` and `start()` are one `screens::search::SearchScreen` call away. An unguarded reference is -/// therefore an undefined symbol at LINK time, which does not fail one test: it stops the whole -/// suite building, exactly as `ff.rs`'s `#[link]` directives used to before that module moved to -/// `dlopen`. SDL is a real link on the device, so the seam here is a `cfg` rather than a `dlopen`. -/// -/// **Only `test` is stubbed.** `hostsim` links desktop SDL2 and takes the real arm — which is the -/// whole point, since the simulator is where the decode path can actually be exercised by typing. -// the stubs carry SDL's own C names ON PURPOSE — `use`d unqualified by the arms below, so the call -// sites read identically in both builds and a signature drift shows up as a type error there -#[allow(non_snake_case)] -#[cfg(test)] -mod host_test_sdl { - use std::os::raw::{c_int, c_void}; - /// No window, so no focus bit — which makes [`super::has_focus`] answer `Some(false)` under - /// test, the same answer a real television gives when the panel cannot rise. - pub(super) unsafe fn SDL_GetWindowFlags(_w: *mut c_void) -> u32 { - 0 - } - /// No panel on the host, matching what the simulator's own boot probe reports (`support=0`). - pub(super) unsafe fn SDL_HasScreenKeyboardSupport() -> c_int { - 0 - } - pub(super) unsafe fn SDL_StartTextInput() {} - pub(super) unsafe fn SDL_StopTextInput() {} -} use plx_base::eventlog::log; -use std::os::raw::{c_int, c_void}; +use std::os::raw::c_void; use std::ptr::{addr_of, addr_of_mut}; -/// `SDL_TEXTINPUTEVENT_TEXT_SIZE` — `char text[32]`, inline in the event rather than a pointer. -/// Both headers agree on the size; they disagree only about where it starts (trap 1). -const TEXT_CAP: usize = 32; - -/// Where that array begins in the raw event bytes. **Trap 1**, and the only number in this file -/// that is wrong on the platform you are not currently building. -/// -/// `cfg!` and not `#[cfg]`, matching `app::decode_key`: both arms stay compiled on both platforms, -/// so the one nobody is building cannot rot into a compile error nobody sees for a month. -const TEXT_OFF: usize = if cfg!(feature = "hostsim") { 12 } else { 16 }; +// What the panel IS (the SDL calls that raise and dismiss it, the focus flag, the driver's own log +// priority) and what an `SDL_TEXTINPUT` event looks like in bytes (LG's fork and stock SDL put the +// text at different offsets, and decoding and encoding are only ever correct as a pair) are the +// stock-SDL shell's: `plx_shell_sdl::text`, which stubs the four SDL calls for a host TEST binary +// (its `test-support` feature, enabled for this crate's tests) exactly as this module did. What +// stays here is the state machine around them and the queue. +pub(crate) use plx_shell_sdl::text::{decode, encode_event}; /// How many un-drained commits to hold before dropping the oldest. /// @@ -181,37 +142,7 @@ static mut WIN: *mut c_void = std::ptr::null_mut(); /// started yet. So [`start`] re-reads it at the one moment it decides anything. pub(crate) fn bind(win: *mut c_void) { unsafe { *addr_of_mut!(WIN) = win }; - trace_driver(); -} - -/// `SDL_LOG_CATEGORY_INPUT` / `SDL_LOG_PRIORITY_DEBUG`, from `SDL_log.h`. -const SDL_LOG_CATEGORY_INPUT: c_int = 3; -const SDL_LOG_PRIORITY_DEBUG: c_int = 2; - -/// Ask LG's SDL to narrate its own keyboard lifecycle into stderr -/// (`/tmp/plxnative-stderr.log`). -/// -/// The driver already logs `[WebOSShowScreenKeyboard] called`, `... called text_model_activate`, -/// `[TextModelLeave] called`, `[TextModelInputPanelState] called - state: %d` and -/// `[WebOSHideScreenKeyboard] called` — at `INPUT`/`DEBUG`, which is below the default priority, -/// so none of it prints. One call makes the whole sequence readable without patching SDL. -/// -/// It is here for a specific open question, not as general noise. Disassembly says the panel -/// cannot be REOPENED because `text_model.leave` NULLs the model *before* calling -/// `SDL_StopTextInput`, so `WebOSHideScreenKeyboard` early-returns and `text_model_deactivate` is -/// never sent — after which the compositor ignores every later `activate`. The decisive -/// observation is whether `[TextModelLeave] called` appears BEFORE our own `stop()`: if it does, -/// the compositor dismissed the panel and that path ran; if it does not, our dismissal sent the -/// deactivate and something else is wrong. One is a five-line mitigation, the other is not. -/// -/// Cheap and permanent: a handful of lines per keyboard session, on a log that is already the -/// primary debugging surface, on a path a user reaches only by opening a text field: Search's, -/// or Settings > Player HUD's "Install from address". -fn trace_driver() { - #[cfg(not(test))] - unsafe { - crate::app::SDL_LogSetPriority(SDL_LOG_CATEGORY_INPUT, SDL_LOG_PRIORITY_DEBUG); - } + plx_shell_sdl::text::trace_driver(); } /// `SDL_GetWindowFlags & SDL_WINDOW_INPUT_FOCUS`, or `None` before [`bind`]. @@ -221,14 +152,14 @@ fn has_focus() -> Option { if win.is_null() { return None; } - Some(SDL_GetWindowFlags(win) & SDL_WINDOW_INPUT_FOCUS != 0) + Some(plx_shell_sdl::text::window_flags(win) & SDL_WINDOW_INPUT_FOCUS != 0) } } /// Does this build/firmware claim a system keyboard? Probed, never assumed — see the module doc. /// A `false` here means the field can still be typed into by other means but no panel will rise. pub(crate) fn available() -> bool { - unsafe { SDL_HasScreenKeyboardSupport() != 0 } + plx_shell_sdl::text::has_screen_keyboard() } /// Raise the keyboard. Idempotent: calling it while the panel is already up is not an error, and @@ -262,7 +193,7 @@ pub(crate) fn start() { None => "?".into(), // bind() was never called — a boot-order bug, not a TV fact } )); - SDL_StartTextInput(); + plx_shell_sdl::text::start_input(); } } @@ -283,7 +214,7 @@ pub(crate) fn stop() { // panel simply never returns — which looks exactly like the driver's own reopen wedge and // is not it. With both transitions logged, one log answers which of the two you have. log("keyboard: stop"); - SDL_StopTextInput(); + plx_shell_sdl::text::stop_input(); } } @@ -352,13 +283,6 @@ pub(crate) fn pending() -> usize { PENDING.with(|pending| pending.borrow().len()) } -/// What [`on_event`] would read out of these bytes, at THIS platform's offset. Exposed so a -/// caller can log the decode without duplicating the choice of offset — which is the one thing in -/// this file that must never be written down twice. -pub(crate) fn decode(ev: &[u8]) -> String { - decode_text_at(ev, TEXT_OFF) -} - /// One `SDL_TEXTINPUT` event, straight off the wire: [`decode`], then [`queue`]. Called by the /// `txt:` remote token (`app/events.rs`), which has the bytes [`encode_event`] built. The event /// loop gets its text already decoded (`HostEvent::Text`) and calls [`queue`] itself. @@ -384,128 +308,11 @@ pub(crate) fn queue(s: String) { }); } -/// The bytes an `SDL_TEXTINPUT` event carries for `text`, in whichever layout [`decode_text_at`] -/// reads — the inverse of it, and, like `app::encode_key`/`app::decode_key`, the pair is only ever -/// correct together. Nothing in the compiler couples them; `encode_decode_round_trips` does. -/// -/// It exists so this seam can be DRIVEN, by `app.rs`'s `txt:` remote token. A real -/// `SDL_TEXTINPUT` needs a human at a keyboard — no trigger raises the panel, and typing into the -/// simulator means somebody physically typing — so without it nothing automated could ever put a -/// character in the search field, on either platform. -/// -/// The bytes are a faithful event in THIS platform's layout, and `txt:` hands them to -/// [`on_event`] rather than to `SDL_PushEvent`: pushing a synthetic `SDL_TEXTINPUT` segfaults -/// inside the Mac's SDL, for the reason recorded at that call site and in the dead ends above. -pub(crate) fn encode_event(text: &str) -> [u8; 128] { - let mut ev = [0u8; 128]; - ev[0..4].copy_from_slice(&crate::app::SDL_TEXTINPUT.to_ne_bytes()); - // `text[32]` holds at most 31 bytes plus its terminator — and the cut must land on a CHAR - // BOUNDARY. Slicing a codepoint in half would make the decoder answer U+FFFD for text that - // was perfectly valid when it was written, which reads as a decoder bug and is not one. - let mut n = text.len().min(TEXT_CAP - 1); - while n > 0 && !text.is_char_boundary(n) { - n -= 1; - } - ev[TEXT_OFF..TEXT_OFF + n].copy_from_slice(&text.as_bytes()[..n]); - ev -} - -/// The committed text in a raw `SDL_TEXTINPUT` event whose `text[]` begins at `off`. -/// -/// Pure, and offset-parameterised rather than reading [`TEXT_OFF`] itself, so `make check` can -/// grade BOTH platforms' layouts on a host that only ever builds one of them — the same reason -/// `app::decode_key` and `app::encode_key` are pure and tested as a pair. -/// -/// Every failure mode here is a byte string somebody else chose: the panel's own IME writes this -/// field, and the app cannot afford a panic inside the SDL event loop (see `remote.rs`, where -/// exactly that class took the app down). So a short buffer, a missing NUL and invalid UTF-8 are -/// all answers, not faults. -fn decode_text_at(ev: &[u8], off: usize) -> String { - // `min(ev.len())` before the slice, not after: `text[32]` is the LAST field of the event, so a - // truncated or short buffer is the ordinary case at the end of the struct, not a malformed one. - let end = off.saturating_add(TEXT_CAP).min(ev.len()); - let Some(field) = ev.get(off..end) else { - return String::new(); // off past the end — `get` refuses the inverted range rather than panicking - }; - // NUL-terminated INSIDE a fixed array: the terminator is the length, and everything after it - // is whatever the last, longer commit left behind. - let n = field.iter().position(|&b| b == 0).unwrap_or(field.len()); - // The two edges of a codepoint the fixed array may have CUT — see `drop_cut_tail`. The tail - // rule is conditional on the array being FULL (`n == TEXT_CAP`), which is the signature of a - // cut; the head rule is unconditional, because no UTF-8 string may begin with a continuation - // byte under any circumstances. Deliberately NOT `n == field.len()`, which is also true when - // the CALLER's buffer ran out before `text[32]` did — a short buffer is the reader's limit, - // not the panel's, and there is nothing to say the panel cut anything at all. - let text = drop_orphan_head(&field[..n]); - let text = if n == TEXT_CAP { - drop_cut_tail(text) - } else { - text - }; - // Lossy, never `from_utf8`: a single bad byte would otherwise discard the whole commit — and - // an IME that emits one is a keystroke the user typed, not an attack. - String::from_utf8_lossy(text).into_owned() -} - -/// Drop a trailing UTF-8 sequence that is well-formed so far but CUT SHORT by the end of the -/// buffer. Everything else — a lone continuation byte, an overlong or out-of-range lead, a -/// surrogate — is left for `from_utf8_lossy` to answer with U+FFFD, because a replacement character -/// is the only visible signal that something arrived broken and it must not be swallowed. -/// -/// **This is LG checklist row #16** (`docs/lg-self-checklist.md` §2), which asks that the character -/// which arrives be the character that was pressed. `text[32]` is a fixed array, so a commit that -/// fills it is cut at a BYTE, and that cut lands mid-codepoint for any query that is not pure -/// ASCII. Decoded lossily, the surviving half becomes a `` the user never typed, in their search -/// field — exactly the substitution the row is about. Nothing can recover the character (its other -/// half is not in this event), so the honest answer is the text that WAS whole. -/// -/// **The classification is `std`'s, not ours.** `Utf8Error::error_len() == None` is precisely -/// "valid so far, ended mid-sequence", and `valid_up_to()` is where to cut — where a hand-rolled -/// lead-byte width table accepts `0xC0`, `0xF5..=0xF7` and surrogate pairs as merely "incomplete" -/// and deletes real corruption without a trace. Only the LAST sequence is offered to it (walk back -/// at most four bytes to the first non-continuation byte; no sequence is longer), so an interior -/// error earlier in the commit cannot suppress the tail rule. -/// -/// **Belt-and-braces for a case this project has not settled.** Stock SDL2 fills `text[32]` with -/// `SDL_utf8strlcpy`, which truncates on a character boundary and always terminates — so on stock -/// SDL this branch is unreachable, and `encode_event` cuts on a boundary too, which is why nothing -/// the simulator or the `txt:` token can drive reaches it either. Whether **LG's fork** does the -/// same is a question for the television's own `libSDL2`, not for a header or another client: -/// `.agents/skills/decompile-tv-lib/` is how the `+16 inputSource` offset above was settled, and it -/// is how this would be. Until then the branch costs one comparison and cannot make a correct -/// commit wrong. -fn drop_cut_tail(b: &[u8]) -> &[u8] { - for back in 1..=b.len().min(4) { - let i = b.len() - back; - if b[i] & 0xC0 == 0x80 { - continue; // a continuation byte — the sequence it belongs to starts further back - } - return match std::str::from_utf8(&b[i..]) { - Err(e) if e.error_len().is_none() => &b[..i], - _ => b, - }; - } - b // nothing but continuation bytes: garbage, and `from_utf8_lossy`'s to answer -} - -/// The other edge of the same cut: drop a leading run of continuation bytes. -/// -/// If the panel really does split a codepoint at `text[32]`, the half [`drop_cut_tail`] discards -/// arrives at the START of the NEXT commit — orphaned, with its lead byte in the event before it. -/// Left alone those bytes are one U+FFFD each, which is the row-#16 substitution again, one -/// character later; dropping the head is what makes the rule whole rather than one-sided. -/// -/// Unconditional, and safe to be: **no UTF-8 string may begin with a continuation byte**, so this -/// can only ever remove bytes that were already unreadable — never a character the user typed. -fn drop_orphan_head(b: &[u8]) -> &[u8] { - let n = b.iter().take_while(|&&c| c & 0xC0 == 0x80).count(); - &b[n..] -} - // --------------------------------------------------------------------------------------- #[cfg(test)] mod tests { use super::*; + use plx_shell_sdl::text::TEXT_OFF; use std::sync::Mutex; /// `STARTED` is a module singleton (and `PENDING` is per thread, but these tests drive both @@ -523,257 +330,6 @@ mod tests { ev } - /// **The trap this whole file is shaped around.** LG's fork inserts `Uint32 inputSource` at - /// +12, so the text is at +16 on the television and at +12 on a desktop. A single hard-coded - /// offset does not fail loudly on the wrong platform — it reads four bytes of `windowID` (or - /// of the text's own head) and commits plausible garbage into the search field. - #[test] - fn the_text_decodes_at_both_platforms_offsets() { - assert_eq!(decode_text_at(&ev_with(16, b"webos"), 16), "webos"); - assert_eq!(decode_text_at(&ev_with(12, b"desktop"), 12), "desktop"); - // …and reading one layout with the other's offset is exactly the silent corruption above: - // at +16 a stock event is four bytes into the text, and at +12 a fork event is inside - // `inputSource`, which is zero — an empty commit. - assert_eq!(decode_text_at(&ev_with(12, b"desktop"), 16), "top"); - assert_eq!(decode_text_at(&ev_with(16, b"webos"), 12), ""); - } - - /// The ordinary case: a short string in a fixed 32-byte array, terminated by NUL. Everything - /// after the terminator is the tail of some LONGER earlier commit, and must not be returned. - #[test] - fn a_nul_terminates_the_string_inside_the_fixed_array() { - let mut ev = ev_with(16, b"ab\0cdefghijklmnop"); - ev[16 + 31] = b'!'; // …up to and including the last byte of text[32] - assert_eq!(decode_text_at(&ev, 16), "ab"); - } - - /// A commit that fills `text[32]` completely has NO terminator — the array is the length. A - /// decoder that insists on finding a NUL reads past the field into `SDL_Event`'s padding. - #[test] - fn a_full_32_byte_commit_has_no_terminator() { - let text = [b'x'; TEXT_CAP]; - let ev = ev_with(16, &text); - assert_eq!(decode_text_at(&ev, 16), "x".repeat(TEXT_CAP)); - } - - /// Invalid UTF-8 must not panic. This runs inside the SDL event loop, where a panic unwinds - /// out of `plex_run` and takes the app with it — `remote.rs` lost the app exactly this way to - /// a multi-byte whitespace. The bytes come from the television's own IME, so "that cannot - /// happen" is not a thing this file gets to assume. - #[test] - fn invalid_utf8_is_replaced_rather_than_panicking() { - let s = decode_text_at(&ev_with(16, b"a\xffb"), 16); - assert_eq!(s, "a\u{fffd}b"); - // A bad byte in the MIDDLE keeps its replacement whatever surrounds it — it is neither - // edge of a cut, so neither trim rule can claim it. (A LEADING continuation byte is the - // orphan case and IS dropped; `a_commit_orphaned_from_its_lead_byte_is_dropped_rather_ - // than_replaced` owns that, and `\x80` alone belongs to it rather than here.) - assert_eq!(decode_text_at(&ev_with(16, b"x\x80y"), 16), "x\u{fffd}y"); - assert_eq!(decode_text_at(&ev_with(16, b"x\xc0y"), 16), "x\u{fffd}y"); - } - - /// **Row #16: a codepoint the fixed array CUT must not arrive as a character nobody typed.** - /// `text[32]` has no room for the tail of a sequence that starts at its last byte, so a lossy - /// decode puts a `` in the user's query — the exact substitution the checklist row is about. - /// The whole prefix is kept; only the half codepoint goes. - #[test] - fn a_codepoint_cut_by_the_end_of_the_field_is_dropped_not_replaced() { - // Each width of lead byte, cut at every point that leaves it incomplete. - for (lead, whole) in [(0xc3u8, "é"), (0xe5, "千"), (0xf0, "🎬")] { - let need = whole.len(); - for kept in 1..need { - let mut raw = vec![b'y'; TEXT_CAP - kept]; - raw.extend_from_slice(&whole.as_bytes()[..kept]); - assert_eq!(raw.len(), TEXT_CAP); - let got = decode_text_at(&ev_with(16, &raw), 16); - assert_eq!( - got, - "y".repeat(TEXT_CAP - kept), - "lead {lead:#x}, {kept} of {need} bytes" - ); - assert!( - !got.contains('\u{fffd}'), - "a cut must not invent a character" - ); - } - // …and the same codepoint that FITS is untouched, which is what proves the rule cuts - // only what was actually truncated. - let mut raw = vec![b'y'; TEXT_CAP - need]; - raw.extend_from_slice(whole.as_bytes()); - assert_eq!( - decode_text_at(&ev_with(16, &raw), 16), - format!("{}{whole}", "y".repeat(TEXT_CAP - need)) - ); - } - } - - /// A TERMINATED commit is as long as the panel meant it to be, so a malformed tail inside one - /// is genuine garbage and keeps the defensive replacement — the cut rule must not swallow it. - /// Neither may a SHORT BUFFER be read as a cut: that is the caller's limit, not the panel's. - #[test] - fn a_bad_tail_before_a_terminator_still_replaces_rather_than_vanishing() { - // `ab` + a bare 3-byte lead + NUL: nothing cut this, the byte is simply wrong. - assert_eq!(decode_text_at(&ev_with(16, b"ab\xe5\0"), 16), "ab\u{fffd}"); - // …and a buffer that ends mid-codepoint is the READER running out, so the tail rule stays - // off and the bad byte is still reported. - assert_eq!( - decode_text_at(&ev_with(16, "é".as_bytes())[..17], 16), - "\u{fffd}" - ); - } - - /// **A byte no cut could have produced keeps its replacement.** The rule is "valid so far, - /// ended mid-sequence" and nothing looser — a hand-rolled lead-byte width table calls all of - /// these merely incomplete and deletes them, which turns real corruption from the panel's IME - /// into a silent shortening with no signal at all. `std::str::from_utf8` draws the line. - #[test] - fn corruption_that_is_not_a_cut_is_reported_rather_than_deleted() { - for (name, tail) in [ - ("overlong lead", &[0xC0u8][..]), - ("out-of-range lead", &[0xF5][..]), - ("never-a-lead byte", &[0xFF][..]), - ("surrogate half", &[0xED, 0xA0][..]), - ] { - let mut raw = vec![b'y'; TEXT_CAP - tail.len()]; - raw.extend_from_slice(tail); - let got = decode_text_at(&ev_with(16, &raw), 16); - assert!( - got.contains('\u{fffd}'), - "{name} must survive as a replacement, got {got:?}" - ); - } - } - - /// The other edge of the same cut: a commit ORPHANED from its lead byte — the remainder of a - /// codepoint the previous event was cut inside — must not arrive as one U+FFFD per byte, which - /// is the row-#16 substitution again, one character later. - #[test] - fn a_commit_orphaned_from_its_lead_byte_is_dropped_rather_than_replaced() { - // "🎬" is F0 9F 8E AC; cut after F0, the next commit opens with its three tail bytes. - assert_eq!( - decode_text_at(&ev_with(16, b"\x9f\x8e\xacstar"), 16), - "star" - ); - // …and a commit that is nothing BUT an orphaned remainder yields nothing, rather than one - // replacement character per byte. - assert_eq!(decode_text_at(&ev_with(16, b"\x80"), 16), ""); - // …and a commit that legitimately STARTS with a multi-byte character is untouched. - assert_eq!( - decode_text_at(&ev_with(16, "🎬star".as_bytes()), 16), - "🎬star" - ); - } - - /// **Capital and small letters transfer as themselves.** The panel's Shift/Caps is resolved on - /// the television — it commits the CASED character — so the app's whole obligation is to carry - /// the bytes through without touching them, and this is what proves it does. (A decoder that - /// normalised case would be invisible until someone searched for a title that differs only by - /// it.) Deliberately cites no checklist row number: `docs/lg-self-checklist.md` records no such - /// row, and a number this repo cannot corroborate does not belong in a permanent comment. - #[test] - fn letter_case_transfers_exactly_as_the_panel_committed_it() { - for s in [ - "A", "a", "Wallace", "WALLACE", "wallace", "WaLlAcE", "Ç", "ç", "Ä", "ä", - ] { - assert_eq!(decode_text_at(&ev_with(16, s.as_bytes()), 16), s); - assert_eq!(decode_text_at(&encode_event(s), TEXT_OFF), s); - } - } - - /// **Row #16, its own worked example.** The checklist names the full-width `\` (U+FF3C) and - /// asks that it not arrive as a backslash — the substitution a keyboard stack makes when it - /// folds full-width forms to ASCII, and the one a byte-oriented decoder makes when it reads one - /// of the three bytes of a full-width form on its own. - /// - /// The `lookalike` column is not a second assertion (the equality above already implies it); - /// it is the table saying what each row is FOR, so the next reader can tell a deliberate pair - /// from an arbitrary one. The rest are the characters a VKB commonly substitutes or a layer - /// below eats — the shell and URL metacharacters, and the quote pair a keyboard "smartens". - #[test] - fn a_full_width_character_is_not_folded_to_its_ascii_lookalike() { - for (typed, _lookalike) in [ - ("\", "\\"), // U+FF3C FULLWIDTH REVERSE SOLIDUS — the row's own example - ("¥", "\\"), // U+FFE5, the same key on a JP panel, and the same wrong answer - ("/", "/"), - (":", ":"), - (" ", " "), // U+3000 IDEOGRAPHIC SPACE - ("“", "\""), - ("’", "'"), - ("-", "-"), - ] { - let got = decode_text_at(&ev_with(16, typed.as_bytes()), 16); - assert_eq!( - got, typed, - "the character pressed must be the character that arrives" - ); - assert_eq!(decode_text_at(&encode_event(typed), TEXT_OFF), typed); - } - // The ASCII originals still arrive as themselves — nothing here rewrites in either - // direction. `\` is the one the row calls out, and the rest are what a URL layer or a - // shell would eat if anything on the path were not byte-transparent. - for s in [ - "\\", "/", "&", "%", "+", "#", "?", "=", "\"", "'", "<", ">", " ", "\t", - ] { - assert_eq!(decode_text_at(&ev_with(16, s.as_bytes()), 16), s); - } - } - - /// A buffer that ends before (or inside) the text field is an answer, not a fault. `SDL_Event` - /// is a union and nothing guarantees a caller polled into 128 bytes. - #[test] - fn a_short_buffer_yields_an_empty_string() { - assert_eq!(decode_text_at(&[0u8; 8], 16), ""); - assert_eq!(decode_text_at(&[], 16), ""); - // Ending mid-field returns the part that IS there, rather than nothing. - let ev = ev_with(16, b"abcdef"); - assert_eq!(decode_text_at(&ev[..19], 16), "abc"); - } - - /// Multi-byte UTF-8 survives intact — the field is bytes, not characters, and a European or - /// CJK query is the normal case for a media library. - #[test] - fn multibyte_text_round_trips() { - assert_eq!( - decode_text_at(&ev_with(16, "Amélie".as_bytes()), 16), - "Amélie" - ); - assert_eq!( - decode_text_at(&ev_with(16, "千と千尋".as_bytes()), 16), - "千と千尋" - ); - } - - /// The encoder writes what the decoder reads, on whichever platform this is — the pair that - /// nothing but this test couples. `app.rs` already lost the simulator's whole remote FIFO to - /// exactly this: `encode_key` wrote LG's layout while `decode_key` had been taught stock - /// SDL2's, so every token was accepted and nothing moved. - #[test] - fn encode_decode_round_trips() { - for s in ["a", "wallace", "Amélie", "千と千尋", "star wars"] { - assert_eq!(decode_text_at(&encode_event(s), TEXT_OFF), s); - } - } - - /// Over-long text is cut to fit `text[32]`, and the cut lands on a CHAR BOUNDARY — a codepoint - /// sliced in half would come back as U+FFFD and look like a decoder fault. - #[test] - fn an_over_long_commit_is_cut_on_a_char_boundary() { - let long = "x".repeat(100); - assert_eq!( - decode_text_at(&encode_event(&long), TEXT_OFF), - "x".repeat(TEXT_CAP - 1) - ); - // 16 CJK codepoints = 48 bytes: the 31-byte limit falls mid-codepoint, so the cut must - // back up to 30 bytes (10 characters) rather than emit a replacement character. - let cjk = "千".repeat(16); - let got = decode_text_at(&encode_event(&cjk), TEXT_OFF); - assert_eq!(got, "千".repeat(10)); - assert!( - !got.contains('\u{fffd}'), - "the cut must not split a codepoint" - ); - } - /// Commits queue in order and `drain` takes them exactly once — the caller appends them to the /// query, so a duplicate is a doubled character and a lost one is a dropped keystroke. #[test] diff --git a/tools/build-bench.py b/tools/build-bench.py index 6a0cbd9cfc..098c53f227 100755 --- a/tools/build-bench.py +++ b/tools/build-bench.py @@ -59,7 +59,7 @@ leaf-inc `leaf` with CARGO_INCREMENTAL=1 in rust-modules/target-fast (the `make test-fast` tree). hub-inc `hub`, incremental. The two -inc rows are skipped with a note when target-fast is absent, unless `--cold` (which builds it, untimed, first). - tests the default-feature unit suite (`cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_owp`, run through + tests the default-feature unit suite (`cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp`, run through tools/cargo-test-parallel.py exactly as the Makefile's recipes do) on a warm tree; the `test result:` counts of every crate are summed. arm the ARM staticlib line (`cargo rustc ... --crate-type staticlib`) after touching lib.rs, @@ -161,7 +161,7 @@ # The cargo subcommand skeletons the Makefile's recipes use. Everything else (toolchain, dirs, # feature flags, RUSTFLAGS) comes from `make -s print-bench-config`. ci/test_build_bench.py compares # these to the recipes in the Makefile. -HOST_TEST_ARGS = ("test", "--lib", "-p", "plxnative-modules", "-p", "plx_base", "-p", "plx_machine", "-p", "plx_os", "-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", "-p", "plx_owp") +HOST_TEST_ARGS = ("test", "--lib", "-p", "plxnative-modules", "-p", "plx_base", "-p", "plx_machine", "-p", "plx_os", "-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", "-p", "plx_shell_sdl", "-p", "plx_owp") HOST_TEST_BUILD_ARGS = HOST_TEST_ARGS + ("--no-run", "--message-format=json") ARM_ARGS_HEAD = ("rustc",) # then the Makefile's ARM_PROFILE_FLAG (`--release` / `--profile tvdev`) ARM_ARGS_TARGET = ("--target",) # then the target triple diff --git a/tools/screenshots.py b/tools/screenshots.py index fffc7609a7..9da8e22fbd 100755 --- a/tools/screenshots.py +++ b/tools/screenshots.py @@ -251,7 +251,7 @@ def png_size(png): def fit_capture(png, w, h): """The capture at exactly `w`x`h` (the canvas times the scene's render scale), which `output_spec`'s crops assume. The simulator writes its DRAWABLE, which it now sizes to the canvas on any display density - (`app::boot::plan_desktop_window`), so a capture arrives at exactly `w`x`h` and passes through untouched. + (`plx_shell_sdl::window::plan_desktop_window`), so a capture arrives at exactly `w`x`h` and passes through untouched. A binary from before that had a drawable 2x the window on a HiDPI display (a Retina Mac): 3840x2160 for the 1920x1080 canvas, whose top-left quadrant a canvas-sized crop then cut, a Library that looked zoomed 2x. That is what this still guards: a whole multiple is downscaled (Lanczos, bit-exact); anything else is refused.""" From 683039d0b977df3d1c9c16c3d665f2e490515627 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 19:51:15 +0300 Subject: [PATCH 2/6] The loop tests' two wheel readers are re-exported for the hostsim build only The default-feature test build does not read them, and a re-export nothing reads is a deny(warnings) failure there. Co-Authored-By: Claude --- rust-modules/src/app/events.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/rust-modules/src/app/events.rs b/rust-modules/src/app/events.rs index ff455dcbea..d6db179e44 100644 --- a/rust-modules/src/app/events.rs +++ b/rust-modules/src/app/events.rs @@ -36,8 +36,9 @@ pub(crate) use plx_shell_sdl::inject::{ synth_key_repeat as remote_synth_key_repeat, synth_lifecycle as remote_synth_lifecycle, synth_pointer as remote_synth_pointer, synth_ptr as remote_synth_ptr, synth_wheel as remote_synth_wheel, }; -// The byte writers and two readers are the loop tests' (they write the bytes a platform would deliver). -#[cfg(test)] +// The byte writers are the loop tests' (they write the bytes a platform would deliver), and the two +// readers are the hostsim wheel test's (the stock layout's float). +#[cfg(all(test, feature = "hostsim"))] pub(crate) use plx_shell_sdl::event::{rd_f32, rd_i32}; #[cfg(test)] pub(crate) use plx_shell_sdl::inject::{encode_key, encode_key_repeat, encode_pointer}; From 40350fd828b1b373fb6ddd21b73e6c35c33db492 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 20:05:46 +0300 Subject: [PATCH 3/6] The prose the SDL shell move made false is corrected, and the certificates are re-sealed over it The doc-claim audit of the move found a handful of sentences it had made false or left behind. The module-layers paragraph for the new crate advertised a synthetic text event pushed back into the queue, the one push the crate documents as fatal under the Mac's SDL: it now names what is pushed (key, pointer, wheel, lifecycle) and who pushes it, and says a text event is built as bytes and handed to the decode. The record of the `hostsim` comment in `rust-modules/Cargo.toml` said W7 would reword it; W6 did, with the certificate. `docs/remote-keys.md` and the fw-compat reviewer's prompt named `decode_key` and the cursor-visibility probe where they used to live, and the reviewer's first-pass scan now reads the shell crate's directory so it still sees the SDL extern block. Inside the new crate, four comments named things that are not there (`app::decode_key`, `text::stubs`, an `app.rs`) or said a `make check` test binary pushes nothing while one of its tests drives SDL's real queue. The remaining mentions of an `app.rs` whose subject moved with the SDL shell (the text-input and window-flag prose, the depth and stencil request, the key decode named in `ui`'s key classifier) now name the crate that holds it. The "stock layouts" wording in the layer config, the manifest comments and the crate description now says both SDLs' layouts, since the crate decodes LG's fork on the television and stock SDL2 under `hostsim`. The comments in the two `Cargo.toml` files changed, so both read-only certificates are re-sealed over the final manifest set. Co-Authored-By: Claude --- .agents/agents/fw-compat-reviewer.md | 4 ++-- ci/mkmacapp.py | 2 +- ci/module-layers.ini | 2 +- ci/proofs/platform-generated-enums.json | 4 ++-- ci/proofs/serde-json-immutable.json | 4 ++-- ci/readonly_dependencies.py | 2 +- ci/readonly_generated.py | 2 +- docs/agent-reference.md | 2 +- docs/module-layers.md | 8 ++++---- docs/remote-keys.md | 2 +- docs/search.md | 8 ++++---- rust-modules/Cargo.toml | 2 +- rust-modules/shell-sdl/Cargo.toml | 2 +- rust-modules/shell-sdl/src/event.rs | 2 +- rust-modules/shell-sdl/src/inject.rs | 8 ++++---- rust-modules/shell-sdl/src/lib.rs | 2 +- rust-modules/shell-sdl/src/sys.rs | 2 +- rust-modules/shell-sdl/src/text.rs | 4 ++-- rust-modules/src/app/exit.rs | 4 ++-- rust-modules/src/app/mod.rs | 7 ++++--- rust-modules/src/system.rs | 4 ++-- rust-modules/src/textinput.rs | 8 ++++---- rust-modules/ui/src/consts.rs | 8 ++++---- 23 files changed, 47 insertions(+), 46 deletions(-) diff --git a/.agents/agents/fw-compat-reviewer.md b/.agents/agents/fw-compat-reviewer.md index 98652f426f..30f2bd3af1 100644 --- a/.agents/agents/fw-compat-reviewer.md +++ b/.agents/agents/fw-compat-reviewer.md @@ -163,7 +163,7 @@ git -C diff HEAD -- rust-modules/base/src/dynlib.rs rust-modules/media-co rust-modules/net/src/net.rs rust-modules/net/src/curlio.rs src/starfish.c src/video_plane.c src/starfish.h \ rust-modules/os/src/webos.rs rust-modules/os/src/webos/ls2/uri.rs Makefile \ ci/expected-dt-needed.txt ci/expected-dt-needed-uri.txt -grep -rn '#\[link\|extern "C"\|__asm__("' rust-modules/src rust-modules/media/src rust-modules/play-feed/src rust-modules/play-uri/src rust-modules/os/src rust-modules/media-codecs/src rust-modules/net/src src # against the diff, not the tree +grep -rn '#\[link\|extern "C"\|__asm__("' rust-modules/src rust-modules/shell-sdl/src rust-modules/media/src rust-modules/play-feed/src rust-modules/play-uri/src rust-modules/os/src rust-modules/media-codecs/src rust-modules/net/src src # against the diff, not the tree ``` ### 1. Decide, out loud, whether you are grading an ELF or grading source @@ -260,7 +260,7 @@ Reading the output: C++11 `std::string` ABI and are untested on a set apart from one 3.4.3 (webOS 1.x/2.x were never tried). They used to fail on two missing symbols, `SDL_webOSCursorVisibility` and `StarfishMediaAPIs::Feed`'s C++11 name, but since #578 both are `dlsym`'d at runtime - (`src/starfish.c`, `rust-modules/src/app/boot.rs`, and `rust-modules/src/system.rs`'s `cursor_door`), so the binary no longer imports them. Re-run + (`src/starfish.c`, and `rust-modules/src/system.rs`'s `webos3_cursor_sleep_hint` and `cursor_door`), so the binary no longer imports them. Re-run `tools/fwcompat.py` for what the old rows print now; they are still printed below the floor and do not set the exit status. * **Baseline as of 2026-08-23** (verified by running it): `15 DT_NEEDED, 319 undefined dynamic diff --git a/ci/mkmacapp.py b/ci/mkmacapp.py index a8df0451de..808a262569 100755 --- a/ci/mkmacapp.py +++ b/ci/mkmacapp.py @@ -155,7 +155,7 @@ def write_icon(res: Path): def write_plist(contents: Path, ver: str): - """`NSHighResolutionCapable` is the half that makes `app.rs`'s ALLOW_HIGHDPI window real: with + """`NSHighResolutionCapable` is the half that makes `plx_shell_sdl`'s ALLOW_HIGHDPI window real: with it the 960x540-point window gets a 1920x1080 drawable, i.e. `surface::scale() == 1.0` — the same 1:1 texel contract the television renders under. Without it the OS hands back a half-resolution surface and doubles the whole interface.""" diff --git a/ci/module-layers.ini b/ci/module-layers.ini index 6a590599ba..c515843672 100644 --- a/ci/module-layers.ini +++ b/ci/module-layers.ini @@ -78,7 +78,7 @@ members = gfx egl text rtl img svg gpu_timer hwcnt overdraw dump # reads it as part of the same module tree through the manifest's `mount = "shell_sdl"` (a path # `plx_shell_sdl::event::decode` names module `shell_sdl::event`), like `plx_play_uri`. # The stock-SDL shell the application opens its window through: SDL's init, the window and its GL context, -# the swap, the event queue, the stock layouts of the key, pointer, wheel and text events, and the synthetic +# the swap, the event queue, the key, pointer, wheel and text layouts of both SDLs, and the synthetic # events pushed back onto the queue. It names no `ui`, no application type and none of [platform webos]; the # application drives it through its own `Shell` and `Surface` (`app::platform`), and the television's LG half # (the SysWMinfo handshake, the Wayland surface, the boot hooks around `SDL_Init`) stays in `system`. The crate diff --git a/ci/proofs/platform-generated-enums.json b/ci/proofs/platform-generated-enums.json index 07f6a9b69b..5c26e2a350 100644 --- a/ci/proofs/platform-generated-enums.json +++ b/ci/proofs/platform-generated-enums.json @@ -33,7 +33,7 @@ "lock": "800367e4065771c60d1fe5c722e209b2483247a620f382b2248e150bf00b3ad0", "machine_newtype": "reviewed local newtype macro emits pub struct Name(pub u32); doc attributes only", "manifests": { - "Cargo.toml": "29fddc70ec0a893de909e79eea1ea5afc615cf43ccdb1a194bc2cce0094a31e3", + "Cargo.toml": "88f7b3a976961d5ed784878f2d968330d64a7d034aad87f3fa71672bcf9a41ac", "appkit/Cargo.toml": "5cc1214cba7746fe0f2d4cfa5047b599e0d5124abe7bdaebe210381021b88c4a", "base/Cargo.toml": "ebe0b95553bd44f33f422f7d8e22b75ddeb53c7ee81bbe738f675690694568f7", "data/Cargo.toml": "74f79e6240f0965069ec34916ae276b3f7e5f4b944cf16a0846570a6b115afa0", @@ -50,7 +50,7 @@ "plex/Cargo.toml": "5cdb185265b7f7217cff08e54ef683a827735c9b3ae7c50161850f7064667b66", "screens/Cargo.toml": "cd42484a49fac394244ebc7b81f30f7e4f9a31cdf7bc1ace5c3fae21afd6d511", "session/Cargo.toml": "ecb49fc9f44177be6de36715ad70845b8929799cdbeb5ce9d6939be741704db0", - "shell-sdl/Cargo.toml": "357aebbf4a32c5b87154d6b91e3cc1ffb105154e974e536b92c61106b0460c14", + "shell-sdl/Cargo.toml": "9bccdb0abdb2ce9afdc030af9454117ed53884f9b50e1ee35a21bcfe6459e9a1", "storage/Cargo.toml": "4b8576b04a5877e95d084a49a16b30224c275ae29b4a192c40725ac819500150", "telemetry/Cargo.toml": "9e514e64ae4a35619294621f22534b5e5b109d9dd3b729b94ed20112f47197bf", "ui/Cargo.toml": "7375c6a73cb2558c7c0f62da7b0bd4beb2a5b78f5460ee35e93b1045c0e80eec" diff --git a/ci/proofs/serde-json-immutable.json b/ci/proofs/serde-json-immutable.json index 507c82a757..1fd2577724 100644 --- a/ci/proofs/serde-json-immutable.json +++ b/ci/proofs/serde-json-immutable.json @@ -373,7 +373,7 @@ }, "lock_sha256": "800367e4065771c60d1fe5c722e209b2483247a620f382b2248e150bf00b3ad0", "manifests": { - "Cargo.toml": "29fddc70ec0a893de909e79eea1ea5afc615cf43ccdb1a194bc2cce0094a31e3", + "Cargo.toml": "88f7b3a976961d5ed784878f2d968330d64a7d034aad87f3fa71672bcf9a41ac", "appkit/Cargo.toml": "5cc1214cba7746fe0f2d4cfa5047b599e0d5124abe7bdaebe210381021b88c4a", "base/Cargo.toml": "ebe0b95553bd44f33f422f7d8e22b75ddeb53c7ee81bbe738f675690694568f7", "data/Cargo.toml": "74f79e6240f0965069ec34916ae276b3f7e5f4b944cf16a0846570a6b115afa0", @@ -390,7 +390,7 @@ "plex/Cargo.toml": "5cdb185265b7f7217cff08e54ef683a827735c9b3ae7c50161850f7064667b66", "screens/Cargo.toml": "cd42484a49fac394244ebc7b81f30f7e4f9a31cdf7bc1ace5c3fae21afd6d511", "session/Cargo.toml": "ecb49fc9f44177be6de36715ad70845b8929799cdbeb5ce9d6939be741704db0", - "shell-sdl/Cargo.toml": "357aebbf4a32c5b87154d6b91e3cc1ffb105154e974e536b92c61106b0460c14", + "shell-sdl/Cargo.toml": "9bccdb0abdb2ce9afdc030af9454117ed53884f9b50e1ee35a21bcfe6459e9a1", "storage/Cargo.toml": "4b8576b04a5877e95d084a49a16b30224c275ae29b4a192c40725ac819500150", "telemetry/Cargo.toml": "9e514e64ae4a35619294621f22534b5e5b109d9dd3b729b94ed20112f47197bf", "ui/Cargo.toml": "7375c6a73cb2558c7c0f62da7b0bd4beb2a5b78f5460ee35e93b1045c0e80eec" diff --git a/ci/readonly_dependencies.py b/ci/readonly_dependencies.py index fe935df6d1..df79c466ca 100644 --- a/ci/readonly_dependencies.py +++ b/ci/readonly_dependencies.py @@ -18,7 +18,7 @@ import tarfile CERTIFICATE_PATH = Path(__file__).with_name('proofs') / 'serde-json-immutable.json' -CERTIFICATE_SHA256 = '1e9efc0c1a9f21baed52d0973d76560d4d68a9c5fe6d35322a7b7add95458d8d' +CERTIFICATE_SHA256 = '75f6923e03ff9d17819d6d921c8715c0e6c3dd6496f6b37274390e62752db121' 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 32097e0897..c670b10cfa 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 = '0840020f76498e3f973f9523cc4b00ab35dc82837b471f71b1c7efb3449e0c5d' +CERTIFICATE_SHA256 = '986f3f070a1d3b219e06c5da96677688d0cede10bc636a5b791b0082bfe560fc' SOURCES = ['os/Cargo.toml', 'os/src/lib.rs', 'os/src/i18n/mod.rs', 'os/build.rs', 'os/build_support/catalog.rs', 'build_support/install_identities.rs', 'machine/src/lib.rs', 'machine/src/machine.rs'] diff --git a/docs/agent-reference.md b/docs/agent-reference.md index 5c89b4e93b..e66f458104 100644 --- a/docs/agent-reference.md +++ b/docs/agent-reference.md @@ -1951,7 +1951,7 @@ behaviour; real GL copies, glyphs and presentation still need a device capture w There **is** a host unit suite, and it is not the real gate — both halves matter, and conflating 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_os -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 -p plx_shell_sdl -p plx_owp` (a bare `cargo test --lib` runs the application crate only and skips every layer crate: `plx_base`, `plx_machine`, `plx_os`, `plx_gfx`, `plx_net`, `plx_ui`, `plx_plex`, `plx_telemetry`, `plx_data`, `plx_session`, `plx_media`, `plx_appkit`, `plx_screens`) runs the whole +**Tier 1 — `make check` (host).** `cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -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 -p plx_shell_sdl -p plx_owp` (a bare `cargo test --lib` runs the application crate only and skips every layer crate: `plx_base`, `plx_machine`, `plx_os`, `plx_gfx`, `plx_net`, `plx_ui`, `plx_plex`, `plx_telemetry`, `plx_data`, `plx_session`, `plx_media`, `plx_appkit`, `plx_screens`, `plx_shell_sdl`) runs the whole 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 diff --git a/docs/module-layers.md b/docs/module-layers.md index 90ef9fa895..5091866d86 100644 --- a/docs/module-layers.md +++ b/docs/module-layers.md @@ -203,8 +203,8 @@ gates as every other layer, and as machine code. its layer may use `base`, `machine` and `os` and the crate names `plx_base` alone. It is the SDL half of the shell that the television and the simulator share: `SDL_Init` and the GL request, the window (the panel's size and its smaller fallback, and under `hostsim` the desktop fit), the swap and its interval, the event poll and decode (LG's fork layout -on the device, stock SDL2 under `hostsim`), the synthetic key, pointer, wheel and text events the dev tooling pushes back -into the queue, and the text-input calls. The LG half does not move: the `SDL_SysWMinfo` buffer, the `wl_proxy_marshal` +on the device, stock SDL2 under `hostsim`), the synthetic key, pointer, wheel and lifecycle events the remote FIFO, Lab Control, replay and the cursor-swap OK push back +into the queue (a text event is built as bytes and handed to the decode, never pushed: pushing one crashes the Mac's SDL), and the text-input calls. The LG half does not move: the `SDL_SysWMinfo` buffer, the `wl_proxy_marshal` opaque region and the LS2 pump stay in `system.rs`, a member of `[platform webos]`, and a pin in the crate's `lib.rs` fails if the crate names the query that overruns it. The application reaches it through `app/platform.rs`, whose `Shell` opens a `Surface` over the crate's `Window`; `Shell`, `Surface` and `HostEvent` stay application-private until W7a. @@ -459,8 +459,8 @@ still webOS's. Three things were left, and item 2 is done: host build of what is not one (the media seam's host sink, the GL context request, the window flags and the keyboard event decode), while the television's wayland and glib calls, like the rest of the television's arms, are compiled in every build and the linker drops them from a host executable. - The comment on the feature in `rust-modules/Cargo.toml` still lists those calls under what it - switches; the certificate pins that file, so W7 rewords it when it re-seals. The + The comment on the feature in `rust-modules/Cargo.toml` says the same since W6, which re-sealed the + certificate with it. The webOS-shaped types in `tv` needed neutral shapes then, and have them since W3d: `tv::secure::Backend` is an opaque tag that stays a string on the wire (the two webOS spellings are constants, and a tag no installed platform knows is refused on open), `tv::sandbox` is `tv::native_video` with a verdict that is diff --git a/docs/remote-keys.md b/docs/remote-keys.md index cbffb39ca6..ceb3d5fcc0 100644 --- a/docs/remote-keys.md +++ b/docs/remote-keys.md @@ -20,7 +20,7 @@ done offline is read out of the television's own harvested `libSDL2`, which is s ## 1. How a press reaches the app An `SDL_KEYDOWN` / `SDL_KEYUP` from LG's SDL fork is read by raw byte offset, because the fork's -`SDL_KeyboardEvent` is **shifted four bytes** against the headers (`app/events.rs::decode_key`, and the +`SDL_KeyboardEvent` is **shifted four bytes** against the headers (`plx_shell_sdl::event::decode_key` in `rust-modules/shell-sdl/src/event.rs`, and the gotcha in `docs/agent-reference.md`): | offset | field | the app calls it | diff --git a/docs/search.md b/docs/search.md index 46b6a102f7..041a09e5e8 100644 --- a/docs/search.md +++ b/docs/search.md @@ -277,7 +277,7 @@ backend is not in the webOS extension API at all — it is inside **LG's Wayland `Wayland_CreateDevice` writes four real hooks into `SDL_VideoDevice` (`WebOSHasScreenKeyboardSupport`, `Show`, `Hide`, `IsShown`), `SDL_StartTextInput` dispatches to the second, and `WebOSShowScreenKeyboard` is a complete `text_model` IME client. Typed text comes back -as an ordinary **`SDL_TEXTINPUT`** event, so `app.rs`'s existing `SDL_PollEvent` loop already sees +as an ordinary **`SDL_TEXTINPUT`** event, so the existing `SDL_PollEvent` loop (`plx_shell_sdl::event`) already sees it. moonlight-tv 1.5.8 shipped exactly this against the TV's own SDL. **Linking is the plain `extern "C"` case, not `dynlib!`.** Verified with @@ -308,7 +308,7 @@ Both halves are checkable on the dev Mac without a television: declares `{ type, timestamp, windowID, inputSource /* webOS specific field */, text[] }` — text at **+16**. -This is the same class of bug as the `SDL_KeyboardEvent` shift `app.rs` already reads around with +This is the same class of bug as the `SDL_KeyboardEvent` shift `plx_shell_sdl::event` already reads around with raw offsets, and it has the same fix: read the bytes, do not trust the struct. Note the offset is a `cfg`, not a constant — under `hostsim` desktop SDL2 is stock and the offset really is +12, so a single hard-coded number ships garbage on one of the two platforms. @@ -339,8 +339,8 @@ Two host-side findings, recorded because both cost time today and neither is a s television. **The boot probe's answer on macOS is `keyboard: support=0 active=1 focus=0 winflags=0x26`.** That -is **trap 2 observed**: `0x26` is `OPENGL | SHOWN | RESIZABLE` (`app.rs`'s `hostsim` arm asks for -`0x2 | 0x20`; SDL adds `SHOWN`), and `0x200` — `SDL_WINDOW_INPUT_FOCUS` — is not in it. The trap is +is **trap 2 observed**: `0x26` is `OPENGL | SHOWN | RESIZABLE` (the `hostsim` arm asked for +`0x2 | 0x20` when this was measured, and is `plx_shell_sdl`'s `SDL_WINDOW_FLAGS` now; SDL adds `SHOWN`), and `0x200` — `SDL_WINDOW_INPUT_FOCUS` — is not in it. The trap is therefore reproducible without a television, which is the useful part; what it does **not** tell you is anything about the TV's own answer, since `support=0` here just means desktop SDL has no screen keyboard at all. diff --git a/rust-modules/Cargo.toml b/rust-modules/Cargo.toml index 425f154200..5bf6addbd6 100644 --- a/rust-modules/Cargo.toml +++ b/rust-modules/Cargo.toml @@ -279,7 +279,7 @@ plx_appkit = { path = "appkit" } plx_screens = { path = "screens" } # The shell_sdl layer (ci/module-layers.ini `[shell_sdl]`): the stock-SDL shell the application opens its # window through: SDL's init, the window and its GL context, the swap, the event queue, the stock -# layouts of the key, pointer, wheel and text events, and the synthetic events pushed back onto the +# key, pointer, wheel and text layouts of both SDLs, and the synthetic events pushed back onto the # queue. It names no application type and none of the webOS platform (`system`, `port`); the # application drives it through its own `Shell` and `Surface`. Its `hostsim` feature is forwarded # above; its build script links SDL2 into a host test binary only. diff --git a/rust-modules/shell-sdl/Cargo.toml b/rust-modules/shell-sdl/Cargo.toml index ad746acb66..03f79e00f8 100644 --- a/rust-modules/shell-sdl/Cargo.toml +++ b/rust-modules/shell-sdl/Cargo.toml @@ -3,7 +3,7 @@ name = "plx_shell_sdl" version = "0.0.0" edition = "2021" license = "GPL-3.0-or-later" -description = "PlxNative stock-SDL shell: SDL bring-up, the window and GL context, the swap, the event drain, the stock key, pointer, wheel and text layouts, and synthetic-event injection." +description = "PlxNative stock-SDL shell: SDL bring-up, the window and GL context, the swap, the event drain, the key, pointer, wheel and text layouts of both SDLs (LG's fork on the television, stock SDL2 under hostsim), and synthetic-event injection." repository = "https://github.com/GLinnik21/plx-native" publish = false build = "build.rs" diff --git a/rust-modules/shell-sdl/src/event.rs b/rust-modules/shell-sdl/src/event.rs index f0e2013af1..205ce782cc 100644 --- a/rust-modules/shell-sdl/src/event.rs +++ b/rust-modules/shell-sdl/src/event.rs @@ -271,7 +271,7 @@ pub fn decode_wheel_dy(ev: &[u8]) -> i32 { /// An SDL pointer event's position, converted from window pixels to the authored 1920x1080 canvas. /// /// THE one place event coordinates enter the UI, so the conversion cannot be forgotten at a new -/// call site — there are nine, and patching them individually is how the tenth ends up wrong. +/// call site: `pointer_event` is the only caller, and a second one would have to convert for itself. /// `surface::to_logical` is the identity while the drawable is 1920x1080, which it is 1:1 unless /// a webOS 1-3 owner picks a smaller Interface resolution (or the debug drawable trigger asks for one). #[inline] diff --git a/rust-modules/shell-sdl/src/inject.rs b/rust-modules/shell-sdl/src/inject.rs index b033dfe087..52f41a024a 100644 --- a/rust-modules/shell-sdl/src/inject.rs +++ b/rust-modules/shell-sdl/src/inject.rs @@ -7,8 +7,8 @@ //! **A synthetic text event is never pushed**: see `text.rs`. `encode_event` builds the bytes and the //! application's `txt:` token hands them to the decode directly. //! -//! The encoders are pure and separate from the pushes that consume them, precisely so a host test -//! can run them: a `make check` test binary pushes nothing. +//! The encoders are pure and separate from the pushes that consume them, so their tests need no +//! queue; one test here does drive SDL's real queue (`EventsOnly`). use crate::event::{ push, rd_u32, SDL_KEYDOWN, SDL_KEYUP, SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP, SDL_MOUSEMOTION, SDL_MOUSEWHEEL, SYNTH_WINDOW, @@ -22,8 +22,8 @@ use std::os::raw::c_uint; /// wrote LG's fork layout while the reading end had been taught stock SDL2's. Nothing in the /// compiler couples them, so `key_bytes_round_trip` (in `event.rs`) is what does. /// -/// Pure, and separate from the `SDL_PushEvent` that consumes it, precisely so that test can run on -/// the host — `make check` links no SDL. +/// Pure, and separate from the `SDL_PushEvent` that consumes it, so that test needs no queue and +/// runs on any host. pub fn encode_key(sym: c_uint, wcode: c_uint, down: bool) -> [u8; 128] { let mut ev = [0u8; 128]; ev[0..4].copy_from_slice(&if down { SDL_KEYDOWN } else { SDL_KEYUP }.to_ne_bytes()); diff --git a/rust-modules/shell-sdl/src/lib.rs b/rust-modules/shell-sdl/src/lib.rs index a36cea0cb4..785a2c0dea 100644 --- a/rust-modules/shell-sdl/src/lib.rs +++ b/rust-modules/shell-sdl/src/lib.rs @@ -18,7 +18,7 @@ //! //! ## One crate, both SDLs //! -//! The television's SDL is a fork (LG's, 2.0.5-based) that lays its keyboard, text and wheel events +//! The television's SDL is a fork (LG's fork of SDL2) that lays its keyboard, text and wheel events //! out differently from the stock SDL2 a desktop links. The choice is `cfg!(feature = "hostsim")` //! and never `#[cfg]`, so both arms of every layout compile in every build and the one nobody is //! building cannot rot; the `hostsim` feature is forwarded from the application crate, which is the diff --git a/rust-modules/shell-sdl/src/sys.rs b/rust-modules/shell-sdl/src/sys.rs index 3d2f674c35..abc6a42016 100644 --- a/rust-modules/shell-sdl/src/sys.rs +++ b/rust-modules/shell-sdl/src/sys.rs @@ -51,7 +51,7 @@ extern "C" { // The system on-screen keyboard (`text`). The text-input family is stock public SDL2 API. // // Under `cfg(test)` and the `test-support` feature the four calls a host test could reach are -// swapped for `text::stubs`, so these declarations lose their last use there and warn; the +// swapped for `text::host_test_sdl`, so these declarations lose their last use there and warn; the // `allow(dead_code)` is narrower than it looks: a real orphan would be silent in every // configuration, and these are live on device. extern "C" { diff --git a/rust-modules/shell-sdl/src/text.rs b/rust-modules/shell-sdl/src/text.rs index 5d5d995860..2a0c8c7667 100644 --- a/rust-modules/shell-sdl/src/text.rs +++ b/rust-modules/shell-sdl/src/text.rs @@ -178,7 +178,7 @@ pub fn encode_event(text: &str) -> [u8; 128] { /// /// Pure, and offset-parameterised rather than reading [`TEXT_OFF`] itself, so `make check` can /// grade BOTH platforms' layouts on a host that only ever builds one of them — the same reason -/// `app::decode_key` and `app::encode_key` are pure and tested as a pair. +/// `event::decode_key` and `inject::encode_key` are pure and tested as a pair. /// /// Every failure mode here is a byte string somebody else chose: the panel's own IME writes this /// field, and the app cannot afford a panic inside the SDL event loop (see `remote.rs`, where @@ -272,7 +272,7 @@ mod tests { use super::*; /// A synthetic event in one platform's layout: type at +0, the text at `off`, NUL-terminated - /// if it fits. `[u8; 128]` because that is what `app.rs` polls into. + /// if it fits. `[u8; 128]` because that is what `event::poll` reads into. fn ev_with(off: usize, text: &[u8]) -> [u8; 128] { let mut ev = [0u8; 128]; ev[0..4].copy_from_slice(&0x303u32.to_ne_bytes()); // SDL_TEXTINPUT diff --git a/rust-modules/src/app/exit.rs b/rust-modules/src/app/exit.rs index a66d6f7f63..f0ff5bf38a 100644 --- a/rust-modules/src/app/exit.rs +++ b/rust-modules/src/app/exit.rs @@ -29,8 +29,8 @@ //! [`release_of`] that ends with `SDL_Quit()` (`NativeExit::Clean`), `Retained` is the arm that logs //! "SDL_Quit skipped" because a native worker is still inside firmware //! (`NativeExit::WorkerInFirmware`) and, for a refusal, "nothing was torn down". The executable -//! ignores it; a hosted entry maps `Retained` to `clean = 0`. Until the shell crate lands, `SDL_Quit` -//! IS the release of the window and the GL context, so `Complete` already means both. +//! ignores it; a hosted entry maps `Retained` to `clean = 0`. `Complete` means `Surface::quit` ran; +//! for the SDL shell that is `SDL_Quit`, which releases the window and the GL context. //! //! # The host doorway //! diff --git a/rust-modules/src/app/mod.rs b/rust-modules/src/app/mod.rs index 761e150d12..da3fc5dabc 100644 --- a/rust-modules/src/app/mod.rs +++ b/rust-modules/src/app/mod.rs @@ -1,6 +1,7 @@ -//! run_application — the Rust app core (was the body of src/main.c). Owns SDL init, the -//! event loop, input decode, the per-frame tick, draw orchestration, app lifecycle, -//! the buffer-feed pump orchestration, and the dev triggers. The C boot shim +//! run_application — the Rust app core (was the body of src/main.c). Drives SDL's bring-up through the +//! platform's `Shell` (the SDL work is `plx_shell_sdl`'s), the event loop, the `HostEvent` mapping, +//! the per-frame tick, draw orchestration, app lifecycle, the buffer-feed pump orchestration, and +//! the dev triggers. The C boot shim //! (main.c) sets up the log and fallback crash tracer, calls the Rust image-marker and native-spool //! entries when required, then calls `plex_run` (port.rs), which hands over to `run_application` //! and, when it returns its `Exit` (`exit.rs`), ends the process. The desktop executable diff --git a/rust-modules/src/system.rs b/rust-modules/src/system.rs index b4d6ea14b0..c7fbd42b72 100644 --- a/rust-modules/src/system.rs +++ b/rust-modules/src/system.rs @@ -7,7 +7,7 @@ use std::os::raw::{c_int, c_uint, c_void}; const SDL_GL_ALPHA_SIZE: c_int = 3; // SDL_GLattr: RED=0,GREEN=1,BLUE=2,ALPHA=3 -/// `SDL_GL_DEPTH_SIZE` / `SDL_GL_STENCIL_SIZE` — same enum, 6 and 7. `app.rs` asks for zero of +/// `SDL_GL_DEPTH_SIZE` / `SDL_GL_STENCIL_SIZE` — same enum, 6 and 7. `plx_shell_sdl::init` asks for zero of /// both; these read back what the driver actually granted, which is the only thing that settles it. const SDL_GL_DEPTH_SIZE: c_int = 6; const SDL_GL_STENCIL_SIZE: c_int = 7; @@ -142,7 +142,7 @@ pub(crate) fn sys_grab_wayland(winp: *mut c_void) { // television's ES2 context, the only one this runs on, both are legal. glGetIntegerv(GL_DEPTH_BITS, &mut dbits); glGetIntegerv(GL_STENCIL_BITS, &mut sbits); - // `depth=`/`stencil=` are here to be READ: `app.rs` asks for zero of each because nothing + // `depth=`/`stencil=` are here to be READ: `plx_shell_sdl::init` asks for zero of each because nothing // in this renderer uses them, and on a tiler a granted depth buffer is a per-frame // write-back of 1920x1080x2 bytes nobody consumes. A non-zero here means the driver // refused and the saving is not real. diff --git a/rust-modules/src/textinput.rs b/rust-modules/src/textinput.rs index 3008c8e651..1354f37947 100644 --- a/rust-modules/src/textinput.rs +++ b/rust-modules/src/textinput.rs @@ -12,8 +12,8 @@ //! `Wayland_CreateDevice` writes four real hooks into `SDL_VideoDevice` //! (`WebOSHasScreenKeyboardSupport`, `Show`, `Hide`, `IsShown`), `SDL_StartTextInput` dispatches to //! the second, and `WebOSShowScreenKeyboard` is a complete `text_model` IME client. Typed text -//! comes back as an ordinary `SDL_TEXTINPUT` event, so `app.rs`'s existing `SDL_PollEvent` loop -//! already sees it. moonlight-tv 1.5.8 shipped exactly this against the TV's own SDL. +//! comes back as an ordinary `SDL_TEXTINPUT` event, so the existing `SDL_PollEvent` loop +//! (`plx_shell_sdl::event`) already sees it. moonlight-tv 1.5.8 shipped exactly this against the TV's own SDL. //! //! Linking is the plain `extern "C"` case (declared in `plx_shell_sdl`'s `sys.rs`), not `dynlib!`: all 14 //! firmware images in `tools/fwcompat.py`'s inventories export the whole `SDL_*TextInput*` family. That says nothing @@ -60,7 +60,7 @@ //! libSDL3**, and SDL3's text event carries a `char *text` POINTER where SDL2's carries an inline //! `char text[32]`; the compat layer dereferences it while converting the pushed event. Keys and //! pointer clicks survive the same trip only because every field they use is a scalar. So -//! `app.rs`'s `txt:` token drives [`on_event`] directly, and what it proves stops one step short +//! the application's `txt:` token drives [`on_event`] directly, and what it proves stops one step short //! of `SDL_PollEvent`'s own delivery. //! //! Two dead ends, so nobody spends a day on them again: the Luna route (only four @@ -322,7 +322,7 @@ mod tests { static BUF: Mutex<()> = Mutex::new(()); /// A synthetic event in one platform's layout: type at +0, the text at `off`, NUL-terminated - /// if it fits. `[u8; 128]` because that is what `app.rs` polls into. + /// if it fits. `[u8; 128]` because that is what `plx_shell_sdl::event::poll` reads into. fn ev_with(off: usize, text: &[u8]) -> [u8; 128] { let mut ev = [0u8; 128]; ev[0..4].copy_from_slice(&0x303u32.to_ne_bytes()); // SDL_TEXTINPUT diff --git a/rust-modules/ui/src/consts.rs b/rust-modules/ui/src/consts.rs index fe4d104344..69a25e4a3d 100644 --- a/rust-modules/ui/src/consts.rs +++ b/rust-modules/ui/src/consts.rs @@ -315,9 +315,9 @@ pub enum Key { /// After the directions the order is the ladder's own — pointer, OK, PAUSE, PLAY, STOP, BACK. The /// two alternate D-pad codes are resolved up here beside the plain ones rather than down where the /// scrub arm tests them, so a pair carrying one of those AND a transport code resolves as the -/// direction rather than as the transport key. Both fields describe ONE press — `app.rs`'s -/// `decode_key` reads them off a single event and its `remote_token_key` builds each synthetic -/// pair from a single token — so a pair naming two DIFFERENT keys is not a shape either path is +/// direction rather than as the transport key. Both fields describe ONE press — the shell's +/// `plx_shell_sdl::event::decode_key` reads them off a single event and the application's `remote_token_key` builds each +/// synthetic pair from a single token — so a pair naming two DIFFERENT keys is not a shape either path is /// built to carry; the order above settles it rather than leaving it to whichever test came first. pub fn classify(sym: c_uint, wcode: c_uint) -> Key { match sym { @@ -464,7 +464,7 @@ pub fn page_dir(sym: c_uint, wcode: c_uint) -> Option { /// number buttons ([`pin_digit`], which owns that behaviour). /// /// **The `sym` field ONLY, and that is a deliberate divergence from [`pin_digit`], which also reads -/// the range out of `wcode`.** `wcode` is a SCANCODE (`app.rs::decode_key`), and 48–57 there are +/// the range out of `wcode`.** `wcode` is a SCANCODE (`plx_shell_sdl::event::decode_key`), and 48–57 there are /// not digits at all: they are `]` `\` `#` `;` `'` `` ` `` `,` `.` `/` and CapsLock. The digits' /// scancodes are 30–39 — which is exactly why 33/34 turned out to be `4` and `5` a few dozen lines /// up. Mirroring [`pin_digit`] would put the retired mis-reading straight back into the gate this From 1650db6be078ee76cb63c95a68fc99b991240ab4 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 20:59:39 +0300 Subject: [PATCH 4/6] The simulator build no longer fails on the window height only the television's request reads `SCR_H` is read by the television's window request in `boot.rs` and by its tests. The desktop sizing that used to read it left for `plx_shell_sdl`, so in the one build that has neither (the simulator, `hostsim` without `cfg(test)`) it was a dead constant, and `-D warnings` made that an error in `make sim-macos`. `make lint`, the unit passes and `make check-nodef` all build with it live, which is why only the simulator link noticed. The constant now exists where it has a reader. Co-Authored-By: Claude --- rust-modules/src/app/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/rust-modules/src/app/mod.rs b/rust-modules/src/app/mod.rs index da3fc5dabc..799b933015 100644 --- a/rust-modules/src/app/mod.rs +++ b/rust-modules/src/app/mod.rs @@ -51,6 +51,8 @@ use plx_ui::consts::{ }; // The window we ASK SDL for. `surface::probe` then reads back what we actually got. const SCR_W: c_int = plx_base::surface::LOGICAL_W as c_int; +// Read only by the television's window request (`boot.rs`): the desktop's own sizing is `plx_shell_sdl`'s. +#[cfg(any(not(feature = "hostsim"), test))] const SCR_H: c_int = plx_base::surface::LOGICAL_H as c_int; pub(crate) const COLS: c_int = 10; From 8b534a62275fd418168ec6763ba0173f6577a259 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 23:55:58 +0300 Subject: [PATCH 5/6] SCR_W is gated like SCR_H, so no hostsim build carries it as a dead constant SCR_W was ungated, and its last non-test hostsim readers (`plan_desktop_window` and `desktop_window_ask`) moved to `plx_shell_sdl::window`. What still read it was the fps digits in `run.rs`, which sit under `devtools`, so every hostsim build without `devtools` had a dead constant, and `-D warnings` made that an error in the three jobs that build that feature set (`cargo check --lib --no-default-features --features hostsim,play-feed`, the macOS app's link line, and the HUD authoring simulator's build). `make sim-macos` builds with devtools and the unit passes with `cfg(test)`, so neither showed it. The fps digits now read `plx_base::surface::LOGICAL_W` directly, the logical width they are placed against, and `SCR_W` takes the gate `SCR_H` already has (`any(not(feature = "hostsim"), test)`): both are read only by the television's window request in `boot.rs`, so they now share one rule. The television build's values are unchanged. The `#[allow(dead_code)]` note on `glDeleteTextures` in `plx_gfx` cited the SDL text-input externs in `app/mod.rs`; they live in `plx_shell_sdl`'s `sys.rs` now, and the note says so. Co-Authored-By: Claude --- rust-modules/gfx/src/gfx.rs | 2 +- rust-modules/src/app/mod.rs | 4 +++- rust-modules/src/app/run.rs | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/rust-modules/gfx/src/gfx.rs b/rust-modules/gfx/src/gfx.rs index 177e13c46f..b20e289972 100644 --- a/rust-modules/gfx/src/gfx.rs +++ b/rust-modules/gfx/src/gfx.rs @@ -328,7 +328,7 @@ extern "C" { #[cfg(feature = "devtriggers")] fn glFlush(); fn glGenTextures(n: c_int, textures: *mut c_uint); - // `#[allow(dead_code)]` — the same shape as `app/mod.rs`'s SDL text-input externs: the sole + // `#[allow(dead_code)]` — the same shape as `plx_shell_sdl`'s SDL text-input externs (`sys.rs`): the sole // caller (`delete_tex`, below) compiles its real call out under `cfg(test)`, so this // declaration loses its only use in the TEST build alone and warns there. It stays live on // device and in the simulator, where `delete_tex` still calls it for real. diff --git a/rust-modules/src/app/mod.rs b/rust-modules/src/app/mod.rs index 799b933015..657912679a 100644 --- a/rust-modules/src/app/mod.rs +++ b/rust-modules/src/app/mod.rs @@ -50,8 +50,10 @@ use plx_ui::consts::{ WCODE_POINTER_HIDDEN, }; // The window we ASK SDL for. `surface::probe` then reads back what we actually got. +// Both are read only by the television's window request (`boot.rs`): the desktop's own sizing is +// `plx_shell_sdl`'s, so a hostsim build has no reader of either and they share one gate. +#[cfg(any(not(feature = "hostsim"), test))] const SCR_W: c_int = plx_base::surface::LOGICAL_W as c_int; -// Read only by the television's window request (`boot.rs`): the desktop's own sizing is `plx_shell_sdl`'s. #[cfg(any(not(feature = "hostsim"), test))] const SCR_H: c_int = plx_base::surface::LOGICAL_H as c_int; pub(crate) const COLS: c_int = 10; diff --git a/rust-modules/src/app/run.rs b/rust-modules/src/app/run.rs index a7a2b17b91..2ef8d7fb06 100644 --- a/rust-modules/src/app/run.rs +++ b/rust-modules/src/app/run.rs @@ -3394,7 +3394,7 @@ pub(crate) unsafe fn draw(app: &mut App, fr: &mut Frame) -> (i32, i32, i32, i32) }; plx_gfx::gfx::draw_number( *fps_shown, - SCR_W as f32 - 70.0, + plx_base::surface::LOGICAL_W - 70.0, 64.0, 46.0, fps_col.as_ptr(), From 3cec9e3f785222c980a3b794ab66d075e53b8770 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Sat, 21 Nov 2026 00:42:19 +0300 Subject: [PATCH 6/6] plx_shell_sdl's SDL symbol claim names its one exception, and its LG-half pin covers the names it forbids `sys.rs` said every SDL2 symbol the crate calls is exported by all 14 firmware inventories. `tools/fwcompat.py --lib libSDL2-2.0.so.0` shows 23 of the 24 names it declares in 1.2.0 through 3.9.2 and all 24 from 4.4.2: the missing one is `SDL_GetDisplayUsableBounds`, which is declared under `cfg(feature = "hostsim")` only, so the ARM binary never imports it (it imports none of the three hostsim names). The sentence now covers the names declared outside the hostsim block and names that one as the exception. The `lib.rs` pin that keeps the Wayland and Luna half out of this crate checked four names (`wl_proxy`, `wl_display`, `LSRegister`, `g_main_context`), so a call into the LG fork or a Luna call by another name would have passed it. It now also forbids `wl_surface`, `LSCall`, `SDL_webOS` and `HELPER_`, and the pin on the over-writing `SDL_SysWMinfo` query also forbids `SDL_GetVersion`, the handshake that lives in the application crate's `system.rs`. None of the new names appears in the crate today, and each was made to fail the pin by writing it into `event.rs` once, then removed again. Co-Authored-By: Claude --- rust-modules/shell-sdl/src/lib.rs | 31 +++++++++++++++++++++++-------- rust-modules/shell-sdl/src/sys.rs | 8 +++++--- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/rust-modules/shell-sdl/src/lib.rs b/rust-modules/shell-sdl/src/lib.rs index 785a2c0dea..507abe9c38 100644 --- a/rust-modules/shell-sdl/src/lib.rs +++ b/rust-modules/shell-sdl/src/lib.rs @@ -71,21 +71,36 @@ mod pins { /// struct on the stack is the "modular-split crash" and the over-allocated buffer with its /// version handshake lives in the application crate's `system.rs`, beside the rest of the LG /// half. Nothing in this crate may call it: not for the window, not for a size, not "just to - /// read the display". + /// read the display". The SDL version query that handshake is built on belongs to the same + /// half and is pinned with it. #[test] fn this_crate_never_calls_the_wayland_info_query() { - let needle = concat!("SDL_GetWindow", "WMInfo"); - for (name, text) in SOURCES { - assert!(!text.contains(needle), "{name} names the television's over-writing query"); + for needle in [concat!("SDL_GetWindow", "WMInfo"), concat!("SDL_Get", "Version")] { + for (name, text) in SOURCES { + assert!(!text.contains(needle), "{name} names {needle}, the television's over-writing query or its handshake"); + } } } - /// The crate links SDL plainly (`sys.rs`), and it must not grow a Wayland or glib call of its - /// own: those are the television's half and are fenced to the webOS platform by - /// `ci/check-module-layers.py`, which cannot see an `extern` block. + /// The crate links SDL plainly (`sys.rs`), and it must not grow a Wayland, glib or LG-fork call + /// of its own: those are the television's half and are fenced to the webOS platform by + /// `ci/check-module-layers.py`, which cannot see an `extern` block. The needles are the + /// Wayland proxy, display and surface names, the Luna register and call families, glib's main + /// context, and the LG fork's own webOS-prefixed SDL entry points and helper-prefixed bridge + /// names; each is split so this file, which the scan reads too, does not name the thing it + /// forbids. #[test] fn this_crate_names_no_wayland_or_luna_symbol() { - for needle in [concat!("wl_", "proxy"), concat!("wl_", "display"), concat!("LS", "Register"), concat!("g_main_", "context")] { + for needle in [ + concat!("wl_", "proxy"), + concat!("wl_", "display"), + concat!("wl_", "surface"), + concat!("LS", "Register"), + concat!("LS", "Call"), + concat!("g_main_", "context"), + concat!("SDL_", "webOS"), + concat!("HELPER", "_"), + ] { for (name, text) in SOURCES { assert!(!text.contains(needle), "{name} names {needle}"); } diff --git a/rust-modules/shell-sdl/src/sys.rs b/rust-modules/shell-sdl/src/sys.rs index abc6a42016..8d82a472c3 100644 --- a/rust-modules/shell-sdl/src/sys.rs +++ b/rust-modules/shell-sdl/src/sys.rs @@ -1,7 +1,9 @@ //! Every SDL2 symbol this crate calls, declared once. A PLAIN link, not `dynlib!`: the rule in -//! `plx_base::dynlib` is for libraries whose SONAME moves, and these are stock public SDL2 API that -//! every firmware inventory exports (`tools/fwcompat.py --lib libSDL2-2.0.so.0` finds the whole -//! family on all 14 images), so there is nothing here for a runtime bind to tolerate. +//! `plx_base::dynlib` is for libraries whose SONAME moves, and these are stock public SDL2 API: +//! every name declared outside the `hostsim` block is exported by all 14 firmware inventories +//! (`tools/fwcompat.py --lib libSDL2-2.0.so.0`), so there is nothing here for a runtime bind to +//! tolerate. The one `hostsim` name the inventories do not all carry is `SDL_GetDisplayUsableBounds`: +//! 1.2.0 through 3.9.2 lack it and 4.4.2 onward have it, and the ARM binary never imports it. //! //! The Wayland and `SDL_SysWMinfo` calls are NOT here and never may be: the television's SDL fork //! writes a larger `SDL_SysWMinfo` than the headers declare, and that over-allocated buffer