From 7b8e55e37dab73fa04cca5ce938d28fe9cea4cde Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 10:14:52 +0300 Subject: [PATCH 1/4] Split tv::Port into tv::Services; the window, bus and frame probes move to app::Platform The 27 fields of plx_os::tv::Port were one flat table that three kinds of reader shared: the lower layers that ask the platform who it is and where credentials go, the loop that drives the window, and the dev frame probe. W2 of the platform plan regroups it by who reads what, with no behaviour change. plx_os::tv::Services holds four groups of hooks, each with a named NONE and every hook required: - identity: probe_device, start_capability_probe, repair_sandbox, system_locale, sound_output. - secure: seal, open, remove and the once-set StoreMode (the separate OnceLock and publish_mode are gone; secure::mode() still answers the same). - system: go_home, poll_home, deliver_toast. - legacy_webos_media: sink, display_sink, uri_media, which stays at the media NONE until W6b. Services::HOST_TEST replaces ABSENT and a host test pins every answer. The table is still installed once through a OnceLock and read only by tv's own modules through a private accessor. The seven window and bus entries and the six frame_probe_* entries leave plx_os. tv/window.rs is deleted. app::platform defines the app-private Shell and FrameProbe traits and Platform { services, shell, diag }, with Platform::HOST_TEST for a process with no platform. port.rs builds the webOS Platform (its Shell and FrameProbe forward to crate::system as before) and installs it first thing in plex_main; app/boot.rs and app/run.rs read the shell and the probe through platform(). Platform carries no MediaBoot yet; that is W6b. Gates follow the move. ci/check-deps.sh's frame gate now pins the call text of the three privileged shell calls (pump_bus, opaque_route, clear_opaque_region) to app/run.rs by receiver, trait path and chain continuation, and tests/test_harness.py proves it rejects a new call site and ignores a Rig forward, a string and a comment. app/exit.rs's scan of port.rs now also asserts `fn plex_run(` and `fn plex_main(` each occur exactly once in the comment-stripped file, with fixtures showing a second cfg-gated definition is refused. The #1479 const proof and the fnlen budgets are unchanged, and no ledger line under ci/allow/ is added. Co-Authored-By: Claude --- ci/check-deps.sh | 28 ++- docs/agent-reference.md | 2 +- docs/module-layers.md | 28 +-- rust-modules/os/src/tv.rs | 219 ++++++++++++++++------- rust-modules/os/src/tv/home.rs | 4 +- rust-modules/os/src/tv/sandbox.rs | 2 +- rust-modules/os/src/tv/secure.rs | 25 +-- rust-modules/os/src/tv/sink.rs | 4 +- rust-modules/os/src/tv/sound.rs | 2 +- rust-modules/os/src/tv/toast.rs | 2 +- rust-modules/os/src/tv/uri.rs | 2 +- rust-modules/os/src/tv/window.rs | 72 -------- rust-modules/os/src/webos.rs | 2 +- rust-modules/plex/src/plex/CLAUDE.md | 2 +- rust-modules/src/app/adapters/hostsim.rs | 2 +- rust-modules/src/app/boot.rs | 12 +- rust-modules/src/app/bridge.rs | 6 +- rust-modules/src/app/exit.rs | 114 +++++++++--- rust-modules/src/app/mod.rs | 1 + rust-modules/src/app/platform.rs | 165 +++++++++++++++++ rust-modules/src/app/run.rs | 46 ++--- rust-modules/src/port.rs | 134 ++++++++++---- tests/test_harness.py | 37 ++++ 23 files changed, 626 insertions(+), 285 deletions(-) delete mode 100644 rust-modules/os/src/tv/window.rs create mode 100644 rust-modules/src/app/platform.rs diff --git a/ci/check-deps.sh b/ci/check-deps.sh index 7eab075634..effc441aba 100755 --- a/ci/check-deps.sh +++ b/ci/check-deps.sh @@ -129,8 +129,8 @@ SRC=rust-modules/src # of a gate. A rule scoped to a directory of $SRC (ui/, screens/, app/ ...) cannot reach a layer # below them and stays as it is, UNLESS the files it policed there were moved out: `machine` came # from ui/, so the rules that read `ui/` read $SRC_MACHINE too, and `ui` is $SRC_UI now (docs/module-layers.md, Split 6). `os` is the layer that held -# `tv/` and `storage/`, and the rules that name a moved module by path (`crate::tv::window::`, -# `crate::storage::`) now spell it `plx_os::`. `gfx` held `text.rs`, the one file the textmeasure +# `tv/` and `storage/`, and the rules that name a moved module by path (`crate::storage::`) +# now spell it `plx_os::`. `gfx` held `text.rs`, the one file the textmeasure # rule exempts, and the rule's pattern now accepts `plx_gfx::text::`. `net` held the loopback fixtures # the `threads` gate skips as test code; they are `cfg(any(test, feature = "test-support"))` now, # which it accepts. @@ -1082,13 +1082,25 @@ want ladder && gate_zero ladder 'fn move_focus|fn pointer_focus|fn top_focus|fn # resume_at/memory_at/open_settings_at/write_at, which are unrelated lookups. want hittest && gate_zero hittest 'pointer_focus\(|\b(failure_quality|icon|scrub)_hit\(' "$SRC/app" -# frame: the three privileged OS-primitive calls, ZERO-TOLERANCE outside `app/run.rs` (D4) — no -# allowlist file, because there is exactly one legitimate home once D1 lands: `app/run.rs` is the -# frame loop, and `app/bridge.rs`'s `Rig` impl delegates to `run::rig_opaque_route`/ -# `rig_clear_opaque_region` (a one-line pass-through) rather than naming `plx_os::tv::window::` itself, +# frame: the three privileged OS-primitive calls — `pump_bus`, `opaque_route` and `clear_opaque_region` +# on the platform's `Shell` (`app::platform`, installed by `port.rs`) — ZERO-TOLERANCE outside +# `app/run.rs` (D4) — no allowlist file, because there is exactly one legitimate home once D1 lands: +# `app/run.rs` is the frame loop, and `app/bridge.rs`'s `Rig` impl delegates to `run::rig_opaque_route`/ +# `rig_clear_opaque_region` (a one-line pass-through) rather than naming the `shell` itself, # which is what keeps this gate's text out of bridge.rs without splitting the `impl Rig # for Bridge` block (a trait's impl for a type is one syntactic unit; it carries two dozen other -# methods beside these three). A self-test that spells two of the three call shapes as STRING +# methods beside these three). +# +# The method names alone are NOT the pin: `Rig` has `opaque_route` and `clear_opaque_region` too, and +# `Bridge`'s forwarding (`self.bridge.opaque_route(..)`) is not an OS call. So the pin is the RECEIVER: +# a call on something named `shell` (`platform().shell.pump_bus()`, `p.shell.opaque_route(..)`), on the +# trait by path (`Shell::pump_bus(..)`, `::pump_bus(..)`), or a continuation line of a +# chain that begins on the line before (`.pump_bus(`, which rustfmt may break out of +# `platform().shell`). A shell held in a differently named local does not match: this is a text gate +# on the loop's own call shape, and the no-op `Platform::HOST_TEST` shell is driven that way by its pin +# test. +# +# A self-test that spells two of the three call shapes as STRING # LITERALS — it reads app/run.rs's own source text at runtime and compares against a copy of the # exact line it expects, which is data, not a call (`app/run.rs`'s own `video_plane_gate_tests` # today, `machine/src/idle.rs`'s before the machine layer left `ui/`) — must not trip this gate in any file @@ -1096,7 +1108,7 @@ want hittest && gate_zero hittest 'pointer_focus\(|\b(failure_quality|icon|scrub # double-quote-depth tracking `tmppath` below uses), rather than exempting files by name: an # actual call typed outside a string still fails this gate. `// `-prefixed comment lines (`app/run.rs` keeps one, describing where a call # used to live) are stripped the same way `grep_code` above does for every other rule. -frame_pat='(crate|plx_os)::tv::window::(pump_bus|opaque_route|clear_opaque_region)\(' +frame_pat='(^|[^A-Za-z0-9_])shell[[:space:]]*\.[[:space:]]*(pump_bus|opaque_route|clear_opaque_region)[[:space:]]*\(|Shell>?::(pump_bus|opaque_route|clear_opaque_region)[[:space:]]*\(|^[[:space:]]*\.[[:space:]]*(pump_bus|opaque_route|clear_opaque_region)[[:space:]]*\(' if want frame; then frame_bad=0 while IFS= read -r f; do diff --git a/docs/agent-reference.md b/docs/agent-reference.md index 15db8fcdde..f1c1556010 100644 --- a/docs/agent-reference.md +++ b/docs/agent-reference.md @@ -1138,7 +1138,7 @@ Two planes are composited by the TV: the app's **GLES/graphics plane** (UI, draw over the hardware **VIDEO overlay plane** (decoded frames). The UI plane is made non-opaque so video shows through. -**UI (the Rust app core — the frame loop in `app/run.rs::run`, entered via `plex_run()` in `port.rs`, which installs the port and runs `app::run_application`, after `app/boot.rs::boot()`):** SDL2 window + GLES2 +**UI (the Rust app core — the frame loop in `app/run.rs::run`, entered via `plex_run()` in `port.rs`, which installs the platform (`app::platform::install`) and runs `app::run_application`, after `app/boot.rs::boot()`):** SDL2 window + GLES2 context. All UI is drawn with two tiny shaders — an SDF rounded-rect/triangle shader (cards, focus 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 diff --git a/docs/module-layers.md b/docs/module-layers.md index 566838556b..8d9018a7ae 100644 --- a/docs/module-layers.md +++ b/docs/module-layers.md @@ -330,9 +330,9 @@ proves the references are gone and nothing more; L15b is open. | **L12** media owns its lifecycle seams — **done** | 7 / 28 | The foreground-resume machine is `player::lifecycle`, its drivers `player::foreground` and the transport-pause contract `player::transport` (`app::lifecycle` re-exports them), the stats switch is `player::DIAG_READOUT_ON`, `Venc::open` takes the capture socket writer as an argument, and `route` takes the HUD context line as a parameter, with the up-next still prefetch a hook the app installs. | | **L13** tests move up to the layer that owns their parts — **done** | 41 / 96 | Part a moved the auth, plex, i18n, task and fontcov tests that named upper layers to `app/` (`session_*_tests.rs`), `screens/login_text_fit_tests.rs`, `plex`, `auth::owner` and `storage::client`, and moved `fontcov`'s `Measure` impl beside the trait, with `ui::machine`'s new `BareArg`/`BareMeasure` fixtures for the rest; part b moved the data, media and ui ones to `app/` (`dispatch_return_tests.rs`, `overscan_audit_tests.rs`) and `screens/` (`plaintext_question`, `library/labels_tests.rs`, `search/tests.rs`, `player`), and rewrote two against their own layer. | | **L14** session-layer presentation to screens — **done** | 2 / 4 | `auth::signed_in_reason` is a private fn of `screens::login`, its only caller, with its two tests; `auth` already handed over the plain account name. | -| **L15** the webOS port — **gate-complete** | 44 / 205 | Everything outside `[platform webos]` reaches the television through the `tv` interfaces in `os` that the port fills at boot: `tv::{device, sandbox, secure, home, toast, window}`, `devcaps::dv`, and `tv::sink::VideoSink`, a Starfish-shaped verb trait that `plx_os::webos::video_sink::StarfishSink` and `plx_play_feed::ffi_host::HostSink` implement. `plex_run` is `port::plex_run`. The allowlist is empty. Not "done": the sink is not OS-neutral and the simulator is not its own port (L15b). | +| **L15** the webOS port — **gate-complete** | 44 / 205 | Everything outside `[platform webos]` reaches the television through the `tv` interfaces in `os` that the port fills at boot: `tv::{device, sandbox, secure, home, toast}` (the window, the bus pump and the frame probe are `app::platform`'s `Shell` and `FrameProbe` since W2), `devcaps::dv`, and `tv::sink::VideoSink`, a Starfish-shaped verb trait that `plx_os::webos::video_sink::StarfishSink` and `plx_play_feed::ffi_host::HostSink` implement. `plex_run` is `port::plex_run`. The allowlist is empty. Not "done": the sink is not OS-neutral and the simulator is not its own port (L15b). | | **L15b** the OS-neutral port — **open** | — | An OS-neutral video sink with the ACB bind sequence behind it, the simulator as its own port, and the webOS facts the gate cannot see. See below. | -| **L15c** the platform value and the three contracts — **planned** | — | Wave R (the rename that gave this page `os` and `[platform webos]`) landed as #1474; what is planned is W2 (`tv::Port` becomes `tv::Services`; the shell and the frame probes move to `app::Platform`) and W3a to W3c: who may persist credentials, what evidence admits a URI player, who ends the process. See "L15c to L15h" below. | +| **L15c** the platform value and the three contracts — **planned** | — | Wave R (the rename that gave this page `os` and `[platform webos]`) landed as #1474; W2 has landed (`tv::Port` became `tv::Services`, with four groups of hooks; the shell and the frame probes moved to `app::Platform`), and what is planned is W3a to W3c: who may persist credentials, what evidence admits a URI player, who ends the process. See "L15c to L15h" below. | | **L15d** neutral types and the simulator as its own platform (L15b item 2) — **planned** | — | W3d (the opaque `Backend` tag, `sandbox` to `native_video`, identity publishes a platform name and version, `device::Info` loses its webOS fields) and W4 (a second fence section, `[platform desktop]`, with its own value; the simulator's host arms leave `system` and `port`, the other `hostsim` terms of the fence go, and the simulator's stand-ins in `webos` and `keymanager` stay, compiled for tests and `test-support`: `docs/platform-ports.md`, W4). The desktop platform is the second implementation. | | **L15e** events, the shell and composition — **planned** | — | W5 (`HostEvent` with `Option`), W6b (platform-supplied composition in two boot phases), W6 (`plx_shell_sdl`, a `[shell_sdl]` layer) and W6c (a URI-only and a two-driver composition play an ordinary title). | | **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. | @@ -350,9 +350,9 @@ L15's 44 entries, 205 references of which 95 were in production code. The port's their layers, so none of this held up the split. L15 moved every one of those references behind an interface in `os`'s new `tv` module that -the port fills at boot. `tv::Port` is a table of function pointers, installed once as the first -statement of `port::plex_run`, before anything that reads it. With no port installed (host unit -tests, where nothing calls `plex_run`) `tv::ABSENT` answers what the host arms answered before; a +the port fills at boot. `tv::Services` is a table of function pointers in four groups (`identity`, `secure`, `system` and `legacy_webos_media`), installed once as the first +statement of `port::plex_main`, through `app::platform::install`, before anything that reads it. With nothing installed (host unit +tests, where nothing calls `plex_run`) `tv::Services::HOST_TEST` answers what the host arms answered before; a shipping build that reaches it logs `tv: port not installed - using the no-port defaults` once. Only `tv`'s own modules read the table. Two things leave it: the sink, through `tv::sink::installed()` (rule `sink` of `ci/check-deps.sh` fences naming `VideoSink` or `installed` to `media`'s @@ -371,17 +371,17 @@ published values rather than hooks: the webOS code writes them into `tv::device` | device identity | `tv::device::{info, device, Info, Hardware}`, published by `webos::probe` | `telemetry`, `diag::schema`, `plex::identity`, `plex::session`'s tests, `screens::login`, `lab::snapshot`, `app`, `player` | | playback capability | `devcaps::dv::{capability, probe, DvCapability}`, published by `webos::caps`; `tv::start_capability_probe` starts the probe | `metadata`, `route`, `player::engine`, `app` | | native-video availability and repair | `tv::sandbox::{blocks_native_video, context, repair, Verdict, State, Failure, FORCE_BLOCKED}`; the verdict is published by `webos::probe` and the repair is a port hook | `player`, `route`, `appkit::player_hud`, `screens::player`, `app::playback` | -| video sink | `tv::sink::VideoSink`, implemented by `plx_os::webos::video_sink::StarfishSink` and `HostSink` (`plx_play_feed::ffi_host`), installed in `Port.sink` and read through `tv::sink::installed` | `player::{adapter, test_physical}`, `plx_play_feed::{native_executor, native_load, physical, seek}` (which receive it injected), `app::adapters::backends` (which resolves `installed` and `display_installed`) | +| video sink | `tv::sink::VideoSink`, implemented by `plx_os::webos::video_sink::StarfishSink` and `HostSink` (`plx_play_feed::ffi_host`), installed in `Services.legacy_webos_media.sink` and read through `tv::sink::installed` | `player::{adapter, test_physical}`, `plx_play_feed::{native_executor, native_load, physical, seek}` (which receive it injected), `app::adapters::backends` (which resolves `installed` and `display_installed`) | | secure store | `tv::secure::{seal, open, remove, Sealed, Backend}` | `plex::session` | | storage backend | `storage::client::install_activator`, which the port calls with `webos::activate_storage_helper` | `port::plex_run` | | locale | `tv::system_locale` and `tv::LocaleReply`; `i18n` still owns the parse and the log lines | `i18n` | -| sound output | `tv::sound::{output, parse_output, Reply}`, filled by `Port.sound_output` (`webos::sound_output`); a blocking read, so never on the frame thread, and asked only on a stack whose lead follows the output (`liblxa` and 2018's `audiosink_new`; `devcaps::audio_stack`; the `lgaudiosink` stack's lead does not depend on the output, and the others have none, so they never ask) | `player::threads` (through `player::engine`, which owns the lead table) | -| window, surface, video plane, bus pump and frame probe | `tv::window` | `app::boot`, `app::run`, `app/mod.rs` | +| sound output | `tv::sound::{output, parse_output, Reply}`, filled by `Services.identity.sound_output` (`webos::sound_output`); a blocking read, so never on the frame thread, and asked only on a stack whose lead follows the output (`liblxa` and 2018's `audiosink_new`; `devcaps::audio_stack`; the `lgaudiosink` stack's lead does not depend on the output, and the others have none, so they never ask) | `player::threads` (through `player::engine`, which owns the lead table) | +| window, surface, video plane, bus pump and frame probe | `app::platform::{Shell, FrameProbe}`, in the application crate beside the loop that is their one consumer; `port.rs` implements them over `crate::system` | `app::boot`, `app::run` | | home key | `tv::home::{go_home, poll, take_root_press, release_root_press}` | `app::input`, `app::run`, `app::adapters::session`, `app::lifecycle`'s tests | | system toast | `tv::toast::{toast, send, Identity, Outcome, Sent}` | `app::clock_notice`, `dev::scenarios::toast_probe` | -`tv` may name only `base`, `machine` and `os`. `port.rs` holds `plex_run` and the `PORT` table -that points each hook at the `webos`, `keymanager` and `system` function behind it. The C shim and +`tv` may name only `base`, `machine` and `os`. `port.rs` holds `plex_run` and the `SERVICES` and `PLATFORM` tables +that point each hook at the `webos`, `keymanager` and `system` function behind it. The C shim and the simulator both enter through `port::plex_run`: it calls `app::run_application`, which returns how the session ended as an `Exit` (a status and whether the teardown released everything), and then ends the process with that status. `lib.rs` declares the port but re-exports nothing from it, because a re-export would @@ -412,7 +412,7 @@ order or its interleaving, and its log lines are graded on the television. A ver can be graded by comparing the television's log before and after; a redesign that changes where those stages run, and when, is its own step's scope and risk. -The simulator runs the same table. Under `hostsim` `port.rs` installs a `PORT` whose fields point +The simulator runs the same tables. Under `hostsim` `port.rs` installs a `SERVICES` and a `PLATFORM` whose fields point at the same `webos`, `keymanager` and `system` functions, whose `hostsim` arms answer on the host, and whose sink is `HostSink`. So the simulator behaves as it did, but it is not yet a second implementation of the interfaces. @@ -476,7 +476,7 @@ the migration table can carry them (L15b's three items keep their meaning and ar and L15h for item 1). Prose on this page written before Wave R says "port" where the plan says platform; the fence section is `[platform X]`, and the plan calls its crates `plx_platform_webos`, `plx_platform_desktop` and `plx_platform_tizen`. Where L15b above speaks of a second `Port` table, the plan's shape is `tv::Services` plus -`app::Platform` (W2). +`app::Platform` (W2, landed). 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 @@ -741,8 +741,8 @@ suite is 5603 tests before and after (157 + 66 + 218 + 5162). What it taught bey any split that moves FFI when no NDK is at hand. - **Gates scoped by the path of a moved file stopped seeing it, and some by its spelling.** `ci/check-deps.sh` reads `SRC_OS` where it read `SRC_MACHINE`; the `frame` and `uistorage` - rules name a moved module as `crate::tv::window::` and `crate::storage::`, which would have kept - passing while matching nothing, so they accept `plx_os::` too; the `sink` gate exempts + rules named a moved module as `crate::tv::window::` and `crate::storage::`, which would have kept + passing while matching nothing, so they accepted `plx_os::` too (the `frame` rule now pins the shell's call text instead); the `sink` gate exempts `$SRC_OS/tv*`; the `fpflags` rule and the harness's private tree copy include the new `Cargo.toml` and `build.rs`. `ci/check-localization.py` named `webos.rs`, `tv/device.rs` and `devcaps/dv.rs` under `rust-modules/src` and skips a missing path without a word: it reads diff --git a/rust-modules/os/src/tv.rs b/rust-modules/os/src/tv.rs index adfeb02b4a..922d71d035 100644 --- a/rust-modules/os/src/tv.rs +++ b/rust-modules/os/src/tv.rs @@ -9,107 +9,194 @@ pub mod sink; pub mod sound; pub mod toast; pub mod uri; -pub mod window; -use std::os::raw::c_void; use std::sync::OnceLock; /// What the platform's settings service said about the locale. i18n owns the parse and the log lines. #[cfg_attr(any(feature = "hostsim", test, feature = "test-support"), allow(dead_code))] // Reply/Unavailable: TV arm only pub enum LocaleReply { NoPlatform, Unavailable, Reply(String) } -pub struct Port { +/// What the lower layers read from the platform, in four groups. Installed once ([`install`]) before +/// anything reads it, and read only by `tv`'s own modules, so no other module can issue a verb the +/// interfaces below do not offer. The window, the bus pump and the frame probe are NOT here: only +/// the loop reads them, so they belong to the application's own `Platform`. +/// +/// Every hook is required. A platform states each field of each group, and a named `NONE` is that +/// statement; a gap filled in by `Default` is not allowed. The one exemption is +/// [`LegacyWebosMedia`], which a platform without the Starfish and ACB verbs leaves at its `NONE`. +pub struct Services { + pub identity: IdentityHooks, + pub secure: SecureHooks, + pub system: SystemHooks, + pub legacy_webos_media: LegacyWebosMedia, +} + +/// What the device is, what it can do and what is wrong with it. +pub struct IdentityHooks { pub probe_device: fn(), pub start_capability_probe: fn(), pub repair_sandbox: fn() -> Result<(), sandbox::Failure>, + pub system_locale: fn() -> LocaleReply, + pub sound_output: fn() -> sound::Reply, +} + +/// The credential store, and whether this platform keeps one the app may use at all. +pub struct SecureHooks { pub seal: fn(&[u8]) -> Option, pub open: fn(&secure::Sealed) -> Option>, pub remove: fn(&secure::Backend, &str), - pub system_locale: fn() -> LocaleReply, - pub sound_output: fn() -> sound::Reply, + /// What [`secure::mode`] answers: a value the platform states, not a hook it runs. + pub mode: secure::StoreMode, +} + +/// The platform's Home key and its system toast. +pub struct SystemHooks { pub go_home: fn(), pub poll_home: fn(), pub deliver_toast: fn(&str, toast::Identity) -> toast::Sent, - pub bind_window: fn(*mut c_void), - pub grab_surface: fn(*mut c_void), - /// Answers whether a surface was held (and so actually let go of). - pub release_surface: fn() -> bool, - pub arm_opaque_region: fn(), - pub opaque_route: fn(bool), - pub clear_opaque_region: fn(), - pub pump_bus: fn(), - pub frame_probe_request: fn(), - pub frame_probe_prepare_begin: fn(), - pub frame_probe_prepare_end: fn(), - pub frame_probe_waiting: fn(), - pub frame_probe_acquired: fn(), - pub frame_probe_fields: fn() -> String, +} + +/// The Starfish, ACB and `com.webos.media` verbs: webOS's own playback seam, named for what it is. +pub struct LegacyWebosMedia { /// The Starfish-shaped verb sink (see `sink::VideoSink`); the OS-neutral sink is step L15b. /// Read only by [`sink::installed`], the one way out of `tv` for it. pub sink: &'static dyn sink::VideoSink, /// Shared display binding, available independently of a packet-feed executor. pub display_sink: &'static dyn sink::DisplaySink, - /// The URI media pipe; the absent port and feature-off webOS port provide `NoUriMedia`. + /// The URI media pipe; a platform without one provides `NoUriMedia`. /// Read only by [`uri::installed`]. pub uri_media: &'static dyn uri::UriMedia, } fn nothing() {} -/// No port installed: host unit tests (nothing calls `plex_run`). Every entry is what today's -/// `cfg(any(hostsim, test))` arm answered, minus the off-device log lines the other entries would -/// write (`deliver_toast` keeps its one). -static ABSENT: Port = Port { - probe_device: nothing, - start_capability_probe: nothing, - repair_sandbox: || Err(sandbox::Failure::Unsupported), - seal: |_| None, - open: |_| None, - remove: |_, _| {}, - system_locale: || LocaleReply::NoPlatform, - sound_output: || sound::Reply::NoPlatform, - go_home: nothing, - poll_home: nothing, - deliver_toast: toast::deliver_without_port, - bind_window: |_| {}, - grab_surface: |_| {}, - release_surface: || false, - arm_opaque_region: nothing, - opaque_route: |_| {}, - clear_opaque_region: nothing, - pump_bus: nothing, - frame_probe_request: nothing, - frame_probe_prepare_begin: nothing, - frame_probe_prepare_end: nothing, - frame_probe_waiting: nothing, - frame_probe_acquired: nothing, - frame_probe_fields: String::new, - sink: &sink::NoSink, - display_sink: &sink::NoSink, - uri_media: &uri::NoUriMedia, -}; - -static INSTALLED: OnceLock<&'static Port> = OnceLock::new(); - -/// Once, first thing in `plex_run`. A second call is refused and changes nothing. -pub fn install(port: &'static Port) -> Result<(), &'static Port> { INSTALLED.set(port) } - -/// The installed port. Only `tv`'s own modules read the table, so no other module can issue a +impl IdentityHooks { + /// A platform with no identity of its own to publish: nothing is probed, the sandbox cannot be + /// repaired and there is no settings service to ask. + pub const NONE: Self = Self { + probe_device: nothing, + start_capability_probe: nothing, + repair_sandbox: || Err(sandbox::Failure::Unsupported), + system_locale: || LocaleReply::NoPlatform, + sound_output: || sound::Reply::NoPlatform, + }; +} + +impl SecureHooks { + /// No key manager: nothing seals and nothing opens. This alone is NOT [`secure::StoreMode::MemoryOnly`]: + /// the session layer then writes a plaintext file of its own, so the mode stays `Durable`. + pub const NONE: Self = Self { + seal: |_| None, + open: |_| None, + remove: |_, _| {}, + mode: secure::StoreMode::Durable, + }; +} + +impl SystemHooks { + /// No Home key and no system bus: the toast says so in the log and reports it was not sent. + pub const NONE: Self = Self { go_home: nothing, poll_home: nothing, deliver_toast: toast::deliver_without_port }; +} + +impl LegacyWebosMedia { + /// No Starfish, no ACB and no URI pipe: every verb is refused. + pub const NONE: Self = Self { sink: &sink::NoSink, display_sink: &sink::NoSink, uri_media: &uri::NoUriMedia }; +} + +impl Services { + /// No platform installed: host unit tests (nothing installs one). Every entry is what today's + /// `cfg(any(hostsim, test))` arm answered, minus the off-device log lines the other entries would + /// write (`deliver_toast` keeps its one). + pub const HOST_TEST: Self = Self { + identity: IdentityHooks::NONE, + secure: SecureHooks::NONE, + system: SystemHooks::NONE, + legacy_webos_media: LegacyWebosMedia::NONE, + }; +} + +static INSTALLED: OnceLock<&'static Services> = OnceLock::new(); + +/// Once, first thing the process does. A second call is refused and changes nothing. +pub fn install(services: &'static Services) -> Result<(), &'static Services> { INSTALLED.set(services) } + +/// The installed services. Only `tv`'s own modules read them, so no other module can issue a /// verb the interfaces below do not offer; the sink leaves through [`sink::installed`] and the /// URI media pipe through `uri::installed`. -pub(in crate::tv) fn port() -> &'static Port { INSTALLED.get().copied().unwrap_or_else(absent) } +pub(in crate::tv) fn services() -> &'static Services { INSTALLED.get().copied().unwrap_or_else(absent) } /// Nothing installed. A host test expects that; the shipping build never should, and a silent -/// fall back to the no-port defaults would read as a television that does nothing, so say it once. -fn absent() -> &'static Port { +/// fall back to the host-test defaults would read as a television that does nothing, so say it once. +fn absent() -> &'static Services { #[cfg(not(any(test, feature = "test-support")))] { static SAID: std::sync::Once = std::sync::Once::new(); SAID.call_once(|| plx_base::eventlog::log("tv: port not installed - using the no-port defaults")); } - &ABSENT + &Services::HOST_TEST } -pub fn probe_device() { (port().probe_device)() } -pub fn start_capability_probe() { (port().start_capability_probe)() } -pub fn system_locale() -> LocaleReply { (port().system_locale)() } +pub fn probe_device() { (services().identity.probe_device)() } +pub fn start_capability_probe() { (services().identity.start_capability_probe)() } +pub fn system_locale() -> LocaleReply { (services().identity.system_locale)() } + +#[cfg(test)] +mod tests { + use super::*; + + /// **Every answer of the host-test services, pinned.** The destructuring names each field of each + /// group and has no `..`, so a hook added to a group breaks this test until it is pinned here. + #[test] + fn the_host_test_services_answer_nothing_and_say_so() { + let Services { + identity: IdentityHooks { probe_device, start_capability_probe, repair_sandbox, system_locale, sound_output }, + secure: SecureHooks { seal, open, remove, mode }, + system: SystemHooks { go_home, poll_home, deliver_toast }, + legacy_webos_media: LegacyWebosMedia { sink, display_sink, uri_media }, + } = Services::HOST_TEST; + + probe_device(); + start_capability_probe(); + assert_eq!(repair_sandbox(), Err(sandbox::Failure::Unsupported)); + assert!(matches!(system_locale(), LocaleReply::NoPlatform)); + assert!(matches!(sound_output(), sound::Reply::NoPlatform)); + + let sealed = secure::Sealed { + backend: secure::Backend::Keymanager3, + key: "k".into(), + iv: "i".into(), + data: "d".into(), + }; + assert!(seal(b"secret").is_none()); + assert!(open(&sealed).is_none()); + remove(&secure::Backend::PalmKeymanager, "k"); + assert_eq!(mode, secure::StoreMode::Durable, "no key manager is not a memory-only platform"); + + go_home(); + poll_home(); + assert_eq!( + deliver_toast("hello", toast::Identity::AsApp), + toast::Sent { reply: None, outcome: toast::Outcome::NoBus } + ); + + assert!(!sink.feed_abi_is_cow(), "the refusing sink, not a native one"); + assert_eq!(display_sink.window_mode(), sink::VP_NONE); + assert_eq!(display_sink.window_id(), c""); + assert_eq!(uri_media.open(uri::Shape::Anon), Err("no bus".into())); + } + + /// Nothing is installed in a test process, so every reader falls back to the host-test services. + #[test] + fn an_uninstalled_process_reads_the_host_test_services() { + assert!(INSTALLED.get().is_none(), "no test installs services; the platform's own entry does"); + probe_device(); + start_capability_probe(); + assert!(matches!(system_locale(), LocaleReply::NoPlatform)); + // The installed value itself, not `secure::mode()`: that one honours the process-global test + // override another test may hold while this one runs. + assert_eq!(services().secure.mode, secure::StoreMode::Durable); + assert!(secure::seal(b"secret").is_none()); + assert_eq!(sandbox::repair(), Err(sandbox::Failure::Unsupported)); + assert_eq!(uri::installed().open(uri::Shape::Anon), Err("no bus".into())); + } +} diff --git a/rust-modules/os/src/tv/home.rs b/rust-modules/os/src/tv/home.rs index 5243cc7d6d..a7672f31b1 100644 --- a/rust-modules/os/src/tv/home.rs +++ b/rust-modules/os/src/tv/home.rs @@ -66,13 +66,13 @@ pub fn home_requests() -> u32 { pub fn go_home() { #[cfg(any(test, feature = "test-support"))] HOME_REQUESTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - (super::port().go_home)() + (super::services().system.go_home)() } /// The frame thread's half of a root press: the platform's fallback leg, when its off-thread leg /// asked for one. pub fn poll() { - (super::port().poll_home)() + (super::services().system.poll_home)() } #[cfg(test)] diff --git a/rust-modules/os/src/tv/sandbox.rs b/rust-modules/os/src/tv/sandbox.rs index a6a2640e64..a23cad15db 100644 --- a/rust-modules/os/src/tv/sandbox.rs +++ b/rust-modules/os/src/tv/sandbox.rs @@ -96,7 +96,7 @@ pub enum State { /// Called only by the PlayerAdapter worker after the owner accepts explicit confirmation. pub fn repair() -> Result<(), Failure> { - (super::port().repair_sandbox)() + (super::services().identity.repair_sandbox)() } #[cfg(test)] diff --git a/rust-modules/os/src/tv/secure.rs b/rust-modules/os/src/tv/secure.rs index 0e4c7c07cb..c961535490 100644 --- a/rust-modules/os/src/tv/secure.rs +++ b/rust-modules/os/src/tv/secure.rs @@ -4,7 +4,6 @@ //! Beside them, [`StoreMode`] says whether this platform keeps a credential across launches at //! all. use serde::{Deserialize, Serialize}; -use std::sync::OnceLock; #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] @@ -40,7 +39,7 @@ pub fn seal(plain: &[u8]) -> Option { if let Some(store) = STORE_FOR_TEST.with(|cell| cell.get()) { return (store.seal)(plain); } - (super::port().seal)(plain) + (super::services().secure.seal)(plain) } pub fn open(sealed: &Sealed) -> Option> { @@ -48,7 +47,7 @@ pub fn open(sealed: &Sealed) -> Option> { if let Some(store) = STORE_FOR_TEST.with(|cell| cell.get()) { return (store.open)(sealed); } - (super::port().open)(sealed) + (super::services().secure.open)(sealed) } pub fn remove(backend: &Backend, key: &str) { @@ -56,7 +55,7 @@ pub fn remove(backend: &Backend, key: &str) { if let Some(store) = STORE_FOR_TEST.with(|cell| cell.get()) { return (store.remove)(backend, key); } - (super::port().remove)(backend, key) + (super::services().secure.remove)(backend, key) } /// Whether this platform keeps the signed-in session across launches. @@ -76,25 +75,19 @@ pub enum StoreMode { MemoryOnly, } -/// The mode the platform published at startup, set once. Unset reads as [`StoreMode::Durable`], -/// which is what every platform before this value existed was. -static MODE: OnceLock = OnceLock::new(); - -/// Publish the platform's mode before the first session read. Once; later calls are ignored. -pub fn publish_mode(mode: StoreMode) { - let _ = MODE.set(mode); -} - /// The persistence mode of this process: what the session layer reads before it touches a store. +/// The platform states it once, as the `mode` of its [`SecureHooks`](super::SecureHooks); a process +/// that installed none is a host test, whose `NONE` group says [`StoreMode::Durable`], which is +/// what every platform before this value existed was. pub fn mode() -> StoreMode { #[cfg(any(test, feature = "test-support"))] if let Some(mode) = mode_override() { return mode; } - MODE.get().copied().unwrap_or_default() + super::services().secure.mode } -/// A host test's replacement for the published mode. It cannot be thread-local like +/// A host test's replacement for the platform's stated mode. It cannot be thread-local like /// [`STORE_FOR_TEST`]: the session writes on `plx_base::storage_worker`, a thread the test that /// sets it does not own. It is a process global, so [`set_mode_for_test`] asserts the crate test /// lock is held and its guard clears the override. @@ -152,7 +145,7 @@ mod tests { fn the_default_mode_is_durable() { let _serial = plx_base::testlock::serial(); assert_eq!(StoreMode::default(), StoreMode::Durable); - assert_eq!(mode(), StoreMode::Durable, "nothing is published in a test process"); + assert_eq!(mode(), StoreMode::Durable, "no services are installed in a test process"); } #[test] diff --git a/rust-modules/os/src/tv/sink.rs b/rust-modules/os/src/tv/sink.rs index 65801bcf91..b36f738050 100644 --- a/rust-modules/os/src/tv/sink.rs +++ b/rust-modules/os/src/tv/sink.rs @@ -200,10 +200,10 @@ pub trait VideoSink: DisplaySink { /// The installed sink: the only way out of `tv` for the Starfish verbs, and only `player/` may /// call it (`ci/check-deps.sh`, rule `sink`). #[cfg_attr(all(any(test, feature = "test-support"), feature = "hostsim"), allow(dead_code))] -pub fn installed() -> &'static dyn VideoSink { super::port().sink } +pub fn installed() -> &'static dyn VideoSink { super::services().legacy_webos_media.sink } /// Resolve the shared display interface in composition/IO code, then inject it into a driver. -pub fn display_installed() -> &'static dyn DisplaySink { super::port().display_sink } +pub fn display_installed() -> &'static dyn DisplaySink { super::services().legacy_webos_media.display_sink } /// Refused native verbs, shared by `NoSink` and `RefusingSink`. Memoized queries /// remain each sink's own. diff --git a/rust-modules/os/src/tv/sound.rs b/rust-modules/os/src/tv/sound.rs index 02963754cc..7404196453 100644 --- a/rust-modules/os/src/tv/sound.rs +++ b/rust-modules/os/src/tv/sound.rs @@ -20,7 +20,7 @@ pub enum Reply { NoPlatform, Unavailable, Reply(String) } pub fn output() -> Option { let _block = plx_base::task::assert_may_block(const { &plx_base::task::BlockingLabel::new("LS2 sound output") }); let started = std::time::Instant::now(); - match (super::port().sound_output)() { + match (super::services().identity.sound_output)() { Reply::NoPlatform => None, Reply::Unavailable => { plx_base::eventlog::log(&format!("sound: output unavailable after {}ms", started.elapsed().as_millis())); diff --git a/rust-modules/os/src/tv/toast.rs b/rust-modules/os/src/tv/toast.rs index b42ac10852..c9021885dd 100644 --- a/rust-modules/os/src/tv/toast.rs +++ b/rust-modules/os/src/tv/toast.rs @@ -51,7 +51,7 @@ pub fn toast(message: &str) -> Outcome { /// One attempt under the chosen [`Identity`], reply and grade both. Blocks. pub fn send(message: &str, identity: Identity) -> Sent { let _block = plx_base::task::assert_may_block(const { &plx_base::task::BlockingLabel::new("LS2 toast") }); - (super::port().deliver_toast)(message, identity) + (super::services().system.deliver_toast)(message, identity) } /// What an absent port answers: nothing was sent, and the log says so. diff --git a/rust-modules/os/src/tv/uri.rs b/rust-modules/os/src/tv/uri.rs index ef0a28b020..485c2a34c9 100644 --- a/rust-modules/os/src/tv/uri.rs +++ b/rust-modules/os/src/tv/uri.rs @@ -75,7 +75,7 @@ pub trait UriMedia: Sync { fn poll(&self, session: SessionId) -> Result; fn close(&self, session: SessionId) -> Result<(), String>; } -pub fn installed() -> &'static dyn UriMedia { super::port().uri_media } +pub fn installed() -> &'static dyn UriMedia { super::services().legacy_webos_media.uri_media } pub struct ReplyQueue { session: SessionId, diff --git a/rust-modules/os/src/tv/window.rs b/rust-modules/os/src/tv/window.rs deleted file mode 100644 index 75b715b543..0000000000 --- a/rust-modules/os/src/tv/window.rs +++ /dev/null @@ -1,72 +0,0 @@ -//! The television's window and bus, as the frame loop drives them: the SDL window and Wayland -//! surface, the opaque-region hint, the platform bus pump and the frame probe. Each call is a hop -//! through the installed port; with no port installed every one is a no-op. -use std::os::raw::c_void; - -/// Hand the port the SDL window, once, at boot — `textinput::bind`'s shape and for its reason: the -/// window is created deep inside `plex_run` and the platform needs it a long way from there. -pub fn bind_window(win: *mut c_void) { - (super::port().bind_window)(win) -} - -/// Take the surface the window presents through. -pub fn grab(win: *mut c_void) { - (super::port().grab_surface)(win) -} - -/// Let go of the surface, without destroying SDL's objects; foreground takes it again. Answers -/// whether a surface was held, so the caller can tell a release from a second, idempotent one. -pub fn release() -> bool { - (super::port().release_surface)() -} - -/// Arm the opaque-region hint at boot. -pub fn arm_opaque_region() { - (super::port().arm_opaque_region)() -} - -/// Route the opaque region for the frame about to present: `player` is whether the video plane -/// shows through. -pub fn opaque_route(player: bool) { - (super::port().opaque_route)(player) -} - -/// Drop the opaque-region hint. -pub fn clear_opaque_region() { - (super::port().clear_opaque_region)() -} - -/// Service the platform bus once; the frame loop calls this every frame. -pub fn pump_bus() { - (super::port().pump_bus)() -} - -/// Ask for this frame's presentation callback. Call on a PRESENTING frame, before the swap. -pub fn frame_probe_request() { - (super::port().frame_probe_request)() -} - -/// `prepare_window` is next: starts the frame's `p` stretch. -pub fn frame_probe_prepare_begin() { - (super::port().frame_probe_prepare_begin)() -} - -/// `prepare_window` has returned: closes the frame's `p` stretch. -pub fn frame_probe_prepare_end() { - (super::port().frame_probe_prepare_end)() -} - -/// The frame's first framebuffer command is next: the wait for a back buffer starts here. -pub fn frame_probe_waiting() { - (super::port().frame_probe_waiting)() -} - -/// The frame's first framebuffer command has returned: the back buffer is acquired. -pub fn frame_probe_acquired() { - (super::port().frame_probe_acquired)() -} - -/// The probe's log fields since the previous line; `""` unarmed. -pub fn frame_probe_fields() -> String { - (super::port().frame_probe_fields)() -} diff --git a/rust-modules/os/src/webos.rs b/rust-modules/os/src/webos.rs index f71e0b7619..74d2c11cae 100644 --- a/rust-modules/os/src/webos.rs +++ b/rust-modules/os/src/webos.rs @@ -645,7 +645,7 @@ pub fn bind_window(win: *mut std::os::raw::c_void) { #[cfg(any(feature = "hostsim", test, feature = "test-support"))] pub fn bind_window(_win: *mut std::os::raw::c_void) {} -/// The URI media pipe the port installs (`tv::Port::uri_media`): the explicitly enabled bus +/// The URI media pipe the port installs (`tv::LegacyWebosMedia::uri_media`): the explicitly enabled bus /// worker on the television, or `NoUriMedia` in a feature-off build, simulator or test. /// This does not select the URI playback route. #[cfg(all(feature = "uri-transport", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] diff --git a/rust-modules/plex/src/plex/CLAUDE.md b/rust-modules/plex/src/plex/CLAUDE.md index 770d3042c0..58e41e3861 100644 --- a/rust-modules/plex/src/plex/CLAUDE.md +++ b/rust-modules/plex/src/plex/CLAUDE.md @@ -683,7 +683,7 @@ a dead source is **absent** from Home and states itself in its own library secti separate `CACHE` today; when it is wired up, it must install into/drop the cache above (`install_locked`/`drop_cache_locked`, under `IO`) instead of maintaining a second copy of the session. - - **Under `StoreMode::MemoryOnly` (`plx_os::tv::secure`, published once at boot; `Durable` is the + - **Under `StoreMode::MemoryOnly` (`plx_os::tv::secure`, the `mode` the platform's `Services.secure` states; `Durable` is the default and what webOS and desktop run) the cache is the ONE authority, not a write-through copy** (`session/memory_only.rs`): reads, guarded edits, revocation and clear all resolve against it, and no credential is committed anywhere, canonical store, sealed or plaintext diff --git a/rust-modules/src/app/adapters/hostsim.rs b/rust-modules/src/app/adapters/hostsim.rs index 05412f46b1..28ca7f9d5f 100644 --- a/rust-modules/src/app/adapters/hostsim.rs +++ b/rust-modules/src/app/adapters/hostsim.rs @@ -11,7 +11,7 @@ mod sim_video; use plx_play_feed::ffi_host::{HostSink, Hooks}; /// The simulator's video sink, built with the simulator's decoded picture. The port table holds -/// it as `Port.sink`; a hostsim test binary of this crate reads it directly. +/// it as `Services.legacy_webos_media.sink`; a hostsim test binary of this crate reads it directly. pub(crate) static HOST_SINK: HostSink = HostSink::new(Hooks::over(&sim_video::SimVideo)); /// The render thread's half of the simulator's picture, once per bound-plane frame, after the diff --git a/rust-modules/src/app/boot.rs b/rust-modules/src/app/boot.rs index 3a2cbea1cd..dd1e39b025 100644 --- a/rust-modules/src/app/boot.rs +++ b/rust-modules/src/app/boot.rs @@ -3,6 +3,7 @@ //! verbatim in phase 1a of the UI restructure (a pure move; `pub(crate)` widening only). 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))] @@ -1390,10 +1391,7 @@ pub(crate) unsafe fn boot( // so it is handed over here, before any playback can land. Replay boots take it too. plx_media::route::install_up_next_still_warm(super::playback::warm_up_next_still); // The dev frame probe's clock is `os`'s, which `gfx` does not depend on. - plx_gfx::gfx::install_clear_probe( - plx_os::tv::window::frame_probe_waiting, - plx_os::tv::window::frame_probe_acquired, - ); + plx_gfx::gfx::install_clear_probe(|| platform().diag.waiting(), || platform().diag.acquired()); let initial = match &preflight { super::bootstrap::Preflight::Live => None, super::bootstrap::Preflight::Record => { @@ -1647,7 +1645,7 @@ pub(crate) unsafe fn construct( crate::textinput::bind(win); // …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. - plx_os::tv::window::bind_window(win); + platform().shell.bind_window(win); let wflags = SDL_GetWindowFlags(win); log(&format!( "keyboard: support={} active={} focus={} winflags=0x{wflags:x}", @@ -1656,11 +1654,11 @@ pub(crate) unsafe fn construct( i32::from(wflags & SDL_WINDOW_INPUT_FOCUS != 0) )); - plx_os::tv::window::grab(win); + platform().shell.grab_surface(win); // EXPERIMENT (`/tmp/plxnative-opaque`), no-op without the trigger: build the full-surface // wl_region once, so `opaque_route` below can declare the UI plane opaque on every screen // that has nothing behind it. See `system.rs`'s section on it. - plx_os::tv::window::arm_opaque_region(); + platform().shell.arm_opaque_region(); // A required shader the driver refuses is a refusal like any other (`Exit::from(GfxFault)`): // the same status the process always ended with, returned instead of `exit_now`'d from inside GL. plx_gfx::gfx::init_gl()?; diff --git a/rust-modules/src/app/bridge.rs b/rust-modules/src/app/bridge.rs index 391d0799c4..44d998dfdf 100644 --- a/rust-modules/src/app/bridge.rs +++ b/rust-modules/src/app/bridge.rs @@ -32,7 +32,7 @@ //! dispatcher does not yet run a phase this early in the frame). `opaque_route` and //! `clear_opaque_region` stopped being no-ops in phase 9 — the rig's hooks are real, but they //! delegate to `app/run.rs::rig_opaque_route`/`rig_clear_opaque_region` rather than naming -//! `plx_os::tv::window::` here, which is what keeps the OS-facing call text in one file (D4; +//! the platform's `shell` here, which is what keeps the OS-facing call text in one file (D4; //! `ci/check-deps.sh`'s `frame` gate). use std::ffi::CStr; @@ -3371,10 +3371,10 @@ impl Rig for Bridge<'_> { fn ls2_pump(&mut self) {} /// §3.3 step 9, every frame, presented or not. Real since phase 9: the argument is the /// dispatcher's `Present::video_plane()`, i.e. the Player machine's own bit arriving as - /// `PresentEvent::VideoPlane`, and `tv::window::opaque_route` only sends a wayland request when + /// `PresentEvent::VideoPlane`, and `Shell::opaque_route` only sends a wayland request when /// the answer CHANGES — so the loop's own call beside it (`app/run.rs`, from the same bit) is /// a `static` read and a return, not a second claim. Delegates to `run::rig_opaque_route` - /// (D4) rather than naming `plx_os::tv::window::opaque_route` here directly — see that function's + /// (D4) rather than naming the platform's `shell.opaque_route` here directly — see that function's /// doc for why. fn opaque_route(&mut self, video_plane_bound: bool) { super::run::rig_opaque_route(video_plane_bound); diff --git a/rust-modules/src/app/exit.rs b/rust-modules/src/app/exit.rs index 786354c0fd..f2eb06f7c6 100644 --- a/rust-modules/src/app/exit.rs +++ b/rust-modules/src/app/exit.rs @@ -523,32 +523,7 @@ mod lifecycle_tests { assert!(prod.contains("fn run_application"), "the scan must still reach run_application"); } if f == root.join("src/port.rs") { - // The process entry ends the process itself and is typed `-> !`: `plex_run` returns - // into `__libc_start_main`'s libc `exit` if it ever returns (#1115). The const is the - // compile-time proof for `plex_main` only; `plex_run`, the C entry, is `-> c_int`, so - // an early `return 2;` above its call to `plex_main` would compile (`!` coerces). This - // holds the const still there, `plex_main` still the one that exits, and `plex_run` - // exactly the one call. All of it is read off comment-stripped lines, so a commented-out - // const or call cannot satisfy it (and no block comment may exist to defeat that). - assert!(!prod.contains("/*"), "port.rs has a block comment; strip those as well"); - let code: String = - prod.lines().map(|l| l.split("//").next().unwrap_or("")).collect::>().join("\n"); - let main = code.split_once("fn plex_main(").expect("port.rs must keep plex_main").1; - let main = main.split_once("\n}\n").expect("the end of plex_main").0; - assert!(main.contains(exit_now), "plex_main must end the process through exit_now"); - assert!( - code.contains("const _: fn(*const c_char, c_int) -> ! = plex_main;"), - "the const proving plex_main never returns is gone" - ); - let run = code.split_once("fn plex_run(").expect("port.rs must keep plex_run").1; - let run = run.split_once('{').expect("the start of plex_run's body").1; - let run = run.split_once('}').expect("the end of plex_run's body").0; - assert_eq!( - run.split_whitespace().collect::>().join(" "), - "plex_main(pms_host, pms_port)", - "plex_run must be exactly the call to plex_main: no `return`, no other statement, \ - or it can return into libc `exit` (#1115)" - ); + assert_process_entry(&text, exit_now); } for (n, line) in prod.lines().enumerate() { let code = line.split("//").next().unwrap_or(""); @@ -567,6 +542,93 @@ mod lifecycle_tests { ); } + /// `port.rs`'s code with its `//` comments dropped, so a commented-out call, const or definition + /// cannot satisfy or trip a scan of it. (A block comment would defeat that, and is refused where + /// this is used.) + fn without_line_comments(text: &str) -> String { + text.lines().map(|l| l.split("//").next().unwrap_or("")).collect::>().join("\n") + } + + /// **The process entry in `port.rs`: `plex_run` is exactly one call, and `plex_main` ends the + /// process.** The process entry ends the process itself and is typed `-> !`: `plex_run` returns + /// into `__libc_start_main`'s libc `exit` if it ever returns (#1115). The const is the + /// compile-time proof for `plex_main` only; `plex_run`, the C entry, is `-> c_int`, so an early + /// `return 2;` above its call to `plex_main` would compile (`!` coerces). This holds the const + /// still there, `plex_main` still the one that exits, and `plex_run` exactly the one call. All of + /// it is read off comment-stripped lines, so a commented-out const or call cannot satisfy it (and + /// no block comment may exist to defeat that). + /// + /// Both entries must also be DEFINED exactly once, anywhere in the file. This scan and + /// `ci/check-deps.sh`'s `fnlen` budgets read only the FIRST `fn plex_run(` and the first + /// `fn plex_main(`, so a second, cfg-gated definition would be the one a build runs while both + /// guards graded the other. + fn assert_process_entry(text: &str, exit_now: &str) { + assert!(!text.contains("/*"), "port.rs has a block comment; strip those as well"); + let every = without_line_comments(text); + for entry in ["fn plex_main(", "fn plex_run("] { + assert_eq!( + every.matches(entry).count(), + 1, + "port.rs must define `{entry}` exactly once: the guards read only the first, so a \ + second (cfg-gated) one would run unguarded (#1115)" + ); + } + let code = without_line_comments(production_prefix(text)); + let main = code.split_once("fn plex_main(").expect("port.rs must keep plex_main").1; + let main = main.split_once("\n}\n").expect("the end of plex_main").0; + assert!(main.contains(exit_now), "plex_main must end the process through exit_now"); + assert!( + code.contains("const _: fn(*const c_char, c_int) -> ! = plex_main;"), + "the const proving plex_main never returns is gone" + ); + let run = code.split_once("fn plex_run(").expect("port.rs must keep plex_run").1; + let run = run.split_once('{').expect("the start of plex_run's body").1; + let run = run.split_once('}').expect("the end of plex_run's body").0; + assert_eq!( + run.split_whitespace().collect::>().join(" "), + "plex_main(pms_host, pms_port)", + "plex_run must be exactly the call to plex_main: no `return`, no other statement, \ + or it can return into libc `exit` (#1115)" + ); + } + + const ENTRY: &str = "\ +#[no_mangle] +pub extern \"C\" fn plex_run(pms_host: *const c_char, pms_port: c_int) -> c_int { + plex_main(pms_host, pms_port) +} +fn plex_main(pms_host: *const c_char, pms_port: c_int) -> ! { + plx_base::process::exit_now(crate::app::run_application(pms_host, pms_port).code) +} +const _: fn(*const c_char, c_int) -> ! = plex_main; +"; + + /// The scan's own control: the entry shape it accepts, so the refusals below fail on what they + /// plant and not on a premise the fixture lacks. + #[test] + fn the_process_entry_scan_accepts_the_one_call_entry() { + assert_process_entry(ENTRY, concat!("exit_", "now(")); + } + + /// A second `plex_run` behind a cfg that is never true compiles everywhere and is invisible to a + /// reader of the first, so the scan counts definitions instead of trusting its first match. The + /// plant follows a test module too: the production prefix must not be where the count stops. + #[test] + #[should_panic(expected = "must define `fn plex_run(` exactly once")] + fn a_second_cfg_gated_plex_run_is_refused() { + let planted = format!( + "{ENTRY}#[cfg(test)]\nmod tests {{\n}}\n#[cfg(any())]\nfn plex_run(h: *const c_char, p: c_int) -> c_int {{\n return 2;\n}}\n" + ); + assert_process_entry(&planted, concat!("exit_", "now(")); + } + + #[test] + #[should_panic(expected = "must define `fn plex_main(` exactly once")] + fn a_second_cfg_gated_plex_main_is_refused() { + let planted = format!("{ENTRY}#[cfg(any())]\nfn plex_main(h: *const c_char, p: c_int) -> ! {{\n loop {{}}\n}}\n"); + assert_process_entry(&planted, concat!("exit_", "now(")); + } + /// The text above the file's first `#[cfg(test)]` MODULE. A `#[cfg(test)]` import or field on the /// way (`app/mod.rs` has both, above `run_application`) must not hide the production code under it. fn production_prefix(text: &str) -> &str { diff --git a/rust-modules/src/app/mod.rs b/rust-modules/src/app/mod.rs index 341e151c8d..ec1d1dbb78 100644 --- a/rust-modules/src/app/mod.rs +++ b/rust-modules/src/app/mod.rs @@ -140,6 +140,7 @@ pub(crate) mod playback; mod preferences; pub(crate) mod input; pub(crate) mod bridge; +pub(crate) mod platform; mod runtime_owners; pub(crate) mod chrome; mod collections_probe; diff --git a/rust-modules/src/app/platform.rs b/rust-modules/src/app/platform.rs new file mode 100644 index 0000000000..af54e2691b --- /dev/null +++ b/rust-modules/src/app/platform.rs @@ -0,0 +1,165 @@ +//! The platform the application runs on, as only the loop reads it. +//! +//! [`Platform`] is what the platform's entry installs once ([`install`]) before the loop starts. It +//! carries three things, split by who reads them: +//! +//! - `services`: [`plx_os::tv::Services`], what the LOWER layers read through the private `tv` +//! accessors (identity, the secure store, Home and the toast, the legacy webOS media verbs). It +//! is installed into `tv` by [`install`] and read from nowhere in the app but there. +//! - `shell`: the window and the bus, [`Shell`]. Its one consumer is the loop (`app::boot` brings +//! the window up, `app::run` drives it every frame), so it is not in the bottom layer's process +//! global. +//! - `diag`: the six frame probes, [`FrameProbe`], read by the same loop and by the one clear hook +//! `app::boot` hands the renderer. +//! +//! `Shell`, `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 values +//! are 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 plx_os::tv::Services; +use std::os::raw::c_void; +use std::sync::OnceLock; + +/// The platform's window and bus, as the frame loop drives them: the SDL window and its surface, the +/// opaque-region hint, and the platform bus pump. Every call runs on the loop thread, and every +/// hook is required: a platform with nothing to do states [`Platform::HOST_TEST`]'s no-ops. +pub(crate) trait Shell: Sync { + /// 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); + /// Take the surface the window presents through. + fn grab_surface(&self, win: *mut c_void); + /// Let go of the surface, without destroying SDL's objects; foreground takes it again. Answers + /// whether a surface was held, so the caller can tell a release from a second, idempotent one. + fn release_surface(&self) -> bool; + /// Arm the opaque-region hint at boot. + fn arm_opaque_region(&self); + /// Route the opaque region for the frame about to present: `player` is whether the video plane + /// shows through. + fn opaque_route(&self, player: bool); + /// Drop the opaque-region hint. + fn clear_opaque_region(&self); + /// Service the platform bus once; the frame loop calls this every frame. + fn pump_bus(&self); +} + +/// 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 { + /// Ask for this frame's presentation callback. Call on a PRESENTING frame, before the swap. + fn request(&self); + /// `prepare_window` is next: starts the frame's `p` stretch. + fn prepare_begin(&self); + /// `prepare_window` has returned: closes the frame's `p` stretch. + fn prepare_end(&self); + /// The frame's first framebuffer command is next: the wait for a back buffer starts here. + fn waiting(&self); + /// The frame's first framebuffer command has returned: the back buffer is acquired. + fn acquired(&self); + /// The probe's log fields since the previous line; `""` unarmed. + fn fields(&self) -> String; +} + +/// Everything the application needs from its platform. Built once by the platform's entry +/// (`port.rs` for webOS) and installed before `run_application`. +pub(crate) struct Platform { + pub(crate) services: &'static Services, + pub(crate) shell: &'static dyn Shell, + pub(crate) diag: &'static dyn FrameProbe, +} + +/// The shell of a process with no platform: a host test, where nothing owns a window or a bus. +struct HostShell; + +impl Shell for HostShell { + fn bind_window(&self, _win: *mut c_void) {} + fn grab_surface(&self, _win: *mut c_void) {} + fn release_surface(&self) -> bool { + false + } + fn arm_opaque_region(&self) {} + fn opaque_route(&self, _player: bool) {} + fn clear_opaque_region(&self) {} + fn pump_bus(&self) {} +} + +/// The frame probe of a process with no platform: always unarmed. +struct HostProbe; + +impl FrameProbe for HostProbe { + fn request(&self) {} + fn prepare_begin(&self) {} + fn prepare_end(&self) {} + fn waiting(&self) {} + fn acquired(&self) {} + fn fields(&self) -> String { + String::new() + } +} + +impl Platform { + /// No platform installed: the loop's host tests, where nothing calls `plex_run`. Every entry is + /// what the no-port defaults answered before the shell and the probe left `tv`. + pub(crate) const HOST_TEST: Platform = + Platform { services: &Services::HOST_TEST, shell: &HostShell, diag: &HostProbe }; +} + +static INSTALLED: OnceLock<&'static Platform> = OnceLock::new(); + +/// Once, first thing the process does: install the platform's `tv` services for the lower layers and +/// keep the platform for the loop. A second call is refused and changes nothing. +pub(crate) fn install(platform: &'static Platform) { + let _ = plx_os::tv::install(platform.services); + let _ = INSTALLED.set(platform); +} + +/// The installed platform, or [`Platform::HOST_TEST`] when none was (a host test, where every +/// entry is a no-op). The loop reads its shell and its frame probe through this. +pub(crate) fn platform() -> &'static Platform { + INSTALLED.get().copied().unwrap_or(&Platform::HOST_TEST) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// **Every answer of the host-test platform, pinned.** The destructuring names each field of + /// the platform and has no `..`, so a field added to it breaks this test until it is pinned. + /// The shell and the probe are driven through plain locals (`s`, `p`): the `frame` gate pins the + /// call text of the loop's own receiver, and this is the no-op one. + #[test] + fn the_host_test_platform_answers_nothing_and_says_so() { + let Platform { services, shell: s, diag: p } = Platform::HOST_TEST; + + assert!( + matches!((services.identity.system_locale)(), plx_os::tv::LocaleReply::NoPlatform), + "the services are the host-test services (`tv`'s own tests pin each answer)" + ); + + let window = std::ptr::null_mut(); + s.bind_window(window); + s.grab_surface(window); + assert!(!s.release_surface(), "no surface was ever held"); + s.arm_opaque_region(); + s.opaque_route(true); + s.opaque_route(false); + s.clear_opaque_region(); + s.pump_bus(); + + p.request(); + p.prepare_begin(); + p.prepare_end(); + p.waiting(); + p.acquired(); + assert_eq!(p.fields(), "", "an unarmed probe has nothing to log"); + } + + /// Nothing is installed in a test process, so the loop reads the host-test platform. + #[test] + fn an_uninstalled_process_reads_the_host_test_platform() { + assert!(INSTALLED.get().is_none(), "no test installs a platform; the platform's own entry does"); + let Platform { shell: s, diag: p, .. } = *platform(); + s.pump_bus(); + assert_eq!(p.fields(), ""); + } +} diff --git a/rust-modules/src/app/run.rs b/rust-modules/src/app/run.rs index 61912e3956..6b14f88d5f 100644 --- a/rust-modules/src/app/run.rs +++ b/rust-modules/src/app/run.rs @@ -34,6 +34,7 @@ use super::*; use plx_ui::dispatch::Rig as _; use super::bridge::AppHost; +use super::platform::platform; use super::exit::{release_of, Release}; /// One lazy product frame-tail hash path for recording and replay grading alike. @@ -171,7 +172,7 @@ impl plx_ui::dispatch::FrameRuntime for ProductFrameRuntime<'_> { if crate::dev::framedump::requested() { crate::dev::framedump::iteration_begin(app); } - plx_os::tv::window::pump_bus(); + platform().shell.pump_bus(); plx_os::tv::home::poll(); // The one toast key mode owes the viewer (`net::keypin`'s facts), on every route. self.clock_notice.poll(); @@ -333,7 +334,7 @@ impl plx_ui::dispatch::FrameRuntime for ProductFrameRuntime<'_> { unsafe { update(app, fr); } app.rec.content_results(); app.instr.mark(plx_base::diag::heartbeat::Phase::TickDrain); // tick_drain - plx_os::tv::window::frame_probe_prepare_begin(); + platform().diag.prepare_begin(); publish_resources(app, fr); } fn admit(&mut self, demand: bool) -> bool { @@ -348,7 +349,7 @@ impl plx_ui::dispatch::FrameRuntime for ProductFrameRuntime<'_> { } fn draw_and_swap(&mut self) -> bool { finish_prepare(self.app); - plx_os::tv::window::frame_probe_prepare_end(); + platform().diag.prepare_end(); unsafe { present_and_swap(self.app, &mut self.fr, #[cfg(all(feature = "hostsim", target_os = "linux"))] self.wslg_frame_budget.take()); } @@ -356,7 +357,7 @@ impl plx_ui::dispatch::FrameRuntime for ProductFrameRuntime<'_> { } fn skipped(&mut self) { finish_prepare(self.app); - plx_os::tv::window::frame_probe_prepare_end(); + platform().diag.prepare_end(); unsafe { present_and_swap(self.app, &mut self.fr, #[cfg(all(feature = "hostsim", target_os = "linux"))] self.wslg_frame_budget.take()); } @@ -718,7 +719,7 @@ fn finish_prepare(app: &mut App) { // there is nothing else in the loop that would carry it: a `return` above, or a term that // only ran on player frames, would leave the compositor believing our surface is still // opaque with an ordinary UI on it. - plx_os::tv::window::opaque_route(app.player.video_plane_bound); + platform().shell.opaque_route(app.player.video_plane_bound); app.instr.mark(plx_base::diag::heartbeat::Phase::Prepare); // prepare // `worstprep=`: the prepare phase is timed on EVERY iteration, presented or not — a // settled screen must never run untimed work at the loop rate (spec §8.3). @@ -844,22 +845,23 @@ fn publish_player_model(app: &mut App) { /// (`app/bridge.rs`) cannot itself move here: a trait's implementation for a type is one /// syntactic unit, and that `impl Rig for Bridge` block carries two dozen other methods /// beside these three — so this is the "or just its three privileged methods" half of the D4 -/// move. `Bridge::opaque_route`/`Bridge::clear_opaque_region` call these instead of -/// `plx_os::tv::window::` directly, which is what keeps the OS-facing text — the thing the `frame` +/// move. `Bridge::opaque_route`/`Bridge::clear_opaque_region` call these instead of naming +/// the platform's `shell` directly, which is what keeps the OS-facing text — the thing the `frame` /// gate greps for — in this ONE file rather than split across the loop and the bridge. Each is a -/// pure pass-through: the loop's own per-frame call above (`plx_os::tv::window::opaque_route`, from +/// pure pass-through: the loop's own per-frame call above (`platform().shell.opaque_route`, from /// `fr`) and the dispatcher's `Rig` hook (from `Bridge`'s own copy of the same bit) are two /// independent callers of one primitive, not two implementations of it. `ls2_pump` needs no /// twin here — `Bridge::ls2_pump` is or stays a no-op, since the dispatcher does not yet run a /// phase this early in the frame. pub(crate) fn rig_opaque_route(video_plane_bound: bool) { - plx_os::tv::window::opaque_route(video_plane_bound); + platform().shell.opaque_route(video_plane_bound); } /// See [`rig_opaque_route`]. The `if self.video_plane` guard stays on `Bridge`'s side — this is -/// the OS call alone, exactly what `plx_os::tv::window::clear_opaque_region` was before the move. +/// the OS call alone, exactly what `tv::window::clear_opaque_region` was before the shell moved to +/// `app::platform`. pub(crate) fn rig_clear_opaque_region() { - plx_os::tv::window::clear_opaque_region(); + platform().shell.clear_opaque_region(); } /// **Simulator only: the television's compositor, over the frame the straighten pass just made.** The @@ -971,7 +973,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. - plx_os::tv::window::frame_probe_request(); + platform().diag.request(); SDL_GL_SwapWindow(app.win); } app.window_activity.presented(fr.player); @@ -1171,7 +1173,7 @@ fn window_step(stage: plx_telemetry::telemetry::window::Stage, playing: Option (i32, i32, i32, i32) plx_ui::profile::phase("frame.ui", || { plx_ui::guard(|| { if fr.player { - // `plx_os::tv::window::clear_opaque_region()` used to be called here. It is + // `clear_opaque_region()` used to be called here. It is // §3.3 step 10's privileged call and belongs at the container library's // OWN draw entry, which `app.pages.draw` below reaches in this same frame: // `Bridge::clear_opaque_region` performs it, keyed on the plane's bit @@ -3139,9 +3141,9 @@ pub(crate) unsafe fn draw(app: &mut App, fr: &mut Frame) -> (i32, i32, i32, i32) // wait for a free back buffer: spanned like every other route's `clear`. // dev (`/tmp/plxnative-framecb`): the frame thread's cost over the wait // and, from the acquired buffer to the swap, over the commit phase. - plx_os::tv::window::frame_probe_waiting(); + platform().diag.waiting(); plx_base::diag::spans::span("clear", || glClear(GL_COLOR_BUFFER_BIT)); - plx_os::tv::window::frame_probe_acquired(); + platform().diag.acquired(); // ONE resolve of which surface owns the "pipeline is working" signal, // handed to both the transport and the read-out, so the centred read-out // and the transport's inline spinner can never both light in the same @@ -3544,7 +3546,7 @@ pub(crate) unsafe fn report(app: &mut App, fr: &mut Frame) { plx_ui::glassload::step_index(), bridge.home_snap_target(&app.pages), bridge.home_snap_pos(&app.pages), - plx_os::tv::window::frame_probe_fields() + platform().diag.fields() ) }) { log(&line); @@ -8263,7 +8265,7 @@ pub(in crate::app) mod lifecycle_regression_tests { fr.now = 32; event(&mut rig.app, &mut fr, 0x104); assert!(rig.app.player.lifecycle.awaiting_load()); - // The host test has no GL context for `tv::window::grab`. Drive the remaining production + // The host test has no GL context for `Shell::grab_surface`. Drive the remaining production // DID-foreground seams directly after granting the same WindowActivity permission. rig.app.window_activity.event(0x106); super::super::bridge::foreground(&mut rig.app.pages); @@ -8566,7 +8568,7 @@ pub(in crate::app) mod lifecycle_regression_tests { fr.now = 32; event(&mut rig.app, &mut fr, 0x104); assert!(rig.app.player.lifecycle.awaiting_load()); - // The host test has no GL context for `tv::window::grab`. Drive the remaining production + // The host test has no GL context for `Shell::grab_surface`. Drive the remaining production // DID-foreground seams directly after granting the same WindowActivity permission. rig.app.window_activity.event(0x106); super::super::bridge::foreground(&mut rig.app.pages); @@ -11190,7 +11192,7 @@ mod video_plane_gate_tests { .next() .expect("the loop's source"); assert!( - !src.contains("plx_os::tv::window::opaque_route(fr.player)"), + !src.contains("shell.opaque_route(fr.player)"), "the opaque region must not be keyed on the ROUTE — the plane's bit is the question", ); // **UNCONDITIONAL.** The claim this pins is not where the call sits relative to the @@ -11205,7 +11207,7 @@ mod video_plane_gate_tests { // 200-line budget, so "the loop body's own depth" is now two claims: the call is at // `prepare_window`'s own body depth (four spaces, never inside that function's one // `if fr.present`), and `prepare_window` itself is called at the loop body's (eight). - const CALL: &str = " plx_os::tv::window::opaque_route(app.player.video_plane_bound);"; + const CALL: &str = " platform().shell.opaque_route(app.player.video_plane_bound);"; assert_eq!( src.lines().filter(|l| *l == CALL).count(), 1, diff --git a/rust-modules/src/port.rs b/rust-modules/src/port.rs index 89f91fbf8f..40dfb1c2ed 100644 --- a/rust-modules/src/port.rs +++ b/rust-modules/src/port.rs @@ -1,10 +1,12 @@ -//! The webOS port: the one table that fills the `tv` interfaces, and the C entry that installs it. +//! The webOS port: the two tables that fill the platform, and the C entry that installs them. //! -//! Everything outside this module reaches the television through `plx_os::tv`; this is the only -//! place that names `webos`, `keymanager`, `system` and the native video sink together. Its functions keep -//! their own `cfg(any(hostsim, test))` arms, so the simulator installs this same table and behaves -//! as it always did. -use std::os::raw::{c_char, c_int}; +//! `plx_os::tv::Services` is what the lower layers read, and `app::platform::Platform` adds the shell +//! and the frame probe the loop alone reads. Everything outside this module reaches the television +//! through those; this is the only place that names `webos`, `keymanager`, `system` and the native +//! video sink together. Its functions keep their own `cfg(any(hostsim, test))` arms, so the +//! simulator installs these same tables and behaves as it always did. +use crate::app::platform::{FrameProbe, Platform, Shell}; +use std::os::raw::{c_char, c_int, c_void}; #[cfg(all(not(feature = "hostsim"), not(test), feature = "play-feed"))] const SINK: &dyn plx_os::tv::sink::VideoSink = &plx_os::webos::video_sink::StarfishSink; @@ -22,36 +24,89 @@ const DISPLAY: &dyn plx_os::tv::sink::DisplaySink = &plx_os::webos::video_sink:: #[cfg(any(feature = "hostsim", test))] const DISPLAY: &dyn plx_os::tv::sink::DisplaySink = SINK; -static PORT: plx_os::tv::Port = plx_os::tv::Port { - probe_device: plx_os::webos::probe, - start_capability_probe: plx_os::webos::caps::start_probe, - repair_sandbox: plx_os::webos::jail_repair::execute, - seal: plx_os::keymanager::seal, - open: plx_os::keymanager::open, - remove: plx_os::keymanager::remove, - system_locale: plx_os::webos::system_locale, - sound_output: plx_os::webos::sound_output, - go_home: plx_os::webos::go_home, - poll_home: plx_os::webos::poll_home, - deliver_toast: plx_os::webos::toast::deliver, - bind_window: plx_os::webos::bind_window, - grab_surface: crate::system::sys_grab_wayland, - release_surface: crate::system::sys_release_wayland, - arm_opaque_region: crate::system::opaque_region_init, - opaque_route: crate::system::opaque_route, - clear_opaque_region: crate::system::clear_opaque_region, - pump_bus: crate::system::ls2_pump, - frame_probe_request: crate::system::frame_probe_request, - frame_probe_prepare_begin: crate::system::frame_probe_prepare_begin, - frame_probe_prepare_end: crate::system::frame_probe_prepare_end, - frame_probe_waiting: crate::system::frame_probe_waiting, - frame_probe_acquired: crate::system::frame_probe_acquired, - frame_probe_fields: crate::system::frame_probe_fields, - sink: SINK, - display_sink: DISPLAY, - uri_media: plx_os::webos::URI_MEDIA, +/// What the lower layers read: the webOS identity, key manager, Home key and toast, and the native +/// playback seam. The window, the bus pump and the frame probe are the loop's own, in [`PLATFORM`]. +static SERVICES: plx_os::tv::Services = plx_os::tv::Services { + identity: plx_os::tv::IdentityHooks { + probe_device: plx_os::webos::probe, + start_capability_probe: plx_os::webos::caps::start_probe, + repair_sandbox: plx_os::webos::jail_repair::execute, + system_locale: plx_os::webos::system_locale, + sound_output: plx_os::webos::sound_output, + }, + secure: plx_os::tv::SecureHooks { + seal: plx_os::keymanager::seal, + open: plx_os::keymanager::open, + remove: plx_os::keymanager::remove, + mode: plx_os::tv::secure::StoreMode::Durable, + }, + system: plx_os::tv::SystemHooks { + go_home: plx_os::webos::go_home, + poll_home: plx_os::webos::poll_home, + deliver_toast: plx_os::webos::toast::deliver, + }, + legacy_webos_media: plx_os::tv::LegacyWebosMedia { + sink: SINK, + display_sink: DISPLAY, + uri_media: plx_os::webos::URI_MEDIA, + }, }; +/// The webOS shell: the SDL window's Wayland surface, the opaque-region hint and the LS2 bus pump. +/// The bodies stay in `crate::system` (and `webos::bind_window`); this is the table over them. +struct WebosShell; + +impl Shell for WebosShell { + fn bind_window(&self, win: *mut c_void) { + plx_os::webos::bind_window(win); + } + fn grab_surface(&self, win: *mut c_void) { + crate::system::sys_grab_wayland(win); + } + fn release_surface(&self) -> bool { + crate::system::sys_release_wayland() + } + fn arm_opaque_region(&self) { + crate::system::opaque_region_init(); + } + fn opaque_route(&self, player: bool) { + crate::system::opaque_route(player); + } + fn clear_opaque_region(&self) { + crate::system::clear_opaque_region(); + } + fn pump_bus(&self) { + crate::system::ls2_pump(); + } +} + +/// The webOS frame probe, over `crate::system`'s compositor-callback clock. +struct WebosProbe; + +impl FrameProbe for WebosProbe { + fn request(&self) { + crate::system::frame_probe_request(); + } + fn prepare_begin(&self) { + crate::system::frame_probe_prepare_begin(); + } + fn prepare_end(&self) { + crate::system::frame_probe_prepare_end(); + } + fn waiting(&self) { + crate::system::frame_probe_waiting(); + } + fn acquired(&self) { + crate::system::frame_probe_acquired(); + } + fn fields(&self) -> String { + crate::system::frame_probe_fields() + } +} + +/// The webOS platform, installed once by `plex_main` before anything reads it. +static PLATFORM: Platform = Platform { services: &SERVICES, shell: &WebosShell, diag: &WebosProbe }; + /// The C shim's entry (`src/main.c`) and the simulator's (`src/bin/sim.rs`). The `-> c_int` is only /// the C signature: `plex_main` never returns, so neither does this. #[no_mangle] @@ -59,7 +114,7 @@ pub extern "C" fn plex_run(pms_host: *const c_char, pms_port: c_int) -> c_int { plex_main(pms_host, pms_port) } -/// The process entry: install the port, hand over to `app::run_application`, then end the process +/// The process entry: install the platform, hand over to `app::run_application`, then end the process /// with the status it returned. /// /// The executable owns the process end: `exit_now` (`_exit`, never libc's `exit`, #1115) right after @@ -73,7 +128,7 @@ pub extern "C" fn plex_run(pms_host: *const c_char, pms_port: c_int) -> c_int { /// `run_application` and `run_and_shutdown` when those started to return an `Exit`: a later edit that /// lets this return does not compile. fn plex_main(pms_host: *const c_char, pms_port: c_int) -> ! { - let _ = plx_os::tv::install(&PORT); + crate::app::platform::install(&PLATFORM); #[cfg(target_os = "linux")] let _ = plx_os::storage::client::install_activator(plx_os::webos::activate_storage_helper); plx_base::process::exit_now(crate::app::run_application(pms_host, pms_port).code) @@ -97,7 +152,7 @@ pub unsafe extern "C" fn plx_launch_args(json: *const c_char) { #[cfg(all(test, feature = "hostsim", feature = "play-feed"))] mod tests { - use super::PORT; + use super::SERVICES; /// The app's plane boot resolves the display through `display_installed()` (this table's /// `display_sink`), where media's old `acb_init` resolved it through `player::display()`. In @@ -106,8 +161,9 @@ mod tests { #[test] fn the_simulator_port_display_is_the_host_sink_the_acb_init_reads() { let host = std::ptr::from_ref(&crate::app::adapters::hostsim::HOST_SINK).cast::<()>(); - assert_eq!(std::ptr::from_ref(PORT.display_sink).cast::<()>(), host, + let media = &SERVICES.legacy_webos_media; + assert_eq!(std::ptr::from_ref(media.display_sink).cast::<()>(), host, "display_installed() is the host sink"); - assert_eq!(std::ptr::from_ref(PORT.sink).cast::<()>(), host, "so is the video sink"); + assert_eq!(std::ptr::from_ref(media.sink).cast::<()>(), host, "so is the video sink"); } } diff --git a/tests/test_harness.py b/tests/test_harness.py index 9e3e55c2f4..de8b54695f 100644 --- a/tests/test_harness.py +++ b/tests/test_harness.py @@ -10381,6 +10381,43 @@ def test_sink_gate_allows_the_player_to_name_the_video_sink(self): self.assertEqual(r.returncode, 0, out) self.assertIn("ok — sink", out) + @_grades("frame") + def test_frame_gate_catches_a_shell_call_outside_the_loop(self): + """D4, and W2 of the platform plan: the window and the bus are the platform's `Shell`, and its + three privileged calls (`pump_bus`, `opaque_route`, `clear_opaque_region`) belong to + `app/run.rs` alone. RED: each way to spell a call on the shell, planted outside `run.rs`, must + fail `frame` and be named: on a receiver called `shell`, through the trait's path, and as a + chain broken onto a continuation line.""" + plants = [ + ("_check_deps_selftest_frame_receiver.rs", + "pub fn pump() {\n platform().shell.pump_bus();\n}\n", None), + ("_check_deps_selftest_frame_path.rs", + "pub fn route(shell: &dyn Shell) {\n Shell::opaque_route(shell, true);\n}\n", None), + ("_check_deps_selftest_frame_chain.rs", + "pub fn clear() {\n platform()\n .shell\n .clear_opaque_region();\n}\n", None), + ] + r = self._plant_all(plants) + self._assert_flagged(r, "frame", [ + ("_check_deps_selftest_frame_receiver.rs", "pump_bus"), + ("_check_deps_selftest_frame_path.rs", "opaque_route"), + ("_check_deps_selftest_frame_chain.rs", "clear_opaque_region"), + ]) + + @_grades("frame") + def test_frame_gate_ignores_a_rig_forward_a_string_and_a_comment(self): + """GREEN: `Rig` has `opaque_route` and `clear_opaque_region` of its own (`Bridge` forwards them), + and a pin test spells the loop's calls as string data. None of those is a call on the shell.""" + r = self._plant( + "_check_deps_selftest_frame_ok.rs", + "pub fn forward(bridge: &mut Bridge) {\n bridge.opaque_route(true);\n" + " self.bridge.clear_opaque_region();\n}\n" + 'pub const PIN: &str = " platform().shell.opaque_route(bound);";\n' + "// platform().shell.pump_bus();\n", + ) + out = r.stdout + r.stderr + self.assertEqual(r.returncode, 0, out) + self.assertIn("ok — frame", out) + @_grades("textmeasure") def test_textmeasure_gate_catches_a_bare_call_outside_the_seam(self): """Phase 12, D4: `textmeasure` went from an allowlist to zero-tolerance. RED: a raw From 79535082713ca4bf5b4c1b5bdce96c3dfe16c8dd Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 10:28:46 +0300 Subject: [PATCH 2/4] run_application takes the Platform; the app-private platform global is gone The first cut of W2 kept the Platform in an app-crate OnceLock read through platform(), with Platform::HOST_TEST as the fallback. That fallback was live in production: an entry that forgot to install would have booted a television with a no-op shell (no bind, no grab, no bus pump) and said nothing. The platform plan's shape is `run_application(&'static Platform) -> Exit`, so the platform is now an argument and forgetting it does not compile. - run_application(platform, pms_host, pms_port) installs tv::Services from platform.services once, before anything reads tv, then enters as before. plex_main hands it &PLATFORM after the storage activator line. The #1479 const proof, the process-entry scan with its exactly-once asserts and the fnlen budgets (run_application 7, plex_main 6, plex_run 3) are unchanged. - app::platform loses INSTALLED, install() and platform(). App gets `platform: &'static Platform`, set at both construction sites (boot's literal and the run.rs test rig, which passes &Platform::HOST_TEST explicitly). Boot code that runs before an App exists (bind_window, grab_surface, arm_opaque_region) takes the platform as a parameter, and the loop reads app.platform.shell and app.platform.diag. - The dispatcher's two opaque-region hooks (Rig::opaque_route and clear_opaque_region) take no platform argument, so BridgeRetained holds the shell as a field, given to its constructors the way now_us is. run::rig_opaque_route and rig_clear_opaque_region take it as a parameter and stay the one place the bridge reaches the shell, which keeps the frame gate's call text in run.rs. The test constructors pass the host-test shell explicitly. - gfx's clear-probe hook takes plain functions and is a once-set, thread-local hook that boot installed. plex_main now installs it with the webOS probe's own functions, on the thread the app boots and draws on. No host test ever ran boot, so host tests still install nothing, as before. - The frame gate's receiver match, its self-tests and the prose that named platform() follow. No new process-global, no cfg(test) fork and no ledger line. Co-Authored-By: Claude --- ci/check-deps.sh | 8 +-- docs/agent-reference.md | 2 +- docs/module-layers.md | 8 +-- rust-modules/os/src/tv.rs | 3 +- rust-modules/src/app/boot.rs | 28 ++++----- rust-modules/src/app/bootstrap/tests.rs | 12 ++-- rust-modules/src/app/bridge.rs | 34 +++++++---- .../app/browse_discovery_admission_tests.rs | 2 +- .../src/app/browse_discovery_drain_tests.rs | 2 +- .../src/app/browse_listing_admission_tests.rs | 2 +- rust-modules/src/app/exit.rs | 2 +- rust-modules/src/app/home_admission_tests.rs | 2 +- .../app/metadata_alt_sources_bridge_tests.rs | 2 +- rust-modules/src/app/mod.rs | 21 ++++--- rust-modules/src/app/notify_bridge_tests.rs | 2 +- rust-modules/src/app/platform.rs | 60 +++++++------------ rust-modules/src/app/recorder.rs | 4 +- .../src/app/recording_erasure_tests.rs | 2 +- rust-modules/src/app/run.rs | 44 +++++++------- .../src/app/session_dispatch_tests.rs | 2 +- .../src/app/viewstate_controlled_tests.rs | 2 +- rust-modules/src/port.rs | 16 ++--- tests/test_harness.py | 8 +-- 23 files changed, 134 insertions(+), 134 deletions(-) diff --git a/ci/check-deps.sh b/ci/check-deps.sh index effc441aba..e42e83623f 100755 --- a/ci/check-deps.sh +++ b/ci/check-deps.sh @@ -1083,7 +1083,7 @@ want ladder && gate_zero ladder 'fn move_focus|fn pointer_focus|fn top_focus|fn want hittest && gate_zero hittest 'pointer_focus\(|\b(failure_quality|icon|scrub)_hit\(' "$SRC/app" # frame: the three privileged OS-primitive calls — `pump_bus`, `opaque_route` and `clear_opaque_region` -# on the platform's `Shell` (`app::platform`, installed by `port.rs`) — ZERO-TOLERANCE outside +# on the platform's `Shell` (`app::platform`, passed to `run_application` by `port.rs`) — ZERO-TOLERANCE outside # `app/run.rs` (D4) — no allowlist file, because there is exactly one legitimate home once D1 lands: # `app/run.rs` is the frame loop, and `app/bridge.rs`'s `Rig` impl delegates to `run::rig_opaque_route`/ # `rig_clear_opaque_region` (a one-line pass-through) rather than naming the `shell` itself, @@ -1093,10 +1093,10 @@ want hittest && gate_zero hittest 'pointer_focus\(|\b(failure_quality|icon|scrub # # The method names alone are NOT the pin: `Rig` has `opaque_route` and `clear_opaque_region` too, and # `Bridge`'s forwarding (`self.bridge.opaque_route(..)`) is not an OS call. So the pin is the RECEIVER: -# a call on something named `shell` (`platform().shell.pump_bus()`, `p.shell.opaque_route(..)`), on the +# a call on something named `shell` (`app.platform.shell.pump_bus()`, `p.shell.opaque_route(..)`), on the # trait by path (`Shell::pump_bus(..)`, `::pump_bus(..)`), or a continuation line of a # chain that begins on the line before (`.pump_bus(`, which rustfmt may break out of -# `platform().shell`). A shell held in a differently named local does not match: this is a text gate +# `app.platform.shell`). A shell held in a differently named local does not match: this is a text gate # on the loop's own call shape, and the no-op `Platform::HOST_TEST` shell is driven that way by its pin # test. # @@ -1170,7 +1170,7 @@ fi fi # route # fnlen: app/run.rs::run <= 200 lines, run_application (app/mod.rs, the D4 skeleton) <= 10 and -# plex_main (port.rs: install, hand over, end the process) <= 10 — counted by brace +# plex_main (port.rs: the clear hook, hand the platform over, end the process) <= 10 — counted by brace # depth from the `fn` line to its matching close, not by grep pattern. fn_body_lines() { # fn_body_lines — prints the line count of the first matching fn's body diff --git a/docs/agent-reference.md b/docs/agent-reference.md index f1c1556010..2207261422 100644 --- a/docs/agent-reference.md +++ b/docs/agent-reference.md @@ -1138,7 +1138,7 @@ Two planes are composited by the TV: the app's **GLES/graphics plane** (UI, draw over the hardware **VIDEO overlay plane** (decoded frames). The UI plane is made non-opaque so video shows through. -**UI (the Rust app core — the frame loop in `app/run.rs::run`, entered via `plex_run()` in `port.rs`, which installs the platform (`app::platform::install`) and runs `app::run_application`, after `app/boot.rs::boot()`):** SDL2 window + GLES2 +**UI (the Rust app core — the frame loop in `app/run.rs::run`, entered via `plex_run()` in `port.rs`, which passes the platform (`app::platform::Platform`) to `app::run_application`, after `app/boot.rs::boot()`):** SDL2 window + GLES2 context. All UI is drawn with two tiny shaders — an SDF rounded-rect/triangle shader (cards, focus 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 diff --git a/docs/module-layers.md b/docs/module-layers.md index 8d9018a7ae..4561d00c55 100644 --- a/docs/module-layers.md +++ b/docs/module-layers.md @@ -350,8 +350,8 @@ L15's 44 entries, 205 references of which 95 were in production code. The port's their layers, so none of this held up the split. L15 moved every one of those references behind an interface in `os`'s new `tv` module that -the port fills at boot. `tv::Services` is a table of function pointers in four groups (`identity`, `secure`, `system` and `legacy_webos_media`), installed once as the first -statement of `port::plex_main`, through `app::platform::install`, before anything that reads it. With nothing installed (host unit +the port fills at boot. `tv::Services` is a table of function pointers in four groups (`identity`, `secure`, `system` and `legacy_webos_media`), installed once by `app::run_application` (from the `Platform` its entry hands it) before anything +that reads it. With nothing installed (host unit tests, where nothing calls `plex_run`) `tv::Services::HOST_TEST` answers what the host arms answered before; a shipping build that reaches it logs `tv: port not installed - using the no-port defaults` once. Only `tv`'s own modules read the table. Two things leave it: the sink, through @@ -376,7 +376,7 @@ published values rather than hooks: the webOS code writes them into `tv::device` | storage backend | `storage::client::install_activator`, which the port calls with `webos::activate_storage_helper` | `port::plex_run` | | locale | `tv::system_locale` and `tv::LocaleReply`; `i18n` still owns the parse and the log lines | `i18n` | | sound output | `tv::sound::{output, parse_output, Reply}`, filled by `Services.identity.sound_output` (`webos::sound_output`); a blocking read, so never on the frame thread, and asked only on a stack whose lead follows the output (`liblxa` and 2018's `audiosink_new`; `devcaps::audio_stack`; the `lgaudiosink` stack's lead does not depend on the output, and the others have none, so they never ask) | `player::threads` (through `player::engine`, which owns the lead table) | -| window, surface, video plane, bus pump and frame probe | `app::platform::{Shell, FrameProbe}`, in the application crate beside the loop that is their one consumer; `port.rs` implements them over `crate::system` | `app::boot`, `app::run` | +| window, surface, video plane, bus pump and frame probe | `app::platform::{Shell, FrameProbe}`, in the application crate beside the loop that is their one consumer; `port.rs` implements them over `crate::system`, and `run_application` takes the `Platform` that holds them (kept as `App::platform`, and as the shell `BridgeRetained` holds for the dispatcher's two opaque-region hooks) | `app::boot`, `app::run`, `app::bridge` | | home key | `tv::home::{go_home, poll, take_root_press, release_root_press}` | `app::input`, `app::run`, `app::adapters::session`, `app::lifecycle`'s tests | | system toast | `tv::toast::{toast, send, Identity, Outcome, Sent}` | `app::clock_notice`, `dev::scenarios::toast_probe` | @@ -412,7 +412,7 @@ order or its interleaving, and its log lines are graded on the television. A ver can be graded by comparing the television's log before and after; a redesign that changes where those stages run, and when, is its own step's scope and risk. -The simulator runs the same tables. Under `hostsim` `port.rs` installs a `SERVICES` and a `PLATFORM` whose fields point +The simulator runs the same tables. Under `hostsim` `port.rs` builds a `SERVICES` and a `PLATFORM` whose fields point at the same `webos`, `keymanager` and `system` functions, whose `hostsim` arms answer on the host, and whose sink is `HostSink`. So the simulator behaves as it did, but it is not yet a second implementation of the interfaces. diff --git a/rust-modules/os/src/tv.rs b/rust-modules/os/src/tv.rs index 922d71d035..558ecb9aa0 100644 --- a/rust-modules/os/src/tv.rs +++ b/rust-modules/os/src/tv.rs @@ -117,7 +117,8 @@ impl Services { static INSTALLED: OnceLock<&'static Services> = OnceLock::new(); -/// Once, first thing the process does. A second call is refused and changes nothing. +/// Once, by the application's entry, before anything reads them. A second call is refused and changes +/// nothing. pub fn install(services: &'static Services) -> Result<(), &'static Services> { INSTALLED.set(services) } /// The installed services. Only `tv`'s own modules read them, so no other module can issue a diff --git a/rust-modules/src/app/boot.rs b/rust-modules/src/app/boot.rs index dd1e39b025..21acced293 100644 --- a/rust-modules/src/app/boot.rs +++ b/rust-modules/src/app/boot.rs @@ -3,7 +3,7 @@ //! verbatim in phase 1a of the UI restructure (a pure move; `pub(crate)` widening only). use super::*; -use super::platform::platform; +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))] @@ -526,7 +526,7 @@ mod seam_order_tests { "one production hand-in; a second could name a different version" ); assert_eq!( - source.matches(concat!("enter_application(", "pms_host,pms_port)")).count(), + source.matches(concat!("enter_application(", "platform, pms_host, pms_port)")).count(), 1, "enter_application has one caller, run_application" ); @@ -555,7 +555,7 @@ mod seam_order_tests { let telemetry = body .find(".then(pre_boot_diagnostics)") .expect("telemetry's boot load"); - let boot = body.find("boot(pms_host").expect("application boot"); + let boot = body.find("boot(platform, pms_host").expect("application boot"); assert!( eraser < telemetry && eraser < boot, "the eraser must be installed before telemetry loads and before anything can play" @@ -601,7 +601,7 @@ mod seam_order_tests { let diagnostics = body .find("plx_os::storage::diagnostics::start(") .expect("diagnostics start"); - let boot = body.find("boot(pms_host").expect("application boot"); + let boot = body.find("boot(platform, pms_host").expect("application boot"); assert!(identity < diagnostics && diagnostics < boot); } @@ -1382,6 +1382,7 @@ pub(super) fn install_pms_owned( /// `&MainThread` (which is `!Send`, so `task::spawn` rejects any closure that captured one), and /// the native session slot takes the adapter itself. See `task::MainThread` and `player::adapter`. pub(crate) unsafe fn boot( + platform: &'static Platform, pms_host: *const c_char, pms_port: c_int, mt: plx_base::task::MainThread, @@ -1390,8 +1391,6 @@ pub(crate) unsafe fn boot( // The Up Next still prefetch `route::pump_play` asks for is `ui`'s, which `route` may not name, // so it is handed over here, before any playback can land. Replay boots take it too. plx_media::route::install_up_next_still_warm(super::playback::warm_up_next_still); - // The dev frame probe's clock is `os`'s, which `gfx` does not depend on. - plx_gfx::gfx::install_clear_probe(|| platform().diag.waiting(), || platform().diag.acquired()); let initial = match &preflight { super::bootstrap::Preflight::Live => None, super::bootstrap::Preflight::Record => { @@ -1404,8 +1403,8 @@ pub(crate) unsafe fn boot( super::bootstrap::Preflight::Replay { initial, .. } => Some((initial.clone(), None)), }; match initial { - Some((initial, deferred)) => App::from_init(initial, preflight, pms_host, pms_port, mt, deferred), - None => construct(pms_host, pms_port, mt, preflight, None, None), + Some((initial, deferred)) => App::from_init(platform, initial, preflight, pms_host, pms_port, mt, deferred), + None => construct(platform, pms_host, pms_port, mt, preflight, None, None), } } @@ -1451,7 +1450,7 @@ pub(super) fn resume_stored(pages: &mut plx_ui::dispatch::Dispatcher, deferred: Option, ) -> Result { @@ -1645,7 +1644,7 @@ pub(crate) unsafe fn construct( crate::textinput::bind(win); // …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); + platform.shell.bind_window(win); let wflags = SDL_GetWindowFlags(win); log(&format!( "keyboard: support={} active={} focus={} winflags=0x{wflags:x}", @@ -1654,11 +1653,11 @@ pub(crate) unsafe fn construct( i32::from(wflags & SDL_WINDOW_INPUT_FOCUS != 0) )); - platform().shell.grab_surface(win); + platform.shell.grab_surface(win); // EXPERIMENT (`/tmp/plxnative-opaque`), no-op without the trigger: build the full-surface // wl_region once, so `opaque_route` below can declare the UI plane opaque on every screen // that has nothing behind it. See `system.rs`'s section on it. - platform().shell.arm_opaque_region(); + platform.shell.arm_opaque_region(); // A required shader the driver refuses is a refusal like any other (`Exit::from(GfxFault)`): // the same status the process always ended with, returned instead of `exit_now`'d from inside GL. plx_gfx::gfx::init_gl()?; @@ -1832,10 +1831,10 @@ pub(crate) unsafe fn construct( captured_dev_sources(&dev_servers.unwrap_or_default())), }; let (mut runtime, mut retained) = if controlled { - super::bridge::BridgeRetained::controlled_home(plx_base::diag::heartbeat::now_us, + super::bridge::BridgeRetained::controlled_home(plx_base::diag::heartbeat::now_us, platform.shell, initial.as_ref().expect("controlled initialization"), &mt, preflight.replay()) } else { - super::bridge::BridgeRetained::new(plx_base::diag::heartbeat::now_us, session_init, + super::bridge::BridgeRetained::new(plx_base::diag::heartbeat::now_us, platform.shell, session_init, plx_telemetry::telemetry::consent::current().unwrap_or_default(), &mt) }; let mut bridge = runtime.bridge(&mut retained); @@ -2406,6 +2405,7 @@ pub(crate) unsafe fn construct( // End the bootstrap capability before moving its physical owners into App. drop(bridge); let mut app = App { + platform, last_input, loop_t, iters_ct, diff --git a/rust-modules/src/app/bootstrap/tests.rs b/rust-modules/src/app/bootstrap/tests.rs index 4c84346778..af7147e1f7 100644 --- a/rust-modules/src/app/bootstrap/tests.rs +++ b/rust-modules/src/app/bootstrap/tests.rs @@ -109,10 +109,10 @@ fn controlled_boot_binds_policy_and_keeps_legacy_default_explicit() { let mt = unsafe { plx_base::task::MainThread::assume() }; let mut initial = Initial::synthetic_home(17, 32517, None).unwrap(); initial.runtime_policy = Some(RuntimePolicy { harness_driven: true, lookahead_rows: 0 }); - let (runtime, retained) = crate::app::bridge::BridgeRetained::controlled_home(|| 0, &initial, &mt, true); + let (runtime, retained) = crate::app::bridge::BridgeRetained::controlled_home(|| 0, crate::app::platform::Platform::HOST_TEST.shell, &initial, &mt, true); let first = crate::app::runtime_owners::Harness::from_parts(runtime, retained); initial.runtime_policy = Some(RuntimePolicy { harness_driven: false, lookahead_rows: 4 }); - let (runtime, retained) = crate::app::bridge::BridgeRetained::controlled_home(|| 0, &initial, &mt, true); + let (runtime, retained) = crate::app::bridge::BridgeRetained::controlled_home(|| 0, crate::app::platform::Platform::HOST_TEST.shell, &initial, &mt, true); let second = crate::app::runtime_owners::Harness::from_parts(runtime, retained); assert!(first.views().inputs.runtime_policy.harness_driven); assert_eq!(first.views().inputs.runtime_policy.lookahead_rows, 0); @@ -122,7 +122,7 @@ fn controlled_boot_binds_policy_and_keeps_legacy_default_explicit() { assert!(!first.views().native_preview_available && !second.views().native_preview_available, "controlled owners never expose a native preview port, independent of harness policy"); initial.runtime_policy = None; - let (runtime, retained) = crate::app::bridge::BridgeRetained::controlled_home(|| 0, &initial, &mt, true); + let (runtime, retained) = crate::app::bridge::BridgeRetained::controlled_home(|| 0, crate::app::platform::Platform::HOST_TEST.shell, &initial, &mt, true); let legacy = crate::app::runtime_owners::Harness::from_parts(runtime, retained); assert_eq!(legacy.views().inputs.runtime_policy, plx_screens::inputs::RuntimePolicy::default()); assert!(crate::app::recorder::Recplay::recording_with_sink(&initial, Box::new(plx_ui::rec::MemSink::default())).is_err()); @@ -439,7 +439,7 @@ fn normal_and_controlled_activation_publish_the_owner_supplied_scope() { let mt = unsafe { plx_base::task::MainThread::assume() }; let initial = Initial::synthetic_home(19,9,None).unwrap(); let (runtime, retained) = super::super::bridge::BridgeRetained::new( - ||0, initial.session.clone(), initial.consent.clone(), &mt); + ||0, crate::app::platform::Platform::HOST_TEST.shell, initial.session.clone(), initial.consent.clone(), &mt); let mut live_owner = crate::app::runtime_owners::Harness::from_parts(runtime, retained); let mut live = live_owner.bridge(); activate(&mut live); @@ -450,7 +450,7 @@ fn normal_and_controlled_activation_publish_the_owner_supplied_scope() { let ambient = plx_plex::plex::session::current_snapshot(); plx_plex::plex::reset_servers_for_test(); plx_plex::plex::Client::restore_generation_seed(initial.primary_client).unwrap(); - let (runtime, retained) = super::super::bridge::BridgeRetained::controlled_home(||0,&initial,&mt,true); + let (runtime, retained) = super::super::bridge::BridgeRetained::controlled_home(||0, crate::app::platform::Platform::HOST_TEST.shell, &initial,&mt,true); let mut controlled_owner = crate::app::runtime_owners::Harness::from_parts(runtime, retained); let mut controlled = controlled_owner.bridge(); let retained = controlled.profile_resource_view().unwrap(); @@ -492,7 +492,7 @@ fn controlled_home_arms_the_detail_tracker_when_content_initial_is_present() { }); plx_data::stores::tape::init(initial.person_credits(), false); plx_machine::landgate::arm_recording(); - let (runtime, retained) = super::super::bridge::BridgeRetained::controlled_home(||0,&initial,&mt,false); + let (runtime, retained) = super::super::bridge::BridgeRetained::controlled_home(||0, crate::app::platform::Platform::HOST_TEST.shell, &initial,&mt,false); let mut harness = crate::app::runtime_owners::Harness::from_parts(runtime, retained); let mut bridge = harness.bridge(); let sid = plx_plex::plex::ServerId::UNSET; diff --git a/rust-modules/src/app/bridge.rs b/rust-modules/src/app/bridge.rs index 44d998dfdf..e08e35cfa1 100644 --- a/rust-modules/src/app/bridge.rs +++ b/rust-modules/src/app/bridge.rs @@ -35,6 +35,7 @@ //! the platform's `shell` here, which is what keeps the OS-facing call text in one file (D4; //! `ci/check-deps.sh`'s `frame` gate). +use super::platform::Shell; use std::ffi::CStr; #[cfg(test)] @@ -731,6 +732,10 @@ pub(crate) struct BridgeRetained { effect_return: ReturnState, now_us: fn() -> u64, + /// **The platform's shell**, for the dispatcher's two opaque-region hooks (`Rig::opaque_route` and + /// `Rig::clear_opaque_region`, below), which take no platform argument. It is the one `App::platform` + /// holds, given to the constructor by the root that has it: a host test passes the host-test shell. + shell: &'static dyn Shell, } impl Bridge<'_> { @@ -800,7 +805,8 @@ impl BridgeRetained { /// `Held` runner exists to remove (`Some(true)`/`Some(false)` flakes), and none does today; a /// test that needs to choose when a fetch settles builds its Bridge with `Held` /// (`StoreRunner::held`) instead. - pub(crate) fn controlled_home(now_us: fn() -> u64, initial: &super::bootstrap::Initial, + pub(crate) fn controlled_home(now_us: fn() -> u64, shell: &'static dyn Shell, + initial: &super::bootstrap::Initial, mt: &plx_base::task::MainThread, replay: bool) -> (super::runtime_owners::RuntimeOwners, Self) { static TTF: plx_gfx::text::TtfMeasure = plx_gfx::text::TtfMeasure; let preferences = initial.session.persisted.clone(); @@ -814,7 +820,7 @@ impl BridgeRetained { // adapter (`plx_data::metadata::record::arm`'s own doc has the history). Must run before this // `Bridge` can admit any detail request. stores.metadata.arm_detail_tracker(initial.content.is_some()); - let (runtime, mut retained) = Self::with_publications_and_stores(&TTF, now_us, initial.session.clone(), + let (runtime, mut retained) = Self::with_publications_and_stores(&TTF, now_us, shell, initial.session.clone(), super::adapters::session::SessionAdapter::controlled_home(mt, replay), initial.consent.clone(), super::adapters::consent::ConsentAdapter::live(), super::adapters::stores::StoreRunner::live(), StorePublications { @@ -835,14 +841,14 @@ impl BridgeRetained { failure: None, profile: runtime.session.adapter.profile_resource_view().expect("controlled publisher") }); (runtime, retained) } - pub(crate) fn new(now_us: fn() -> u64, init: plx_session::auth::SessionInit, + pub(crate) fn new(now_us: fn() -> u64, shell: &'static dyn Shell, init: plx_session::auth::SessionInit, consent: plx_telemetry::telemetry::consent::Consent, mt: &plx_base::task::MainThread) -> (super::runtime_owners::RuntimeOwners, Self) { // A `static`, not `&TtfMeasure` inline: a unit-struct literal DOES const-promote to // `'static` today, but that is a rule about the expression rather than a promise about // this field, and a `static` states the lifetime outright. Same reasoning as the one // `screens::settings`'s test module writes out beside its own measure. static TTF: plx_gfx::text::TtfMeasure = plx_gfx::text::TtfMeasure; - Self::with_measure(&TTF, now_us, init, super::adapters::session::SessionAdapter::live(mt), + Self::with_measure(&TTF, now_us, shell, init, super::adapters::session::SessionAdapter::live(mt), consent, super::adapters::consent::ConsentAdapter::live(), super::adapters::stores::StoreRunner::live()) } @@ -853,7 +859,7 @@ impl BridgeRetained { #[cfg(test)] pub(crate) fn for_test(now_us: fn() -> u64) -> (super::runtime_owners::RuntimeOwners, Self) { static FIXTURE: plx_ui::fixture::FixtureMeasure = plx_ui::fixture::FixtureMeasure; - let (mut runtime, mut retained) = Self::with_measure(&FIXTURE, now_us, + let (mut runtime, mut retained) = Self::with_measure(&FIXTURE, now_us, super::platform::Platform::HOST_TEST.shell, plx_session::auth::SessionInit::captured(plx_plex::plex::session::Session::default()), super::adapters::session::SessionAdapter::fixture(), Default::default(), super::adapters::consent::ConsentAdapter::fixture(), @@ -866,7 +872,7 @@ impl BridgeRetained { (runtime, retained) } - fn with_measure(measure: &'static dyn Measure, now_us: fn() -> u64, + fn with_measure(measure: &'static dyn Measure, now_us: fn() -> u64, shell: &'static dyn Shell, init: plx_session::auth::SessionInit, session_adapter: super::adapters::session::SessionAdapter, consent: plx_telemetry::telemetry::consent::Consent, consent_adapter: super::adapters::consent::ConsentAdapter, @@ -878,7 +884,7 @@ impl BridgeRetained { visible_generation: 0, settled: false, profile_key: "", }); - let (mut runtime, mut retained) = Self::with_publications_and_stores(measure, now_us, init, session_adapter, consent, + let (mut runtime, mut retained) = Self::with_publications_and_stores(measure, now_us, shell, init, session_adapter, consent, consent_adapter, store_runner, StorePublications { hubs: stores.hubs.snapshot(), listing: browse.listing, @@ -937,14 +943,15 @@ impl BridgeRetained { consent: plx_telemetry::telemetry::consent::Consent, consent_adapter: super::adapters::consent::ConsentAdapter, reads: StorePublications) -> (super::runtime_owners::RuntimeOwners, Self) { - let (runtime, mut retained) = Self::with_publications_and_stores(measure, now_us, init, session_adapter, consent, + let (runtime, mut retained) = Self::with_publications_and_stores(measure, now_us, super::platform::Platform::HOST_TEST.shell, init, + session_adapter, consent, consent_adapter, super::adapters::stores::StoreRunner::held(), reads, Default::default(), true); retained.metadata_alt_host = |request, _| request.answer(None); retained.card_motion_policy = super::card_motion_policy::Capture::neutral(); (runtime, retained) } - fn with_publications_and_stores(measure: &'static dyn Measure, now_us: fn() -> u64, + fn with_publications_and_stores(measure: &'static dyn Measure, now_us: fn() -> u64, shell: &'static dyn Shell, init: plx_session::auth::SessionInit, session_adapter: super::adapters::session::SessionAdapter, consent: plx_telemetry::telemetry::consent::Consent, consent_adapter: super::adapters::consent::ConsentAdapter, @@ -1033,6 +1040,7 @@ impl BridgeRetained { effect_return: ReturnState::default(), now_us, + shell, }; if live_screen_inputs { @@ -3377,7 +3385,7 @@ impl Rig for Bridge<'_> { /// (D4) rather than naming the platform's `shell.opaque_route` here directly — see that function's /// doc for why. fn opaque_route(&mut self, video_plane_bound: bool) { - super::run::rig_opaque_route(video_plane_bound); + super::run::rig_opaque_route(self.retained.shell, video_plane_bound); } /// §3.3 step 10, at draw entry. Real since phase 9, and conditional on the same bit: NULLing /// the opaque region on a frame with no plane under it would silently retract the claim @@ -3386,7 +3394,7 @@ impl Rig for Bridge<'_> { /// `run::rig_clear_opaque_region` (D4); the guard stays here. fn clear_opaque_region(&mut self) { if self.retained.video_plane { - super::run::rig_clear_opaque_region(); + super::run::rig_clear_opaque_region(self.retained.shell); } } fn now_us(&self) -> u64 { @@ -5888,7 +5896,7 @@ mod preference_effect_tests { let mode = plx_media::route::direct_play_mode(); for replay in [false, true] { let initial = super::super::bootstrap::Initial::synthetic_home(17, 32517, None).unwrap(); - let (runtime, retained) = BridgeRetained::controlled_home(|| 0, &initial, &mt, replay); + let (runtime, retained) = BridgeRetained::controlled_home(|| 0, crate::app::platform::Platform::HOST_TEST.shell, &initial, &mt, replay); let mut owner = crate::app::runtime_owners::Harness::from_parts(runtime, retained); let mut bridge = owner.bridge(); let mut d = Dispatcher::::new(); @@ -6104,7 +6112,7 @@ mod screen_input_publication_tests { let initial = crate::app::bootstrap::Initial::synthetic_home(17, 32517, None).unwrap(); let mt = unsafe { plx_base::task::MainThread::assume() }; for replay in [false, true] { - let (runtime, retained) = BridgeRetained::controlled_home(|| 0, &initial, &mt, replay); + let (runtime, retained) = BridgeRetained::controlled_home(|| 0, crate::app::platform::Platform::HOST_TEST.shell, &initial, &mt, replay); let mut owner = crate::app::runtime_owners::Harness::from_parts(runtime, retained); let mut bridge = owner.bridge(); let mut present = plx_machine::present::Present::new(); diff --git a/rust-modules/src/app/browse_discovery_admission_tests.rs b/rust-modules/src/app/browse_discovery_admission_tests.rs index 433babc0af..c422e79c15 100644 --- a/rust-modules/src/app/browse_discovery_admission_tests.rs +++ b/rust-modules/src/app/browse_discovery_admission_tests.rs @@ -41,7 +41,7 @@ fn one_server() -> (ServerId, &'static plx_plex::plex::Client) { fn controlled(replay: bool) -> crate::app::runtime_owners::Harness { let mt = unsafe { plx_base::task::MainThread::assume() }; let initial = crate::app::bootstrap::Initial::synthetic_home(17, 32517, None).unwrap(); - let (runtime, retained) = super::super::bridge::BridgeRetained::controlled_home(|| 0, &initial, &mt, replay); + let (runtime, retained) = super::super::bridge::BridgeRetained::controlled_home(|| 0, crate::app::platform::Platform::HOST_TEST.shell, &initial, &mt, replay); crate::app::runtime_owners::Harness::from_parts(runtime, retained) } diff --git a/rust-modules/src/app/browse_discovery_drain_tests.rs b/rust-modules/src/app/browse_discovery_drain_tests.rs index 6fda05ec2e..c30a3482fa 100644 --- a/rust-modules/src/app/browse_discovery_drain_tests.rs +++ b/rust-modules/src/app/browse_discovery_drain_tests.rs @@ -129,7 +129,7 @@ fn the_controlled_discovery_arm_records_a_refused_launch_as_not_admitted() { one_server(); let mt = unsafe { plx_base::task::MainThread::assume() }; let initial = super::super::bootstrap::Initial::synthetic_home(17, 32517, None).unwrap(); - let (runtime, retained) = super::super::bridge::BridgeRetained::controlled_home(|| 0, &initial, &mt, false); + let (runtime, retained) = super::super::bridge::BridgeRetained::controlled_home(|| 0, crate::app::platform::Platform::HOST_TEST.shell, &initial, &mt, false); let mut owner = crate::app::runtime_owners::Harness::from_parts(runtime, retained); let mut bridge = owner.bridge(); crate::app::adapters::stores::with_refused_hubs_launches_for_test(|| { diff --git a/rust-modules/src/app/browse_listing_admission_tests.rs b/rust-modules/src/app/browse_listing_admission_tests.rs index a9e3650e26..3d9544976c 100644 --- a/rust-modules/src/app/browse_listing_admission_tests.rs +++ b/rust-modules/src/app/browse_listing_admission_tests.rs @@ -162,7 +162,7 @@ fn a_controlled_runs_browse_commands_emit_no_page_or_directory_read() { for replay in [false, true] { let (own, shared, client) = two_servers(); let initial = crate::app::bootstrap::Initial::synthetic_home(17, 32517, None).unwrap(); - let (runtime, retained) = super::super::bridge::BridgeRetained::controlled_home(|| 0, &initial, &mt, replay); + let (runtime, retained) = super::super::bridge::BridgeRetained::controlled_home(|| 0, crate::app::platform::Platform::HOST_TEST.shell, &initial, &mt, replay); let mut owner = crate::app::runtime_owners::Harness::from_parts(runtime, retained); let mut bridge = owner.bridge(); seeded(&mut bridge, own, shared); diff --git a/rust-modules/src/app/exit.rs b/rust-modules/src/app/exit.rs index f2eb06f7c6..0b9ed5ec6e 100644 --- a/rust-modules/src/app/exit.rs +++ b/rust-modules/src/app/exit.rs @@ -598,7 +598,7 @@ pub extern \"C\" fn plex_run(pms_host: *const c_char, pms_port: c_int) -> c_int plex_main(pms_host, pms_port) } fn plex_main(pms_host: *const c_char, pms_port: c_int) -> ! { - plx_base::process::exit_now(crate::app::run_application(pms_host, pms_port).code) + plx_base::process::exit_now(crate::app::run_application(&PLATFORM, pms_host, pms_port).code) } const _: fn(*const c_char, c_int) -> ! = plex_main; "; diff --git a/rust-modules/src/app/home_admission_tests.rs b/rust-modules/src/app/home_admission_tests.rs index b27b53a6e5..c3b7f8815e 100644 --- a/rust-modules/src/app/home_admission_tests.rs +++ b/rust-modules/src/app/home_admission_tests.rs @@ -39,7 +39,7 @@ fn recording_home() -> (crate::app::runtime_owners::Harness, ServerId, &'static let client = plx_plex::plex::client_for(sid).expect("registered"); let mt = unsafe { plx_base::task::MainThread::assume() }; let initial = super::super::bootstrap::Initial::synthetic_home(17, 32517, None).unwrap(); - let (runtime, retained) = super::super::bridge::BridgeRetained::controlled_home(|| 0, &initial, &mt, false); + let (runtime, retained) = super::super::bridge::BridgeRetained::controlled_home(|| 0, crate::app::platform::Platform::HOST_TEST.shell, &initial, &mt, false); (crate::app::runtime_owners::Harness::from_parts(runtime, retained), sid, client) } diff --git a/rust-modules/src/app/metadata_alt_sources_bridge_tests.rs b/rust-modules/src/app/metadata_alt_sources_bridge_tests.rs index 69047c8d9d..d01abfcda3 100644 --- a/rust-modules/src/app/metadata_alt_sources_bridge_tests.rs +++ b/rust-modules/src/app/metadata_alt_sources_bridge_tests.rs @@ -116,7 +116,7 @@ fn entering_controlled_home_never_reuses_a_live_detail_source_override() { })); let initial = super::super::bootstrap::Initial::synthetic_home(41, 17, None).unwrap(); let mt = unsafe { plx_base::task::MainThread::assume() }; - let (runtime, retained) = crate::app::bridge::BridgeRetained::controlled_home(|| 0, &initial, &mt, false); + let (runtime, retained) = crate::app::bridge::BridgeRetained::controlled_home(|| 0, crate::app::platform::Platform::HOST_TEST.shell, &initial, &mt, false); let mut controlled_owner = crate::app::runtime_owners::Harness::from_parts(runtime, retained); let controlled = controlled_owner.bridge(); assert_eq!(live.metadata_view().current().unwrap().source(), "live-only"); diff --git a/rust-modules/src/app/mod.rs b/rust-modules/src/app/mod.rs index ec1d1dbb78..24f61e1559 100644 --- a/rust-modules/src/app/mod.rs +++ b/rust-modules/src/app/mod.rs @@ -406,6 +406,11 @@ pub(crate) struct App { pub(crate) runtime: runtime_owners::RuntimeOwners, /// Retained publications and IO bookkeeping; each turn borrows these alongside `runtime`. pub(crate) bridge: bridge::BridgeRetained, + /// **The platform this process runs on**, handed to `run_application` by the entry and kept here so + /// the loop reads its shell (the window, the opaque region, the bus pump) and its frame probes from + /// the value it was given. There is no process-global copy: a missing one is a compile error, not + /// a television that boots with no window. A host test builds an `App` with [`platform::Platform::HOST_TEST`]. + platform: &'static platform::Platform, } impl App { @@ -442,10 +447,10 @@ impl App { self.instr.present_interval_ms() } /// Controlled construction receives decoded/captured inputs before bootstrap effects. - pub(crate) unsafe fn from_init(initial: bootstrap::Initial, mode: bootstrap::Preflight, - pms_host: *const c_char, pms_port: c_int, mt: plx_base::task::MainThread, + pub(crate) unsafe fn from_init(platform: &'static platform::Platform, initial: bootstrap::Initial, + mode: bootstrap::Preflight, pms_host: *const c_char, pms_port: c_int, mt: plx_base::task::MainThread, deferred: Option) -> Result { - boot::construct(pms_host, pms_port, mt, mode, Some(initial), deferred) + boot::construct(platform, pms_host, pms_port, mt, mode, Some(initial), deferred) } /// **Which page is on top** (spec §15.2) — the container's answer, and since D1 the ONLY one. /// @@ -610,7 +615,8 @@ pub fn synthetic_home_initial(seed: u32, port: u16, settings: Option) serde_json::to_string_pretty(&initial).map_err(|_| "cannot encode synthetic initial inputs") } -fn enter_application(pms_host: *const c_char, pms_port: c_int) -> Result { +fn enter_application(platform: &'static platform::Platform, pms_host: *const c_char, pms_port: c_int) + -> Result { // What `plx_plex` reports as `X-Plex-Version` is this build's `PLX_VERSION`, which a // `cargo:rustc-env` makes visible to this crate only; before anything can build a header. plx_plex::plex::identity::set_version(env!("PLX_VERSION")); @@ -646,17 +652,18 @@ fn enter_application(pms_host: *const c_char, pms_port: c_int) -> Result Exit { +pub(crate) fn run_application(platform: &'static platform::Platform, pms_host: *const c_char, pms_port: c_int) -> Exit { // Returns how it ended and drops nothing: an early-boot refusal has live workers (diagnostics, // capability probe, telemetry) just as a played session does, so `exit::entry` leaks the `App`. // Ending the process is the entry's (`port::plex_run`); a hosted entry never does. - exit::entry(|| enter_application(pms_host,pms_port), |app| unsafe { run_and_shutdown(app) }) + let _ = plx_os::tv::install(platform.services); // once, before anything below reads `tv` + exit::entry(|| enter_application(platform, pms_host, pms_port), |app| unsafe { run_and_shutdown(app) }) } diff --git a/rust-modules/src/app/notify_bridge_tests.rs b/rust-modules/src/app/notify_bridge_tests.rs index a97a39d590..e1c38b86fa 100644 --- a/rust-modules/src/app/notify_bridge_tests.rs +++ b/rust-modules/src/app/notify_bridge_tests.rs @@ -67,7 +67,7 @@ fn direct_stream_bypasses_supplied_home_ledger_and_tape_in_record_and_replay() { let mt = unsafe { plx_base::task::MainThread::assume() }; for replay in [false, true] { let initial = crate::app::bootstrap::Initial::synthetic_home(17, 32517, None).unwrap(); - let (runtime, retained) = crate::app::bridge::BridgeRetained::controlled_home(|| 0, &initial, &mt, replay); + let (runtime, retained) = crate::app::bridge::BridgeRetained::controlled_home(|| 0, crate::app::platform::Platform::HOST_TEST.shell, &initial, &mt, replay); let mut harness = crate::app::runtime_owners::Harness::from_parts(runtime, retained); let mut bridge = harness.bridge(); boot(&mut bridge, false); capture(&mut bridge, &[a], true); diff --git a/rust-modules/src/app/platform.rs b/rust-modules/src/app/platform.rs index af54e2691b..099b19af5e 100644 --- a/rust-modules/src/app/platform.rs +++ b/rust-modules/src/app/platform.rs @@ -1,24 +1,24 @@ //! The platform the application runs on, as only the loop reads it. //! -//! [`Platform`] is what the platform's entry installs once ([`install`]) before the loop starts. It -//! carries three things, split by who reads them: +//! [`Platform`] is the one value a platform's entry hands `run_application`, so an entry that forgot +//! it does not compile. It carries three things, split by who reads them: //! //! - `services`: [`plx_os::tv::Services`], what the LOWER layers read through the private `tv` -//! accessors (identity, the secure store, Home and the toast, the legacy webOS media verbs). It -//! is installed into `tv` by [`install`] and read from nowhere in the app but there. -//! - `shell`: the window and the bus, [`Shell`]. Its one consumer is the loop (`app::boot` brings -//! the window up, `app::run` drives it every frame), so it is not in the bottom layer's process -//! global. -//! - `diag`: the six frame probes, [`FrameProbe`], read by the same loop and by the one clear hook -//! `app::boot` hands the renderer. +//! 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 and the bus, [`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. +//! - `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`). //! //! `Shell`, `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 values -//! are built by `port.rs`; `ci/check-deps.sh`'s `frame` gate pins the call text of the three +//! 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 plx_os::tv::Services; use std::os::raw::c_void; -use std::sync::OnceLock; /// The platform's window and bus, as the frame loop drives them: the SDL window and its surface, the /// opaque-region hint, and the platform bus pump. Every call runs on the loop thread, and every @@ -60,8 +60,8 @@ pub(crate) trait FrameProbe: Sync { fn fields(&self) -> String; } -/// Everything the application needs from its platform. Built once by the platform's entry -/// (`port.rs` for webOS) and installed before `run_application`. +/// Everything the application needs from its platform. Built by the platform's entry (`port.rs` for +/// webOS) and passed to `run_application`, which keeps it as `App::platform`. pub(crate) struct Platform { pub(crate) services: &'static Services, pub(crate) shell: &'static dyn Shell, @@ -69,6 +69,7 @@ pub(crate) struct Platform { } /// The shell of a process with no platform: a host test, where nothing owns a window or a bus. +#[cfg_attr(not(test), allow(dead_code))] struct HostShell; impl Shell for HostShell { @@ -84,6 +85,7 @@ impl Shell for HostShell { } /// The frame probe of a process with no platform: always unarmed. +#[cfg_attr(not(test), allow(dead_code))] struct HostProbe; impl FrameProbe for HostProbe { @@ -98,27 +100,14 @@ impl FrameProbe for HostProbe { } impl Platform { - /// No platform installed: the loop's host tests, where nothing calls `plex_run`. Every entry is - /// what the no-port defaults answered before the shell and the probe left `tv`. + /// No platform: the loop's host tests, which build an `App` without an entry and say so by passing + /// this to it. Every entry is what the no-port defaults answered before the shell and the probe + /// left `tv`. No production path reads it: an entry that has no platform does not compile. + #[cfg_attr(not(test), allow(dead_code))] pub(crate) const HOST_TEST: Platform = Platform { services: &Services::HOST_TEST, shell: &HostShell, diag: &HostProbe }; } -static INSTALLED: OnceLock<&'static Platform> = OnceLock::new(); - -/// Once, first thing the process does: install the platform's `tv` services for the lower layers and -/// keep the platform for the loop. A second call is refused and changes nothing. -pub(crate) fn install(platform: &'static Platform) { - let _ = plx_os::tv::install(platform.services); - let _ = INSTALLED.set(platform); -} - -/// The installed platform, or [`Platform::HOST_TEST`] when none was (a host test, where every -/// entry is a no-op). The loop reads its shell and its frame probe through this. -pub(crate) fn platform() -> &'static Platform { - INSTALLED.get().copied().unwrap_or(&Platform::HOST_TEST) -} - #[cfg(test)] mod tests { use super::*; @@ -153,13 +142,4 @@ mod tests { p.acquired(); assert_eq!(p.fields(), "", "an unarmed probe has nothing to log"); } - - /// Nothing is installed in a test process, so the loop reads the host-test platform. - #[test] - fn an_uninstalled_process_reads_the_host_test_platform() { - assert!(INSTALLED.get().is_none(), "no test installs a platform; the platform's own entry does"); - let Platform { shell: s, diag: p, .. } = *platform(); - s.pump_bus(); - assert_eq!(p.fields(), ""); - } } diff --git a/rust-modules/src/app/recorder.rs b/rust-modules/src/app/recorder.rs index f29bb6b08d..51aaa3f49d 100644 --- a/rust-modules/src/app/recorder.rs +++ b/rust-modules/src/app/recorder.rs @@ -2117,12 +2117,12 @@ mod tests { let _serial=plx_base::testlock::serial(); let initial=super::super::bootstrap::Initial::synthetic_home(1,32517,None).unwrap(); let mt=unsafe {plx_base::task::MainThread::assume()}; - let (runtime, retained) = super::super::bridge::BridgeRetained::controlled_home(||0,&initial,&mt,true); + let (runtime, retained) = super::super::bridge::BridgeRetained::controlled_home(||0, crate::app::platform::Platform::HOST_TEST.shell, &initial,&mt,true); let mut harness = crate::app::runtime_owners::Harness::from_parts(runtime, retained); let mut bridge = harness.bridge(); bridge.split().measure.width(c"no fonts loaded",28,false); assert!(bridge.take_measurements().is_err(),"construction-order violations must latch"); - let (runtime, retained) = super::super::bridge::BridgeRetained::controlled_home(||0,&initial,&mt,true); + let (runtime, retained) = super::super::bridge::BridgeRetained::controlled_home(||0, crate::app::platform::Platform::HOST_TEST.shell, &initial,&mt,true); let mut harness = crate::app::runtime_owners::Harness::from_parts(runtime, retained); let mut bridge = harness.bridge(); let table=[ diff --git a/rust-modules/src/app/recording_erasure_tests.rs b/rust-modules/src/app/recording_erasure_tests.rs index 280a291b11..fd52c2d77d 100644 --- a/rust-modules/src/app/recording_erasure_tests.rs +++ b/rust-modules/src/app/recording_erasure_tests.rs @@ -164,7 +164,7 @@ fn replay_cannot_authorize_erasure_of_a_recording_target() { temp.assert_only_target(); let before = std::fs::read(temp.path()).unwrap(); let initial = bootstrap::Initial::synthetic_home(17, 32517, None).unwrap(); - let (runtime, retained) = crate::app::bridge::BridgeRetained::controlled_home(|| 0, &initial, &mt, true); + let (runtime, retained) = crate::app::bridge::BridgeRetained::controlled_home(|| 0, crate::app::platform::Platform::HOST_TEST.shell, &initial, &mt, true); let mut harness = crate::app::runtime_owners::Harness::from_parts(runtime, retained); let mut bridge = harness.bridge(); let mut pages = Dispatcher::::new(); diff --git a/rust-modules/src/app/run.rs b/rust-modules/src/app/run.rs index 6b14f88d5f..4dc98fe9de 100644 --- a/rust-modules/src/app/run.rs +++ b/rust-modules/src/app/run.rs @@ -34,7 +34,7 @@ use super::*; use plx_ui::dispatch::Rig as _; use super::bridge::AppHost; -use super::platform::platform; +use super::platform::Shell; use super::exit::{release_of, Release}; /// One lazy product frame-tail hash path for recording and replay grading alike. @@ -172,7 +172,7 @@ impl plx_ui::dispatch::FrameRuntime for ProductFrameRuntime<'_> { if crate::dev::framedump::requested() { crate::dev::framedump::iteration_begin(app); } - platform().shell.pump_bus(); + app.platform.shell.pump_bus(); plx_os::tv::home::poll(); // The one toast key mode owes the viewer (`net::keypin`'s facts), on every route. self.clock_notice.poll(); @@ -334,7 +334,7 @@ impl plx_ui::dispatch::FrameRuntime for ProductFrameRuntime<'_> { unsafe { update(app, fr); } app.rec.content_results(); app.instr.mark(plx_base::diag::heartbeat::Phase::TickDrain); // tick_drain - platform().diag.prepare_begin(); + app.platform.diag.prepare_begin(); publish_resources(app, fr); } fn admit(&mut self, demand: bool) -> bool { @@ -349,7 +349,7 @@ impl plx_ui::dispatch::FrameRuntime for ProductFrameRuntime<'_> { } fn draw_and_swap(&mut self) -> bool { finish_prepare(self.app); - platform().diag.prepare_end(); + self.app.platform.diag.prepare_end(); unsafe { present_and_swap(self.app, &mut self.fr, #[cfg(all(feature = "hostsim", target_os = "linux"))] self.wslg_frame_budget.take()); } @@ -357,7 +357,7 @@ impl plx_ui::dispatch::FrameRuntime for ProductFrameRuntime<'_> { } fn skipped(&mut self) { finish_prepare(self.app); - platform().diag.prepare_end(); + self.app.platform.diag.prepare_end(); unsafe { present_and_swap(self.app, &mut self.fr, #[cfg(all(feature = "hostsim", target_os = "linux"))] self.wslg_frame_budget.take()); } @@ -719,7 +719,7 @@ fn finish_prepare(app: &mut App) { // there is nothing else in the loop that would carry it: a `return` above, or a term that // only ran on player frames, would leave the compositor believing our surface is still // opaque with an ordinary UI on it. - platform().shell.opaque_route(app.player.video_plane_bound); + app.platform.shell.opaque_route(app.player.video_plane_bound); app.instr.mark(plx_base::diag::heartbeat::Phase::Prepare); // prepare // `worstprep=`: the prepare phase is timed on EVERY iteration, presented or not — a // settled screen must never run untimed work at the loop rate (spec §8.3). @@ -848,20 +848,20 @@ fn publish_player_model(app: &mut App) { /// move. `Bridge::opaque_route`/`Bridge::clear_opaque_region` call these instead of naming /// the platform's `shell` directly, which is what keeps the OS-facing text — the thing the `frame` /// gate greps for — in this ONE file rather than split across the loop and the bridge. Each is a -/// pure pass-through: the loop's own per-frame call above (`platform().shell.opaque_route`, from -/// `fr`) and the dispatcher's `Rig` hook (from `Bridge`'s own copy of the same bit) are two -/// independent callers of one primitive, not two implementations of it. `ls2_pump` needs no +/// pure pass-through: the loop's own per-frame call above (`app.platform.shell.opaque_route`, from +/// `app`) and the dispatcher's `Rig` hook (from `Bridge`'s own copy of the same bit and the shell it +/// was constructed with) are two independent callers of one primitive, not two implementations of it. `ls2_pump` needs no /// twin here — `Bridge::ls2_pump` is or stays a no-op, since the dispatcher does not yet run a /// phase this early in the frame. -pub(crate) fn rig_opaque_route(video_plane_bound: bool) { - platform().shell.opaque_route(video_plane_bound); +pub(crate) fn rig_opaque_route(shell: &dyn Shell, video_plane_bound: bool) { + shell.opaque_route(video_plane_bound); } /// See [`rig_opaque_route`]. The `if self.video_plane` guard stays on `Bridge`'s side — this is /// the OS call alone, exactly what `tv::window::clear_opaque_region` was before the shell moved to /// `app::platform`. -pub(crate) fn rig_clear_opaque_region() { - platform().shell.clear_opaque_region(); +pub(crate) fn rig_clear_opaque_region(shell: &dyn Shell) { + shell.clear_opaque_region(); } /// **Simulator only: the television's compositor, over the frame the straighten pass just made.** The @@ -973,7 +973,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. - platform().diag.request(); + app.platform.diag.request(); SDL_GL_SwapWindow(app.win); } app.window_activity.presented(fr.player); @@ -1173,7 +1173,8 @@ fn window_step(stage: plx_telemetry::telemetry::window::Stage, playing: Option (i32, i32, i32, i32) // read of loop state, so the closure only borrows; nothing is moved out of the loop. // An empty selected phase provides the profiler floor for this build; it // deliberately issues no GL commands between its two boundaries. - let App { runtime, bridge: retained, player, pages, glass, diagnostics, lab_toast, + let App { runtime, bridge: retained, player, pages, glass, diagnostics, lab_toast, platform, #[cfg(feature = "threadcheck")] boot_initial, #[cfg(feature = "devtools")] buffer_flip_count, #[cfg(feature = "devtools")] fps_shown, @@ -3141,9 +3142,9 @@ pub(crate) unsafe fn draw(app: &mut App, fr: &mut Frame) -> (i32, i32, i32, i32) // wait for a free back buffer: spanned like every other route's `clear`. // dev (`/tmp/plxnative-framecb`): the frame thread's cost over the wait // and, from the acquired buffer to the swap, over the commit phase. - platform().diag.waiting(); + platform.diag.waiting(); plx_base::diag::spans::span("clear", || glClear(GL_COLOR_BUFFER_BIT)); - platform().diag.acquired(); + platform.diag.acquired(); // ONE resolve of which surface owns the "pipeline is working" signal, // handed to both the transport and the read-out, so the centred read-out // and the transport's inline spinner can never both light in the same @@ -3546,7 +3547,7 @@ pub(crate) unsafe fn report(app: &mut App, fr: &mut Frame) { plx_ui::glassload::step_index(), bridge.home_snap_target(&app.pages), bridge.home_snap_pos(&app.pages), - platform().diag.fields() + app.platform.diag.fields() ) }) { log(&line); @@ -3981,6 +3982,7 @@ pub(in crate::app) mod lifecycle_regression_tests { plx_play_feed::ff_test_support::reset_session_for_test(&mut plx_media::player::reset_common_for_test); let (runtime, bridge) = super::super::bridge::BridgeRetained::for_test(|| 0); let mut app = App { + platform: &crate::app::platform::Platform::HOST_TEST, last_input: Default::default(), loop_t: Default::default(), iters_ct: Default::default(), @@ -11207,7 +11209,7 @@ mod video_plane_gate_tests { // 200-line budget, so "the loop body's own depth" is now two claims: the call is at // `prepare_window`'s own body depth (four spaces, never inside that function's one // `if fr.present`), and `prepare_window` itself is called at the loop body's (eight). - const CALL: &str = " platform().shell.opaque_route(app.player.video_plane_bound);"; + const CALL: &str = " app.platform.shell.opaque_route(app.player.video_plane_bound);"; assert_eq!( src.lines().filter(|l| *l == CALL).count(), 1, diff --git a/rust-modules/src/app/session_dispatch_tests.rs b/rust-modules/src/app/session_dispatch_tests.rs index 2a35d0435a..e4ff5507a0 100644 --- a/rust-modules/src/app/session_dispatch_tests.rs +++ b/rust-modules/src/app/session_dispatch_tests.rs @@ -58,7 +58,7 @@ fn controlled_remaining_commands_refuse_before_any_resource_execution() { let _guard = plx_base::testlock::serial(); let mt = unsafe { plx_base::task::MainThread::assume() }; let initial = super::super::bootstrap::Initial::synthetic_home(17, 32517, None).unwrap(); - let (runtime, retained) = crate::app::bridge::BridgeRetained::controlled_home(|| 0, &initial, &mt, true); + let (runtime, retained) = crate::app::bridge::BridgeRetained::controlled_home(|| 0, crate::app::platform::Platform::HOST_TEST.shell, &initial, &mt, true); let mut harness = crate::app::runtime_owners::Harness::from_parts(runtime, retained); let mut rig = harness.bridge(); let before = rig.session_subhash(); diff --git a/rust-modules/src/app/viewstate_controlled_tests.rs b/rust-modules/src/app/viewstate_controlled_tests.rs index 45ca5e9140..c90acee06c 100644 --- a/rust-modules/src/app/viewstate_controlled_tests.rs +++ b/rust-modules/src/app/viewstate_controlled_tests.rs @@ -25,7 +25,7 @@ use plx_screens::registry::ItemMenuReq; fn refused(replay: bool, fx: AppFx) -> (Option<&'static str>, crate::app::runtime_owners::Harness, usize) { let mt = unsafe { plx_base::task::MainThread::assume() }; let initial = super::super::bootstrap::Initial::synthetic_home(17, 32517, None).unwrap(); - let (runtime, retained) = crate::app::bridge::BridgeRetained::controlled_home(|| 0, &initial, &mt, replay); + let (runtime, retained) = crate::app::bridge::BridgeRetained::controlled_home(|| 0, crate::app::platform::Platform::HOST_TEST.shell, &initial, &mt, replay); let mut harness = crate::app::runtime_owners::Harness::from_parts(runtime, retained); let mut bridge = harness.bridge(); let mut emitted = Vec::new(); diff --git a/rust-modules/src/port.rs b/rust-modules/src/port.rs index 40dfb1c2ed..fc37f87e60 100644 --- a/rust-modules/src/port.rs +++ b/rust-modules/src/port.rs @@ -1,10 +1,10 @@ -//! The webOS port: the two tables that fill the platform, and the C entry that installs them. +//! The webOS port: the two tables that fill the platform, and the C entry that hands them over. //! //! `plx_os::tv::Services` is what the lower layers read, and `app::platform::Platform` adds the shell //! and the frame probe the loop alone reads. Everything outside this module reaches the television //! through those; this is the only place that names `webos`, `keymanager`, `system` and the native //! video sink together. Its functions keep their own `cfg(any(hostsim, test))` arms, so the -//! simulator installs these same tables and behaves as it always did. +//! simulator runs on these same tables and behaves as it always did. use crate::app::platform::{FrameProbe, Platform, Shell}; use std::os::raw::{c_char, c_int, c_void}; @@ -104,7 +104,8 @@ impl FrameProbe for WebosProbe { } } -/// The webOS platform, installed once by `plex_main` before anything reads it. +/// The webOS platform: what `plex_main` hands `app::run_application`, which installs its services +/// for the lower layers and keeps it for the loop. static PLATFORM: Platform = Platform { services: &SERVICES, shell: &WebosShell, diag: &WebosProbe }; /// The C shim's entry (`src/main.c`) and the simulator's (`src/bin/sim.rs`). The `-> c_int` is only @@ -114,8 +115,9 @@ pub extern "C" fn plex_run(pms_host: *const c_char, pms_port: c_int) -> c_int { plex_main(pms_host, pms_port) } -/// The process entry: install the platform, hand over to `app::run_application`, then end the process -/// with the status it returned. +/// The process entry: hand the platform to `app::run_application`, then end the process with the +/// status it returned. The renderer's clear hook (`gfx::install_clear_probe`) takes plain functions, so +/// it is installed here, with the webOS frame probe's own, on the thread the app boots and draws on. /// /// The executable owns the process end: `exit_now` (`_exit`, never libc's `exit`, #1115) right after /// the app returns, in the order the app always ended in. A process that hosts the app never calls it. @@ -128,10 +130,10 @@ pub extern "C" fn plex_run(pms_host: *const c_char, pms_port: c_int) -> c_int { /// `run_application` and `run_and_shutdown` when those started to return an `Exit`: a later edit that /// lets this return does not compile. fn plex_main(pms_host: *const c_char, pms_port: c_int) -> ! { - crate::app::platform::install(&PLATFORM); #[cfg(target_os = "linux")] let _ = plx_os::storage::client::install_activator(plx_os::webos::activate_storage_helper); - plx_base::process::exit_now(crate::app::run_application(pms_host, pms_port).code) + plx_gfx::gfx::install_clear_probe(crate::system::frame_probe_waiting, crate::system::frame_probe_acquired); + plx_base::process::exit_now(crate::app::run_application(&PLATFORM, pms_host, pms_port).code) } const _: fn(*const c_char, c_int) -> ! = plex_main; diff --git a/tests/test_harness.py b/tests/test_harness.py index de8b54695f..4c9b7932bc 100644 --- a/tests/test_harness.py +++ b/tests/test_harness.py @@ -10390,11 +10390,11 @@ def test_frame_gate_catches_a_shell_call_outside_the_loop(self): chain broken onto a continuation line.""" plants = [ ("_check_deps_selftest_frame_receiver.rs", - "pub fn pump() {\n platform().shell.pump_bus();\n}\n", None), + "pub fn pump(app: &App) {\n app.platform.shell.pump_bus();\n}\n", None), ("_check_deps_selftest_frame_path.rs", "pub fn route(shell: &dyn Shell) {\n Shell::opaque_route(shell, true);\n}\n", None), ("_check_deps_selftest_frame_chain.rs", - "pub fn clear() {\n platform()\n .shell\n .clear_opaque_region();\n}\n", None), + "pub fn clear(app: &App) {\n app.platform\n .shell\n .clear_opaque_region();\n}\n", None), ] r = self._plant_all(plants) self._assert_flagged(r, "frame", [ @@ -10411,8 +10411,8 @@ def test_frame_gate_ignores_a_rig_forward_a_string_and_a_comment(self): "_check_deps_selftest_frame_ok.rs", "pub fn forward(bridge: &mut Bridge) {\n bridge.opaque_route(true);\n" " self.bridge.clear_opaque_region();\n}\n" - 'pub const PIN: &str = " platform().shell.opaque_route(bound);";\n' - "// platform().shell.pump_bus();\n", + 'pub const PIN: &str = " app.platform.shell.opaque_route(bound);";\n' + "// app.platform.shell.pump_bus();\n", ) out = r.stdout + r.stderr self.assertEqual(r.returncode, 0, out) From e0945df1ba2bd2dcaa76b88e430e254e8b759c72 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 11:00:48 +0300 Subject: [PATCH 3/4] Platform keeps its services private, the host-test platform is test-only, the frame gate follows the receiver Three things the review of the first W2 cut found. - app::Platform.services was pub(crate), and every group field of Services is pub, so any app module could have called a raw hook and skipped the guards tv's own functions put around it (sound::output's blocking check, secure's test store, home's request counter). The field is now private to app::platform. A platform's entry builds the value with the const fn Platform::new, and run_application calls Platform::install_services, which does the one plx_os::tv::install. Nothing else in the app crate names the hooks, so the tv doc ("read only by tv's own modules") is true again for app. - HostShell, HostProbe and Platform::HOST_TEST carried allow(dead_code) outside tests, so a future entry could have passed the no-op platform to run_application and booted with no window grab and no bus pump. They are cfg(test) now, so that is a compile error. No ledger moves: forks stays at 58 sites and globals at 19. - The frame gate's chain-continuation alternative matched any `.pump_bus(` / `.opaque_route(` / `.clear_opaque_region(` that started a line, whatever the receiver, so a wrapped Rig forward (`self.bridge` then `.opaque_route(true)`, or the dispatcher's `rig` then `.clear_opaque_region()`) would have failed it. A continuation line now counts only when the previous non-blank line ends in `shell`. The self-test plants a wrapped Rig forward on the green side and a `app.platform.shell` break on the red side. Co-Authored-By: Claude --- ci/check-deps.sh | 23 +++++++++++----- rust-modules/src/app/mod.rs | 4 +-- rust-modules/src/app/platform.rs | 46 ++++++++++++++++++++++++-------- rust-modules/src/port.rs | 2 +- tests/test_harness.py | 10 +++++-- 5 files changed, 62 insertions(+), 23 deletions(-) diff --git a/ci/check-deps.sh b/ci/check-deps.sh index e42e83623f..7ef2fd2fe5 100755 --- a/ci/check-deps.sh +++ b/ci/check-deps.sh @@ -1094,11 +1094,13 @@ want hittest && gate_zero hittest 'pointer_focus\(|\b(failure_quality|icon|scrub # The method names alone are NOT the pin: `Rig` has `opaque_route` and `clear_opaque_region` too, and # `Bridge`'s forwarding (`self.bridge.opaque_route(..)`) is not an OS call. So the pin is the RECEIVER: # a call on something named `shell` (`app.platform.shell.pump_bus()`, `p.shell.opaque_route(..)`), on the -# trait by path (`Shell::pump_bus(..)`, `::pump_bus(..)`), or a continuation line of a -# chain that begins on the line before (`.pump_bus(`, which rustfmt may break out of -# `app.platform.shell`). A shell held in a differently named local does not match: this is a text gate -# on the loop's own call shape, and the no-op `Platform::HOST_TEST` shell is driven that way by its pin -# test. +# trait by path (`Shell::pump_bus(..)`, `::pump_bus(..)`), or a continuation line (`.pump_bus(` +# first on its line) whose PREVIOUS non-blank line ends in `shell`, which is how rustfmt breaks +# `app.platform.shell.pump_bus()` apart. A continuation line after any other receiver is not a shell +# call, so a wrapped `Rig` forward (`self.bridge\n .opaque_route(true)`, the dispatcher's +# `rig\n .clear_opaque_region()`) passes. A shell held in a differently named local does not match: this +# is a text gate on the loop's own call shape, and the no-op host-test shell is driven that way by its +# pin test. # # A self-test that spells two of the three call shapes as STRING # LITERALS — it reads app/run.rs's own source text at runtime and compares against a copy of the @@ -1108,12 +1110,19 @@ want hittest && gate_zero hittest 'pointer_focus\(|\b(failure_quality|icon|scrub # double-quote-depth tracking `tmppath` below uses), rather than exempting files by name: an # actual call typed outside a string still fails this gate. `// `-prefixed comment lines (`app/run.rs` keeps one, describing where a call # used to live) are stripped the same way `grep_code` above does for every other rule. -frame_pat='(^|[^A-Za-z0-9_])shell[[:space:]]*\.[[:space:]]*(pump_bus|opaque_route|clear_opaque_region)[[:space:]]*\(|Shell>?::(pump_bus|opaque_route|clear_opaque_region)[[:space:]]*\(|^[[:space:]]*\.[[:space:]]*(pump_bus|opaque_route|clear_opaque_region)[[:space:]]*\(' +# `[.]` and `[(]`, not `\.` and `\(`: `awk -v` would eat the backslashes. +frame_recv='(^|[^A-Za-z0-9_])shell[[:space:]]*[.][[:space:]]*(pump_bus|opaque_route|clear_opaque_region)[[:space:]]*[(]|Shell>?::(pump_bus|opaque_route|clear_opaque_region)[[:space:]]*[(]' +frame_cont='^[[:space:]]*[.][[:space:]]*(pump_bus|opaque_route|clear_opaque_region)[[:space:]]*[(]' +frame_tail='(^|[^A-Za-z0-9_])shell[[:space:]]*$' +# The files to look at: any line of either shape (the cheap `grep` pass); `awk` below decides which hit counts. +frame_pat="$frame_recv|$frame_cont" if want frame; then frame_bad=0 while IFS= read -r f; do [ "$f" = "$SRC/app/run.rs" ] && continue - hits=$(strip_strings_and_comments "$f" | grep -nE "$frame_pat" || true) + hits=$(strip_strings_and_comments "$f" | awk -v recv="$frame_recv" -v cont="$frame_cont" -v tail="$frame_tail" ' + $0 ~ recv || ($0 ~ cont && prev ~ tail) { print NR ":" $0 } + $0 !~ /^[[:space:]]*$/ { prev = $0 }' || true) [ -z "$hits" ] && continue while IFS= read -r h; do ln="${h%%:*}" diff --git a/rust-modules/src/app/mod.rs b/rust-modules/src/app/mod.rs index 24f61e1559..e6966f1e4c 100644 --- a/rust-modules/src/app/mod.rs +++ b/rust-modules/src/app/mod.rs @@ -409,7 +409,7 @@ pub(crate) struct App { /// **The platform this process runs on**, handed to `run_application` by the entry and kept here so /// the loop reads its shell (the window, the opaque region, the bus pump) and its frame probes from /// the value it was given. There is no process-global copy: a missing one is a compile error, not - /// a television that boots with no window. A host test builds an `App` with [`platform::Platform::HOST_TEST`]. + /// a television that boots with no window. A host test builds an `App` with `platform::Platform::HOST_TEST`. platform: &'static platform::Platform, } @@ -662,7 +662,7 @@ pub(crate) fn run_application(platform: &'static platform::Platform, pms_host: * // Returns how it ended and drops nothing: an early-boot refusal has live workers (diagnostics, // capability probe, telemetry) just as a played session does, so `exit::entry` leaks the `App`. // Ending the process is the entry's (`port::plex_run`); a hosted entry never does. - let _ = plx_os::tv::install(platform.services); // once, before anything below reads `tv` + platform.install_services(); // once, before anything below reads `tv` exit::entry(|| enter_application(platform, pms_host, pms_port), |app| unsafe { run_and_shutdown(app) }) } diff --git a/rust-modules/src/app/platform.rs b/rust-modules/src/app/platform.rs index 099b19af5e..d9ffd985a5 100644 --- a/rust-modules/src/app/platform.rs +++ b/rust-modules/src/app/platform.rs @@ -22,7 +22,7 @@ use std::os::raw::c_void; /// The platform's window and bus, as the frame loop drives them: the SDL window and its surface, the /// opaque-region hint, and the platform bus pump. Every call runs on the loop thread, and every -/// hook is required: a platform with nothing to do states [`Platform::HOST_TEST`]'s no-ops. +/// hook is required: a platform with nothing to do states a no-op, as the test-only host platform does. pub(crate) trait Shell: Sync { /// 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). @@ -61,17 +61,41 @@ pub(crate) trait FrameProbe: Sync { } /// Everything the application needs from its platform. Built by the platform's entry (`port.rs` for -/// webOS) and passed to `run_application`, which keeps it as `App::platform`. +/// webOS) with [`Platform::new`] and passed to `run_application`, which keeps it as `App::platform`. +/// +/// `services` is private to this module on purpose: its hooks are the raw verbs, and `tv`'s own +/// functions put their guards around them (`sound::output`'s blocking check, `secure`'s test store, +/// `home`'s request counter). The one thing the application does with it is +/// [`install_services`](Platform::install_services); nothing in `app` can call a hook directly. pub(crate) struct Platform { - pub(crate) services: &'static Services, + services: &'static Services, pub(crate) shell: &'static dyn Shell, pub(crate) diag: &'static dyn FrameProbe, } -/// The shell of a process with no platform: a host test, where nothing owns a window or a bus. -#[cfg_attr(not(test), allow(dead_code))] +impl Platform { + /// A platform's entry states its three parts once, in a `static`. + pub(crate) const fn new( + services: &'static Services, + shell: &'static dyn Shell, + diag: &'static dyn FrameProbe, + ) -> Self { + Platform { services, shell, diag } + } + + /// Hand the lower layers the platform's `tv` services, once: `run_application` does it before + /// anything reads `tv`. A second call is refused by `tv` and changes nothing. + pub(crate) fn install_services(&self) { + let _ = plx_os::tv::install(self.services); + } +} + +/// The shell of a process with no platform: a host test, where nothing owns a window or a bus. Test +/// builds only, so no entry can boot the application on it. +#[cfg(test)] struct HostShell; +#[cfg(test)] impl Shell for HostShell { fn bind_window(&self, _win: *mut c_void) {} fn grab_surface(&self, _win: *mut c_void) {} @@ -84,10 +108,11 @@ impl Shell for HostShell { fn pump_bus(&self) {} } -/// The frame probe of a process with no platform: always unarmed. -#[cfg_attr(not(test), allow(dead_code))] +/// The frame probe of a process with no platform: always unarmed. Test builds only. +#[cfg(test)] struct HostProbe; +#[cfg(test)] impl FrameProbe for HostProbe { fn request(&self) {} fn prepare_begin(&self) {} @@ -99,13 +124,12 @@ impl FrameProbe for HostProbe { } } +#[cfg(test)] impl Platform { /// No platform: the loop's host tests, which build an `App` without an entry and say so by passing /// this to it. Every entry is what the no-port defaults answered before the shell and the probe - /// left `tv`. No production path reads it: an entry that has no platform does not compile. - #[cfg_attr(not(test), allow(dead_code))] - pub(crate) const HOST_TEST: Platform = - Platform { services: &Services::HOST_TEST, shell: &HostShell, diag: &HostProbe }; + /// left `tv`. It exists in test builds only: a production entry that passes it does not compile. + pub(crate) const HOST_TEST: Platform = Platform::new(&Services::HOST_TEST, &HostShell, &HostProbe); } #[cfg(test)] diff --git a/rust-modules/src/port.rs b/rust-modules/src/port.rs index fc37f87e60..060fad0397 100644 --- a/rust-modules/src/port.rs +++ b/rust-modules/src/port.rs @@ -106,7 +106,7 @@ impl FrameProbe for WebosProbe { /// The webOS platform: what `plex_main` hands `app::run_application`, which installs its services /// for the lower layers and keeps it for the loop. -static PLATFORM: Platform = Platform { services: &SERVICES, shell: &WebosShell, diag: &WebosProbe }; +static PLATFORM: Platform = Platform::new(&SERVICES, &WebosShell, &WebosProbe); /// The C shim's entry (`src/main.c`) and the simulator's (`src/bin/sim.rs`). The `-> c_int` is only /// the C signature: `plex_main` never returns, so neither does this. diff --git a/tests/test_harness.py b/tests/test_harness.py index 4c9b7932bc..efb4c5d575 100644 --- a/tests/test_harness.py +++ b/tests/test_harness.py @@ -10395,22 +10395,28 @@ def test_frame_gate_catches_a_shell_call_outside_the_loop(self): "pub fn route(shell: &dyn Shell) {\n Shell::opaque_route(shell, true);\n}\n", None), ("_check_deps_selftest_frame_chain.rs", "pub fn clear(app: &App) {\n app.platform\n .shell\n .clear_opaque_region();\n}\n", None), + ("_check_deps_selftest_frame_chain_tail.rs", + "pub fn pump(app: &App) {\n app.platform.shell\n .pump_bus();\n}\n", None), ] r = self._plant_all(plants) self._assert_flagged(r, "frame", [ ("_check_deps_selftest_frame_receiver.rs", "pump_bus"), ("_check_deps_selftest_frame_path.rs", "opaque_route"), ("_check_deps_selftest_frame_chain.rs", "clear_opaque_region"), + ("_check_deps_selftest_frame_chain_tail.rs", "pump_bus"), ]) @_grades("frame") def test_frame_gate_ignores_a_rig_forward_a_string_and_a_comment(self): - """GREEN: `Rig` has `opaque_route` and `clear_opaque_region` of its own (`Bridge` forwards them), + """GREEN: `Rig` has `opaque_route` and `clear_opaque_region` of its own (`Bridge` forwards them, and + the dispatcher calls them on its `rig`, either on one line or wrapped onto a continuation line), and a pin test spells the loop's calls as string data. None of those is a call on the shell.""" r = self._plant( "_check_deps_selftest_frame_ok.rs", "pub fn forward(bridge: &mut Bridge) {\n bridge.opaque_route(true);\n" - " self.bridge.clear_opaque_region();\n}\n" + " self.bridge.clear_opaque_region();\n" + " self.bridge\n .opaque_route(true);\n" + " rig\n .clear_opaque_region();\n}\n" 'pub const PIN: &str = " app.platform.shell.opaque_route(bound);";\n' "// app.platform.shell.pump_bus();\n", ) From 6d6f1de6b648193fa432232a07ee43d65ac2f3f0 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 11:30:05 +0300 Subject: [PATCH 4/4] Comments the platform split made false: the port installs nothing, the probe edges come from port.rs The [platform webos] fence comment said `port` holds "the table the port installs at boot" and that everything else reaches the television through the `tv` interfaces the port fills at boot. port.rs holds `SERVICES` and `PLATFORM` and installs neither: `run_application` installs the services through `Platform::install_services`, and the window, bus pump and frame probes are `app::platform`'s `Shell` and `FrameProbe`. `gfx::install_clear_probe` said the application hands its edges down at boot; they are `crate::system::frame_probe_*`, installed by `port::plex_main` before `run_application`. The sink rule said port.rs "installs" a `VideoSink`; it names one in `SERVICES.legacy_webos_media`. Comments only. Co-Authored-By: Claude --- ci/check-deps.sh | 2 +- ci/module-layers.ini | 15 +++++++++------ rust-modules/gfx/src/gfx.rs | 8 +++++--- 3 files changed, 15 insertions(+), 10 deletions(-) diff --git a/ci/check-deps.sh b/ci/check-deps.sh index 7ef2fd2fe5..f48a647e67 100755 --- a/ci/check-deps.sh +++ b/ci/check-deps.sh @@ -1140,7 +1140,7 @@ else fail "frame: $frame_bad line(s) of a privileged OS-primitive call outside a fi # frame # sink: the Starfish/ACB verbs (`tv::sink::VideoSink`) are the player's alone (step L15). Only -# `player/`, `play-uri/`, the native `webos/` port, and `port.rs` (which installs one) +# `player/`, `play-uri/`, the native `webos/` port, and `port.rs` (which names one) # and `tv.rs` with `tv/` (which hold it) name `tv::sink::installed` or `VideoSink`; so does # `app/adapters/backends.rs`, the boot composition that resolves the installed display once for the # ACB plane's boot and hands it on (it was `player/plane_boot.rs`; the composition root is where the diff --git a/ci/module-layers.ini b/ci/module-layers.ini index 1718bb4bdc..e0dacdde5d 100644 --- a/ci/module-layers.ini +++ b/ci/module-layers.ini @@ -196,11 +196,14 @@ members = # Not a layer: the modules that exist only because the target is webOS. Identity, capability and # repair (`webos`), the LS2 key stores (`keymanager`), the SDL/Wayland window glue (`system`), the # Starfish/ACB playback seam (`webos::video_sink`, which implements `tv::sink::VideoSink`) and `port`, -# which holds `plex_run` and the table the port installs at boot. They stay in their layers above -# for the crate split, and nothing outside the port may name them. +# which holds `plex_run` and the platform's two tables: `SERVICES` (what `tv` serves) and `PLATFORM` +# (those services plus the app's `Shell` and `FrameProbe`), which it hands to `run_application`, which +# installs the services. They stay in their layers above for the crate split, and nothing outside the +# port may name them. # The native port does not carry the simulator's stand-ins: `play-feed/src/ffi_host.rs` is the -# simulator's own `VideoSink` (it lives with the Feed backend, in `[play_feed]`), outside this fence. Everything else reaches the television through -# the interfaces in [os]'s `tv` that the port fills at boot (docs/module-layers.md, step -# L15). Nothing outside names the port, so it can become its own crate on top, and another TV OS -# another port beside it. +# simulator's own `VideoSink` (it lives with the Feed backend, in `[play_feed]`), outside this fence. +# Everything else reaches the television through [os]'s `tv`, except the window, the bus pump and the +# frame probe, which the loop reaches through `app::platform`'s `Shell` and `FrameProbe`, implemented in +# `port.rs` (docs/module-layers.md, step L15). Nothing outside names the port, so it can become its own +# crate on top, and another TV OS another port beside it. members = webos keymanager system port diff --git a/rust-modules/gfx/src/gfx.rs b/rust-modules/gfx/src/gfx.rs index da67d32133..177e13c46f 100644 --- a/rust-modules/gfx/src/gfx.rs +++ b/rust-modules/gfx/src/gfx.rs @@ -754,9 +754,11 @@ fn probed_clear(presented: impl FnOnce() -> bool, clear: impl FnOnce()) { /// The frame's first framebuffer-0 command is where this driver parks the wait for a free back /// buffer, and on every route but the player it is the page's [`frame_clear`]. The dev frame -/// probe (`/tmp/plxnative-framecb`) prices that wait, but its clock is `os`'s and this -/// crate does not depend on `os`, so the application hands the two edges down once at boot: -/// `waiting` runs just before the clear, `acquired` just after it returns. +/// probe (`/tmp/plxnative-framecb`) prices that wait, but its clock is the platform's +/// (`crate::system` on webOS, which the loop reaches as `app::platform::FrameProbe`), in the +/// application crate above this one, so the platform's entry (`port::plex_main`) hands the two +/// edges down once, before `run_application`: `waiting` runs just before the clear, `acquired` +/// just after it returns. pub fn install_clear_probe(waiting: fn(), acquired: fn()) { CLEAR_PROBE.with(|p| p.hooks.set(Some((waiting, acquired)))); }