From eb74ef882cc5e83f11addd3a15e9aa5142b74c70 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 09:14:12 +0300 Subject: [PATCH 01/26] gfx: one name per uniform statement, so the Tizen emulator compiles the ambient shader (#1481) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Samsung's TV 10.0 emulator (YaGL GLES 2.0 over the host's Mesa) refused the ambient vertex shader, so plx_gfx could not start there: a required shader's rejection stops the app from starting. The one statement in `shaders/` that declared several names, `uniform vec4 u_atl, u_atr, u_abr, u_abl;` in `vs_ambient.vert`, is now four statements, and a host test keeps every shader to one name per `uniform`, `varying` or `attribute` statement. On the emulator (probe build `samsung/hello-tpk` at e8da14ce6) the unsplit source fails with `0:37(9): error: syntax error, unexpected NEW_IDENTIFIER` at `varying highp vec2 v_dither_nc;` and the split one compiles, as does a cut-down variant before and after; with the split, all 14 required programs compile and link and plx_gfx draws, with glGetError clean. A `#version 100` preamble also made it compile but failed the link on a language-version mismatch, so it was dropped. Why YaGL rejects the multi-declarator is not established, and the optional straighten program still fails there with the same kind of error. On the LG dev set the driver compiles both spellings to the same GPU code: `glGetProgramBinaryOES` returned byte-identical Mali binaries before and after for all four programs built from `vs_ambient.vert` (APROG, APROG_PLAIN, SCRIM_PROG, ART_WASH) and for two unchanged controls, with identical uniform and attribute tables, so frame cost cannot change. The scan blanks comments and preprocessor lines, cuts statements at `;`, `{` and `}`, and counts a storage-qualified statement with a comma outside every `(…)` and `[…]`; its self-test covers the array and multi-line forms and leaves comments, parameter lists, array sizes, locals and longer identifiers alone. It walks `shaders/`, so a new shader is covered by being added. --- rust-modules/gfx/src/gfx.rs | 206 ++++++++++++++++++- rust-modules/gfx/src/shaders/vs_ambient.vert | 10 +- 2 files changed, 205 insertions(+), 11 deletions(-) diff --git a/rust-modules/gfx/src/gfx.rs b/rust-modules/gfx/src/gfx.rs index 2d69342b4b..6eae044146 100644 --- a/rust-modules/gfx/src/gfx.rs +++ b/rust-modules/gfx/src/gfx.rs @@ -9554,23 +9554,14 @@ mod tests { /// directory, so a new shader is covered by being added. #[test] fn no_shader_source_names_a_dev_trigger() { - let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/shaders"); - let mut scanned = 0; let mut found = Vec::new(); - for entry in std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display())) { - let path = entry.expect("a directory entry").path(); - // Lossy: a stray non-UTF-8 file (a Finder `.DS_Store`) is not a shader and must not - // turn this red; the bytes the scan reads are the same either way. - let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); - let text = String::from_utf8_lossy(&bytes); - scanned += 1; + for (path, text) in shader_files() { for (n, line) in text.lines().enumerate() { if line.contains("plxnative-") { found.push(format!("{}:{}: {}", path.display(), n + 1, line.trim())); } } } - assert!(scanned > 0, "no shader sources under {}", dir.display()); assert!( found.is_empty(), "shader sources are embedded verbatim in the binary, comments included, and the \ @@ -9580,6 +9571,201 @@ mod tests { ); } + /// Every file under `shaders/`, as (path, text), in path order: the one directory walk the + /// whole-directory source scans share, so a new shader is covered by being added. + fn shader_files() -> Vec<(std::path::PathBuf, String)> { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/shaders"); + let mut files = Vec::new(); + for entry in std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display())) { + let path = entry.expect("a directory entry").path(); + // Lossy: a stray non-UTF-8 file (a Finder `.DS_Store`) is not a shader and must not + // turn a scan red; the bytes a scan reads are the same either way. + let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + files.push((path, String::from_utf8_lossy(&bytes).into_owned())); + } + assert!(!files.is_empty(), "no shader sources under {}", dir.display()); + files.sort(); + files + } + + /// The `uniform` / `varying` / `attribute` statements in `src` that declare more than one name + /// (`uniform vec4 a, b;`), as (line of the storage keyword, the statement on one line). + /// + /// Comments and preprocessor lines are blanked first (a trailing `// (x, y, 1/w, 1/h)` note + /// holds commas), then the text is cut into statements at `;`, `{` and `}`; a statement + /// holding a storage keyword as a whole word is multi-declarator when a comma sits outside + /// every `(…)` and `[…]`, which keeps an array size such as `u_sc[12]` out of the count and + /// catches `u_a[2], u_b` and a statement that runs over several lines. + fn multi_declarator_statements(src: &str) -> Vec<(usize, String)> { + // Pass 1: blank comments and preprocessor lines, keeping every newline so line numbers hold. + let mut code = String::with_capacity(src.len()); + let mut chars = src.chars().peekable(); + let mut line_start = true; + while let Some(c) = chars.next() { + match (c, chars.peek().copied()) { + ('/', Some('/')) => { + while chars.peek().is_some_and(|&n| n != '\n') { + chars.next(); + } + } + ('/', Some('*')) => { + chars.next(); + let mut prev = ' '; + for n in chars.by_ref() { + if n == '\n' { + code.push('\n'); + } + if prev == '*' && n == '/' { + break; + } + prev = n; + } + } + ('#', _) if line_start => { + // A directive runs to the end of its line, or past a `\` continuation. + let mut prev = ' '; + while let Some(&n) = chars.peek() { + if n == '\n' && prev != '\\' { + break; + } + if n == '\n' { + code.push('\n'); + } + prev = n; + chars.next(); + } + } + _ => { + code.push(c); + if c == '\n' { + line_start = true; + } else if !c.is_whitespace() { + line_start = false; + } + } + } + } + // Pass 2: statements, and the commas at depth 0 of the storage-qualified ones. + let mut found = Vec::new(); + let mut line = 1; + let mut stmt = String::new(); + let mut stmt_line = 1; + for c in code.chars().chain(std::iter::once(';')) { + if !matches!(c, ';' | '{' | '}') { + if stmt.is_empty() && c.is_whitespace() { + if c == '\n' { + line += 1; + } + continue; + } + if stmt.is_empty() { + stmt_line = line; + } + stmt.push(c); + if c == '\n' { + line += 1; + } + continue; + } + let storage = stmt + .split(|ch: char| !(ch.is_alphanumeric() || ch == '_')) + .any(|w| matches!(w, "uniform" | "varying" | "attribute")); + if storage { + let mut depth = 0i32; + let mut multi = false; + for ch in stmt.chars() { + match ch { + '(' | '[' => depth += 1, + ')' | ']' => depth -= 1, + ',' if depth == 0 => multi = true, + _ => {} + } + } + if multi { + found.push((stmt_line, stmt.split_whitespace().collect::>().join(" "))); + } + } + stmt.clear(); + } + found + } + + /// **The scan that keeps a shader to one name per `uniform` / `varying` / `attribute` + /// statement is itself right.** It must count `uniform vec4 a, b;` and its array and multi-line + /// forms, and must not count a comma in a comment, a function's parameter list, an array + /// size, a local declaration or a longer identifier that merely contains a storage keyword. + #[test] + fn the_one_name_per_declaration_scan_counts_exactly_the_storage_statements_with_two_names() { + let hits = |src: &str| multi_declarator_statements(src).len(); + for src in [ + "uniform vec4 a, b;", + "varying highp vec2 a, b;", + "attribute vec2 a, b;", + "uniform vec4 u_a[2], u_b;", + "uniform vec4 u_a, u_b[2];", + "invariant varying vec4 a, b;", + "uniform float a,\n b;", + "uniform vec4 a, b, c;", + "#ifdef X\nuniform vec4 a, b;\n#endif", + "float f(int i) { return 1.0; }\nuniform vec4 a, b;", + ] { + assert_eq!(hits(src), 1, "must count: {src:?}"); + } + for src in [ + "uniform vec4 a;\nuniform vec4 b;", + "uniform vec4 u_sc[12];", + "uniform highp vec4 u_art; // the art quad: (x, y, 1/w, 1/h) in authored pixels", + "// uniform vec4 a, b;", + "/* uniform vec4 a,\n b; */ uniform vec4 c;", + "float shade_block(int i, vec2 px) { return 1.0; }", + "void main(){ vec2 a, b; a = b; }", + "float uniform_scale = 1.0, y;", + "#define PAIR uniform vec4 a, b;", + "#define LONG(a) \\\n uniform vec4 a, b;\nuniform vec4 c;", + "uniform vec4 u_m[2 * (1 + 2)];", + "", + ] { + assert_eq!(hits(src), 0, "must not count: {src:?}"); + } + // The line is that of the storage keyword, past the blanked comments and directives. + assert_eq!( + multi_declarator_statements("// note\n#define A 1\n\nuniform vec4 a,\n b;\nuniform vec4 c;"), + vec![(4, "uniform vec4 a, b".to_string())] + ); + } + + /// **A shader declares one name per `uniform` / `varying` / `attribute` statement.** The Samsung + /// TV 10.0 emulator (YaGL over Mesa llvmpipe) rejected `VS_AMBIENT_DITHERED` at + /// `varying highp vec2 v_dither_nc;` ("syntax error, unexpected NEW_IDENTIFIER"), and a required + /// shader's rejection stops the app from starting. `vs_ambient.vert`'s + /// `uniform vec4 u_atl, u_atr, u_abr, u_abl;` was the only multi-declarator in `shaders/`, and + /// splitting it is what made the program compile there. Measured on that emulator with the Tizen + /// hello-world probe (`samsung/hello-tpk` at `e8da14ce6`): the unsplit source failed, the split + /// source compiled, a cut-down variant did the same, and with the split all 14 required programs + /// compiled and linked and `plx_gfx` drew. Why YaGL rejects the statement is not established (the + /// message is the one Mesa gives for raw desktop GLSL 1.10, where `highp` is an ordinary + /// identifier), and an optional program, the straighten copy variant, still fails there with the + /// same kind of error and no multi-declarator, its cause also not established. Every other source + /// already spelled one name per statement, and a driver that reads either spelling sees the same + /// program, so the sources keep to the spelling the other drivers have read. It lists the + /// directory, so a new shader is covered by being added. + #[test] + fn every_shader_keeps_one_name_per_declaration_in_a_uniform_varying_or_attribute_statement() { + let mut found = Vec::new(); + for (path, text) in shader_files() { + for (line, stmt) in multi_declarator_statements(&text) { + found.push(format!("{}:{line}: {stmt}", path.display())); + } + } + assert!( + found.is_empty(), + "a multi-declarator made the TV 10.0 emulator (YaGL) reject `vs_ambient.vert` until it \ + was split, so a `uniform` / `varying` / `attribute` statement names one variable; \ + split these:\n{}", + found.join("\n") + ); + } + /// **A frozen menu glass reads its ground ONCE per fragment, dim included.** The modal dim's /// ink on a menu is the latched underlay field times a weight (`underlay::Role::Dim`), and the /// glass's body is that same field (`UnderlayField::ground_tex`), both read at the screen point diff --git a/rust-modules/gfx/src/shaders/vs_ambient.vert b/rust-modules/gfx/src/shaders/vs_ambient.vert index 18d82628f4..18d46a0948 100644 --- a/rust-modules/gfx/src/shaders/vs_ambient.vert +++ b/rust-modules/gfx/src/shaders/vs_ambient.vert @@ -25,7 +25,15 @@ attribute vec2 a_pos; uniform vec4 u_rect; uniform vec2 u_screen; -uniform vec4 u_atl, u_atr, u_abr, u_abl; +// One name per `uniform` / `varying` / `attribute` statement, here and in every shader. The four +// corners below were one `uniform vec4 a, b, c, d;` statement, the only multi-declarator in `shaders/`. +// The Samsung TV 10.0 emulator (YaGL over Mesa) rejected this program with that statement and compiles +// it with the split (measured there; a host test in `gfx.rs` keeps every such statement to one name). +// The uniforms are found by name, so a driver that reads either spelling sees the same program. +uniform vec4 u_atl; +uniform vec4 u_atr; +uniform vec4 u_abr; +uniform vec4 u_abl; varying vec4 v_col; #ifdef PLX_DITHER_NC // The dither tile's coordinate (`shaders/dither.glsl`, cost rule 4): target px / NOISE_DIM, linear From 4894d0f8b1209f22aaa32c3ab5954dcc1e45f5a6 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 09:25:57 +0300 Subject: [PATCH 02/26] Platform plan: webOS, the desktop simulators and Samsung Tizen as platforms of one app (#1480) The plan for running PlxNative on webOS, the desktop simulators and Samsung Tizen from one repo is now in `docs/platform-ports.md` (step W0 of discussion #1460). Documentation only. - One crate per platform sits on top of the app crate: `plx_platform_webos`, `plx_platform_desktop` and `plx_platform_tizen`. Exactly one is compiled per build, chosen by a `PLATFORM` make axis. There is no runtime capability registry. - `tv::Port` becomes `tv::Services`, and every hook in it is required except the legacy webOS media group. - The contracts land first: W3a, a memory-only store mode; W3b, URI drivers reporting their own display evidence; W3c, `run_application` returning its exit. After them, W1-W7 make the platforms real crates, W8 splits the shared pieces and W9 brings up Tizen. - Samsung goes through a thin C# .NET `.tpk` host that loads the Rust `.so`. Rust creates its own Ecore_Wl2 window and EGL context on its own thread. - The MVP is W9 on the TV 10.0 x86_64 emulator, labelled emulator only: the interface on a dev-token boot against `tests/mock_pms.py`, with no playback. Signing in against the mock plex.tv comes later, because `plex_tv()` accepts only loopback and that rule is not widened. Retail sets wait on H1 (armv7 or aarch64) and H2 (whether the `.so` loads under a Public certificate). - The emulator evidence (E1-E13) is folded in: the hosted window, EGL and key path, curl to the mock, and plx_gfx on YaGL after the one-declaration split. - `docs/module-layers.md` describes the landing order: `system` and `port` are modules of the top crate, not of `plx_os`. The top crate stays the staticlib root until L15f puts the platform crates on top, and W9 adds `plx_platform_tizen`. --- docs/module-layers.md | 76 +- docs/platform-ports.md | 1808 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 1866 insertions(+), 18 deletions(-) create mode 100644 docs/platform-ports.md diff --git a/docs/module-layers.md b/docs/module-layers.md index f3d15e3572..0a7b78b0fc 100644 --- a/docs/module-layers.md +++ b/docs/module-layers.md @@ -15,16 +15,22 @@ up the split. **Thirteen of the fourteen layers, `base`, `machine`, `os`, `gfx`, `machine/`, `os/`, `gfx/`, `net/`, `ui/`, `plex/`, `telemetry/`, `data/`, `session/`, `media/`, `appkit/` and `screens/`; "Split 1: base" to "Split 13 (screens)" below, and "Splits 9 and 10 together" for how those two were combined). **The split is finished.** What is left in -`rust-modules/src/` is the last layer, `app`, and it stays the top crate `plxnative-modules`: the +`rust-modules/src/` is the last layer, `app`, and it is the top crate `plxnative-modules` until L15f +puts `plx_platform_webos` and `plx_platform_desktop` on top of it, the webOS one taking over the staticlib the +Makefile links (`docs/platform-ports.md`, W7b): the loop, its adapters, every dev and diagnostic surface, and the application's side of the port -(`port`, `system`, and the other `[platform webos]` members that are not in a layer crate). They are +(`port`, `system`, and the other `[platform webos]` members that are not in a layer crate). Today they are the one `staticlib` the Makefile links and the one place that may name every other layer, so there -is nothing below it to split off. **Decision: the `[platform webos]` members stay where they are** -(`webos`, `keymanager` and `system` are modules of `plx_os` (the Starfish sink is -`webos::video_sink`), and `port` of the top crate) **until a second TV OS exists.** A port crate now would have one -customer and a boundary drawn from guesses about the second; the fence in `ci/check-module-layers.py` -(a reference from outside `[platform webos]` to a member of it fails) already holds the line a crate -would, and L15b is where the port's OS-neutral shape is worked out. +is nothing below it to split off. **Decision, revised 2026-11-20: the `[platform webos]` members stay where they are +until the simulator is its own platform, and then leave for crates of their own on top.** +(`webos` and `keymanager` are modules of `plx_os`, the Starfish sink being `webos::video_sink`; `system` and `port` +are modules of the top crate.) The earlier decision was to wait **until a second TV OS exists**: +a port crate would have had one customer and a boundary drawn from guesses about the second. The desktop platform, the +simulator and `PlxNative.app` as a platform of their own (L15d), is a second implementation of the same interfaces, +which is what the wait was for, so the crates are extracted (L15f) after it and no second TV OS has to exist first +(`docs/platform-ports.md`, Decision 3; "L15c to L15h" below maps its workstreams to steps). Until then the fence +in `ci/check-module-layers.py` (a reference from outside `[platform webos]` to a member of it fails) already holds +the line a crate would, and L15b is where the port's OS-neutral shape is worked out. The gate is `ci/check-module-layers.py` and its config is `ci/module-layers.ini`. The gate also checks each extracted crate's local Cargo declarations, including build, dev, @@ -326,6 +332,12 @@ proves the references are gone and nothing more; L15b is open. | **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). | | **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. | +| **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. | +| **L15g** the webOS facts and the remaining `hostsim` (L15b item 3) — **planned** | — | W8: the `target_arch = "arm"` and `target_os = "linux"` sites sorted into "is webOS" (a platform value or runner) and "is 32-bit ARM" or "is Linux" (stays), then the library name lists, `paths`, the packaging and the 363 `feature = "hostsim"` lines outside the fence (360 cfg lines and three doc comments). | +| **L15h** the OS-neutral Feed sink (L15b item 1) — **planned** | — | W11: `plx_acb` (an `[acb]` layer) takes the ACB plane owner and the URI media verbs out of `os`, the Feed-side ACB results become neutral, and the bind sequence moves behind a neutral sink. Needs the television. | ### L15: the webOS port @@ -421,12 +433,16 @@ still webOS's. Three things are left: `sf_on_event`/`acb_on_event` and `sink_counter_kind(ty, major)` in `player/mod.rs` move behind it, into the port. This changes where the stages and the callback decode live and when they run, so it needs the television: see the reasons above. -2. **The simulator as its own port.** `ffi_host` and the `hostsim` arms of `webos`, `system` and - `keymanager` become a second `Port` table, a second implementation of the same interfaces, - instead of the webOS table running its host arms. That keeps both honest. The webOS-shaped types - in `tv` also need neutral shapes then: `tv::secure::Backend` names the two webOS key managers - and is part of the on-disk envelope, and `tv::sandbox`'s verdict and repair describe webOS's - own device jail. +2. **The simulator as its own port.** `ffi_host` and the simulator's arms of `system` and `port` + become a second `Port` table, a second implementation of the same interfaces, instead of the + webOS table running its host arms. That keeps both honest. The stand-ins in `webos` and + `keymanager` do not move: the nine `any(hostsim, test, test-support)` items are what the + simulator runs today (`launch_home`, `system_locale`, `sound_output`, `bind_window`, the + keymanager client, `deliver`, `call_hbc` among them), and they stay compiled for tests and + `test-support` with only their `hostsim` term gone (`docs/platform-ports.md`, W4). The + webOS-shaped types in `tv` also need neutral shapes then: `tv::secure::Backend` names the two + webOS key managers and is part of the on-disk envelope, and `tv::sandbox`'s verdict and repair + describe webOS's own device jail. 3. **The webOS facts the gate cannot see.** The gate sees names, not literals, and not modules that stay where they are. The port takes these too: @@ -443,10 +459,34 @@ still webOS's. Three things are left: and `.ipk` packaging. L15b is done when the sink is OS-neutral, the simulator is its own port, and these facts are the -port's. The port can then leave its layers for a crate of its own on top: it names `app` to start -it, and nothing names it. `plxnative-modules` stays the staticlib the Makefile links, now holding -the port. Another TV OS is another port in that position. The simulator binary, `src/bin/sim.rs`, -is already a separate crate there, and enters through `port::plex_run`. +port's. The port does not wait for all three before it leaves its layers. The order, amended 2026-11-20, is item 2 +(the simulator as its own port), then the extraction, then item 3 and item 1 ("L15c to L15h" below). Extracted, the +port is a crate of its own on top: it names `app` to start it, and nothing names it. `plx_platform_webos` +produces the staticlib the Makefile links, and `plxnative-modules` stays the application crate beneath it. Another TV +OS is another platform in that position. The simulator binary, `src/bin/sim.rs`, is already a separate crate there, +and enters through `port::plex_run` until W4 gives it its own platform value. + +### L15c to L15h: the platform plan + +`docs/platform-ports.md` plans making the application run and plug in on several platforms: webOS, the desktop +simulator and `PlxNative.app`, and Samsung Tizen. It carries the design, the facts behind it and the workstreams W0 to +W13; the six steps below are its layer-graph side, and the lettering L15c to L15h is introduced by this amendment so +the migration table can carry them (L15b's three items keep their meaning and are L15d for item 2, L15g for item 3 +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). + +The order is L15c; then L15d and L15e, which overlap (W3d then W4 runs beside W5, and W6b, W6 and W6c wait for both); +then L15f; then L15g and L15h. So the extraction (L15f, W7) follows item 2 (L15d, W4), and item 3 (L15g, W8) and +item 1 (L15h, W11) come afterwards. The earlier order put the extraction after all of L15b, which would have made W7 +wait for the neutral sink: item 1 needs the television and gates nothing the other platforms need, and W8 follows W7. +The steps are L15b's three items and the moves that serve them: the contracts they rest on (L15c), the events and +composition (L15e) and the extraction (L15f). The other workstreams are not steps of this table: W0 (the record of the +plan, this amendment), W1 (the `PLATFORM` build axis), W9 (the Tizen platform, which adds `plx_platform_tizen` and a +`[platform tizen]` section to the arrangement L15f creates, as a user of the neutral port and not a step toward it), +and W10, W12 and W13 (its URI and Feed drivers and the desktop products), which add code to the `plx_platform_tizen` +and `plx_platform_desktop` crates. ### Then the split diff --git a/docs/platform-ports.md b/docs/platform-ports.md new file mode 100644 index 0000000000..c516f7c551 --- /dev/null +++ b/docs/platform-ports.md @@ -0,0 +1,1808 @@ +# Platform ports: running PlxNative on more than webOS + +Status: approved 2026-11-20 and recorded here (workstream W0). This is a plan, not a description of the tree: a +workstream is done when its PR has landed. The owner's decisions are at the end of the page and the body follows +them; no owner question is open. The waves, each lane's files, its bounded tests and its television and +build-bench flags are in "Workstreams". The layer-graph side of the plan is `docs/module-layers.md`, steps L15c to +L15h. Unprefixed ids are this page's own: F facts, T Tizen research, E emulator evidence, H hello-world questions and +W workstreams. + +The sections "Verified facts" (F1-F52), "Tizen research" (T1-T8) and "Emulator run, 2026-11-20" (E1-E13) quote the +tree at `e9924f0f9`, before the bottom-layer rename (Wave R), so they keep the old names and the old line numbers; +"Names and paths" gives the map. Every other section uses the final names (Wave R's own text names the old ones it +replaces), and "today", "now" and "as today" anywhere on the page mean that tree. Hello-world refs +(`tizen/hello/...`) pin to `origin/samsung/hello-tpk` at `72c5cd82a`, except the H5 result (E10), which pins to +`64c609a46`, the tester build of E11, `1afe1978b`, and the probe build of E13, `e8da14ce6`. + +## History + +The plan was written by a planner and revised over six rounds with a critic and after two independent reviews of its +drafts; the critic approved it on 2026-11-20. Finding ids in the body: review B1-B3, M4-M11, C1-C10 (the two reviews); +critic M1-M12, F1-F12, G1-G8, N1-N5 (its passes, in order); "critic round N, point M" (earlier rounds). Every finding +was accepted unless an owner decision of 2026-11-20 overrode it, and the body says where it landed; the changelog and +review texts are not kept, and no section depends on a revision number. + +## Names and paths + +Wave R renames the bottom layer first, so the design below uses the final names: crate `plx_os` (directory +`rust-modules/os`, layer `[os]`, inner module `tv` unchanged), fence sections `[platform ]` +(was `[port ]`), platform crates `plx_platform_webos`, `plx_platform_desktop`, `plx_platform_tizen`. +Verified facts F1-F52, T1-T8 and E1-E13 quote the tree at `e9924f0f9`, before the rename, where the old names +stand, so every grep in them reproduces: read `plx_platform` as `plx_os`, `rust-modules/platform/` as +`rust-modules/os/`, `[platform]` as `[os]` and `[port X]` as `[platform X]`; the bare path `platform/src/...` +(relative to `rust-modules/`, as `ci/list-caps.ini` and the certificates spell it) is `os/src/...`, and the shell +variable `SRC_PLATFORM` is `SRC_OS`. Every `path:line` citation on this page is a line of the `e9924f0f9` tree, in +the target-shape and workstream sections as well as the fact sections: the rename can reorder `use` lines and later +changes move the rest, so a lane re-verifies a citation by grep on the symbol, and every brief carries this map. +Layer rules quoted from `ci/module-layers.ini` are quoted at `e9924f0f9` (`[play_uri] uses = base platform +playback_contract`, `:148`): after Wave R the same line reads `uses = base os playback_contract`. + +## Problem + +PlxNative is one Rust application (17 layer crates, the 13 named in `docs/module-layers.md:12-17` plus playback_contract, media_codecs, play_uri and play_feed, under the top crate `plxnative-modules`) that +reaches the device through `plx_os::tv`, a function-pointer table filled once at boot by the +webOS port (`port::plex_run`). Today there is exactly one implementation of that table. The desktop +simulator and `PlxNative.app` install the SAME webOS table and take the `hostsim` arms inside the +webOS code. The interfaces are also still webOS-shaped: a 29-verb Starfish sink, ACB plane verbs, +an LG key-manager enum in the on-disk envelope, SDL-event bytes in the loop. + +The owner wants the app runnable and pluggable on several platforms: +- webOS (shipping, must keep shipping at every step); +- Samsung Tizen through a C# .NET `.tpk` host that P/Invokes our native library; +- the macOS and Windows/Linux simulators and the macOS app as real platforms of their own; +- later possibly iOS/tvOS and Android (no Flutter path: owner decision). + +This plan gives: +- the target crate and layer shape and the platform interfaces: window/surface, events/input, + lifecycle, key store, identity/caps, video sink and playback backends, entry point; +- what each platform supplies; +- a PLATFORM build axis next to FLAVOR, with packaging and CI; +- what moves where, and an ordered multi-PR migration from the `[platform webos]` fence (`[port webos]` before + Wave R) and the open L15b step of `docs/module-layers.md`. + +Every step keeps three rules: layers point only down, machines stay Sans-IO, and the ledgers only +shrink. + +## Verified facts + +Citations in this section quote the tree at e9924f0f9 with its old names (see "Names and paths"). + +### The fence and the gate + +- F1. `[port webos]` has members `webos keymanager system port` (`ci/module-layers.ini:191-202`, last + line `members = webos keymanager system port`). The gate checks ports generically: + - a member listed in two ports is an error (`ci/check-module-layers.py:81-82`); + - a reference passes only when source and target are in the SAME port (`:139-140`, `if source is + not None and source[1] == target[1]: continue`). + + So a second or third `[port X]` section needs no gate code. Anything two ports share must be a + LAYER, not a port member. That holds for another section under today's keyword. Renaming the + keyword to `platform` (the owner's naming) is gate code: the parser keys on + `startswith('port ')` (`ci/check-module-layers.py:68,74`), and a layer `[platform]` already + exists (`ci/module-layers.ini:53`) (critic M9; F36). Wave R renames that layer (to `os`) and then the keyword, first and alone. +- F2. `port` and `system` are members of `[app]` (the `[app]` members line ends `system release_line + port`). `webos` and `keymanager` are members of `[platform]`. Port members stay placed in their + layers (`ci/check-module-layers.py:14-15`). A port is "Not a layer" (ini comment under `[port + webos]`). +- F3. The design record: + - The port crate waits: "the `[port webos]` members stay where they are ... **until a second TV OS + exists.**" (`docs/module-layers.md:21-27`, the quoted words at `:24`). + - "L15b is done when the sink is OS-neutral, the simulator is its own port, and these facts are the + port's. The port can then leave its layers for a crate of its own on top" (`:434-436`). So the + record orders crate extraction AFTER all of L15b. + - The three L15b items are: item 1 (OS-neutral sink, needs the television) at `:407-412`, item 2 + (simulator as its own port, plus neutral `tv::secure::Backend` and `tv::sandbox`) at `:413-418`, + and item 3 (webOS facts the gate cannot see) at `:419-433`. +- F4. `ci/allow/layers.txt` is empty and only shrinks (`docs/module-layers.md:30-34`). The ledger + ratchet compares every `ci/allow/` counter with the BASE branch. A family directory + (`workers/ globals/ forks/ fxlanes/`) is one total, "so an entry may move between the area files of + a family" (`ci/check-ledger-ratchet.py` docstring). No `ci/allow` file names `webos.rs`, + `keymanager`, `port.rs` or `system.rs` as an entry. `grep -n 'webos\|keymanager\|system\.rs\|port\.rs' + ci/allow/...` hits only explanatory text: `wall.txt:7` names `app/window_activity.rs` "out of + system.rs". + +### The port table + +- F5. `plx_platform::tv::Port` (`rust-modules/platform/src/tv.rs:21-55`) has 27 fields in one flat + table: + - 11 identity, caps, sandbox, store, locale, sound, home and toast entries; + - 7 window, surface, opaque-region and bus entries (`bind_window` .. `pump_bus`, `:33-40`); + - 6 `frame_probe_*` entries; + - `sink`, `display_sink` and `uri_media`. + + `ABSENT` holds the no-port defaults (`:62-90`). `install` uses a `OnceLock` (`:92-95`), and only + `tv`'s own modules read the table (`:100`). +- F6. The webOS table is `rust-modules/src/port.rs:25-53`. `plex_run` installs it, then calls + `install_activator(webos::activate_storage_helper)` under `cfg(target_os = "linux")`, then + `app::run_application` (`:57-63`). Under `hostsim` the same table points its sink at `HOST_SINK` + (`:11-12`). +- F7. `src/bin/sim.rs` enters through `use plxnative_modules::port::plex_run;`. +- F8. The interfaces in `rust-modules/platform/src/tv/` total 3127 lines (`wc -l`): + - `plane.rs` (1598) is "The ACB video-plane owner" (`:1`). It is ACB semantics, and it is named from + BELOW `app`: `grep -rln 'tv::plane\|PlaneOwner'` hits these files: + - `play-uri/src/{backend,picture_gate,uri_lifecycle,acb_drive,uriprobe_drive}.rs`; + - `play-feed/src/{control,ffi_host,feed_pump,native_executor}.rs`; + - `media/src/player/{mod,pump,engine,uriprobe_drive,test_physical}.rs`. + - `sink.rs` (484): `DisplaySink` at `:85` (window create/place/destroy plus the `plane_*` ACB verbs) + and `VideoSink: DisplaySink` at `:155`. + - `uri.rs` (156): `UriMedia` at `:71`. `tv::uri`/`UriMedia` is named in `play-uri` (7 files), + `platform` (4) and `media` (1). + - The app crate also names the plane owner: `src/app/adapters/backends.rs:25-31` (`use + plx_platform::tv::plane::{self, PlaneFacts, PlaneOwner};` and three more), plus + `src/app/run_uri_boot_tests.rs` and `src/dev/uriprobe_tests.rs` (critic round 1, point 1). + +### `hostsim` and the television cfgs + +- F9. There are 465 `feature = "hostsim"` lines. Per crate (`grep -rn 'feature = "hostsim"' --include='*.rs' | wc -l`): + - src 232, media 71, platform 58, gfx 30, telemetry 28, plex 21, base 16, play-feed 9; + - 0 in ui, appkit, screens, data, session, net, machine, play-uri and playback-contract. +- F10. Of those, 102 are inside the fence members (`grep -c` per file): + - `system.rs` 53, `webos.rs` 22, `webos/caps.rs` 8, `port.rs` 7; + - `webos/toast.rs` 5, `webos/jail_repair.rs` 5, `keymanager.rs` 2, `webos/video_sink.rs` 0. + + The other 363 `feature = "hostsim"` lines are outside, so L15b item 2 alone does not retire `hostsim`. Of + those 363, 360 are cfg lines and three are doc comments (`base/src/paths.rs:1347`, + `src/app/session_picker_regression_tests.rs:326`, `src/app/surface_navigation_tests.rs:4`; `git grep -n + 'feature = "hostsim"' -- '*.rs' | grep -E ':[0-9]+:\s*//'` finds them). +- F11. `hostsim` is forwarded to ten crates (`rust-modules/Cargo.toml:179`). Its comment relies on + the app crate being "a leaf with no dependents, so feature unification can never enable it behind + someone's back". `make check` DOES resolve the whole workspace at once: + - `lint` runs `cargo +RUST_TOOLCHAIN clippy --workspace --all-targets` (`Makefile:2094`); + - `Makefile:1682` (`check --lib --tests -p plxnative-modules -p plx_base ...`) and `:1776` (`test + --lib -p ...`) resolve many packages in one invocation. + + So a workspace member that depends on the app crate WITH `hostsim` would switch `hostsim` on for the + whole lint pass, and the television arms would stop being linted. W7 states the mechanism that + prevents it. +- F12. "Television" is also spelled `target_arch = "arm"`, in 20 files under `rust-modules` + (`grep -rln 'target_arch = "arm"' --include='*.rs' rust-modules | grep -v /target | wc -l`). They + include `platform/src/{webos.rs, webos/caps.rs, storage/mod.rs, storage_service/*}`, + `plex/src/plex/session*.rs`, `telemetry/*`, `src/lib.rs`, `src/app/boot.rs`, four `build.rs`, + `storage/src/main.rs` and `build_support/host_link.rs`. + + `target_os = "linux"` is 151 lines in 27 files (`grep -rn 'target_os = "linux"' --include='*.rs' + rust-modules | grep -v /target`). Per directory: + - platform 45, telemetry 41, plex 21, src 20, base 11, storage 8, play-feed 5; + - the largest files are telemetry/persistence.rs 23, plex/session/persistence.rs 15, + storage_service/runtime.rs 12, src/app/run.rs 10, and 9 each in base/task.rs, storage/mod.rs, + storage/client.rs and telemetry/native.rs (critic round 1, point 3; per-directory sums checked). + + A Tizen ARM build is `linux` + `arm` + not `hostsim`, so today it would compile every webOS arm. +- F13. `target_os = "android"` appears 8 times: 5 in `base/src/task.rs` and 3 in + `telemetry/src/telemetry/crashreport.rs`. + +### SDL, input and the loop + +- F14. The app crate calls SDL directly: + - the extern block is in `src/app/mod.rs:154-175`; + - `SDL_Init` is at `app/boot.rs:1547`, `SDL_CreateWindow` at `:1648` and `SDL_GL_CreateContext` at + `:1652`; + - the swap is at `app/run.rs:974` and the poll at `app/run.rs:1066-1069`. + + Source-text pins search for those calls: tests at `app/boot.rs:705-785` look for `"SDL_Init("` and + `"SDL_CreateWindow("`, and `app/run.rs:11467` looks for `"SDL_GL_SwapWindow(app.win);"`. +- F15. SDL is also below `app`: + - `base/src/surface.rs:38-39`; + - `base/src/diag/heartbeat.rs:30-31`; + - `gfx/src/gpu_timer.rs:89`; + - `gfx/src/text.rs:220`, with `TTF_` in `gfx/src/text.rs` and `base/src/fontcov.rs`. + + Labels rasterize through SDL2_ttf (the `src/ass_text.c` header reads "The application draws its + labels with the television's SDL2_ttf 2.0.x"). The link line is `LIBS_REAL = -lSDL2 -lSDL2_ttf + -lGLESv2 -lluna-service2 -lglib-2.0 -lwayland-client` (`Makefile:404-405`). +- F16. Events are decoded from raw SDL bytes in two layouts. "LG's fork writes `state` (u32) at +16, + the webOS keycode at +20 and the SDL sym at +24. Stock SDL2 ... every field the app reads is at a + different offset" (`app/events.rs:24-34`), and `decode_key` switches on `cfg!(feature = "hostsim")` + (`:84-86`). Lifecycle arrives as SDL app events: `0x103|0x104` (background), `0x106` (restore) and + `SDL_QUIT` (`app/run.rs:1194-1196, 1239-1242`). The recorder encodes them by SDL code: + `app.rec.input(super::recorder::enc_lifecycle(et))` (`app/run.rs:1236-1237`). +- F17. There are two key vocabularies, and the raw codes are part of the contract: + - `plx_machine::machine::Key { Up, Down, Left, Right, Ok, Back, Other }` + (`machine/src/machine.rs:867-875`) and `InputKind` with `Key { key, sym, wcode, edge, at_edge + }`, `Pointer`, `Click`, `Drag` and `Wheel` (`:878-905`). The app builds these at + `src/app/bridge.rs:5471-5561`. + - `plx_ui::consts::Key` (`ui/src/consts.rs:269`) comes from `classify(sym, wcode)` (`:322`), with + `SDLK_*` (e.g. `:137`) and LG `WCODE_*` (`:184-190`). + + `consts.rs` is NOT movable as a whole. It names `plx_machine::machine::Key` (`:380` + `classify_input`), `plx_platform::labcfg::is_trigger_key` (`:484`), and `crate::card_row`/`crate::Rect` + (`:52-113`). + + "`Other` does NOT mean unbound" (`consts.rs:262-267`): the CH rocker, `SDLK_PAGE*`, + `SDLK_BACKSPACE`/`SDLK_CLEAR` and the PIN digits are read from the raw sym/wcode. These files name + `WCODE_`/`classify(`: + - `screens/src/{login,hud_settings,detail/trailer,player/*}.rs`; + - `src/app/{events,bridge,run,mod,adapters/huds,adapters/poster,adapters/session}.rs`; + - `src/app/adapters/poster/{refresh,baked_tests}.rs`. + + Target shape 2 and F33 (review M6) change what crosses the platform edge. +- F18. `MainThread` is "Proof that the holder runs on the SDL main thread" (`base/src/task.rs:105`). + It is minted in production at `src/app/mod.rs:635` (`let main_thread = unsafe { + plx_base::task::MainThread::assume() };`), inside the app's boot path, not in `port.rs`. Its + mechanism is a `!Send + !Sync` ZST (`task.rs:107-109`). So the token tracks the thread that runs + the boot and loop, whichever OS thread that is. + +### C sources + +- F19. `src/*.c` has 12 files (`ls src/*.c`, header lines read): + - `main.c` (195), the webOS executable shim. It runs the Sentry spool re-entry (`:162`), the + event, crash and stderr descriptors with `dup2` (`:163-187`), `plx_crash_install` (`:188`), + `plx_launch_args(argv[1])` (`:191`) and `setenv("SDL_WEBOS_ACCESS_POLICY_KEYS_BACK", ...)` + (`:193`), then `plex_run`. + - `access.c` and `exit.c`: "the executable's own definition of libc `access`" and "`exit`". + - `crashtrace.c`: the signal tracer. + - `sentry_context.c`. + - `starfish.c` (602): the Feed seam. + - `video_plane.c` (418): ACB on 2.2.3-4.10, the SDL exported window on 5.3.1-11.2 (`:14-37`). + - `svg.c`: nanosvg. + - `ass.c`, `ass_fonts.c` and `ass_text.c`: compiled into libass-plx. + - `gpdebug.c`: debug only. + +### Playback + +- F20. A backend-neutral contract exists in `plx_playback_contract`: + - `DriverSet` (`playback-contract/src/lib.rs:276-283`): `capabilities`, `dispatch`, `poll`, + `discard_staged` and `exit_disposition`; + - `UriDriver: DriverSet` (`uri.rs:60-81`): `stage_source`, `cancel_staged`, `plane_owned`, + `maps_track` and `ready_to_start`. + + `UriNotReady` has the single variant `AcbHandle` (`uri.rs:84-88`). The contract is NOT clean of + webOS names: F31 lists the types and result variants that carry ACB (critic M2). The composition is `compose_backends` (`app/adapters/backends.rs:141-164`), + with `acb_init` at `:64`. +- F21. `play-uri` is the webOS URI driver. Its files include `acb_bind.rs`, `acb_drive.rs` and + `acb_envelope.rs`, and its layer uses `base platform playback_contract` (`ci/module-layers.ini` + `[play_uri]`). Production routes choose Feed: the qualifier "returns Unknown ... so ordinary routes + still choose Feed" (`media/src/player/CLAUDE.md:25-33`). The opt-in reaches the planner as a + snapshot in `ResolveEnv::uri_engine` (same file, `:50-53`). `ResolveEnv` is in + `media/src/route/decision.rs` (`grep -rln`). +- F22. The Feed bind stages are in `pump`'s `Stage` machine, and no host test covers them + (`docs/module-layers.md:375-385`). + +### Build and packaging + +- F23. The Makefile is webOS-only: + - `WEBOS_SDK` (`Makefile:246`), `TOOLPREFIX` (`:261`), `CC = ci/arm-cc.py` (`:262`) and `SYSROOT` + (`:265`); + - `RUST_TARGET = armv7-unknown-linux-gnueabi` (`:881`), and `RUST_LIB` names + `libplxnative_modules.a` (`:882`). + + `FLAVOR ?= debug` (`:128`) is validated by `ci/flavor.py --list` (`:126`) and is install identity + (APPID `:135`, RUNDIR `:155`). `PLAYBACK_BACKENDS ?= both` maps to `play-uri`/`play-feed` + (`:565-577`). Other targets: `ipk:` at `:2219`, `sim-macos:` at `:2521`, `sim-linux:` at `:2573`, + `sim-wsl: sim-linux` at `:2595` and `macapp:` at `:2668`. There is no PLATFORM variable: `grep -n + '^PLATFORM' Makefile` printed nothing. The query targets are explicit `print-flavor:`, + `print-appid:`, ... (`Makefile:189-207`), and there is no `print-%` pattern rule (`grep -n + '^print-[A-Za-z%_-]*:'`). +- F24. The app crate is `crate-type = ["rlib"]` (`rust-modules/Cargo.toml:61`), and the ARM archive + comes from `cargo rustc --crate-type staticlib`. `ci/test_no_host_staticlib.py` fails a non-rlib + crate type on the app crate (its docstring). + +### Path-pinned checks, run-time names, identity + +- F25. These name the moving files (`grep -rln` over `ci tools tests .github`): + - the `sink` rule in `ci/check-deps.sh:17,1119-1131`; + - `ci/test_sim_backend.py`, `ci/mkmacapp.py:8,129`, `ci/test_test_crate.py:214` and + `.github/workflows/ci.yml:379`; + - `ci/allow/wall.txt` and `ci/allow/forks/play-feed.txt`; + - `tests/test_harness.py` and `tests/fixtures/persistence/generated/generators.patch`. + + `ci/proofs/platform-generated-enums.json` with `ci/readonly_generated.py` pins 8 sources by sha256 + (`SOURCES`, `ci/readonly_generated.py:17-19`): + - `platform/Cargo.toml`, `platform/src/lib.rs`, `platform/src/i18n/mod.rs`, `platform/build.rs`; + - `platform/build_support/catalog.rs`, `build_support/install_identities.rs`; + - `machine/src/lib.rs`, `machine/src/machine.rs`. + + Its docstring reads "certificate changes require source review". It pins `CERTIFICATE_SHA256` and + per-file hash lists in code, and no regenerating tool exists. So an edit to any of the 8 is a + REVIEWED certificate change in the same PR. `platform/src/lib.rs:26` is `pub mod keymanager;` and + `:33` is `pub mod webos;`. A new `tv::*` file is declared in `tv.rs` and does not touch the pin. + + `ci/check-staticlib-artifact.py` has `CRATE = "plxnative_modules"` and requires exactly one `.a` for + that crate at the path make links (critic round 1, point 8). `ci/build-budgets.json` budgets the + stripped ARM binary. `Makefile` itself is a prerequisite of `RUST_LIB` (`Makefile:1017`), and many + `ci/test_*.py` read Makefile text (critic: 27 files; not recounted). +- F26. `plex::identity::PLATFORM` is `"webOS"` (`plex/src/plex/identity.rs:86`), sent as + `X-Plex-Platform` (`plex/src/plex/client.rs:307`, `account.rs:443`). +- F27. The run-time library name lists: + - `EGL_SONAMES: &[&str] = &["libEGLfk.so.2", "libEGL.so.1", "libEGL.so"]` (`gfx/src/egl.rs:110`); + - libcurl's `["libcurl.so.4", "libcurl.so.5", "libcurl.4.dylib"]` + (`net/src/net/connect_only.rs:14`). +- F28. Branch `samsung/hello-tpk` now carries the hello-world. `git log --oneline + origin/main..origin/samsung/hello-tpk` lists `72c5cd82a` ("tizen/hello: sign with a Samsung + certificate profile, stream the log over UDP"), `ab0ba40ca` ("tizen/hello: log without eprint, ...") + and `f51d0db87` ("Samsung Tizen TV step 1: hello-world .tpk (throwaway test build)"). It is + `tizen/hello/`: a standalone Rust cdylib (critic: `crate-type = ["cdylib"]`, only `libc`, its own + `[workspace]`) plus a C# `CoreUIApplication` host. Its README (`git show + samsung/hello-tpk:tizen/hello/README.md`, `:8`, `:19-21`) says: + - "It answers four questions": host starts, `.so` loads, window draws, keys arrive; + - "`OnCreate` calls the library once on the main thread; the library creates an Ecore_Wl2 window + there (Ecore's main loop runs on that thread), registers key handlers there, and a separate Rust + thread owns the EGL context and draws." + + That is window Option B with GL on a non-main thread. It links no SDL2/SDL2_ttf and plays no + media. Since `72c5cd82a` it signs only with a Samsung certificate profile (E2) and streams every log line + over UDP (E5); the emulator run (E1-E9) used that build. + +### Evidence from the first reviews: F29-F39 (each citation checked in the tree) + +- F29. The process end (review B1). + - `run_application` is `-> !` (`rust-modules/src/app/mod.rs:642`). An early-boot refusal calls + `exit_now(code)` (`:645`). A played session ends in `run_and_shutdown -> !` (`:561`): `run::shutdown` + (`:572`), the telemetry guard drop, then `exit_now(code)` (`:576`). + - `exit_now` is `fflush(NULL)` then `_exit` (`base/src/process.rs:30`). Its module doc (`:1-10`) says + why not `exit`: OpenSSL's `atexit` cleanup frees locks under the detached curl workers + (notification feed, metadata, watchlist, auth probes), a SIGSEGV on a clean exit (#1115), and the + firmware libraries' finalizers run under a worker. `src/exit.c` interposes `exit` only in the TV + executable (F19), so a host-loaded `.so` has no such guard. `src/bin/sim.rs:149-152` already says + `plex_run` ends the process itself. + - The hello-world leaves teardown to process exit when its render thread is still busy after 2 s + (`origin/samsung/hello-tpk:tizen/hello/plx/src/lib.rs:79-80, 342-365` at `72c5cd82a`: `terminate` + starts at `:342` and the timeout message is at `:359`; `:339-358` and `:339` were the earlier commit's + lines). +- F30. Session persistence (review B2). + - `save_legacy_fallback_locked` (`plex/src/plex/session.rs:4826`) is reached when the canonical + write fails (`:4777`). It tries `tv::secure::seal` (`:4837`). With no protected record and a seal + that answers `None`, it serializes the session and writes it to each candidate path in turn + (`:4872-4882`): a plaintext credential file. So `secure::NONE` (seal answers `None`) does not give + an ephemeral sign-in. An earlier draft of W3 and W9 said it did; that was wrong. + - The session file has four writers behind one door, and `peek()` serves a cache filled by reads + and durable writes (`plex/src/plex/CLAUDE.md`). No memory-only mode exists: + `session/memory_tests.rs` is the preference "memory door", unrelated. +- F31. URI admission and the shared contract (review B3, critic M1, M2, review M8). + - `Binding { Exported{canvas}, Acb, Unbound }` is in the shared contract (`playback-contract/src/uri.rs:13`). + `ProductEvidence::unqualified_on` compares the display mode with the LG constant + `tv::sink::VP_EXPORTED` (`media/src/route/uri_preflight.rs:45`). `display_path_offerable` + (`:76-82`) is false for `Unbound`, true for `Acb`, and true for `Exported` only with + `display_exported` and a positive canvas. `permits` (`:84-91`) needs that plus callable and + certified pause and seek and the requirement flags. `certified` is all false until the viewer's + opt-in (`opted_in`, `:55-69`). A Tizen URI driver today would have to fake `VP_EXPORTED`, a + canvas and an opt-in. The composition builds that evidence at `app/adapters/backends.rs:386`. + - `BackendSet` is already "the set a composition's installed drivers form" + (`playback-contract/src/lib.rs:34-48`). `compose_backends` ends with + `session.install_backends(adapter.composed_backends())` (`backends.rs:163`). The session starts + at `BackendSet::FEED` (`media/src/route/decision.rs:387,1686`). So `default_backend` repeats a + fact the set already holds. The recipe table already carries `URI_PMS_*` conversions + (`media/src/route/backend_policy.rs:130-155`). + - ACB is in contract RESULT types too: `Accepted { resume_acb }` (`playback-contract/src/feed.rs:385`), + `Played { resume_acb }` (`:416`), `AcbPlaneUnload` (`:1115`), `UriNotReady::AcbHandle` + (`uri.rs:84-88`). The URI-side one goes in W3b (F45: three files name it, nothing pins its text), + before Tizen's driver. The Feed-side ones are debt that exits in W11a, because Tizen has no Feed + before W12. + - `tv::sink` (`sink.rs:85-197`) and `tv::uri` (`uri.rs:1,71-76`) are Starfish, ACB and + `com.webos.media` verbs, read by shared `media` through globals (`media/src/player/mod.rs:97,1676`). + A fake URI driver exists: `playback-contract/src/test_support.rs:143` (`FakeUriDriver`). +- F32. Boot order and the thread token (review M4, M5). + - `acb_init(&mt)` runs at `app/boot.rs:2043` inside `if !controlled`, before + `plx_media_codecs::ffi::boot()`. `PlayerAdapter::new(mt)` consumes the token (`:2316`) and + `compose_backends` runs later (`:2323`, every build). So `acb_init` is an early phase and + composition a late one. The review cited `:2042` (the `if`) and `:2311` (a comment). + - `MainThread` is the struct at `base/src/task.rs:129`. The "this is the SDL main thread" safety + text is on `assume` (`:138`), which `app/mod.rs:635` calls on whichever thread runs the boot. + - The hello-world creates the window and registers key handlers on the host main thread inside + `plx_tizen_create` (`lib.rs:126`; window `:229`, handlers `:235`) and starts a separate render + thread (`:251`). The emulator run exercised it (E6, E8). +- F33. Keys as the code has them (review M6, critic M7). + - `plx_machine::machine::Key` has seven variants (F17). `InputKind::Key` carries `key`, `sym`, + `wcode`, `edge`, `at_edge` (`machine/src/machine.rs:878-891`), and `InputKind::Wheel { dy }` exists + (`:903`). The tape canon writes `sym` and `wcode` (`:816-819`). `machine.rs` is hash-pinned (F25), + so changing the machine's key type is a certificate review plus a tape-format change. + - The wheel delta is read at a different offset per host: an `i32` at +20 on the TV, a float at +32 + under `hostsim` (`app/run.rs:1855-1877`), so the pointer event needs a wheel member. + - `classify` takes Pause and Play from `wcode` alone but their alternates and Stop from either field, + and `SDLK_SELECT` is really END (`ui/src/consts.rs:137-145, 322-375`). `classify_input` trusts the + machine's canonical key first (`:380`). `classify` alone is `Other` for paging (`page_dir`, `:433`), + digits (`screens/src/profiles.rs:340`) and the edit keys, so a decode guard needs all four readers. + - Readers of the raw pair: `WCODE_` or `classify(` appears in 7 files under `screens/src` + (`grep -rlE 'WCODE_|classify\(' screens/src`); a looser pattern (`sym`/`wcode` in any spelling) + gives 49. The critic's "16 screens files" did not reproduce; an earlier F17 list had 16 names across + `screens` and `src/app`. + - `remote_token_key` (`app/events.rs:211-246`) names 19 tokens plus `k:,`. +- F34. Who calls the shell and the frame probes (critic M4). + - Every `tv::window::` caller is in the app crate: `src/app/boot.rs:1460-1729`, `bridge.rs:35,3374-3377` + and `run.rs:173-11199` (the critic listed boot and run, not `bridge.rs`; hits past `run.rs:8200` are in or + beside test modules and were not classified one by one). The dispatcher reaches them through a rig + trait that `app/run.rs` implements (`ui/src/dispatch.rs:728-730`). `ci/check-deps.sh:1097` (the `frame` + gate) pins the call text `tv::window::(pump_bus|opaque_route|clear_opaque_region)(` to `run.rs`. +- F35. The hostsim gate's package list (review M11). + - `check-cargo-unit-hostsim` (`Makefile:1764`) names eleven packages inline (`:1776`: `plxnative-modules + plx_base plx_machine plx_platform plx_gfx plx_plex plx_telemetry plx_data plx_session plx_media + plx_play_feed`), the same eleven as `HOSTSIM_SUITE` (`:1713`). `HOSTSIM_PKGS` (`:1859`) is only + the developer's `make test-hostsim` list. An earlier draft named the second as the gate's. + - The app's lifecycle suite is `#[cfg(all(test, feature = "hostsim", feature = "play-feed"))] mod + lifecycle_regression_tests` (`app/run.rs:3914-3915`). +- F36. Naming (critic M9) and the size of Wave R. `plx_platform` is the bottom-layer crate + (`rust-modules/Cargo.toml:231`, `ci/module-layers.ini:53,64`). Counted: 3280 lines (3438 + occurrences) in 296 `.rs` files, 12 `Cargo.toml` files plus `Cargo.lock`, the nested `CLAUDE.md` files + (`ui/src`, `media/src/player`), and 26 files under `ci/ tools/ tests/ .github/ Makefile docs/` + (`grep -rIlw plx_platform`). Two readonly certificates name the package or its paths and pin every member + manifest and `Cargo.lock` (F47: both pin every member manifest and `Cargo.lock`, not only the crate's + `Cargo.toml` and `lib.rs`; `ci/readonly_generated.py:60` is the package field, that certificate's own hash is at + `:16`). The layer holds more than `tv` (`webos storage keymanager devcaps imgcache i18n labcfg tv playback_trace`, + `ci/module-layers.ini:53-64`). 25 tracked files name the path `rust-modules/platform/` (`git grep -Il`; F48 adds the + bare and assembled spellings), among them `.agents/agents/fw-compat-reviewer.md`, `tools/plxnative-lab`, + `ci/check-build-budgets.py`, `.claude/hooks/release-config-check-test.py` and `docs/`. Source-text pins and CI + tests embed the name: `src/app/boot.rs:640,668` (`"plx_platform::storage::diagnostics::start("`), + `src/app/run.rs:11184,11199` (`plx_platform::tv::window::opaque_route(...)`), `ci/test_ci_split.py:58-67` + (a regex over Makefile `-p plx_platform`), `tests/test_harness.py:9916`, `ci/test_test_crate.py`, + `ci/test_no_host_staticlib.py`, `ci/test_build_bench.py` and `tools/build-bench.py`. The gate keys on the + keyword (`ci/check-module-layers.py:68,74`). These are the size of Wave R. +- F37. What the hello-world build can answer (review M9, M10); the emulator's results are E1-E13. + - It builds one library per `--arch`: `arm` for retail 2021+ sets, `x86_64` ("the default emulator + target") and `i686` (the older emulator) (`tizen/hello/README.md:41-43`). The emulator cannot test + `Tizen.Multimedia` (`:120`), and the run did not probe it (E9). The host's TFM is `tizen80` + (`PlxHello.csproj:14`), and its comment says coverage of later firmware by `tizen80` alone is + UNVERIFIED (`:7-8`); E4 settles that for the Tizen 10 emulator only. + - So an emulator run loads the x86 library. It answered H3 and H4 (E6, E8) and answers neither the + retail process architecture (H1) nor whether the NDK-linked ARM library loads under a Public + certificate (H2). The Samsung pages the review cites were not read here. +- F38. Fourth-platform leftovers (critic M12). `tv::device::Info` has webOS fields (`codename`, `api`, + `name`, `major`; `platform/src/tv/device.rs:15-25`). `sandbox::Verdict` is the `/dev/rtkmem` probe + (`sandbox.rs:1-14`). +- F39. What a launch with no credential on disk already reads (Decision 7; checked in the tree). + - The two halves of a session already separate: `split_canonical` (`plex/src/plex/session.rs:692`) cuts a + `Session` into a public payload (preferences, `client_id`, pins, recents: `split_public`, `:713`) and a protected + auth string; `public_session` (`:790`) is the credential-free snapshot. The legacy fallback does NOT use that + cut: it writes the whole `Session` in one file (`fallback_bytes(s)`, `:4812`; `save_legacy_fallback_locked`, + `:4826`). + - What sign-out keeps is defined twice. `Mutation::ClearTenure` (`platform/src/storage/state.rs:709`) keeps + `public.preferences` minus the seven `ACCOUNT_BOUND_PREFERENCES` (`:184-192`) and drops pins, recents and + `client_id`. The file authorities keep only `install_preferences::Retained`, `language` and `ui_resolution` + (`session/install_preferences.rs:10`), "credential-free ... cannot authorize login" (`:1-3`); `clear_for_erase` + saves it before a file backend's credential file goes (`session.rs:5344`) and after a DB8 sign-out whose helper + clear failed (`:5481`); "Delete all local data" erases it (`:5473`). With no session file the legacy read ends + at `install_preferences::load()`: a `Retained` file reads as `Cleared { kept }`, none as `Missing` (`:4222`). + - Per-profile settings live in `profile_prefs`, account-bound ("a household member's habits, so it goes with the + credentials", `state.rs:175`), so they are forgotten with the credentials. + - `client_id` is in the public half, not a credential, and `plex/CLAUDE.md:398-399` says "a new id raises a + new-device alert". First boot persists it through a token-less session save (`load`'s doc, `session.rs:4326`; + `load_login_client_id`, `:4336-4349`), reusing one process-local id when storage is unavailable. + `install_preferences::Saved` is `deny_unknown_fields`, version 1 (`:28-38`): it cannot carry the id without a + new version. + - The authority is chosen by `target_arch = "arm"`, not by a platform value (`session/persistence.rs:1400-1425`, + `commit_data` `:288-308`); a Tizen ARM build would select the DB8 arm with no helper behind it (F12). The + `MemoryOnly` gate sits above that selection, and W8a re-keys it. + +### Evidence from the second reviews: F40-F46 (each citation checked in the tree) + +- F40. Exits a hosted process can reach (review C1; critic F8). + - `gfx_compile` (`gfx/src/gfx.rs:1231-1233`) calls `exit_now(1)` on a compile rejection, and `link_program` + (`:1281-1283`) goes through it for both shaders, so every REQUIRED program exits on a compile failure; the + base program also exits on a link failure (`:1444-1452`, the call at `:1451`). Boot runs `init_gl`, + `init_text`, `init_image` and `init_blur` back to back (`app/boot.rs:1730-1733`), but `blur_lazy_init` + (`gfx.rs:6217`; called from the frame at `:4054`, `:6212`, `:6400`, `:7845`) links mid-loop through the + same function: one exit is frame-time, not boot-time. Optional programs already use + `link_optional_program` (`:1285`) and degrade. + - Every `exit_now(` site: `gfx.rs:1232,1451`, `app/mod.rs:576,645`, `bin/sim.rs` (six) and + `dev/framedump.rs:691` (`devtriggers`, off in a RELEASE build, `Makefile:581`). `std::process::abort` + (`base/src/task/blocking.rs:116`) is `threadcheck`-only. The source guard `app/boot.rs:545` forbids + `process::exit(` and `libc::exit(` only, so it permits `exit_now`; `const _` at `:540-541` pins + `run_application` and `run_and_shutdown` to `-> !`. +- F41. What returning from the loop does today (review C2; critic F1). + - `run_and_shutdown` (`app/mod.rs:561-576`) relies on `exit_now` diverging: "nothing drops the `App`" (`:574`). + `run::shutdown` (`app/run.rs:3723-3752`) returns nothing, and `quits_sdl` (`:3712`) acts on a + `NativeExit::WorkerInFirmware` that nothing else records. + - A returned `App` would run `SessionAdapter::drop` (`app/adapters/session.rs:332`), GL object drops + (`QrCode::drop` deletes a texture, `ui/src/qr.rs:147`) and field drops under live detached workers + (#1115). `Engine`'s explicit `Drop` is test-only (`play-feed/src/feed_state.rs:242-246`) and feeds the + counter `ENGINES_DROPPED` (`:235`). +- F42. The watchdog has no disarm. `set_foreground` (`base/src/task/watchdog.rs:222`) only mutes freeze + reports (`:585-588,778`). Its fatal arm (`:812-820`, `threadcheck` only) and the SIGUSR2 probe (`:686-702`) + `pthread_kill` a thread id captured from the loop owner "for the whole process"; after a hosted loop thread + returns, that id is dead. +- F43. Composition publishes in two places (review C3; critic F7). `compose_backends` + (`app/adapters/backends.rs:141-164`) takes `&mut PlaybackSession` and ends with `install_backends` (`:163`); + `install_uri_product_with_ports` calls `session.install_uri_preflight_port(port)` (`:421`) only after the + physical install succeeded (`:418`). The planner reads that port (`media/src/route/plan.rs:2048`, `NoPort` + when absent); the session starts at `FEED` (F31). +- F44. The session authority (review C4; critic F3). + - `update_guarded_with_outcome` (`plex/src/plex/session.rs:4555`) rereads `read_live_locked()` on every edit + and can replace the cache or refuse it; `cache_revoked` and `clear_for_erase` (`:5340`) are separate + doors; `peek()` caches what reads and durable writes installed. The auth owner releases a held handoff and + sets `proves_saved_login` only on a `Durable` completion (`session/src/auth/owner.rs:3478,3507`). + - `CompletionOutcome` (`plex/src/plex/session/async_persistence.rs:112`) and `LiveWrite` are matched in + `session.rs`, `session/{persistence,async_persistence,prefs/profile_prefs}.rs`, `session/src/auth/owner.rs`, + `telemetry/src/telemetry/incident.rs:592-600`, `src/app/adapters/session.rs` and three test files. + - `install_preferences::candidates` (`:40`) and `clear_for_erase` (`session.rs:5341`) key on the ARM cfg, so + Tizen ARM reads `native = true`; `load` accepts `version == 1` only (`:59`) and `Saved` is + `deny_unknown_fields`. The ARM canonical write is cfg'd out of host tests (`session/persistence.rs:1400-1425`). + - `ci/check-deps.sh`: `plex/` is in `FORK_SCOPE`, `session.rs` in `MACHINES` (`:1406-1408`): a new + `cfg(test)` branch there is a `forks` line, a new static a `statics` line. `platform/` is not in `FORK_SCOPE`, + and only `platform/src/tv/plane.rs` is in `MACHINES` (`:1406-1408`; the scan `find` at `:1439` lists it too). The + `globals` pattern (`:1429`) does not name `secure::mode`: UNVERIFIED whether it should. +- F45. Facts that fix file ownership (the lanes' Files lines are these). + - `src/app/run_uri_boot_tests.rs` is `include!`d at `src/app/run.rs:6953`: a test added there needs no line in + `run.rs`, and runs under `make test-hostsim`. `src/dev/uriprobe.rs:117` `#[path]`-includes `uriprobe_tests.rs`. + - `ScreenInputs` (`screens/src/inputs.rs:29`) is filled in `src/app/bridge.rs` (`:1700`). + - `device::Info.codename/api/name` are read in `platform/src/{webos,devcaps}.rs`, + `telemetry/src/telemetry/native.rs:896`, `src/app/diagnostics.rs:465,596`, `src/lab/snapshot.rs:279-281`; + `.major` in `app/boot.rs:906`, `adapters/backends.rs:378`, `media/src/player/pump.rs`, + `play-feed/src/{feed_pump,seek,sf_event}.rs`, `play-uri/src/backend.rs`. The sandbox verdict is read in + `media/src/{route/decision,player/{mod,adapter,machine,route_start}}.rs`, `appkit/src/player_hud/state.rs`, + `screens/src/player/mod.rs`, `src/app/playback.rs` and telemetry. + - The contract `Binding` is named in `playback-contract/src/uri.rs`, `play-uri/src/{backend,acb_bind}.rs`, + `media/src/route/{uri_preflight,plan,decision_version_tests (26),decision_resolve_route_tests}.rs`, + `src/app/{run_uri_boot_tests (18),adapters/backends,diagnostics}.rs`, `src/dev/{uri_product,uri_exported}.rs`; + `media/src/player/preview.rs` matches a different `Binding` (`Phase::Binding`). + - `AcbHandle` is named in `playback-contract/src/uri.rs` (type, `log_name`), `play-uri/src/backend.rs:1130` + and two adapter tests (`media/src/player/adapter.rs:224,273`); nothing under `tests/`, `tools/` or `ci/`. +- F46. `ci/mkmacapp.py:32`, `ci/build-libass.py:13` and `ci/test-compat.py:6` import the stdlib `platform` and + call `platform.system()` / `.machine()`: a `ci/platform.py` would shadow it for every script run from `ci/`. + +### Evidence from the critic's third pass: F47-F52 (each citation checked in the tree at `e9924f0f9`) + +- F47. The two reviewed certificates (G1). Both pin every member manifest and `Cargo.lock`, so the rename, + which edits 12 manifests and the lock, invalidates both. + - `ci/readonly_generated.py:16`: `CERTIFICATE_SHA256` over `ci/proofs/platform-generated-enums.json`. `SOURCES` + (`:17-19`) is eight files: five under the moved directory (`platform/Cargo.toml`, `platform/src/lib.rs`, + `platform/src/i18n/mod.rs`, `platform/build.rs`, `platform/build_support/catalog.rs`; `catalog.rs` is the + only file in that `build_support/`), one OUTSIDE it (`build_support/install_identities.rs`, that is + `rust-modules/build_support/`; its line 3 names `plx_platform` and `platform/src/storage/state.rs`, so the + script rewrites it and its hash changes; `platform/build.rs:19` includes it by `#[path = "../build_support/... + "]`, which survives the move) and two in `machine`. `produce_certificate` writes `package: "plx_platform"` and + `module: platform/src/i18n/mod.rs` (`:60-61`). The `.json` holds seven bare `platform/` strings. + - `ci/readonly_dependencies.py:21`: `CERTIFICATE_SHA256` over `ci/proofs/serde-json-immutable.json` (`:20`), + checked at `:388-389` and `:458-471`. It holds `workspace.manifests` (19 hashes: the root and 18 members, + keyed by path, among them `platform/Cargo.toml`), `workspace.lock_sha256`, and `workspace.owners` (13 + manifests, among them `platform/Cargo.toml` with `lib: platform/src/lib.rs` and its `lib_sha256`). It is + regenerated by `python3 ci/readonly_dependencies.py --produce --root + rust-modules --output ci/proofs/serde-json-immutable.json` (`:488-497`), which prints the SHA256 to pin + after review. + - `ci/test_readonly_generated.py` builds a scratch tree in the bare spelling: 13 `platform/...` lines (`:31, + 102,121,127,132-139,141,169`) and a `plx_platform` source string (`:179-180`). `ci/test_check_machine_shape.py:153` + lists `platform/build.rs`, `platform/build_support/catalog.rs` and `build_support/install_identities.rs` too. +- F48. The old name, by spelling, counted with `git grep` at e9924f0f9 (G2). The F36 count covers only the first. + - A. `plx_platform` not followed by `_webos`, `_desktop` or `_tizen`: 338 tracked files, 3461 lines (296 `.rs` files, + 3280 lines; 12 manifests and `Cargo.lock`; two nested `CLAUDE.md`; 27 files under `ci/ tools/ tests/ + .github/ Makefile docs/ .agents/`). It includes the `-p plx_platform` package lists in the `Makefile` (`:1682, + 1701,1713,1742,1776,1800`) and cargo features such as `plx_platform/uri-transport` (`rust-modules/Cargo.toml:81`). + - B1. The path `rust-modules/platform/`: 25 tracked files. `Makefile:1016` (`RUST_INPUTS`) and `:1055` + (`STORAGE_INPUTS`, with `2>/dev/null`) name `rust-modules/platform` and `rust-modules/platform/src/ + storage_service` inside `find` lists: a missing directory is dropped from the list, silently (the ARM library + and the storage helper would then not rebuild when `os/` changes). + - B2. The bare path `platform/...`, relative to `rust-modules/`: 23 tracked files outside the directory. + `ci/list-caps.ini` (23 section keys such as `[platform/src/devcaps.rs::PCM_MAX_CHANNELS]`; a key that matches no + constant is reported stale by `ci/check-list-caps.py:49`, so this one is loud), `ci/test_readonly_generated.py` (13), + `ci/readonly_generated.py` (7) and both proofs, `ci/test_storage_package_isolated.py` (2), + `ci/test_check_machine_shape.py:153`, `ci/test_build_bench.py:61`, `ci/check-deps.sh:1402`, + `rust-modules/build.rs:4`, `rust-modules/storage/{build.rs:1,Cargo.toml:16}`, + `rust-modules/build_support/install_identities.rs:3`, `Makefile:1052`, and prose in `docs/`. + - B3. Manifest and workspace paths: `members = [..., "platform", ...]` (`rust-modules/Cargo.toml:14`) and 21 + `path = "platform"` / `"../platform"` lines in the 12 manifests. + - B4. A path assembled from components, invisible to a path grep: `tools/cargo-seed.py:190` + (`os.path.join(root, "rust-modules", "platform", "Cargo.toml")`; `read_bytes` returns `b""` for a missing file, + `:122-127`, so the cargo seed key silently stops covering the bottom layer's manifest) and + `ci/test_no_host_staticlib.py:45` (`WORKSPACE_FILES`, a quoted `"platform"`: its symlink dangles, so cargo + fails loudly). + - C. The layer token: `[platform]` (`ci/module-layers.ini:53`), the token in 13 `uses =` lines (`:73,84,92,102, + 112,123,134,148,152,162,172,182,187`), comments (`:54,56,72,80,120,199`), `docs/module-layers.md`, and + `rust-modules/Cargo.toml:228`. The fence keyword `[port X]` is a second rename in the same files (`ci/check- + module-layers.py:14-15,68-84`, `docs/module-layers.md`: 9 lines). The new keyword `[platform X]` shares its + word with the old layer `[platform]`: `--reverse` must turn `[platform webos]` into `[port webos]` BEFORE it + turns `[os]` into `[platform]`, and it must never rewrite a bare `os/` or `os` anywhere but the sites the + forward pass wrote (a bare `os/` is also `std::os/`, `libc` paths and prose). + - D. Names derived from it: `SRC_PLATFORM` (`ci/check-deps.sh` 18 lines, `docs/module-layers.md` 3, `tests/ + test_harness.py` 1) and the build-bench scenario `platform` (`tools/build-bench.py:132,149,171,180,201`, + `ci/test_build_bench.py:96,212,229,244-245`). + - Exempt, dated records that keep the old name: `docs/release-audits/*`, `docs/measurements/*`, dated + `docs/*-20YY-MM-DD*.md`, and this plan (the whole page, `tools/rename-os-layer.py`'s `EXEMPT`). +- F49. `ProductQualifier` and the layer rule (G3). + - It is a unit struct in `plx_media` (`media/src/route/uri_preflight.rs:768`) implementing media's + `OriginalQualifier`; the composition builds it at `src/app/adapters/backends.rs:387`, after the + `dev::uri_exported::compose` override of the binding (`:384-385`) and before the `dev::uri_product::compose` + swap (`:393`); that dev route already swaps an `Arc` in the app crate + (`src/dev/uri_product.rs:230`). `OriginalRequest.binding` (`uri_preflight.rs:278`) is read only by this + qualifier (`:775`) and by tests. + - `[play_uri] uses = base platform playback_contract` (`ci/module-layers.ini:148`) cannot name `plx_media`, so a + qualifier implemented inside `plx_play_uri` is a layer violation, and moving + `OriginalQualifier`, `OriginalRequest` and the verdict types to `playback_contract` would put route policy + into the contract. `[app]` (`:187`) uses media and play_uri. + - Named in 10 tracked files: the three media files, `backends.rs`, `run_uri_boot_tests.rs`, `dev/uri_exported.rs`, + `dev/uri_product.rs`, `media/src/player/CLAUDE.md`, and two that name it only in prose: + `plex/src/plex/session/playback_options.rs:39` (a doc comment naming `route::uri_preflight::ProductQualifier`) + and `docs/module-layers.md:180`. + - `backends.rs`'s tests are `#[cfg(test)]` (`:455`) in the app crate and `default` includes `play-uri` + (`rust-modules/Cargo.toml:78`): they run under `make test-hostsim`, not under `make test-crate C=plx_media`. +- F50. W3a's test seam, the globals ledger and the doc (G6). + - `secure.rs` already has a per-THREAD test seam, `STORE_FOR_TEST` (`:23-31`). A mode override cannot be + thread-local: session writes run on `plx_base::storage_worker` (`async_persistence.rs:3,968-969`). The session + persistence tests already hold `testlock::serial()` (`session_persistence_tests.rs:11,24,40,...`), and + `testlock::assert_held` (`base/src/testlock.rs:152`) is what "any new global store" owes (its module doc). + - `globals_pat` (`ci/check-deps.sh:1429`) is a fixed list of spellings and `secure::` is not in it: `plx_platform:: + tv::secure::mode()`, `::open(` and `::set_mode_for_test(` do not match it (`grep -E`). `session.rs` already + makes four unledgered `secure::` calls (`:4197,4837,4921,5454`); `ci/allow/globals/plex.txt` has 12 lines + (`peek`, `peek_settled`, `current_snapshot`); the rule scans MACHINES files, `session.rs` as a file and not its + `session/*.rs` children. So a mode read adds no ledger line, and extending the pattern would turn four + existing calls into new sites (counts only fall). F44's UNVERIFIED is settled: no line, no pattern change. + - `plex/src/plex/CLAUDE.md:501,646` call `peek()` "a write-through cache over the persisted session". Under + `MemoryOnly` it is the authority; the PR updates that prose. +- F51. The shutdown plumbing (G4, G5). + - `run_application` (`app/mod.rs:642-647`) has a 10-line budget: `ci/check-deps.sh:1176-1178` (`fnlen`). The leak and + the `Exit` mapping therefore live in `app/exit.rs`, and the gate is not edited. + - `quits_sdl` (`app/run.rs:3712-3718`) matches the two variants of `NativeExit` (`media/src/player/route_start.rs: + 1082`): `Clean => true` and `WorkerInFirmware => false`; `shutdown` (`:3723-3752`) logs "SDL_Quit skipped" on + the second. `run.rs:3921` asserts the second. + - `App` is built at two sites (`app/boot.rs:2474`, the `app/run.rs:3973` test rig); `AGENTS.md` requires a new + field to be read and initialised at both. `rust-modules/src` is outside `FORK_SCOPE` (`check-deps.sh:1409`), so a + `cfg(test)` field adds no `forks` line; a field, unlike a static, adds no `statics` line. + - `gfx/src/gfx/straighten.rs:1272` finds `pub fn init_gl()` by text and `gfx/src/gfx.rs:10616` finds `pub fn + init_image(`: both survive a return-type change. +- F52. W7a's test has no runner (G8). + - `rust-modules/tests/` does not exist. Every unit target runs `cargo test --lib` (`Makefile:1742,1776,1800,1869`); + `--tests` appears only in `cargo check` (`:1682`). The root crate is `crate-type = ["rlib"]` (`rust-modules/ + Cargo.toml:61`), so an integration test can link it. + - `$(UNIT_RUN)` (`Makefile:1700`, `tools/cargo-test-parallel.py`) is documented for `cargo test --lib` and wants one + executable per `-p` package; UNVERIFIED whether it accepts `--test host_interface` (one package, one executable + would hold). The precedent for a non-`--lib` run inside a gate is `cargo test -p plxnative-storage --bin + plxnative-storage` (`Makefile:1744`). + - `ci/test_ci_split.py:58-67` pins each cargo gate's recipe and which of the three `check-cargo-*` targets holds + it. `DISK_ENTRIES` (`Makefile:1548`) and `ci/test_disk_preflight.py` require every cargo-running target to join. + +### Tizen research + +From the Tizen research report (not in the repository), by section. None of it is checked on a retail set; where +the emulator runs (E1-E13) measured it, the item says so. +- T1. A retail TV refuses a native `capp`. The host is a `type="dotnet"` C# `.tpk` P/Invoking our + `.so` (section 1). +- T2. The floor is Tizen 6.0 (2021). The 4.0-5.5 sets block file-backed exec of the app's `.so`, and + Rust std's TLS defeats the in-memory loaders (sections 1 and 4, item 2). +- T3. The ABI is armv7 softfp NEON. Whether a model year is aarch64 is undetermined (2c); open as H1, + the emulator is x86_64 and says nothing about retail sets (E1, E9). +- T4. glibc is 2.30 on Tizen 6.0-9.0 and 2.40 on Tizen 10 (ABI break) (2c). E3 measured 2.40 on the + Tizen 10 x86_64 image; the 2.30 of the 6.0-9.0 sets is not measured. UNVERIFIED (H2): that an `.so` + linked against our NDK's glibc 2.12 sysroot loads on Tizen; the x86_64 library (at most + `GLIBC_2.34`) loading on the 2.40 image is no evidence for ARM. libstdc++/libgcc and the absence of + SDL or libcurl on a retail set are not checked (the emulator image's libcurl and other libraries are E12). +- T5. Window Option A is host-owned GLView/GLWindow with the EGL context handed over, and SDL2 static + with the dummy video driver. Option B is a native Ecore_Wl2 window with EGL. esplusplayer needs + Option B's `Ecore_Wl2_Window*`. SDL2 on a retail Tizen TV is not evidenced (2d, 1); the emulator ran static SDL2 + SDL2_ttf with `SDL_Init(TIMER|EVENTS)` + and no video driver (E10), so the dummy-video-driver variant of Option A was not exercised. Option B drawing + from a Rust thread works on the emulator (H3, H4; E6, E8) and is unmeasured on a retail set. +- T6. URI playback via `Tizen.Multimedia.Player` (C#) is proven: + - only the User-Agent and Cookie headers pass; + - no DTS or TrueHD; + - esplusplayer feed is firmware-dependent (2e). +- T7. Use one `.tpk` per API generation, bundle no TizenFX DLLs, force `LC_NUMERIC=C`, export every + `DllImport` symbol, and keep certs and DUIDs out of the repo (2b, 2d, 2f). Measured: a `tizen80` + `.tpk` runs on Tizen 10 (E4), so one `.tpk` is viable to start; sets of Tizen 6.0-9.0 and `tizen90` + are untested. +- T8. There is no `sdb shell` or `dlog` on a retail TV, so logs must be in-app (2a). Measured on the + TV 10.0 emulator too: UDP is the only channel out, and a file in the app data dir cannot be read (E5). + +### The hello-world questions (H1-H8) + +The Tizen hello-world (F28) exists to answer these, and the text cites them by number: +- H1: whether a retail set's host process is armv7 or aarch64 (T3). +- H2: whether the NDK-linked ARM `.so` loads under a Samsung Public certificate on a retail set (T2, T4). +- H3: whether Option B, a native Ecore_Wl2 window, draws from a Rust thread (T5). +- H4: whether Ecore main-thread handlers and a Rust loop thread run without deadlock (T5, F32). +- H5: whether static SDL2 and SDL2_ttf draw text and a GLES2 texture through our path (F15). +- H6: whether `Tizen.Multimedia.Player` shows a mock title beneath our window and survives a TV-menu round trip + (T6, W10). +- H7: whether the application's own renderer, `plx_gfx`, compiles its shader programs and draws on the set's GL + (README "H7" on `samsung/hello-tpk` at `e8da14ce6`; F40 says why a rejected required shader ends the process). +- H8: whether the application's own libcurl binding (`plx_net` on the `dynlib!` loader) finds a libcurl on the set + and reaches a server on the tester's PC (README "H8" on `samsung/hello-tpk` at `e8da14ce6`; F27). + +Status: H3, H4 and H5 are answered yes, on the emulator only (E6, E8, E10); H1 and H2 are open and need a retail +set (E9); H6 is not probed (E9, E11). H7 and H8 were probed by the build of E13: H8 yes, and H7 yes once +`vs_ambient.vert`'s one multi-declarator is split, with one optional program still failing; both on the emulator +only. + +### Emulator run, 2026-11-20 + +Reported by the operator of the emulator run (E1-E9, built from `origin/samsung/hello-tpk` at `72c5cd82a`); +E10-E13 are later runs on the same emulator. Measured on the emulator only; no retail set has reported a result. + +- E1. Setup. TV Extension 10.0 emulator, image 10.0.6 (`tv-samsung-10.0-x86_64`, BUILD_ID + `EMULATOR64-202601071715`), under WSL2/KVM; the library is x86_64, built on Ubuntu 22.04. `sdb + capability`: `cpu_arch x86_64`; `intershell`, `rootperm` and `appcmd` disabled. WSLg's Mesa D3D12 + segfaults the emulator in `yagl_host_eglSwapBuffers`, so it ran with `LIBGL_ALWAYS_SOFTWARE=1 + GALLIUM_DRIVER=llvmpipe`. Certificate Manager under WSLg needs `GDK_BACKEND=x11`. +- E2. Signing. Tizen.NET.Sdk 1.1.9's bundled certificates are expired (author 2019-01-01, distributor + 2022-10-27). A renewed "Tizen Studio Public Signer" distributor is still refused (`Check certificate + error`, 118,-12): the image's `fingerprint_list.xml` trusts only Samsung VD roots for the public and + partner domains. Install worked with a Samsung certificate profile from Certificate Manager (TV, + Public): author Samsung VD Author CA to Tizen Developers Root; distributor VD DEVELOPER Public CA to + VD DEVELOPER Public Root, bound to the emulator's DUID, valid to 2027-11-19. So the emulator needs the + same Samsung Public profile as a retail TV. Samsung's FAQ says a Tizen profile suffices for the + emulator; that is false for this image. `build.sh`'s `PLX_TIZEN_*` path signed with it, and + Certificate Manager's `.p12` (`pbeWithSHA1And3DES`, SHA-1 MAC) was accepted. +- E3. The image. glibc 2.40, newest symbol node `GLIBC_2.39`. .NET runtimes 2.0 to 8.0.11 and the full + TizenFX TV set. `/usr/lib64` has `libecore_wl2.so.1` (1.25.1), `libEGL.so.1`, `libGLESv2.so.2`, + `libwayland-client.so.0`, `libtbm.so.1`, `libcapi-appfw-application.so.0` and `libdlog.so.0`. The + hello-world's x86_64 `.so` needs at most `GLIBC_2.34`. That is one x86_64 data point: the ARM + library's limit is unmeasured (H2). +- E4. Run. Install took 1277 ms; launch with `sdb shell 0 execute plxnhello0`; executable + `/usr/bin/dotnet-launcher`. The `tizen80` host runs on Tizen 10: .NET 8.0.11, `ProcessArchitecture` + X64, `IntPtr.Size` 8. It was launched through sdb, not from the TV menu. +- E5. Logs. `res/log-host.txt` was found, and UDP from the emulator to `10.0.2.2` delivered 206 lines with + 0 sequence gaps. It is the only log channel on this image: `sdb shell ` prints nothing (only + `sdb shell 0 ` answers), `sdb dlog` returns 0 lines and `sdb pull` of the app data dir is + refused. A retail set has no sdb shell or dlog (T8, research; not measured here). +- E6. Window and GL (H3). `ecore_wl2` display connect, `window_new` 1920x1080, `egl_window_create`, + TOPLEVEL, alpha false; `ecore_event_handler_add` resolved from `libecore_wl2.so.1`. EGL 1.4, vendor + Samsung; ES2 context, RGBA8888; `eglMakeCurrent` on the Rust render thread; `eglSwapInterval(0)` + then 1; renderer "YaGL GLESv2"; first frame presented, `glGetError` 0. The emulator draws through + YaGL over llvmpipe, so this is no GPU, compositor or frame-rate result. +- E7. Keys. Injected with `ecp-cli` as evdev events: Right keycode 114, Left 113, Up 111, Down 116 and + Return 36, reported as Ecore key names. Every press changed the colour. Key to frame took 8-30 ms (key + on the host thread, colour on the render thread): an emulator figure, not a retail one. Back, media + keys, digits and the channel rocker were not exercised by this run (the colour button came later, E11), and a + retail remote's codes are not measured. +- E8. Lifecycle (H4). OnResume after create; focus IN at +1.9 s. A kill gave OnPause (the render thread + idles), then OnTerminate: handlers deleted, the render loop stopped after 2478 frames, EGL destroyed + and terminated, the `ecore_wl2` window and display torn down, "terminate: done". No deadlock between + the Ecore main-thread handlers and the Rust render thread. `terminate: done` is logged only after the + render thread joined (`lib.rs:365`), so the 2 s fallback of F29 was not taken. +- E9. Not answered. H1 (retail armv7 or aarch64) and H2 (the NDK-linked ARM `.so` under a Public + certificate on a retail set): the emulator is x86_64 and runs a different build. H6 (the player under our + window) was not probed, and H5 (SDL2 + SDL2_ttf) was not probed by THIS run (it came later: E10). The ~33 fps is llvmpipe through + YaGL, not an app measurement. Launch from the TV menu and its pause behaviour (README, report item 5) + are untested, because the run launched through sdb. + +- E10. H5, SDL2 + SDL2_ttf inside the host (2026-11-20, the same emulator; `samsung/hello-tpk` at `64c609a46`). + PASSED, emulator only. What the run measured: + - static SDL2 2.32.10 and SDL2_ttf 2.24.0 (FreeType 2.13.2, no HarfBuzz) linked into `libplx.so`, loaded by the + .NET host; + - `SDL_Init(SDL_INIT_TIMER | SDL_INIT_EVENTS)` with `SDL_NO_SIGNAL_HANDLERS=1` succeeded; the SDL timer thread + ran. The video subsystem was not initialised; + - TTF rendered Latin, the check mark and Cyrillic with Inter; a GLES2 texture was drawn on the Rust render thread + (YaGL); + - keys worked and teardown (`TTF_Quit`, `SDL_Quit`) was clean; + - the x86_64 `.so` is 2.5 MB, needs at most `GLIBC_2.34`, and its SDL symbols are local; + - the screen output could not be screenshotted: QEMU's `screendump` cannot capture YaGL output. + This answers H5 on the emulator. It is no retail-set result (H1, H2: the ABI and the loader), no frame-rate + claim and no armv7 size or symbol figure. The tester build whose screen shows diagnostics and a key-code panel + is E11 on the emulator; its run on a retail set, which would answer H1 and H2 and return a retail key table + (E7's codes are the emulator's), had not been reported on 2026-11-20. + +- E11. Tester build `1afe1978b`, on-screen panel photographed (2026-11-20, relayed from the emulator operator). + Emulator only; it is not H6 (no player in this build). + - All seven steps green on the panel: the `.so` loaded (x86_64); six libraries `dlopen`ed; Ecore_Wl2 1920x1080 + with four of four handlers (key down and up, focus in and out); EGL 1.4 Samsung, ES2; GL renderer YaGL GLESv2 + "OpenGL ES 2.0"; SDL2 2.32.10 and SDL2_ttf 2.24.0; the UTF-8 sample string (Latin, a check mark, Cyrillic). + - Keys: the panel listed 31 distinct keys. The one new beyond the earlier emulator key table (not reproduced here) + is the remote's colour-key button, `XF86Color` = 385. `Shift_L` = 50 came after Home and is most likely the host keyboard (the screenshot + shortcut), not a remote key. The other codes were not relayed, so none is recorded here. + - Home round trip: pause at +181.7 s together with focus OUT; resume at +191.6 s after 9.9 s paused; focus IN + at +191.7 s. The panel redrew after the resume, so the window and the EGL surface survive a Home pause and + resume on the emulator. No player was running, so this is not H6. + - Device line: Tizen 10.0 (native API 3.0), model Emulator, build `tizen_20260107.16983968`, .NET 8.0.11 X64, + `IntPtr` 8 bytes, glibc 2.40, executable `/usr/bin/dotnet-launcher`. The panel's CPU line was truncated + ("aarch64 (unav...") and is not read as a result; the process architecture is the device line's X64. + The build commit `d8c4b2766` shortens that line's "(unavailable)" text to "n/a". + +- E12. Image library check for W9 (2026-11-20, read-only inspection of the base emulator image + `emulimg-10.0.x86_64`). Emulator image only; a retail set's libraries are not measured. + - libcurl: `/usr/lib64/libcurl.so.4` (`.4.8.0`, SONAME `libcurl.so.4`, libcurl/8.11.0, TLS OpenSSL 1.1), with + its `NEEDED` libraries (`libcares.so.2`, `libnghttp2.so.14`, `libssl.so.1.1`, `libcrypto.so.1.1`, + `libz.so.1`) all present. There is no unversioned `libcurl.so`; our list's first name, `libcurl.so.4` (F27), + matches. The default CAINFO is `/etc/ssl/ca-bundle.pem`, which resolves to + `/opt/var/lib/ca-certificates/ca-bundle.pem` (202 certificates, base image), and the CAPATH `/etc/ssl/certs` + resolves to `/opt/etc/ssl/certs`. + - Also present, all in `/usr/lib64`: `libssl.so.1.1` and `.so.3`, `libcrypto.so.1.1` and `.so.3`, `libz.so.1`, + `libfreetype.so.6`, `libpng16.so.16`, `libjpeg.so.8`, `libbrotli*.so.1` and `libnss3.so`. There is no gnutls. + - The mock server: `tests/mock_pms.py` runs under the host's python3 (3.10) and defaults to `--host 127.0.0.1 + --port 32499`. The emulator's `10.0.2.2` is the host's loopback (QEMU user networking), as for the UDP log (E5). + - W9 design note. The mock plex.tv override (`plex_tv()` in `plex/src/plex/account.rs`) accepts only + `127.0.0.1` and `localhost`, on purpose: the trigger carries the token. Reaching it from the guest would need a + reverse forward into the emulator (`sdb reverse` mode: unchecked), so the emulator MVP (Decision 8) boots on the + dev-token path (a `--guest --mock` style boot, the PMS advertised as `10.0.2.2`), and the sign-in against the + mock plex.tv is a follow-up check. The loopback rule is not widened. + +- E13. The real renderer and libcurl (H7, H8; 2026-11-20, the TV 10.0 x86_64 emulator, a probe build of + `samsung/hello-tpk` at `e8da14ce6`). Emulator only; no retail set has run it. + - H8: yes. libcurl, loaded through the app's own `dynlib` mechanism (`libcurl.so.4`, E12), reached + `tests/mock_pms.py` on the host as `10.0.2.2` and got HTTP 200. + - H7, shaders. YaGL ("YaGL GLESv2", OpenGL ES 2.0, GLSL ES 1.4, over the host's Mesa llvmpipe) rejected + `VS_AMBIENT_DITHERED` with `0:37(9): error: syntax error, unexpected NEW_IDENTIFIER`, at + `varying highp vec2 v_dither_nc;`. That is the error Mesa gives for raw desktop GLSL 1.10, where `highp` is an + ordinary identifier, so the source looks passed through untranslated (an inference from the message, not a + measurement of YaGL). + - The only multi-declarator in `shaders/`, `uniform vec4 u_atl, u_atr, u_abr, u_abl;` in `vs_ambient.vert`, + split into four declarations, makes it compile. Before and after: the original fails and the split compiles, + and a cut-down variant does the same. The tree these facts pin still has the statement; the split was made in + the probe build. + - A `#version 100` preamble also made it compile, but the link then failed ("all shaders must use same shading + language version"), so that route was dropped. + - With the split, all 14 required programs compile and link. `plx_gfx`'s `init_gl`, `init_text`, `init_image` + and `init_blur` all returned, and it drew a rect and text. `glGetError` was 0 at init, frame and swap, and it + drew 3420 frames at about 33 fps (llvmpipe through YaGL: no frame-rate claim, E6). + - One optional program still fails the same way. The straighten program (`fs_straighten.frag`, its copy variant, + because the emulator has neither framebuffer-fetch extension) fails with `0:37(1): syntax error, unexpected + NEW_IDENTIFIER` at `precision mediump float;`. It degrades ("frames over the video plane stay premultiplied") + and does not exit. The suspect, untested, is its `#extension ... : require` lines inside inactive `#if` + branches. It matters only over the video plane, so it is for W10, not the W9 MVP. + - Font. `plx_gfx` opens `/appfont.ttf`, but the executable is `/usr/bin/dotnet-launcher` (E4), so the open + fails. The probe retried from the package's `res/` and it opened. The resource directory has to become a + platform value (W8b, W9). + - Linking. `plx_gfx` imports `gl*` at link time, and the hosted `.so` is loaded `BIND_NOW`. The probe used a + `dlsym` shim; W9 either links `libGLESv2.so.2` or keeps a shim. + +## Target shape + +### What stays shared (every platform) + +- All layer crates: base, machine, os (the bottom layer, Wave R), gfx, net, plex, telemetry, data, session, + media, appkit, screens and ui. Also playback-contract, media-codecs, the neutral part of play-feed (demux, + HLS, ABR) and the app crate `plxnative-modules` (loop, adapters, dev surfaces). +- Every machine, the route planner, the stores and the screens. A platform adds no machine. It supplies + runners, function-pointer hooks and published boot values, exactly as F5's table does now. +- FFmpeg, libass, the `dynlib!` mechanism, the GLES2 renderer and SDL2_ttf text (F15). SDL2 stays a shared + dependency for timing, surfaces and TTF; on Tizen that is verified on the emulator only (E10, H5: static SDL2 + + SDL2_ttf, no video subsystem) and still unverified on a retail set (H1, H2). The SDL VIDEO driver is + the platform's choice. Removing SDL from gfx and base is out of scope. + +### The exported value and the two tables + +Names follow the owner: the crates are `plx_platform_webos`, `plx_platform_desktop` and `plx_platform_tizen` +(Decision 1, B); the bottom layer is `plx_os` after Wave R, so no layer shares a crate's name. Each exports one +`pub static PLATFORM: host::Platform` (Target shape 8), and exactly one is the root of a build. The value is +split by who reads it (critic M4): + +1. `tv::Services` (`plx_os::tv`, installed once by `run_application`) holds what LOWER layers read through the + private `tv::port()` (F5): + - `identity { probe_device, start_capability_probe, repair_sandbox, system_locale, sound_output }`; + - `secure { seal, open, remove, mode }` (Target shape 4; until W2 `mode` is W3a's own once-set value); + - `system { go_home, poll_home, deliver_toast }`; + - `legacy_webos_media { sink, display_sink, uri_media }`: the Starfish, ACB and `com.webos.media` verbs (F31), + named for what they are (critic M3). Every hook is required (Decision 2, C): a platform states each field, + a named `NONE` being a statement and a `Default`-filled gap not allowed. The one exemption is this group: + until W11a a non-webOS platform leaves it at `media::NONE` (`NoSink`/`NoUriMedia`), as `ABSENT` does today, + and W11a injects the LG transports into the LG drivers, so the group and the exemption disappear. +2. `app::Platform` (the app crate) holds what only the loop reads; the shell and the frame probes have one + consumer, the loop (F34), so they do not belong in the bottom layer's process global: + ``` + pub struct Platform { + pub services: &'static tv::Services, + pub shell: &'static dyn Shell, // a Sync FACTORY of the loop's surface (Target shape 8) + pub diag: &'static dyn FrameProbe, // the six frame probes; a named NONE is fine + pub media: MediaBoot, // Target shape 6a + } + pub fn run_application(p: &'static Platform) -> Exit; // returns; Target shape 7 + ``` + `Shell` and `FrameProbe` are traits in the app crate, beside their consumer. A `&'static dyn` can read its + own statics (the Tizen host table); a plain `fn` field could not (critic M6). A new `App` field is + initialised at both construction sites (AGENTS.md), and `Platform::HOST_TEST` replaces the "no port + installed, every hook is a no-op" default for the loop's host tests. + +There is no `default_backend` (review M8, critic M1): the backend set is derived from the installed drivers (F31, +6a). There is no runtime capability registry (owner decision). + +### 1. Shell + +`Shell` (the factory) opens the loop's `Surface`: `create_surface`, `make_current`, `swap`, `drawable_size`, +`gl_proc_address`; `release`/`reacquire` around background; `video_hole(Option)`, which replaces +`arm_opaque_region`, `opaque_route` and `clear_opaque_region`; `pump()`, which replaces `pump_bus`. The trait doc +states which thread runs each call (Target shape 7). `Shell`, `Surface` and `HostEvent` stay app-private until +H1 and H2 return (critic M5; H3, H4 and H5 returned on the emulator only, E6, E8, E10; Decision 3, A): code moves +now, but no type a Samsung shell must match leaves the app crate; Target shape 8 is the one narrow, public +construction interface. The dispatcher's rig hooks (`ui/src/dispatch.rs:728-730`) keep delegating through +`run::rig_*`. + +### 2. Input and lifecycle: canonical actions (review M6, C8; critic F11) + +This replaces two earlier designs, "`HostEvent::Key` carries SDL keycodes plus LG scancodes" and critic M7's "map +Ecore names to `remote_token_key` pairs". +- `HostEvent` (app-private, like `Shell`) has: + - `Key { action: Option, edge: Edge, raw: Option }`, `Edge` being `Down | Repeat | Up` as in + `InputKind::Key` (F33). `action` is `Option` because unbound keys flow today as raw pairs (`k:0,269` HOME, + `app/events.rs:202-212`), the configurable lab trigger consumes pairs no `Action` names, and the recorder + retains them: a raw-only event keeps its original pair and edge, and the loop treats `action: None` as the + raw path it is today; + - `Text(String)` and `Edit`; `Pointer { x, y, buttons, shown }` and `Wheel { dy }` (carried explicitly, F33); + - `Lifecycle(WillBackground | DidBackground | WillForeground | DidForeground)` and `Quit`; + - `LocaleChanged`, `LowMemory` and `Launch(String)`. +- `Action` names what callers consume, not a physical key: `Up Down Left Right Ok Back Play Pause PlayPause Stop + Rewind FastForward Exit PageUp PageDown Backspace ClearAll Digit(0-9) PointerHidden`. The final list comes + from W5b's inventory. +- It lives in `plx_ui::consts` (not hash-pinned), beside `classify` and `is_bound`. Two total functions: + `raw_pair(Action) -> (sym, wcode)`, the only place a pair is built, and `action_of(sym, wcode) -> + Option`, the only decode, built from `classify`, `page_dir`, the edit-key readers and the digit rule. + `classify` alone returns `Other` for paging, editing and digits (F33), so it cannot be the guard. +- Digits. `Action::Digit` reads `sym` only, as `is_bound` does (`ui/src/consts.rs:466-483`: desktop punctuation + shares the wcode range 48-57, so a wcode-only digit is deliberately not bound). The PIN keypad reads 48-57 from + either field (`screens/src/profiles.rs:340`, `digit_of`). That reader moves down into `consts` unchanged as its + own `pin_digit(sym, wcode)`; a wcode-only press stays a raw event whose PIN effect is exactly today's. +- The SDL decoders (LG layout, stock layout) fill `raw` and, where defined, `action`. A platform that is not SDL + sets `action` only, and the app derives the pair with `raw_pair`. So `InputKind::Key`, the machines, the tape + codec and the 7 raw-reading screens are unchanged, and tapes stay byte-identical (F16). +- A platform's key table maps its native names to `Action` and nothing else; no platform builds a pair. The + round trip `action_of(raw_pair(a)) == Some(a)` stays as a unit test but is NOT the guard: it never calls the + native-name decoder and cannot see a swapped table. The guard (W5b, extended by W9 for Ecore) is native name + -> the platform's decoder -> the real consumer's effect: transport (Play is not Pause, Rewind is + `Left { alt: true }`, never plain `Left`), paging (PageUp is not PageDown), Search editing and the PIN keypad + (each digit its own). Further cases: an unknown pair (no action, raw kept, ignored as today), a lab trigger key, + a wcode-only punctuation press on the PIN screen and in `is_bound`, and a replay that is byte-identical, `Edge` + included. The review's example, a Tizen table that swaps Play and Pause and still passes `is_bound`, fails it. +- Measured so far (E7): Right is keycode 114, Left 113, Up 111, Down 116 and Return 36, as Ecore key names. They + seed the table's first rows; `Return` (36) is the candidate for Ok, not for Back. E11 adds the remote's colour + button, `XF86Color` = 385 (its panel listed 31 distinct keys; this is the one new beyond the earlier emulator key + table, which is not reproduced here). Everything else waits for a key dump from a retail set. +- Raw SDL stays where it is: `decode_key`/`rd_u32`, the `TEXTINPUT` offset, both wheel offsets and the + sdl2-compat injected-key carrier (`app/events.rs:40-70`) move into the SDL decoders unchanged. +- Exit step (critic M7): the machine's own key type carries the full `Action`: a certificate review of + `machine.rs` and a tape-format version (F33). It is W5d, due before a FOURTH platform (Decision 6, A). + +### 3. Home, toast, launch: `tv::home`, `tv::toast` and `tv::launch` are already neutral and unchanged. + +### 4. Secure store and the persistence mode (review B2, C4; critic M8, F2, F3; Decision 7, B) + +- The envelope's `Backend` stops being a closed enum in shared code (`secure.rs:8-11`): an opaque string tag, + serde-transparent, with constants for `"keymanager3"` and `"palm_keymanager"`, so every sealed session on a + TV still opens. W3d's literal fixture guards the wire form. A platform adds its own tag in its own crate + (`"host_file"`; a Tizen tag, UNVERIFIED which Tizen API a dotnet app may call). A tag no installed platform + knows is refused on open, never reinterpreted. +- Mode. `secure::mode() -> StoreMode { Durable, MemoryOnly }` is a once-set value (`secure::publish_mode`) in + `os/src/tv/secure.rs`, default `Durable`. It is NOT a `Port` field in W3a (critic F2): W2 folds it into + `Services.secure` and the accessor's signature does not change. `secure::NONE` alone is NOT memory-only (F30). +- The test override (G6; F50). `tv::install` is once-only, so a test cannot go through it, and the once-set value + cannot be reset. The override is therefore a SEPARATE process-global in `secure.rs` (an atomic), consulted + before the once-set value under `cfg(any(test, feature = "test-support"))`, like `STORE_FOR_TEST` but NOT + thread-local: session writes run on `plx_base::storage_worker`, a thread the setting test does not own. + `secure::set_mode_for_test(StoreMode) -> ModeReset` calls `plx_base::testlock::assert_held(..)` first and its + guard restores `Durable` on drop, so a failing test cannot leave `MemoryOnly` behind for the next one. Every test + that sets it begins with `let _serial = plx_base::testlock::serial();` (the session persistence tests already do), + and no test sets it without that. `os/` is not in `FORK_SCOPE`, and only `os/src/tv/plane.rs` of it is in + `MACHINES`, so the override in `tv/secure.rs` adds no ledger line. +- Globals (G6; F44, F50). Reading `secure::mode()` from the session code adds NO line to `ci/allow/globals/`: the + gate's pattern is a fixed list of spellings that does not name `secure::`, and `session.rs` already makes four + unledgered `secure::` calls. The pattern is NOT extended (it would turn those four into new sites, and counts + only fall). W3a shows `ci/check-deps.sh --only workers,globals,forks,fxlanes` and `ci/check-ledger-ratchet.py` + with no ledger delta. +- Authority. Under `MemoryOnly` the session boundary has ONE process-local authority for reads, guarded edits + (`update_guarded*`), revocation (`cache_revoked`) and clear (`clear_for_erase`): the `peek()` cache cell becomes + the source of truth, `read_live_locked()` answers from it, and no durable credential read or write is + reachable (the four writers, the canonical commit and `save_legacy_fallback_locked`'s plaintext arm). The gate + sits above the `target_arch = "arm"` selection (F39, F44). It adds no `cfg(test)` branch to `session.rs` + (F44: a `forks` line) and extends the existing cache rather than adding a second static. +- Outcome. A successful memory-only write reports a new ephemeral outcome (`LiveWrite` and `CompletionOutcome` + gain `Ephemeral`; not `Durable`, not `Failed`). The auth owner treats it as signed in for this run: it + releases the held fresh-login handoff and proceeds to Home, `proves_saved_login` stays false, no "saved" + claim is shown, and one event-log line says memory only. Every consumer in F44 handles the variant. +- Decision 7, B (owner, 2026-11-20): what persists is `client_id`, language and interface resolution, nothing + else. The carrier is the `install_preferences` file at version 2, which adds `client_id`. Version 2 is written + only under `MemoryOnly` (the id is serialized only when set), `load` accepts versions 1 and 2, and webOS and + desktop keep writing version 1, so their files are byte-identical (v1 is `deny_unknown_fields`). No session + writer runs in `MemoryOnly`; the v2 file is written when the id is minted (`load_login_client_id`'s + `save_locked`) and when language or resolution changes. `candidates()` and `clear_for_erase` follow + `StoreMode`, not the ARM cfg (F44). Sign-out drops the in-memory session and keeps the v2 file; "Delete all + local data" removes it too. Every other preference, the per-profile settings among them, is forgotten each + launch, and the Tizen PR says so. +- Tests (W3a). Mock sign-in through to the auth owner's Home state under `MemoryOnly` with a writable data + directory: no credential file, and a scan of the WHOLE data directory finds no byte of the mock token. A + profile/settings edit after sign-in neither refuses nor loses the session. Sign-out, then erase, leaves nothing. + A fresh process on the same directory with planted legacy credentials ignores them, asks for sign-in again and + has the same `client_id`, language and resolution, with per-profile settings forgotten. A failure-injection + test forces the canonical write to fail and drives the legacy fallback: under `Durable` it writes (the control), + under `MemoryOnly` it never runs. webOS/desktop `Retained` fixtures are byte-identical; existing LG envelope + fixtures are graded separately. + +### 5. Device, caps, sandbox + +- Identity publishes `platform` and `platform_version`, and `plex::identity::PLATFORM` (F26) is the default + until the platform publishes. `device::Info`'s webOS-only fields (`codename`, `api`, `name`) move behind a + webOS-owned detail (F38); `release`, `build` and `major` stay as the neutral OS-version facts. +- The devcaps file reader moves to the platform, and the parsed model stays. +- The sandbox becomes `native_video: Available | Blocked(reason) | NotApplicable` with an optional repair hook. + +### 6. Media, as four things + +- a. Composition and the two boot phases (review M5, C3; critic F7). `Platform.media` is `MediaBoot { early_init: + fn(&MainThread), compose: fn(&mut PlayerAdapter, &PlaybackSession, controlled: bool) -> Composition }`, with + `Composition { resolver: Option }`: + - `early_init` runs at today's `acb_init` site (`app/boot.rs:2043`, inside `if !controlled`, before + `ffi::boot()`, F32). webOS fills it with `acb_init`, the others with a no-op. + - `compose` runs where `compose_backends` runs (`:2323`). webOS fills it with today's function + (`backends.rs:64,141-164`) minus both publications; the desktop installs HostSink Feed; Tizen installs + nothing (W9), then its URI driver (W10). It returns the resolver of a URI product only when the physical + install succeeded (today's `install_uri_product_with_ports`, `:418-421`); `None` on a refused install, a + controlled boot or no URI driver. It reads the session (`&PlaybackSession`: a driver may need a snapshot) and + publishes nothing. + - After `compose` returns, the APP publishes both facts in one function, once, always: the resolver + (`install_uri_preflight_port`) if present, then `install_backends(adapter.composed_backends())`, + `BackendSet::NONE` included (`backends.rs:163` and `:421` moved app-side, F43). The session starts at `FEED` + (F31), so a zero-driver platform that forgot the call would offer Feed, and a set that advertised URI without + its resolver would reach the planner as `NoPort`. No platform keeps adapter and session in step. + - The Cargo feature `play-uri` (`rust-modules/Cargo.toml:81`) keeps meaning "the webOS ACB URI driver" and is + webOS-only. `PLAYBACK_BACKENDS` maps per platform (Tizen: its own `uri` feature; `play-uri` never). The 37 + `feature = "play-uri"` sites in `rust-modules/src` are sorted in W6b: composition and `acb_init` go to the + webOS platform; `playback.rs`, `run.rs` and `dev.rs` read `adapter.composed_backends()` at run time, or stay + webOS-platform code if they name ACB. +- b. Evidence is the driver's, in three separate decisions (review B3, C5; critic M1, F12). + - Display readiness: `UriDriver::display() -> DisplayEvidence { readiness: Ready | NotReady(DisplayUnavailable), + preview_rectangle, tag }`, beside the capabilities and certification its offers carry. `Binding` leaves the + shared contract; `Acb`, `Exported{canvas}` and the `VP_EXPORTED` comparison become the LG driver's own detail + inside `plx_play_uri` (`Binding` is defined there; the app names it as `plx_play_uri::backend::Binding`, + `backends.rs:45`). + - Source qualification: whether THIS source may play stays the composition's qualifier, and the qualifier stays + in the app crate (G3; F49). LG's rule that declines a multi-audio original on an exported display + (`ProductQualifier`, `uri_preflight.rs:771-775`) and the viewer opt-in (`uri_opt_in`, `:771`, independent of the + capability bits) move from `plx_media` to `src/app/adapters/backends.rs`, where the qualifier is built + (`:387`). They do not go "into `plx_play_uri`'s qualifier": `[play_uri] uses = base os playback_contract` + (`ci/module-layers.ini:148`, where it read `base platform playback_contract` at `e9924f0f9`) forbids + `plx_play_uri` to name `plx_media`'s `OriginalQualifier`, and moving that trait, `OriginalRequest` and the verdict types to + `playback_contract` would put route policy into the contract, so neither move is made. `ProductQualifier` + keeps its name and implements media's `OriginalQualifier` in the app crate (`[app]` may use `media` and + `play_uri`, `:187`). It holds the `Binding` it was built with, read from the same value the driver is + configured with, so `OriginalRequest.binding` is deleted. It is built AFTER the `dev::uri_exported::compose` + override of the binding (as `:384-387` already orders it) and BEFORE the `dev::uri_product::compose` swap. + The shared route reads only immutable evidence, which the resolve worker receives: `plx_media` holds + `DisplayEvidence` and an opaque display tag (`&'static str` the driver names, printed in the boot log and the + diagnostics, branched on by no shared code), and never a `Binding`. + - Start readiness: `ready_to_start` stays an on-thread check (the ACB handle is made lazily on the loop thread, + `play-uri/src/backend.rs:1124`; `media/src/player/adapter.rs:1175` falls back to Feed when it fails). + - A driver that is a platform's only path declares its own certification (Tizen: its capability set); the + webOS driver keeps `certified` empty until the viewer's opt-in, as today. + - `UriNotReady` gains `DisplayUnavailable`, and `AcbHandle` is replaced in W3b by a driver-owned reason + (`UriNotReady::Driver(&'static str)`, the LG text unchanged) because three files name it and nothing pins its + text (F45); `log_name()` still prints the same line. + - The ACB plane owner (`tv/plane.rs`), `tv::uri` and the `plane_*` half of `DisplaySink` are webOS DRIVER code + named by layers below `app` (F8), so they go to a new layer crate `plx_acb` (`[acb]`, `uses = base machine + os`) in W11a, once neither `media` nor the app crate names them. The app's own names go to the webOS platform + in W6b. Until W11a the contract is NOT called neutral (critic M3). +- c. The Feed sink (L15b item 1): codec config plus timestamped access units, with seek, flush, pause and events; + the Starfish half of play-feed moves behind it in W11b. It does not gate Tizen URI playback: a Tizen URI driver + implements `UriDriver` and never touches `VideoSink`. +- d. Routing stays as it is. `BackendKind::{Uri, Feed}` means locator versus packets and `Capabilities` states + needs (critic M10). The set comes from the installed drivers. W6c exercises zero drivers, URI only with the + experimental setting off, a source the preferred driver declines (review M8), and a TWO-driver set: today's + `backend_policy::Offer::rank` (`media/src/route/backend_policy.rs:48`) hard-codes a URI tie-break and a + `FEED_ORIGINAL` tier, which a URI-only fixture cannot see; W3b pins that order first (C5). + +### 7. Entry, shutdown and the host doorway + +- Entry: webOS is `src/main.c` calling `plex_run`; desktop is the `plxnative-sim` bin; Tizen is a shared library + exporting the three calls below. +- Return (review B1, C2; critic F1, F8). `run_application` returns `Exit { code, release }` instead of `-> !` + (`release` is `Release::Complete | Retained`). An early-boot refusal returns its code, and a played session + returns after `run::shutdown` and the telemetry guard drop (F29). The executable entries own the process end: + `plex_run`, for webOS and the desktop, calls `exit_now(code)` right after, in today's order, so webOS + behaviour is unchanged. A hosted library never calls `exit_now` or `exit`. +- Exit inventory (C1; F40). No exit a hosted process can reach remains. The graphics boot (`init_gl`, + `init_text`, `init_image`, `init_blur`) returns a typed `GfxFault` for a compile or link failure of a required + program and `enter_application` returns it as an `Exit`. `blur_lazy_init` links mid-loop (F40); its programs + take the optional path (a compile rejection then degrades as its link failure already does), and a required + program ever linked lazily ends the loop through a loop-level fatal with code 1. The source guard + (`app/boot.rs:545`) drops the `-> !` pins and becomes a scan: no production `exit_now(` outside `src/port.rs`, + `src/bin/sim.rs`, `src/dev/framedump.rs` (`devtriggers`) and `base/src/process.rs`. Tests inject a compile and a + link failure: the fake host stays alive and receives the failure code. +- App stays leaked (critic F1; G5; F41, F51). The `App` is `ManuallyDrop`/`forget`-ed after the loop on BOTH entry + kinds, so returning drops nothing: `SessionAdapter::drop`, GL objects and the feed `Engine` never run under live + workers. The sentinel is a probe FIELD on `App` itself, not a counter on the dropped types: a + `#[cfg(test)] drop_probe: DropProbe` (an `Arc` whose `Drop` increments), so dropping the `App` + drops the probe whatever its other fields are. It is a field, not a static (no `statics` line), and + `rust-modules/src` is outside `FORK_SCOPE`. Like every new `App` field it is read (dead-code is denied in test + builds) and initialised at BOTH construction sites (`app/boot.rs:2474` and the `app/run.rs:3973` test rig). The + host test hands such an `App` to the returning exit path and asserts the count is 0, and a control drops + an `App` the ordinary way and asserts 1, so the probe is shown to detect. The leak and the `Exit` mapping live in + `app/exit.rs`: `run_application` keeps its 10-line `fnlen` budget (`ci/check-deps.sh:1176-1178`), which W3c does + not edit. +- Release status (C2; G4; F51). `run::shutdown` returns a `Release`, and `Release::Complete` is defined from the + arm of `quits_sdl` (`app/run.rs:3712-3718`) that ends with `SDL_Quit()`: `NativeExit::Clean`. `NativeExit:: + WorkerInFirmware`, the arm that logs "SDL_Quit skipped" today, is `Retained`. ONE function computes both from the + one `native_exit` (`quits_sdl(e)` is `release_of(e) == Complete`, or the reverse), by an exhaustive `match` with + no `_` arm, so a third `NativeExit` fails to compile in both and the hosted report cannot say `Complete` where + the executable skipped `SDL_Quit`. The existing assertion (`run.rs:3921`) is extended to pin both variants of + both answers. `Complete` additionally needs the loop to have released its GL context (`Shell::release`); + `Retained` otherwise. Teardown order is unchanged. The executable ignores it; the hosted entry maps `Retained` + to `clean = 0`. +- Drain and gating (C2; critic F8). Every host-bound callback (window, player request, log sink, `on_stopped`) + enters through one `HostGate { stopping: AtomicBool, inflight: AtomicUsize }` and is refused once `stopping` + is set; a late player completion is dropped. `clean = 1` is delivered only after the loop returned + `Complete` AND `inflight == 0`: a flag alone picks the completion sender but cannot drain a callback already + running. The watchdog is disarmed before `on_stopped` and across `OnPause` (`watchdog::disarm`/`arm`, new in + W3c, F42; `arm` re-captures the loop thread id). +- The hosted contract is private to the Tizen platform (review M4, critic M6): + - `plx_host_start(const PlxHostApi *, const char *launch_json)`, `plx_host_post(const PlxHostEvent *)` and + `plx_host_stop()`. `PlxHostApi` starts with `size` and `abi_version`; the library reads a later field only + when `size` covers it and refuses a table smaller than version 1. + - Threads. `plx_host_start` runs on the host's main thread inside `OnCreate`: it creates the Ecore_Wl2 window and + registers the key handlers there (the hello-world's model, F28; E6, E8), copies the table and the launch + string, spawns the loop thread and returns. `plx_host_post` may be called from any thread: a bounded queue + push and a wake, never a block. `plx_host_stop` runs on the host main thread, sets `stopping` and returns. + - The loop thread runs `run_application` and mints `MainThread` (F32). There the token means "the loop thread": + it authorises the player adapter and EGL, NOT Ecore window calls, and `MainThread::assume`'s safety text + (`base/src/task.rs:138`, "the SDL main thread") is updated in W9 before it is minted there. Work that must run + on the host thread leaves as a queued request through the callback table and comes back as an addressed + completion event; the loop never waits on the host thread. + - Ownership: a string passed into the library is copied before the call returns; a string passed to the host + is valid for that call only; the host keeps its managed delegates alive until completion. + - Completion. `on_stopped(code, clean)` is delivered exactly once, guarded by an atomic flag. On a clean stop the + loop thread calls it with `clean = 1` once the drain above holds. If the loop has not finished within a + deadline (a stalled swap), a watchdog thread started by `plx_host_stop` calls it with `clean = 0` and the + loop's own report is suppressed. After the call no callback is made again; with `clean = 1` the host may + release callbacks and surfaces, with `clean = 0` it releases nothing and treats process exit as the teardown, + as the hello-world does (`lib.rs:342-365`; the emulator run took the clean path, E8). + - The library is never `dlclose`d, and detached workers keep running until the process ends. The host must not + call `exit()`: without `src/exit.c` the #1115 hazard returns. UNVERIFIED: how Tizen ends a .NET app's + process, and whether our signal tracer can be installed in the host process. + - Host-driven loops (iOS, Android; critic M12) are not built; the contract is in thread roles so a host tick can + be added later, and `start` reserves a `flags` word. + - Tests: a fake host table in host tests is the second implementation (W3c builds the gate and the fake; W9 + wires the C ABI to it): boot refusal; quit during playback; stop with a player request outstanding and a late + completion; a returning loop with a retained worker (`clean = 0`); a callback in flight at stop (`clean = 1` + only after it returns); a swap that stalls and wakes after the timeout; pause then stop; the drop probe (G5). +- `access.c` and `exit.c` do not apply in a host-loaded `.so` (F19). +- Diagnostics (requirement; E5, T8). A Tizen build streams its event log from inside the app: one UDP datagram per + line to an address the developer configures at build or launch, as the hello-world does (`--log-host`, + `res/log-host.txt`): a sequence number per sender so a lost datagram shows as a gap, non-blocking sends, + failures ignored, off unless configured, an IPv4 literal; the host's own lines (a failed `.so` load) leave the + same way. A file in the app data dir is not a channel: it cannot be read off the device (E5). W9 decides where + the sink plugs into the app's event log (`plx_base`); the acceptance is a run whose log reaches a receiver + with no gap. + +### 8. The cross-crate construction interface (review C9; W7a) + +- The problem. W7 makes the platform crates siblings of the app crate, but `mod app;` is private + (`src/lib.rs:17`), so a sibling cannot name `app::Platform` or implement a crate-private `Shell`; and a + `static PLATFORM` must be `Sync`, while window state is thread-affine (`MainThread` is `!Send + !Sync`, + `base/src/task.rs:129`). +- The interface. One narrow public module, `plxnative_modules::host`, of re-exports only: `Platform`, `Services`, + `Shell`, `Surface`, `FrameProbe`, `MediaBoot`, `Composition`, `Exit`, `Release` and an `EventSink` trait. The + split is by thread: registration data (the `static PLATFORM`: function pointers and `&'static dyn` of `Sync` + types, `Shell` included as a factory) is `Sync` and shared; thread-affine state (window, GL context, the + Ecore handles) lives only in a `Surface` that `Shell::open(&self, &MainThread)` returns on the loop thread and + that the app owns inside `App`. The platform reports input through `EventSink` (`key(Option, + Option, Edge)`, `text`, `pointer`, `wheel`, `lifecycle`, `quit`, ...); the APP converts to its private + `HostEvent`, so the owner's decision that the event API stays private holds. `Action`, `RawKey` and `Edge` + are already public lower-layer types. +- Gate. Before extraction, a desktop-shaped root is compiled against `host` alone: an integration test + (`rust-modules/tests/host_interface.rs`, a separate crate that can name only `pub` items) builds a + `static PLATFORM` with a fake `Shell` and boots it under `hostsim`. W7b extracts only after it passes. +- Runner (G8; F52). No target runs it today (every one is `cargo test --lib`; `rust-modules/tests/` does not + exist), so a test file alone would be a gate nobody runs. W7a adds (1) `make test-host-interface`: `cargo + test -p plxnative-modules --features hostsim --test host_interface`, incrementally in `target-hostsim` like + `make test-hostsim`, through `$(UNIT_RUN)` if it accepts `--test` (UNVERIFIED: F52) and as a plain `cargo test` + otherwise; it is a cargo-running target, so it joins `DISK_ENTRIES` (with its `DISK_TREE` line) or + `ci/test_disk_preflight.py` fails; and (2) the same invocation as a recipe line of `check-cargo-unit-hostsim`, the + `host-unit-hostsim` CI job's target, so `make check` and CI run it, pinned in `ci/test_ci_split.py`'s `GATES`. + + +### What each platform supplies + +| interface | webOS | desktop | Tizen | +|---|---|---|---| +| entry | `main.c` exe, `plex_run` | `plxnative-sim` bin, `PlxNative.app` | `.so` + C# host, `plx_host_*` | +| shell (a `Surface` the loop owns, Target shape 8) | `plx_shell_sdl` + LG-fork bits (SysWMinfo, `wl_surface` opaque region, LS2 pump) | `plx_shell_sdl`, stock SDL | Ecore_Wl2 window on the host thread, EGL on the loop thread (F28; H3 and H4 yes on the emulator, E6, E8); Option A only if a retail run fails | +| input | LG layout `decode_key`, Magic Remote | stock layout, FIFO injection | Ecore key names to `Action` (Target shape 2; five codes measured, E7) | +| lifecycle | SDL app events | SDL app events | C# OnPause/OnResume/OnTerminate through `plx_host_post`; stop request and completion | +| key store | keymanager3 / palm, `Durable` | `HostFile` (later Keychain) | `MemoryOnly` first (client id, language, resolution kept; Decision 7, B), then the Tizen store | +| identity, caps | `webos::probe`, codec table, jail verdict | host values, `NotApplicable` | `Tizen` + version, player codec set, `NotApplicable` | +| backends | Feed (Starfish) + URI (`play-uri`, ACB) | Feed over `HostSink` | URI over `Tizen.Multimedia.Player` (W10), Feed later (W12) | +| display evidence | the LG driver's (ACB, exported window) | n/a | the Tizen driver's own | +| storage helper | LS2/DB8 service (`rust-modules/storage`) | none | none | +| diagnostics | event, crash and stderr descriptors (`main.c`, F19) | unchanged | in-app UDP log sink, required (Target shape 7, E5) | +| packaging | `.ipk` (`ci/mkipk.py`) | `.app` (`ci/mkmacapp.py`), bare bin | one `.tpk` first per configuration (x86_64 for the emulator MVP, armv7 for retail; Decision 8), signed with a Samsung Public profile (PLATFORM axis, E2) | + +### Crates and layers at the end + +- `[shell_sdl]`: layer crate `plx_shell_sdl` (`uses = base machine os`): SDL window, GL context, event drain and + stock key layout. A layer because webOS and the desktop share it (F1); not the shell Tizen will use (critic M11). +- `[acb]`: layer crate `plx_acb` (6b), used by `play_uri`, the Starfish half of `play_feed` and the webOS + platform. W11a. +- `[platform webos]`: crate `plx_platform_webos` (`rust-modules/platform-webos`): `webos`, `keymanager`, the LG + half of `system`, `webos::video_sink`, the storage activator, the value and `plex_run`; it produces the + staticlib `main.c` links. +- `[platform desktop]`: crate `plx_platform_desktop`: the desktop value, the 5 host arms of the fence that only the + simulator uses (W4: two stubs in `system.rs`, the two `SINK` arms and the table's test in `port.rs`; the other 97 + lines are television gates, the simulator's stand-ins kept for tests and `test-support`, or TV-side lines and + stay) and the sim bin. `HostSink` stays in `play_feed`. +- `[platform tizen]`: crate `plx_platform_tizen` plus top-level `tizen/` (C# host, manifest, sysroot scripts). +- The bottom layer is `[os]`, crate `plx_os` in `rust-modules/os`: Wave R (Decision 1, B; owner 2026-11-20: first + and alone) renames it with its directory, its 12 manifests and its references (F36), keeping the inner `tv` + module so a call site changes by its crate segment only. W7 later drops `webos` and `keymanager` from it. +- `plxnative-modules` (`[app]`) loses `port` and `system`, names no platform and gains the public `host` module + (Target shape 8). +- Gate change. Wave R switches the fence keyword (`[port X]` to `[platform X]`: gate code, since the parser keys + on `startswith('port ')`, F1, F36) together with the layer name. W7: a platform section whose members form one + crate above `app` may carry `uses` (every layer). Platforms may not name one another (F1), and nothing names + a platform. + +### The PLATFORM axis + +- `PLATFORM ?= webos`, validated by a new `ci/platform_axis.py --list` as FLAVOR is (F23). The selector is NOT + `ci/platform.py`: scripts run from `ci/` already import the stdlib `platform` (F46), and `ci/test_platform_axis.py` + also runs an existing consumer (`ci/mkmacapp.py`'s import, `ci/test-compat.py --help`) from that directory so a + shadow fails a test, not only a `make -n` diff. Values: `webos`, `desktop`, `tizen`. FLAVOR stays install identity. +- `PLATFORM` does not choose the compatibility axis (review M10): Rust target, sysroot, managed TFM, firmware floor + and signing path. Each platform records its tested configurations, one per Rust target it is tested on. Tizen has + two (Decision 8). x86_64 is a first-class configuration of `mk/platform-tizen.mk`: the TV 10.0 emulator, `tizen80`, + the Samsung Public certificate profile the emulator needs too (E2), and the configuration W9's MVP is accepted on. + armv7 softfp (T3) with the NDK sysroot, a named firmware range and the same kind of profile is the retail + configuration; it is recorded but untested until a retail set answers H1 and H2. Their variables are printed by the + CI job and quoted in the PR. What has run so far is x86_64 on the Tizen 10 emulator (E1-E13): it exercised + `tizen80`, the signing path and the host contract but neither the ARM library nor the NDK sysroot (H1, H2), and its + results read "emulator only". A further configuration (aarch64, `tizen90`, glibc 2.40) is added only when a + measured incompatibility on a named device requires it (E4: `tizen80` runs on Tizen 10). The packaged `.so` is + inspected (`readelf -d`, its undefined symbols against the sysroot's glibc symbol versions), and that exact `.tpk` is the one loaded on the device. One `.tpk` starts; T7's "one `.tpk` per API + generation" is the later case. +- W1 adds the variable, its validation and the `print-platform`/`print-rust-target` query targets (explicit + entries beside `Makefile:189-207`). Public targets (`sim-*`, `macapp`, `ipk`) keep their names. Per-platform + `mk/` files are split out only when `mk/platform-tizen.mk` exists (critic M11). +- Cargo: the root of each build is exactly one platform crate, and platform crates never depend on one another. + `make check` lints `--workspace` (F11), so a platform crate's edge to the app crate carries NO platform feature. + `plx_platform_desktop` has its own `hostsim` feature, off by default, forwarding `plxnative-modules/hostsim`; + its lib body is `#![cfg(feature = "hostsim")]`, so the workspace lint compiles it empty. `plx_platform_tizen` + does the same with a `tizen` feature. +- Stages that need a second invocation exist already: the hostsim type-check (`.github/workflows/ci.yml:379`), + `make test-hostsim`, the `sim-*`/`macapp` builds, `check-cargo-unit-hostsim` and `check-nodef` + (`Makefile:1928`), which after W7 also checks `-p plx_platform_webos`. A Tizen clippy pass runs in the Tizen CI job. +- The hostsim gate (review M11, F35). `check-cargo-unit-hostsim` keeps its eleven packages, including + `-p plxnative-modules --features hostsim`, and adds `plx_platform_desktop`; `HOSTSIM_PKGS` is the developer's + loop. Before and after every PR that moves tests (W4, W7), a script lists the discovered test names + (`cargo test --lib -- --list`, run with the gate's package AND feature arguments) and the diff must be moves + only, the app's lifecycle suite (`run.rs:3915`) and the Feed suites included. A separate check asserts that each + artifact root has exactly one `plx_platform_*` in its normal dependency tree. +- Tizen link shape: `cargo rustc --crate-type staticlib` of `plx_platform_tizen` (F24), then `cc -shared + -Wl,--whole-archive` over it plus `svg.o`, `sentry_context.o`, `crashtrace.o` and libass-plx. No `main.c`, + `access.c`, `exit.c`, `starfish.c` or `video_plane.c`; no cdylib crate type, so `ci/test_no_host_staticlib.py` + is untouched. +- CI: `cross-build` (`ci.yml:531`) stays required and webOS-only. A new compile-only `tizen` job builds the `.so` + and checks its exports against the C# `DllImport` list (T7); it stops at the `.so` (`build.sh --so-only` needs + no certificate): the `.tpk` needs a device-bound profile that stays out of the repo (T7, E2). The simulators + job runs `PLATFORM=desktop`. + +## Workstreams (ordered; every PR ships webOS) + +Groups: (N) needs nothing from Tizen and no television; (H) gated on a named hello-world result; (T) needs the +webOS television for acceptance. Lanes in a wave are file-disjoint by the Files lines below; `->` is a stack +inside one lane (the next PR starts after the previous merged). + +| Wave | Lanes | Bounded test (`make test-crate C=`, or `test-hostsim`) | TV | build-bench | +|---|---|---|---|---| +| R | the rename, alone | its own review gate: `--check`, the `--reverse` equivalence, two rehearsals (below) | boot log diff | yes | +| 0 | W0 | none (doc-claim-auditor) | no | no | +| 1 | W3a; W3b; W3c | W3a `plx_plex`, `plx_session`, `plx_media`; W3b `plx_media`, `plx_play_uri`, `plx_playback_contract`, hostsim; W3c hostsim, `plx_gfx`, `plx_base` | W3b, W3c | no | +| 2 | W1; W2 | W1 python tests; W2 `plx_os`, hostsim | W2 | W1 | +| 3 | W3d -> W4; W5a -> W5b -> W5c | W3d `plx_os`, `plx_plex`; W4 hostsim; W5 hostsim, `plx_ui` | W5b | W4 | +| 4 | W6b, then W6 and W6c | W6b hostsim, `plx_media`; W6 hostsim; W6c `plx_media`, `plx_screens`, hostsim | W6b, W6 | W6 | +| 5 | W7a -> W7b | hostsim, `make test-host-interface` (the integration test; G8) | W7b | W7a, W7b | + +Order (Decision 4, A, with the owner's rename decision of 2026-11-20): R; W0; the three contracts W3a-c (who +may persist credentials, what evidence admits a URI player, who ends the process); W1 and W2; W3d then W4 +beside W5; W6b; W6 and W6c; W7 (Decision 3, A: H3 and H4 are in on the emulator only, H1 and H2 gate a retail +set, not W7; Decision 8 takes W9's MVP to the emulator); W8; then W9-W10. W11a/b and W13 are independent. Why the +cut (review C6; critic F2, F5, F6; F45): +- R first and alone: a lane open across it re-runs the script, and W0's document then carries the final names. +- W1 leaves wave 1: Decision 4 puts it after W3a-c and nothing in them needs the Makefile. +- W2 before W3d: both own `tv/*.rs`. W3d before W4: both edit `os/src/webos.rs`, `webos/caps.rs` and + `webos/jail_repair.rs` (W3d writes `Info` and reads the sandbox there; W4 moves the hostsim arms out of them), + so they stack in one lane. W3d keeps `app/{boot,run,bridge,mod}.rs` out of its Files, so the W5 chain, + which owns those, runs beside it (the `devcaps` calls keep their signature). +- W6b after W4 (`src/port.rs`, `platform_desktop*`, the `sink` rule) and W5 (`run.rs`, the event dispatcher). + W6c consumes W6b's installed set and resolver, so it is not beside W6b but beside W6: its tests extend + `run_uri_boot_tests.rs` (`include!`d, F45) and the `backends.rs` tests, W6 owns `boot.rs`, `run.rs`, `mod.rs`. + +Gates (review C7; critic F9; owner, 2026-11-20): +- A lane runs one bounded `make test-crate C= T=` per crate its tests live in, or `make + test-hostsim [C=] [T=]` for `hostsim` tests; no `make check` and no cross-build in a lane. +- Each PR's own CI gates its own head (`make check`, `make check-nodef`, the ARM cross-build). A tree merged from + several lanes is never the evidence for one of them. +- One review reads 2-3 PRs together (each `base...head`) and is recorded on each head + (`tools/pr-land.py reviewed`); a push after it needs a new review. fw-compat-reviewer where a lane lists it; + doc-claim-auditor after behaviour change. +- TV checks are batched: one `--guest --mock` lease, taken with `tv-lock` and released at once, on the commit the + result supports (a wave's last-merged PR, for its file-disjoint lanes). +- A `make build-bench` table on the PR that changes `Makefile`, `Cargo.toml`, workflows or the module layout. +- `ci/check-module-layers.py` with `ci/allow/layers.txt` empty and `ci/check-ledger-ratchet.py` on every Rust PR (a + ledger line is never the fix); a reviewed `ci/readonly_generated.py` certificate change for any PR that edits + one of its pinned sources (F25). +- TWO reviewed certificates pin every member manifest and `Cargo.lock` (F47): any PR that changes a `Cargo.toml` + or the lock (Wave R, W6's workspace `Cargo.toml`, W7b, W9) re-pins BOTH + (`ci/readonly_generated.py:16` and `ci/readonly_dependencies.py:21`) in the same PR, each a reviewed change. + +### Wave R (N, also T). Rename the bottom layer, first and alone (Decision 1, B; owner, 2026-11-20) +- Status: landed on 2026-11-20 as #1474 (`e2088058d`); `origin/main` has the names this page's non-fact sections use. +- Goal: `plx_platform` becomes `plx_os`, one PR, no behaviour change, before W0 and with no other PR merging + meanwhile (critic F4: the "quiet window" the old W6d relied on does not exist). + - Package, directory (`git mv rust-modules/platform rust-modules/os`), 12 manifests, `Cargo.lock`, the 3280 lines + in 296 `.rs` files, the nested `CLAUDE.md` files and the 27 files under `ci/ tools/ tests/ .github/ Makefile + docs/ .agents/` (F36, F48 A: 3461 lines in 338 files counting every kind). + - `[platform]` becomes `[os]` in `ci/module-layers.ini` (the section, the token in 13 `uses =` lines, the + comments) and in `docs/module-layers.md`; the fence keyword `[port X]` becomes `[platform X]` (gate code, + `ci/check-module-layers.py:14-15,68-84`); the inner `tv::` module stays. `SRC_PLATFORM` becomes `SRC_OS`. + - Pins that embed the name are changed in the same PR, each found by grep (F36, F48): `app/boot.rs:640,668`, + `app/run.rs:11184,11199`, `ci/test_ci_split.py:58-67`, `tests/test_harness.py:9916`, + `ci/test_{test_crate,no_host_staticlib,build_bench,storage_package_isolated,check_machine_shape}.py`, + `tools/build-bench.py` (package, leaf file and the scenario id `platform`), `ci/check-deps.sh`, the `Makefile` + gate package lists and its two `find` lists (`:1016,1055`), `ci/list-caps.ini`'s 23 keys, + `tools/cargo-seed.py:190`, `rust-modules/{build.rs,storage/build.rs,storage/Cargo.toml}`, `.github/workflows/ + ci.yml`, `.agents/agents/fw-compat-reviewer.md`. + - Certificates (G1; F47): TWO reviewed re-pins, not one. `ci/readonly_generated.py` (`:16` the constant, `:17-19` + `SOURCES`, `:60-61` package and module) with `ci/proofs/platform-generated-enums.json` (the file keeps its + name), and `ci/readonly_dependencies.py:21` with `ci/proofs/serde-json-immutable.json` (its manifest keys, the + `platform/Cargo.toml` owner entry and `lib_sha256`, `lock_sha256`). The pinned sources are five files under the + directory (`Cargo.toml`, `src/lib.rs`, `src/i18n/mod.rs`, `build.rs`, `build_support/catalog.rs`) AND + `rust-modules/build_support/install_identities.rs`, which is outside it and which the directory move does not + carry. `ci/test_readonly_generated.py` is edited with them (13 bare paths). Order, because each step feeds + the next: script; `Cargo.lock` regenerated by cargo (`--locked` fails until it is); any reflow; both + certificates regenerated; both constants re-pinned. + - It ships `tools/rename-os-layer.py`: idempotent; `--check` (below); `--reverse`, which rewrites a tree back to + the old names, and `--reverse-patch FILE`, which rewrites a backport's diff to the old names so that a + `backport` cherry-pick of a later fix onto a release line, which still has the old names, applies + (`backport.yml` opens nothing when a pick conflicts, and every pick touching a renamed path does); and + `--equivalence BASE` (below). The script does not run rustfmt, and `--reverse` rewrites only the sites the + forward pass wrote (F48 C). +- Proof (G2). A missed reference does NOT always fail the build: `tools/cargo-seed.py:190` reads a missing manifest + as empty and `Makefile:1016,1055` drop a missing directory from their `find` lists (F48 B1, B4), and both stay green. + Two checks are needed for that reason. + - `--check` lists the old-name sites left, in every spelling of F48, not one: (1) `plx_platform` not followed by + `_webos`, `_desktop` or `_tizen`; (2) the path `rust-modules/platform` NOT followed by `-webos`, `-desktop` or + `-tizen` (after W7b those directories exist and would match, N3), the bare `platform/...` paths relative to + `rust-modules/` with or without `../` prefixes (the `#[path = "../../platform/src/..."]` lines of + `storage/src/main.rs` and `manifest.join("../platform/src")` in `base/src/eventlog/scrub.rs:1081`, N2), the + manifest forms (`path = "platform"`, `"../platform"`, the `members` entry) and every quoted `"platform"` or + `'platform'` (the components assembled in `cargo-seed.py`, `ci/test_no_host_staticlib.py` and the build-bench + scenario, and the sites a hand list missed, N1). The script classifies EACH such hit over the tracked files as + renamed or exempt (`sys.platform`, a JSON key) and FAILS on an unclassified one; it does not rely on a list of + files. The silent one is `rust-modules/media/src/player/report.rs:3135` (the layer array of the `fetch_update` + scan: `walk` returns on a missing directory and `files > 500` still holds, so the scan drops the bottom layer and + every gate, `--equivalence` included, stays green); `.claude/hooks/release-config-check.py:276` is loud only + through its test (`:69`); (3) the layer token: `[platform]` and `platform` in a `uses =` line of `ci/module-layers.ini`, + and `[port X]`. Exempt, by a list in the script: `docs/release-audits/*`, `docs/measurements/*`, dated + `docs/*-20YY-MM-DD*.md` and this plan (the whole page: the Wave R section itself quotes the old names). It must + print zero outside the list. The reviewer ALSO + runs plain `git grep` counts for each class of F48 before and after, in the PR body, so a bug shared by the + script's rewrite and its check cannot hide. + - Equivalence: `--equivalence BASE` applies the forward pass to a scratch copy of BASE and `--reverse` to a scratch + copy of the head, and compares each with the other side. The only differences allowed are an enumerated list, + printed with the result: (a) the two certificates, each a `.json` and one constant line; (b) + `rust-modules/Cargo.lock` (the package renames and re-sorts); (c) a `.rs` hunk that is a pure reflow or `use` + reorder (the same multiset of tokens), which the shorter name causes (`plx_os` sorts differently and lets a + wrapped line fit); (d) the tool itself, its test and its two lines (a comment and the step) in + `ci/check-python-steps.txt`. Everything else must be byte-identical; a file in none of the four classes fails the + gate. The reviewer reads the list, not the 338-file stat (AGENTS: a diff stat is + not a measure of change). + - Two rehearsals, before the PR lands, results in the PR body. (1) One open PR head (the one touching the most + renamed paths; `gh pr list`): run the open-PR recipe on it (before Wave R lands, `origin/main` in the recipe is + the Wave R branch) and build its tests. The recipe's ORDER is decided by the rehearsal and recorded: the first + recipe was `git merge origin/main`, then the script, then commit; the alternative + is the script first, commit, then the merge, where both sides made the same edit to every renamed line. The + rehearsal runs both on the same head and writes down each one's conflict count and which won; the briefs carry + the winner. (2) `release/v0.10` (it exists on `origin`): no real post-rename fix exists before Wave R + lands, and the reverse of the PR's own diff reproduces the base by construction (vacuous, N4), so make a + synthetic content edit on the Wave R branch (one changed line in a file the rename rewrites, one in a file it + leaves alone), rewrite its diff with `--reverse-patch`, `git apply --check` it on a scratch checkout of the line, + and run `--check` on the result (the old names must be back, the new ones gone). +- Files: everything above; `docs/module-layers.md` here only for the names (W0 follows). Also `rust-modules/ + build_support/install_identities.rs` (outside the directory, F47) and the bare-path files of F48 B2 (a + `rust-modules/platform/` grep does not find them), and the sites of N1 and N2: `media/src/player/report.rs`, + `.claude/hooks/release-config-check.py` with its test, `storage/src/main.rs` and `base/src/eventlog/scrub.rs`. +- Gate (its own review): a `make build-bench` before/after table (the PR touches `Cargo.toml` and the + layout); fw-compat-reviewer (the move touches `os/src/webos/ls2/uri.rs`, a file on its list); both certificate + re-pins; the old name counted by the F36 and F48 greps before and 0 after (outside the exempt list); the + `--equivalence` result; `make check`, `make check-nodef` and the ARM cross-build on the PR's own CI; the + discovered-test diff (moves only); `ci/check-module-layers.py` with `layers.txt` still empty; a `--guest --mock` + TV boot with the log diff; the `make` input lists (`RUST_INPUTS`, `STORAGE_INPUTS`) printed before and after, equal + but for the directory name, and the cargo seed key (`tools/cargo-seed.py`) computed over both manifests. +- Risk: the silent sites above, which the second check exists for; a lane open across the rename conflicts on + every touched line (the script is the mitigation); `--reverse` over-reaching (the bare `os/`). + +### W0 (N). Record the plan +- Goal: `docs/platform-ports.md` (this page: the plan with final names; its fact sections quote the old names on + purpose) and an amendment of `docs/module-layers.md`: steps L15c-L15h, introduced there, mapped to the + workstreams, and its order (F3) amended from "extraction after all of L15b" to "extraction (W7) after item 2 (W4); + item 3 (W8) and item 1 (W11) afterwards". The desktop platform satisfies "a second implementation", and an order of + "after items 2 and 3" would contradict W8, which follows W7 (review C6). The page records H3 and H4 as answered on + the emulator only, H5 likewise, and H1 and H2 as open: they gate a retail set, not the emulator MVP of W9 + (Decision 8). It also records the owner decisions at the end of the page. W0 does not wait for a retail set. +- Files: `docs/platform-ports.md`, `docs/module-layers.md`. Verify: doc-claim-auditor reports no contradiction. No + test, no TV, no build-bench. + +### W1 (N). The PLATFORM axis, webOS and desktop only +- Goal: `PLATFORM ?= webos`, `ci/platform_axis.py`, the compatibility-axis variables, the two query targets. + `sim-*` and `macapp` imply `PLATFORM=desktop`. No `mk/` split yet. No behaviour change. +- Files: `Makefile`, `ci/platform_axis.py`, `ci/test_platform_axis.py`, and `DISK_ENTRIES` if a cargo-running + target is added (`ci/test_disk_preflight.py`). +- Test: `python3 ci/test_platform_axis.py` (includes the stdlib-shadow case, F46) and `ci/test_disk_preflight.py`. +- Verify: `make -s print-flavor print-appid` unchanged plus `print-platform`; the ARM link command diffed before + and after from `make -n` (a byte-identical binary is NOT claimed); a build-bench table. TV: no. +- Risk: a variable changes through include order; the `make -n` diff catches it. + +### W2 (N, also T). Split `tv::Port`; shell and diag move to `app::Platform` +- Goal (critic M4): F5's 27 fields regrouped with the same function pointers. + - `tv::Services { identity, secure, system, legacy_webos_media }` as in Target shape 1; W3a's once-set + `StoreMode` is folded into `secure` with the accessor unchanged (critic F2). + - The seven window and bus entries and the six frame probes leave `plx_os` for the app crate as `Shell` and + `FrameProbe`; `tv/window.rs` is deleted; `app/{boot,run,bridge}.rs` call `Platform`'s members. The webOS + implementations stay in `crate::system` (already `[app]`, F2) until W6. + - `ABSENT` becomes `Services::HOST_TEST` and `Platform::HOST_TEST`. +- Files: `os/src/tv.rs`, `os/src/tv/*.rs`, `src/port.rs`, `src/app/{boot,run,bridge,mod}.rs`, `ci/check-deps.sh` (the + `frame` gate at `:1097` is rewritten to pin the `Shell` call text to `run.rs`). `os/src/lib.rs` is untouched. +- Test: `make test-crate C=plx_os T=tv`, `make test-hostsim`; a host test pins every `HOST_TEST` answer; the + `frame` gate's self-test still rejects a new call site. TV: a `--guest --mock` boot, log diff. Risk: low. + +### W3 (N, W3b and W3c also T). The three contracts, then neutral types + +W3a. Persistence mode (review B2, C4; critic F2, F3; F30, F39, F44; Target shape 4; Decision 7, B). +- Goal: the once-set `StoreMode` (default `Durable`, no `Port` field) with a SEPARATE test override (a + process-global guarded by `testlock::serial()` and reset on drop, G6), the memory-only authority, the `Ephemeral` + outcome and the `install_preferences` v2 carrier, all as Target shape 4. +- Files: `os/src/tv/secure.rs`; `plex/src/plex/session.rs`; `plex/src/plex/session/{persistence,async_persistence, + install_preferences}.rs` and `session/prefs/profile_prefs.rs`; `plex/src/plex/session/migration_tests.rs` (`:779`, + only if `Retained` gains a field); `plex/src/plex/session_persistence_tests.rs`; + `session/src/auth/owner.rs` and `owner/attempt_characterization_tests.rs`; `telemetry/src/telemetry/incident.rs`; + `src/app/adapters/session.rs`; `media/src/route/decision_prefs_characterisation_tests.rs`; and + `plex/src/plex/CLAUDE.md` (`:501,646` say `peek()` is a write-through cache; F50). Not `tv.rs`, not + `src/port.rs`, not `src/app/{mod,run,boot}.rs`. Read `plex/src/plex/CLAUDE.md` first. +- Test: `make test-crate C=plx_plex T=session`, `C=plx_session T=auth` and `C=plx_media T=prefs_characterisation` (that + file is `#[cfg(test)]` under `route/decision.rs:14253`, not `hostsim`; the cases of Target shape 4, on + `tests/mock_pms.py` and the mock plex.tv, never a real account); every existing session test unchanged; + a test that sets the mode holds `testlock::serial()` and the setter's guard resets it (G6); `ci/check-deps.sh + --only workers,globals,forks,fxlanes` and `ci/check-ledger-ratchet.py` show no ledger delta: `secure::` is not + in the `globals` pattern and the pattern is not extended (F44, F50). TV: no. +- Risk: `session.rs` is the largest file and a gate at one writer leaves another writing plaintext: the data-dir + scan, not a list of writers, is the check. + +W3b. URI evidence (review B3, C5; critic M1, F10, F12; F31, F45; Target shape 6b). +- Goal: `DisplayEvidence` (with the opaque display tag), `UriDriver::display`, `UriNotReady::{DisplayUnavailable, + Driver}` (replacing `AcbHandle`); `Binding` and the `VP_EXPORTED` comparison move into the LG driver in + `plx_play_uri`; LG's multi-audio rule and the opt-in move with `ProductQualifier` from `plx_media` to + `src/app/adapters/backends.rs`, NOT into `plx_play_uri` (its layer may not name media) and with no trait or + request type moved to `playback_contract` (G3; F49); `OriginalRequest.binding` is deleted; `ProductEvidence` is + built from driver evidence; `ready_to_start` stays on-thread. webOS behaviour is identical. +- Files: `playback-contract/src/{uri,test_support}.rs`; `media/src/route/{uri_preflight,plan,backend_policy, + decision_version_tests,decision_resolve_route_tests}.rs`; `media/src/player/adapter.rs` (two tests) and + `media/src/player/CLAUDE.md:30-56`; `play-uri/src/*`; `src/app/adapters/backends.rs`, `src/app/{run_uri_boot_tests, + diagnostics}.rs`; `src/dev/{uri_product,uri_exported,uriprobe_tests}.rs`; and two that named the old home of the + qualifier (G7; F49): `plex/src/plex/session/playback_options.rs:39` (a doc comment) and `docs/module-layers.md:180`. + Not `run.rs` (it only `include!`s the test file). +- Test: `make test-crate C=plx_media T=route::`, `C=plx_play_uri`, `C=plx_playback_contract`; `make test-hostsim + T=backends` and `T=uri_boot`. The qualifier's own tests leave `plx_media` with it (`uri_preflight.rs:838-869, + 1490-1512`) and run in the app crate, where a `plx_media` run does not execute them: the hostsim runs are their + bounded test (`--require-match`: a `T=` that matches nothing fails). The route tests that stay in media run over a + fake qualifier. The expectations are unchanged, plus: a test that the qualifier is built from the binding AFTER the + `dev::uri_exported` override (`devtriggers`); `ci/check-module-layers.py` with `layers.txt` empty (no + `plx_play_uri` item names `plx_media`); the same multi-audio source on both LG paths (ACB accepts, exported refuses); a failed lazy + ACB handle falls back to Feed; a certified non-LG driver with the opt-in off is admitted and starts; a + TWO-driver (Feed plus URI) selection that pins today's `Offer::rank` order (C5). fw-compat-reviewer + (`play-uri/src` is on its list). TV: a `--guest --mock` boot and play, the URI opt-in declines or plays as before. + +W3c. Shutdown ownership (review B1, C1, C2; critic F1, F8; F29, F40-F42; Target shape 7). +- Goal: `run_application` returns `Exit { code, release }`; the exit inventory, the leaked `App` with its drop + probe field (G5), the release status defined from `quits_sdl`'s arm (G4), the `HostGate` and the watchdog disarm + of Target shape 7; `plex_run` and the sim call `exit_now` in today's order. The C ABI is W9's; W3c ships the + gate and a fake host. `run_application` stays within its 10-line `fnlen` budget (`ci/check-deps.sh:1176-1178`, + F51): the leak and the `Exit` mapping are in `app/exit.rs`, and the gate is not edited. +- Files: `src/app/{mod,run,boot}.rs` and a new `src/app/exit.rs`; `src/port.rs`; `src/bin/sim.rs`; + `gfx/src/{gfx,text}.rs`; `base/src/task/watchdog.rs`. Not `adapters/*` (the drop probe is a `cfg(test)` field of + `App`, read in the test and set at the two construction sites, `app/boot.rs` and the `run.rs` test rig), not + `backends.rs`. `gfx/src/gfx/straighten.rs:1272` pins `pub fn init_gl()` by text and survives the new return type + (F51); it is read, not edited. +- Test: `make test-hostsim T=lifecycle` (boot refusal returns its code; quit; the cases of Target shape 7 through + the fake host; the drop probe and its control; `release_of` and `quits_sdl` agreeing on both `NativeExit` + variants; the rewritten source guard), `make test-crate C=plx_gfx T=fault` (injected + compile and link failures return a `GfxFault`), `C=plx_base T=watchdog`. TV: a `--guest --mock` boot and quit + with the same last log lines and exit status. Risk: teardown order, which stays as today. + +W3d. Neutral types (L15b item 2 prerequisites; part of item 3). +- Goal: the opaque `Backend` tag (critic M8); `sandbox` becomes `native_video`; identity publishes + `platform`/`platform_version` and `device::Info` loses `codename`, `api` and `name` to a webOS-owned detail (F38, + F45); the devcaps reader moves behind the platform. +- Files: `os/src/tv/{secure,sandbox,device}.rs`, `os/src/{webos,devcaps}.rs`, `os/src/webos/{caps,jail_repair}.rs`, + `os/src/keymanager.rs` (the tag constants), `plex/src/plex/identity.rs`, `plex/src/plex/session_persistence_tests.rs` + (`Backend::Keymanager3` at `:769,1724,1730`; W3a's file too, but W3a is merged before wave 3), the sandbox and `Info` readers of F45 + except `app/{boot,run,bridge,mod}.rs`, `src/app/{diagnostics,playback}.rs`, `src/lab/snapshot.rs`, and the L15 + table in `docs/module-layers.md`. `devcaps::probe()` and `caps()` keep path and signature (the file read moves + behind `probe`), so their callers `app/mod.rs:537` and five in `run.rs` stay W5's, untouched (grep). +- Test: `make test-crate C=plx_os`, `C=plx_plex T=identity`. A host test serializes and deserializes a `Sealed` + for each existing tag and compares the JSON with a literal fixture written from today's code; the X-Plex headers + test (`plex/src/plex/client.rs:1099`) is unchanged. UNVERIFIED whether `tests/fixtures/persistence` already + pins envelopes; this test is added either way. Risk: a changed tag loses every TV's saved session; the fixture + is the guard. TV: no. + +### W4 (N). The simulator as its own platform (L15b item 2) +- Goal: a second fence section, `[platform desktop]` (no gate code: Wave R already switched the keyword, F1), with + member `platform_desktop` (a module of the app crate until W7) and its own `Platform` value; the simulator's host + arms (5 of the fence's 102 `hostsim` lines, sorted by the rule below) move out of `system` and `port` into it; the + other `hostsim` terms of `webos`, `keymanager`, `system` and `port` go (the simulator's stand-ins in `webos` and + `keymanager` stay, compiled for tests and `test-support`: see the rule below); `sim.rs` names it (F7). +- Rule for the three configurations. The 102 fenced `hostsim` lines (F10) are cfg lines of both polarities, not 102 + host arms. Each was read and classified by what it gates (the same counts at `e9924f0f9` and on `main` after Wave R). + - 77 carry a negated `hostsim` (`git grep -h 'feature = "hostsim"' -- | grep -c -e 'not(feature = + "hostsim")' -e '!cfg!(feature = "hostsim")'`): they gate the TELEVISION arm, so they lose only the `hostsim` term + and stay in their files (`src/system.rs` included). 17 of them are exactly `all(not(feature = "hostsim"), + not(any(test, feature = "test-support")))` (`webos/toast.rs:26`) and keep their `not(any(test, ...))` term: + dropping it would turn a production gate into a test-only one. + - The other 25 name `hostsim` only positively. 5 move to `platform_desktop`: the host stubs `opaque_region_init` + and `opaque_route` (`system.rs:423,469`), `port.rs`'s two simulator `SINK` arms (`:11,14`), and the simulator + table's test (`port.rs:79`, `all(test, hostsim, play-feed)`: it names `app::adapters::hostsim::HOST_SINK`, which + exists only under `all(hostsim, play-feed)`, so dropping the term would break the plain test build). + - The other 20 stay: + - 10 lose only the `hostsim` term. Nine are the simulator's stand-ins for the television's services, + `any(feature = "hostsim", test, feature = "test-support")` (`keymanager.rs:198`, `webos.rs` six times, + `webos/jail_repair.rs:44`, `webos/toast.rs:55`): what the simulator runs today (`launch_home`, + `system_locale`, `sound_output`, `bind_window`, the keymanager client, `deliver` and `call_hbc` among + them), so more than test seams. They stay in `webos` and `keymanager`, compiled for tests and + `test-support` as `cfg(any(test, feature = "test-support"))`. The tenth, `port.rs:22`'s `any(hostsim, + test)`, becomes `cfg(test)`. + - 6 are the frame-probe no-op stubs (`system.rs:761-772`, `any(feature = "hostsim", not(feature = + "devtriggers"))`). Every TV build without `devtriggers` compiles them, a RELEASE build included, and + `app/run.rs` reaches them through the port, so they are re-gated as `cfg(not(feature = "devtriggers"))`. + - 3 are `cfg_attr(feature = "hostsim", allow(dead_code))` on TV items (`webos/toast.rs:33,40`, `system.rs:22`) + and stay with their item, and 1 is the `let _ = winp;` statement inside a TV function (`system.rs:173`). + - Under `cfg(test)` without `hostsim` the webOS table stays as today (`SINK = NoSink`, `DISPLAY = SINK`). +- Order: after W2 and W3d (stacked in its lane). Files: `src/port.rs`, `src/platform_desktop*`, `src/lib.rs`, + `src/system.rs`, `os/src/webos*.rs`, `os/src/keymanager.rs`, `src/bin/sim.rs`, `ci/module-layers.ini`, + `ci/check-deps.sh` (the `sink` rule's paths, F25), `ci/mkmacapp.py`, `ci/test_sim_backend.py`, + `ci/test_test_crate.py`, `.github/workflows/ci.yml:379`. +- Test: `make test-hostsim`; the fenced `hostsim` count (F10's grep) falls from 102 to 0 (77 television gates lose a + term, 10 stand-ins kept for tests do too, 6 stubs are re-gated on `devtriggers`, 4 lines stay with their TV items, + 5 host arms move; the five numbers, each with the grep that gives it, in the PR); the discovered-test diff; + `make sim-macos` and `make macapp` booting to Home under ui-sim; replay fixtures unchanged; a build-bench table; + fw-compat-reviewer (`system.rs`'s Wayland and SDL externs are split). TV: none beyond the wave's. Risk: the 363 + non-fence `feature = "hostsim"` lines (360 cfg lines) remain (W8); F11's mechanism lands in W7. + +### W5 (N, W5b also T). The event contract (one lane: W5a -> W5b -> W5c) +- Goal: `HostEvent` with `Option` (Target shape 2), app-private, consumed by the loop. `drain_sdl` + (`app/run.rs:1066-1069`) becomes a shell drain; `decode_key`/`rd_u32`, the wheel and `TEXTINPUT` decodes move + into the SDL decoders unchanged. +- PRs: W5a lifecycle and quit (the hosted stop request arrives as `Quit`). W5b keys and text: step 1 is the + inventory (review M6): a PR table with one row per consumer of a raw pair (the 7 `screens` files naming + `WCODE_`/`classify(`, Search editing, Library `page_dir`, the PIN keypad, Player transport, the HUD, + `app/{events,bridge,run}`) saying what each does on each `Action`; then `Action`, `raw_pair`, `action_of`, the + `pin_digit` move and the tests of Target shape 2 (C8). W5c the pointer and `Wheel { dy }` and the Magic Remote + hide (`app/boot.rs:794-836`, UNVERIFIED location). W5d, the exit step (Decision 6, A), is not scheduled until a + fourth platform is planned. +- Files: `src/app/{events,run,input,mod,lifecycle,recorder,bridge}.rs`, `src/app/boot.rs` (W5c only), + `src/textinput.rs`, `ui/src/consts.rs`, `screens/src/profiles.rs` (W5b only). +- Test: `make test-hostsim` with the FIFO, `make test-crate C=plx_ui T=consts`; replay tapes replay identically, + `enc_lifecycle` is byte-equal, `tests/keytable.json` unchanged. TV: W5b only, one `--guest --mock` lease (the LG + layout is device-only, F16). Risk: the LG `TEXTINPUT` offset (`app/run.rs:1208-1212`) and the sdl2-compat carrier + must move unchanged. + +### W6 (N, accepted T). The shell and `plx_shell_sdl` +- Goal: `rust-modules/shell-sdl` (`[shell_sdl]`) takes window creation (`app/boot.rs:1547-1652`), the swap + (`app/run.rs:974`), the drain and the stock decode, behind `Shell`/`Surface`. The LG half of `system.rs` + (SysWMinfo over-allocation, `wl_proxy_marshal` opaque region, the `g_main_context` pump; `system.rs:1-6,34-38`) + stays in the webOS platform. No Samsung shell is designed here. +- Order: after W6b. Files: `src/app/{boot,run,mod}.rs` (not `bridge.rs`), `src/system.rs`, `rust-modules/shell-sdl/`, + the workspace `Cargo.toml`, `ci/module-layers.ini`. The source-text pins at `app/boot.rs:705-785` and + `app/run.rs:11467` (F14) move with the code they search. +- Test: `make test-hostsim`; a build-bench table; `check-nodef`, the ARM cross-build and fw-compat-reviewer; a TV + lease: boot log diff and the video plane still showing through (opaque region); frame claims only via + `profile-tv`. Risk: the SysWMinfo overrun (`system.rs:4-5`); that code moves verbatim. + +### W6b (N, accepted T). Platform-supplied composition, two phases +- Goal: `app::Platform.media` (Target shape 6a). `acb_init` moves behind `early_init` at its present call site + (`app/boot.rs:2043`); `compose_backends` minus both publications behind `compose`, which returns the installed + resolver; the app publishes resolver then set in one function. The 37 `play-uri` sites are sorted as 6a says. + The desktop composes HostSink Feed. +- Order: after W4, W5 and W3b. Files: `src/app/adapters/backends.rs`, `src/app/{playback,run,boot}.rs`, `src/dev.rs`, + `src/lib.rs`, `src/app/run_uri_boot_tests.rs`, `src/dev/uriprobe_tests.rs`, `src/port.rs`, `src/platform_desktop*` + and the `sink` rule in `ci/check-deps.sh` (its allowed paths name `app/adapters/backends.rs`, F25). +- Test: `make test-hostsim T=uri_boot` and `make test-crate C=plx_media`, with REAL composition (review C3): success, + a refused URI install, a controlled boot and zero drivers, each asserting the session's set and resolver + agree; the PR's CI runs `PLAYBACK_BACKENDS=uri|feed|none`; fw-compat-reviewer (the ACB init path moves). TV: a + `--guest --mock` lease: Feed plays a mock title, the URI opt-in declines or plays as before, and the boot log + shows `acb_init` at the same point. +- Risk: `acb_init`'s order relative to `ffi::boot()` and the first frame; moving it into `compose` would change + its timing (review M5). + +### W6c (N). A URI-only and a two-driver composition play an ordinary title (host tests, before W10) +- Goal (review B3, M8, C5; critic M1): through the real planner, with `FakeUriDriver` (`test_support.rs:143`) carrying + no LG binding and no Feed driver, an ordinary title resolves to a URI offer and starts. Also: zero drivers + (typed refusal, Play disabled with a reason through the new `ScreenInputs.backends`); URI only with the + experimental setting off, the driver certifying itself; a source the driver declines (a `URI_PMS_*` conversion + or a refusal); and the two-driver case of Target shape 6d. +- Order: after W6b, beside W6. Files: new `media/src/route/*_tests.rs`, `screens/src/inputs.rs` and the Play + control that reads `backends` (UNVERIFIED which `screens/` file; no other wave-4 lane edits `screens/`), `src/app/bridge.rs` (`:1700`, where `ScreenInputs` is + filled), tests in `src/app/adapters/backends.rs` and `src/app/run_uri_boot_tests.rs`. No `run.rs` line. +- Test: each owning crate: `make test-crate C=plx_media`, `C=plx_screens`, and `make test-hostsim T=uri_boot` + (a `plx_media` run alone does not execute the app tests). Risk: if this step needs planner changes they are the + hidden W10 work critic M1 named, and they land here. + +### W7 (N, accepted T). Extract the platform crates (W7a -> W7b) +- W7a: the interface of Target shape 8: `pub mod host` in `src/lib.rs`, `host_interface.rs`, a desktop-shaped root + compiled against it. W7b: `[platform webos]` becomes `rust-modules/platform-webos` and `[platform desktop]` + becomes `rust-modules/platform-desktop`. `RUST_LIB` (`Makefile:882`) archives `plx_platform_webos`; the gate + learns "platform as crate above app". `tv/plane.rs` and `tv::uri` stay in the bottom layer until W11a. +- Order: after W0, W4, W6, W6b, W6c and Wave R. W0's reading (the desktop counts as the second implementation) + reverses `docs/module-layers.md:22-24`; the owner's yes is Decision 3, A. The owner's condition was H1-H4 from + the emulator or a set: H3 and H4 returned on the emulator (E6, E8) and are recorded as answered on the + emulator only; H1 and H2 are open (E9), recorded as open, and gate a retail set, not W7 (nor the emulator MVP of W9, + Decision 8). `HostEvent` and `Shell` stay app-private. +- The Cargo mechanism of the PLATFORM axis lands here: the ARM recipe passes `RUST_FEATFLAGS` + (`Makefile:1023-1024`), so each platform crate depends on the app with `default-features = false` and forwards + every app feature the Makefile passes (`rust-modules/Cargo.toml:78-82`), same defaults. +- Files: `src/lib.rs`, `rust-modules/tests/host_interface.rs`, `rust-modules/Cargo.toml`, the `Makefile` `RUST_LIB` + and `cargo rustc` lines and (W7a, G8; F52) the new `test-host-interface` target with its `DISK_ENTRIES` entry and a + line in `check-cargo-unit-hostsim`, `ci/test_ci_split.py` (its `GATES`), `ci/check-staticlib-artifact.py` + (`CRATE`, F25), `ci/check-module-layers.py`, + `ci/module-layers.ini`, `docs/module-layers.md`, `ci/build-budgets.json` (re-measure; no raise), and the bottom + layer's `src/lib.rs` (drops `pub mod keymanager;` and `pub mod webos;`) with its `Cargo.toml`: both pinned, a + reviewed certificate change (F25). +- Test: `make test-hostsim` and `make test-host-interface` (the integration test, run by no target today; `ci/ + test_disk_preflight.py` and `ci/test_ci_split.py` pass with it); W7a changes the `Makefile`, so its PR carries a + build-bench table as well as W7b's; `ARM_PROFILE=release` size within budget; + every undefined symbol of the C objects (`main.c`, `crashtrace.c`, `sentry_context.c`, `starfish.c`, + `video_plane.c`, ...) resolves in the new archive, by a scripted `nm -u` against `nm --defined-only`; a + `--guest --mock` TV boot with log diff; fw-compat-reviewer; `--report` shows the platforms and 0 entries; the + gate package list and the test-name diff (review M11). Risk: a symbol dropped from the archive fails the exe link; + CI's cross-build catches it. + +### W8 (N). The webOS facts and the remaining `hostsim` (L15b item 3, F9) +- W8a, required before W9: review the 20 `target_arch = "arm"` files and the 151 `target_os = "linux"` + lines in 27 files (F12). An "is webOS" site becomes a platform value or runner; an "is 32-bit ARM" or + "is Linux" site stays. One PR per directory: os (45), telemetry (41), plex (21), src (20), base + (11), storage (8, the LS2 helper), play-feed (5). Each reports its count before and after. +- W8b, one row per fact: the library name lists (F27) become per-platform lists supplied through the + platform (`dynlib!` stays shared); `paths`'s fallback install prefix becomes a platform value; the + storage helper is packaged only by `PLATFORM=webos`; `main.c` and `starfish.c` are webOS-only. +- W8c, the 363 non-fence `feature = "hostsim"` lines (360 cfg lines and three doc comments), sorted per crate: a + host difference becomes a platform value or runner; simulator tooling goes under a renamed `sim` feature; a test + seam goes to `test-support`. +- Verify: the F9/F12 grep count before and after; `ci/check-ledger-ratchet.py` at or below every family + total (a host difference that needs IO becomes a runner, never a `forks/` line); fw-compat-reviewer on + W8b; a build-bench table for W8b. Risk: size. W8c blocks nothing Tizen needs; only W8a does. + +### W9 (H). The Tizen skeleton: the UI on a dev-token boot, no playback +- Prerequisites: the hello-world's four answers (F28), as the emulator runs left them (E1-E13; what the + emulator can and cannot answer: F37, Decision 3); H5 (static SDL2 + SDL2_ttf draws text and a GLES2 texture + through our path, F15): ANSWERED, yes, emulator only (E10); a Samsung Public certificate profile naming each + device's DUID, kept out of the repo (E2, T7); W8a; W3a-c. + - H3: Option B draws from the Rust thread. ANSWERED, yes, emulator only (E6); Option A is the + fallback if a retail run fails. H4: Ecore main-thread handlers plus a Rust loop thread do not + deadlock. ANSWERED, yes, emulator only (E8). + - H1: armv7 or aarch64 (T3). H2: whether the NDK-linked `.so` loads under a Public cert (T2, T4). OPEN. + They gate a retail set, not the emulator MVP (Decision 8) and not W7 (Decision 3, A): both need a retail set + (E9). The tester build with an on-screen diagnostics and key-code panel has run on the emulator (E11); its + run on a retail set would answer H1 and H2 and return a retail key table, which replaces E7's and E11's + emulator codes as the table W5b and W9 build from. The tester request on #1460 covering H1, H2 and H6 is + posted only with the owner's approval (Decision 5). +- Goal: taken to the TV 10.0 x86_64 emulator as the MVP (Decision 8): the interface on the dev-token path (a + `--guest --mock` style boot, the PMS advertised as `10.0.2.2`) against the mock server, no playback, labelled + emulator only. The sign-in against the mock plex.tv is a follow-up check, and the `plex_tv()` loopback rule is not + widened (E12, "W9 design note"). `[platform tizen]`, `rust-modules/platform-tizen` and `tizen/host/` + (T7); the hosted contract of Target shape 7 with its fake host; the Ecore key table to `Action` (Target shape 2; + E7's five codes first, E11's colour button); in-app UDP logging (Target shape 7, E5); `StoreMode::MemoryOnly` (no + credential is persisted; per Decision 7, B only `client_id`, language and interface resolution are, in the + `install_preferences` v2 file, and every other setting is forgotten each launch: stated in the PR); identity + `Tizen`, `native_video: NotApplicable`, `PLAYBACK_BACKENDS=none`, `BackendSet::NONE` with Play disabled and a + reason; `mk/platform-tizen.mk` with its two configurations, x86_64 first class and armv7 recorded (the PLATFORM + axis); the CI compile-only job. +- Verify: a build-bench table; the export check against `DllImport`; the webOS ARM link command unchanged + (`make -n` diff); fw-compat-reviewer; the packaged `.so`'s dependencies inspected, that exact `.tpk` loaded; + `ci/check-deps.sh` confirms the new thread and the host-table static trip no ledger (UNVERIFIED: the ledgers scan + machine crates; this crate is runner code). + - MVP acceptance (Decision 8): an emulator run (x86_64, the TV 10.0 image) against `tests/mock_pms.py`, never a + real account: the interface draws, the Ecore keys drive it, there is no playback, and the log reaches a UDP + receiver with no sequence gap (E5). It is labelled emulator only and gives no frame-rate or latency claim (E6). + The emulator boots on the dev-token path against the mock PMS advertised as `10.0.2.2`; the sign-in against the + mock plex.tv is a follow-up check, because that override stays loopback-only and is not widened (E12). + - Retail acceptance, not part of the MVP: a device run on the owner's Samsung set, never a real account, in the + shape of the MVP: the dev-token boot against `tests/mock_pms.py` running on a PC the set can reach. The sign-in + against the mock plex.tv is a follow-up here too: the `plex_tv()` override accepts only loopback and is not + widened (E12), and a retail set has no `sdb shell` (T8), so `sdb reverse` (the only route E12 names; emulator, + unchecked) is not assumed to reach it. It answers H1 and H2 (E9). + - The LG TV lock covers neither. +- Risk: store distribution may need Partner status for a native `.so` (report 2b). Sideloading does not. The MVP + proves the emulator only: a retail set may still fail H1 or H2. + +### W10 (H). The Tizen URI playback driver +- Prerequisites: W9, W6c, and H6: `Tizen.Multimedia.Player` shows a mock title beneath our window with + the alpha model that works (report 2e, open conflict). It also survives a TV-menu round trip (review + M9). The hello-world plays no media (F28, F37), so H6 needs a step-3 probe and a retail set: the + emulator cannot test `Tizen.Multimedia` (F37) and the runs did not probe it (E9, E11). The Home round trip of E11 + covers the window and the EGL surface on the emulator only, with no player, so it is not H6. The tester request + for H6 (with H1 and H2) is posted only with the owner's approval (Decision 5). +- Goal: a `UriDriver` in `plx_platform_tizen` over `PlxHostApi` player calls (T6): capabilities (no + DTS/TrueHD, token in the query string, no variable speed), `display()` evidence including readiness, and + the shell's `video_hole`. No LG binding is faked and no default is published (Target shape 6b). +- Verify: `DriverSet` contract tests against the fake host table, and a late completion after stop; a + device run on mock media. Risk: UNVERIFIED how PMS's decision answers `X-Plex-Platform: Tizen`: measured + on the mock, then on a household-owned test server only with the owner's consent. + +### W11 (T). The OS-neutral Feed sink (L15b item 1) and `plx_acb`, in two halves (critic M3, review M7) +- W11a: `tv/plane.rs`, `tv::uri` and the `plane_*` verbs leave `os` for `plx_acb`; the Feed-side + results (`resume_acb`, `AcbPlaneUnload`, F31) become neutral; the LG transports are injected into the LG drivers instead of read through globals + (`legacy_webos_media` disappears, and with it Decision 2's exemption: every hook is then plainly + required). The exit condition is that neither `media` nor the app crate names + them (F8; W6b moves the app's names). Until it lands, no document calls the contract neutral. It also + edits the pinned `os/Cargo.toml` if the `uri-transport`/`feed-sink` features move: a certificate + review. `ci/check-deps.sh` carries the `os/src/tv/plane.rs` entry of `MACHINES` and its path in the scan `find` + with the file to `plx_acb`. +- W11b: the ACB bind sequence, `sf_on_event`/`acb_on_event` and `sink_counter_kind` move behind a neutral + Feed sink (`docs/module-layers.md:407-412`). +- Order: after W7; independent of W9-W10. Verify: the TV log graded before and after (F22), + fw-compat-reviewer, `profile-tv` for frame claims, the release-profile size budget, a build-bench + table. Risk: F22; the riskiest webOS change. It gates neither W9 nor W10. + +### W12 (H, after W10 and W11). Tizen feed over esplusplayer (optional) +- A Feed sink over `dlopen("libesplusplayer.so")` (T6), after Option B is chosen. Verify: struct layouts + against the set's binary (report 2e), a device run on mock media. Risk: firmware-dependent ABI and + certificate policy; decided after W10 ships. + +### W13 (N). The macOS app and the Windows simulator as product platforms +- A Keychain key store, and a URI driver over AVPlayer or a Feed sink over VideoToolbox ("A Mac playback + backend would be a new media engine", `docs/macos-app.md`); Windows stays `sim-linux` under WSLg + (`Makefile:2571-2595`). In `plx_platform_desktop`, after W7, each its own plan; this plan guarantees the seams. + +## Where the Tizen hello-world on `samsung/hello-tpk` fits + +- It does not land on main (owner decision). It is committed on the branch (F28) and ran on the TV 10.0 emulator + on 2026-11-20 (E1-E13): H3, H4, H5, H7 and H8 yes, emulator only (H7 after one shader source change, with one + optional program still failing, E13); H1 and H2 need a retail set (F37). Its Option B (EGL on a + Rust thread) is what W9's shell follows unless a retail run fails; its `plx_tizen_*` exports grow into Target + shape 7. H5 (SDL2 + SDL2_ttf) passed on the emulator at `64c609a46` (E10, Decision 5, emulator only); the + tester build with an on-screen diagnostics and key-code panel (`1afe1978b`) has also run on the emulator (E11) and, + as of 2026-11-20, is the next probe for a retail set (H1, H2, a retail key table). H6 needs a retail set and a + step-3 probe: the tester request on #1460 is posted only with the owner's approval. The branch links nothing from `rust-modules`, so + it runs in parallel with every wave; its C# host and build commands seed `tizen/host/` and `mk/platform-tizen.mk` + in W9, whose MVP is accepted on the emulator (Decision 8). + +## Later platforms (seam check only) + +- iOS/tvOS and Android own the run loop: `plx_shell_sdl` plus a platform crate; Keychain and an AVPlayer URI driver + on iOS; the 8 android cfgs (F13) and a MediaCodec Feed sink after W11b on Android. They use the hosted contract's + tick word and thread roles (critic M12); their keys arrive as `Action`, and W5d is due before them. + +## Out of scope + +- Removing SDL2/SDL2_ttf from `gfx` and `base` (F15). Samsung store submission, Partner membership and certificates + beyond the developer's own Public profile (E2). HDR and Dolby Vision off webOS (report 2e). Tizen 4.0-5.5 (T2). + Changing FLAVOR or release lines. Flutter, anywhere (owner decision). + +## Decisions for the owner + +None open. Decisions 1-8 were answered on 2026-11-20 (Decision 7 after the second reviews, Decision 8 after the +emulator runs E11 and E12); they are recorded below and the body follows them. + +## Conceded points + +- The earlier rounds' 20 accepted critic points stand, except: round 1 point 5 and round 2 point 3 (keys in the + sym/wcode namespace) became Target shape 2; `PortApp` (round 1 point 1) is `app::Platform`; round 2 point 1's package-list + sentence is corrected by F35. + +## Owner decisions after approval + +- 2026-11-19, W7: wait for the hello-world run. W7 starts only after H1-H4 come back from the emulator or a + Samsung set. Read with Decision 3 (below): H3 and H4 came back on the emulator, which cannot answer H1 and H2. +- 2026-11-19, amendments proposed to the owner (naming + `plx_platform_*` / `tv::Services` / `app::Platform`; every hook required with per-group `NONE`; one exported + `PLATFORM`; screen inputs for backends and sign-in kept; C entry for the Tizen host only): accepted 2026-11-20 + by Decisions 1 and 2. Changed by review: `HostEvent` carries canonical actions, not LG key codes (review M6); + `default_backend` is dropped (review M8, critic M1); shell and diag sit on `app::Platform`, not `tv::Services` + (critic M4); the doorway gains the stop/completion and thread contract (review B1, M4). +- 2026-11-19, standing: naming is "platform", not "port"; no runtime capability registry (one platform per + build); no Flutter anywhere; the plan goes to `docs/` after test results (this page, W0). +- 2026-11-20, emulator run: the hello-world ran on the Samsung TV 10.0 emulator and returned H3 and H4 (yes, + emulator only; E6, E8). H1 and H2 stay open and need a retail set (E9). The owner said to use this evidence. +- 2026-11-20, Decision 1 (naming): B. Keep `plx_platform_webos`, `_desktop` and `_tizen`; rename the bottom layer + first. Superseded in timing below: the rename is no longer W6d. +- 2026-11-20, Decision 2 (hooks): C. Every hook is required, except the `legacy_webos_media` group until W11a; + W11a injects the LG transports into the LG drivers. +- 2026-11-20, Decision 3 (W7 gate): A. W7 may start. H3 and H4 recorded as answered on the emulator only; H1 and + H2 stay open and gate W9, not W7. `Shell` and `HostEvent` stay app-private. Read with Decision 8: the emulator MVP + of W9 does not wait for H1 and H2 either. +- 2026-11-20, Decision 4 (order): A. The three contracts (W3a-c) first, then the rest, the Samsung-facing types + app-private. Cut into the waves of "Workstreams". +- 2026-11-20, Decision 5 (probes): go. H5 was built on `samsung/hello-tpk` for the emulator and passed there (E10, + `64c609a46`); the tester request on #1460 for H1, H2 and H6 is posted only with the owner's + approval; the tester build with an on-screen diagnostics and key-code panel ran on the emulator (E11) and is the + next probe for a retail set. +- 2026-11-20, critic G1-G8 (no owner decision): the critic's findings G1-G8 on the third draft accepted as brief + amendments; the qualifier stays in the app crate (G3). The owner's decisions above are unchanged. +- 2026-11-20, Decision 6 (keys): A. `Action` at the edge with `raw_pair` translation; the machine, tapes and + screens are unchanged; W5d before a fourth platform. +- 2026-11-20, after the second reviews (review: no-go on Wave 1; critic: BLOCKED): (a) the bottom-layer rename runs FIRST and + ALONE, before W0: `plx_platform` becomes `plx_os` (crate, directory, layer `[os]`; fence keyword `[platform X]`), + with its own review gate (build-bench, fw-compat-reviewer, certificate re-pin, the CI tests and source-text pins + that embed the name) and a shipped rename script so open PRs can apply it; later briefs use a path map; W6d is + removed; the platform crates keep `plx_platform_webos`, `_desktop`, `_tizen`. (b) Gating: lanes run one bounded + `make test-crate C= T=` (or `make test-hostsim` where needed), each PR's own CI gates its own head, + one review reads 2-3 PRs together and is recorded per PR head (`tools/pr-land.py reviewed`), TV checks are + batched on the commit the result supports, build-bench rides the PR that changes build or layout. (c) Decision 7: + B. Persist only `client_id`, language and interface resolution, carried by the `install_preferences` file at + version 2 (adds `client_id`), written only under `MemoryOnly`; no session writer runs in `MemoryOnly`; webOS and + desktop files stay byte-identical (v1 is `deny_unknown_fields`). +- 2026-11-20, Decision 8 (MVP target): W9 is taken to the TV 10.0 x86_64 emulator as the MVP (the interface on the + dev-token path against the mock PMS advertised as `10.0.2.2`, no playback, labelled emulator only; the sign-in + against the mock plex.tv is a follow-up check and the `plex_tv()` loopback rule is not widened, E12). H1 and H2 + still gate a retail set. x86_64 is a + first-class configuration of `mk/platform-tizen.mk`. + +## Open disagreements + +None between planner and critic. No owner question is open. From e96b9c212325db53e5179be223ccf9098b79ad34 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 09:41:30 +0300 Subject: [PATCH 03/26] run_application returns its exit; only the executable entry ends the process (#1479) `run_application` now returns its exit, and only the executable entry ends the process (step W3c of the platform plan, discussion #1460). A library that another program hosts must never end that program's process. On Samsung the .NET host owns it, and until now `run_application` ended in `_exit`. On webOS the process ends in the same order as before. - `run_application` returns `Exit { code, release: Complete | Retained }`. `port::plex_run` keeps its C signature and is one call to the private `fn plex_main(..) -> !`. That function installs the port, runs the app and calls `plx_base::process::exit_now(exit.code)` straight after it returns. `main.c`, `sim.rs` and the teardown order are unchanged. - The entry is still proven never to return. `const _: fn(*const c_char, c_int) -> ! = plex_main;` replaces the `-> !` consts on `run_and_shutdown` and `run_application`. The lifecycle scan in `app/exit.rs` holds `plex_run`'s comment-stripped body to exactly `plex_main(pms_host, pms_port)`, and requires the const and `plex_main`'s `exit_now(`. `ci/check-deps.sh` budgets `plex_main` at 10 lines and `plex_run` at 3. If `plex_run` could return, `main.c` would return into `__libc_start_main`'s libc `exit`, and `OPENSSL_cleanup` would run under live curl workers (#1115). - New `app/exit.rs`: - `release_of`, an exhaustive match over `NativeExit` that `quits_sdl` is derived from; - `entry`, which leaks the App through `ManuallyDrop`; - `HostGate { stopping, inflight }`, so a stop report waits for a callback in flight; - a once-only `Completion` shared by the loop and deadline threads, which disarms the watchdog before `on_stopped`; - the libc-exit source guard, moved from `boot.rs`. It now also covers `exit_now`, which only `port.rs`, `bin/sim.rs` and `dev/framedump.rs` may call. - `plx_gfx`'s shader and link exits return a typed `GfxFault` through `init_gl`, `init_text` and `init_image`, and `link_required` runs over an injected `ProgramDriver`. Every refusal in the boot chain returns `Err(Exit)` with the same status (1), so a shader fault now drops the telemetry guard on the way out like the SDL_Init and GL-context refusals. - Behaviour change: a driver that rejects the `fs_blur` or `fs_glass` compile no longer refuses the boot. The blur backdrop's lazy link uses `link_optional_program`, so the app boots with blur off and opaque panels, as a link failure already did. - `watchdog::disarm`, `arm` and `is_armed`. The loop thread id sits in a mutex slot held across the signal send, so `disarm` waits for a probe in flight. On the dev set, a `--guest --mock` boot and a close by app id matched main within the noise floor, each ending `APP_CLOSED` with `exit_status: 0`. --- ci/check-deps.sh | 12 +- docs/module-layers.md | 5 +- rust-modules/base/src/task/watchdog.rs | 163 ++++++- rust-modules/gfx/src/gfx.rs | 277 ++++++++--- rust-modules/gfx/src/text.rs | 33 +- rust-modules/src/app/boot.rs | 106 +---- rust-modules/src/app/exit.rs | 622 +++++++++++++++++++++++++ rust-modules/src/app/mod.rs | 38 +- rust-modules/src/app/run.rs | 35 +- rust-modules/src/port.rs | 25 +- 10 files changed, 1107 insertions(+), 209 deletions(-) create mode 100644 rust-modules/src/app/exit.rs diff --git a/ci/check-deps.sh b/ci/check-deps.sh index 8e448ca617..7eab075634 100755 --- a/ci/check-deps.sh +++ b/ci/check-deps.sh @@ -1158,7 +1158,7 @@ fi fi # route # fnlen: app/run.rs::run <= 200 lines, run_application (app/mod.rs, the D4 skeleton) <= 10 and -# plex_run (port.rs: install, then hand over) <= 10 — counted by brace +# plex_main (port.rs: install, hand 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 @@ -1178,9 +1178,15 @@ else fail "fnlen: app/run.rs::run is ${run_len:-unknown} lines, budget 200 — a runapp_len=$(fn_body_lines "$SRC/app/mod.rs" 'run_application') if [ -n "$runapp_len" ] && [ "$runapp_len" -le 10 ]; then ok "fnlen: run_application (app/mod.rs) ($runapp_len lines)" else fail "fnlen: run_application (app/mod.rs) is ${runapp_len:-unknown} lines, budget 10"; fi +plexmain_len=$(fn_body_lines "$SRC/port.rs" 'plex_main') +if [ -n "$plexmain_len" ] && [ "$plexmain_len" -le 10 ]; then ok "fnlen: plex_main (port.rs) ($plexmain_len lines)" +else fail "fnlen: plex_main (port.rs) is ${plexmain_len:-unknown} lines, budget 10"; fi +# plex_run is the one-line C wrapper over plex_main (the `-> !` entry the const beside it proves): its +# signature, the call and the closing brace. `app::exit`'s lifecycle_no_production_exit test holds the +# body to exactly that call. plexrun_len=$(fn_body_lines "$SRC/port.rs" 'plex_run') -if [ -n "$plexrun_len" ] && [ "$plexrun_len" -le 10 ]; then ok "fnlen: plex_run (port.rs) ($plexrun_len lines)" -else fail "fnlen: plex_run (port.rs) is ${plexrun_len:-unknown} lines, budget 10"; fi +if [ -n "$plexrun_len" ] && [ "$plexrun_len" -le 3 ]; then ok "fnlen: plex_run (port.rs) ($plexrun_len lines)" +else fail "fnlen: plex_run (port.rs) is ${plexrun_len:-unknown} lines, budget 3 — it only calls plex_main"; fi fi # fnlen # testmod: `#[cfg(test)] mod` count in app/mod.rs = 0 (D4/D8) — every test module named in D8's diff --git a/docs/module-layers.md b/docs/module-layers.md index 0a7b78b0fc..566838556b 100644 --- a/docs/module-layers.md +++ b/docs/module-layers.md @@ -382,8 +382,9 @@ published values rather than hooks: the webOS code writes them into `tv::device` `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 -the simulator both enter through `port::plex_run`; `app::run_application` is the two-line body it -hands over to. `lib.rs` declares the port but re-exports nothing from it, because a re-export would +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 be a reference from the crate root into the port, which the gate refuses. The video sink landed as a verb-level cut. `tv::sink::VideoSink` has one method per verb of the diff --git a/rust-modules/base/src/task/watchdog.rs b/rust-modules/base/src/task/watchdog.rs index 7e8724871d..07d81b0c87 100644 --- a/rust-modules/base/src/task/watchdog.rs +++ b/rust-modules/base/src/task/watchdog.rs @@ -12,7 +12,7 @@ use std::{ cell::Cell, marker::PhantomData, rc::Rc, - sync::{atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicU8, AtomicUsize, Ordering}, OnceLock}, + sync::{atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicU8, AtomicUsize, Ordering}, Mutex, OnceLock, PoisonError}, time::{Duration, Instant}, }; @@ -186,6 +186,49 @@ struct Signals { foreground: AtomicBool, progress: AtomicUsize, label: AtomicPtr, + /// The thread a freeze probe (and the developer build's fatal abort) signals. + loop_thread: LoopThread, +} + +/// **The loop owner's thread id, and whether anything may signal it.** Captured on the loop thread +/// itself ([`LoopThread::arm`]) because it is the target of `pthread_kill`; cleared +/// ([`LoopThread::disarm`]) whenever that id must not be used: a hosted loop thread that has +/// returned leaves a dead id the system may hand to an unrelated thread, and a paused host has no +/// loop to probe. The id sits behind a lock held for the length of a send, so once `disarm` +/// returns no signal is in flight and none will start. +struct LoopThread(Mutex>); + +impl LoopThread { + const fn new() -> Self { + Self(Mutex::new(None)) + } + + fn slot(&self) -> std::sync::MutexGuard<'_, Option> { + self.0.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Capture the CALLING thread as the loop owner. Called on the loop thread, never on the + /// observer. A second call replaces the first: this is the re-capture. + fn arm(&self) { + // SAFETY: `pthread_self` takes no argument and cannot fail. libc supplies the native + // `pthread_t` ABI (pointer on Darwin, unsigned long on ARM Linux), widened to the word + // the slot stores. + *self.slot() = Some(unsafe { libc::pthread_self() } as usize); + } + + fn disarm(&self) { + *self.slot() = None; + } + + fn armed(&self) -> bool { + self.slot().is_some() + } + + /// Run `send` against the armed loop thread while the slot is held; `None` (and `send` never + /// runs) when disarmed. + fn with(&self, send: impl FnOnce(usize) -> R) -> Option { + self.slot().map(send) + } } impl Signals { @@ -196,6 +239,7 @@ impl Signals { foreground: AtomicBool::new(true), progress: AtomicUsize::new(0), label: AtomicPtr::new(&UNLABELED as *const BlockingLabel as *mut BlockingLabel), + loop_thread: LoopThread::new(), } } @@ -223,6 +267,24 @@ pub fn set_foreground(foreground: bool) { SIGNALS.foreground.store(foreground, Ordering::Release); } +/// Stop the observer signalling the loop thread, for good or until [`arm`]. Returns once no signal +/// is in flight. A hosted entry calls it before it reports its stop (the loop thread is about to +/// end, and its id with it) and while the host is paused; `LoopWatch::start` arms again. +pub fn disarm() { + SIGNALS.loop_thread.disarm(); +} + +/// Make the CALLING thread the one the observer signals: call it on the loop thread after a +/// [`disarm`]. [`LoopWatch::start`] does the same at every loop start. +pub fn arm() { + SIGNALS.loop_thread.arm(); +} + +/// Whether the observer may signal a loop thread right now. +pub fn is_armed() -> bool { + SIGNALS.loop_thread.armed() +} + thread_local! { /// Other workers may enter blocking scopes, but cannot publish the frame thread's label. static WATCHED: Cell> = const { Cell::new(None) }; @@ -494,24 +556,27 @@ impl LoopWatch { // task::spawn uses std::thread::Builder::spawn and logs EAGAIN as an error return. // Exactly one observer lives for this process; a failed start stays disabled. // - // The loop owner's thread is captured HERE, on the loop owner, never inside the - // observer: it is the target of the freeze probe (and of the developer build's fatal - // abort). libc supplies the native pthread_t ABI (pointer on Darwin, unsigned long on - // ARM Linux); fwcompat inventories export `pthread_self` and `pthread_kill` at - // GLIBC_2.4 across all releases: libpthread on older firmware, libc after the glibc - // pthread merge. - let main_thread = unsafe { libc::pthread_self() } as usize; + // The observer never captures the loop owner's thread: that id lives in + // `SIGNALS.loop_thread`, written on the loop owner below, because it is the target of + // the freeze probe (and of the developer build's fatal abort) and a hosted loop can + // end and start again on another thread. fwcompat inventories export `pthread_self` + // and `pthread_kill` at GLIBC_2.4 across all releases: libpthread on older firmware, + // libc after the glibc pthread merge. #[cfg(feature = "threadcheck")] let log_only = crate::devtrig::guard_log_only(); #[cfg(feature = "threadcheck")] - let started = super::spawn("main-thread watchdog", move || observe_loop(main_thread, log_only)).is_some(); + let started = super::spawn("main-thread watchdog", move || observe_loop(log_only)).is_some(); #[cfg(not(feature = "threadcheck"))] - let started = super::spawn("main-thread watchdog", move || observe_loop(main_thread)).is_some(); + let started = super::spawn("main-thread watchdog", observe_loop).is_some(); if !started { crate::eventlog::log("main-thread watchdog: unavailable; hang detection disabled"); } started }); if !started { return Self::disabled(); } - Self::attach(&SIGNALS) + let watch = Self::attach(&SIGNALS); + // Only the loop that attached becomes the signal target: a refused second loop must not + // retarget the first. + if watch.signals.is_some() { arm(); } + watch } fn attach(signals: &'static Signals) -> Self { @@ -685,8 +750,9 @@ pub fn set_crash_phase(phase: CrashPhase) { /// at playback) is never signalled. Returns whether the signal was sent. fn probe_main_thread(main_thread: usize, seq: u32) -> bool { // SAFETY: `sigaction` with a null new action only reads the current disposition into `old`, - // a zeroed plain-data struct; `pthread_kill` on a thread id captured from the loop owner, - // which lives for the whole process, is the call the developer build's abort already makes. + // a zeroed plain-data struct; `pthread_kill` on a thread id captured from the loop owner + // ([`LoopThread`]; its caller holds the slot, so the id is the live loop's or this is not + // reached) is the call the developer build's abort already makes. unsafe { let mut old: libc::sigaction = std::mem::zeroed(); if libc::sigaction(libc::SIGUSR2, std::ptr::null(), &mut old) != 0 { @@ -707,6 +773,12 @@ fn probe_main_thread(main_thread: usize, seq: u32) -> bool { } } +/// [`probe_main_thread`] against the loop thread, if one is armed. The slot stays held for the send, +/// so a [`disarm`] that returns has no probe still on its way to a thread that is gone. +fn probe_loop(loop_thread: &LoopThread, seq: u32) -> bool { + loop_thread.with(|thread| probe_main_thread(thread, seq)).unwrap_or(false) +} + /// Whether `handler` lives in the same loaded object as this code, i.e. is the crash tracer's own /// `freeze_handler` and not a library's that took `SIGUSR2` after the tracer was installed /// (ACB is `dlopen`ed at playback). A stranger's handler fired at a random moment is not a probe. @@ -750,7 +822,7 @@ fn answer_probe( (sent, format!("main-thread freeze: {ms}ms without loop progress{at} (probe {seq}, recorded={sent})")) } -fn observe_loop(main_thread: usize, #[cfg(feature = "threadcheck")] log_only: bool) { +fn observe_loop(#[cfg(feature = "threadcheck")] log_only: bool) { let origin = Instant::now(); let mut freezes = Freezes::default(); // The probe whose recovery this thread must write down: set only when the probe was really @@ -779,7 +851,7 @@ fn observe_loop(main_thread: usize, #[cfg(feature = "threadcheck")] log_only: bo Some(FreezeEvent::Probe { seq, ms }) => { let crash_log = crate::paths::in_runtime_dir(crate::paths::runtime_file::CRASH); let (sent, line) = - answer_probe(&crash_log, seq, ms, current_leg(), |seq| probe_main_thread(main_thread, seq)); + answer_probe(&crash_log, seq, ms, current_leg(), |seq| probe_loop(&SIGNALS.loop_thread, seq)); if !sent { freezes.unsent(); } @@ -816,8 +888,9 @@ fn observe_loop(main_thread: usize, #[cfg(feature = "threadcheck")] log_only: bo // stale sample; the next poll will rebase and discard its warning as well. let sample_age = origin.elapsed().as_millis().saturating_sub(now as u128); if sample_age <= MAX_POLL_GAP_MS as u128 && SIGNALS.progress() == progress { - let rc = unsafe { libc::pthread_kill(main_thread as libc::pthread_t, libc::SIGABRT) }; - if rc != 0 { crate::eventlog::log(&format!("main-thread hang: pthread_kill failed: {rc}")); } + // A disarmed loop has nobody to abort: `with` runs nothing. + let rc = SIGNALS.loop_thread.with(|thread| unsafe { libc::pthread_kill(thread as libc::pthread_t, libc::SIGABRT) }); + if let Some(rc) = rc.filter(|rc| *rc != 0) { crate::eventlog::log(&format!("main-thread hang: pthread_kill failed: {rc}")); } } } } @@ -1533,4 +1606,60 @@ mod tests { assert_eq!(plx_freeze_seq.load(Ordering::Acquire), 0, "an unsent probe arms nothing"); } + fn this_thread() -> usize { + unsafe { libc::pthread_self() as usize } + } + + #[test] + fn a_disarmed_loop_thread_is_never_signalled() { + let loop_thread = LoopThread::new(); + assert!(!loop_thread.armed()); + let mut sent = false; + assert_eq!(loop_thread.with(|_| sent = true), None); + assert!(!sent, "nothing runs against a loop that was never armed"); + assert!(!probe_loop(&loop_thread, 1), "and a probe is reported unsent"); + loop_thread.arm(); + assert!(loop_thread.armed()); + loop_thread.disarm(); + assert!(!loop_thread.armed()); + assert_eq!(loop_thread.with(|_| sent = true), None); + assert!(!sent, "a disarmed loop is not signalled either"); + } + + #[test] + fn arming_captures_the_calling_thread_and_a_second_arm_recaptures() { + let loop_thread = std::sync::Arc::new(LoopThread::new()); + loop_thread.arm(); + assert_eq!(loop_thread.with(|thread| thread), Some(this_thread())); + let later = std::sync::Arc::clone(&loop_thread); + let theirs = std::thread::Builder::new().spawn(move || { + later.arm(); + this_thread() + }).unwrap().join().unwrap(); + assert_ne!(theirs, this_thread(), "the two threads are two ids"); + assert_eq!(loop_thread.with(|thread| thread), Some(theirs), + "an arm from a new loop thread replaces the id of the one that ended"); + } + + #[test] + fn disarm_cannot_return_while_a_signal_is_in_flight() { + let loop_thread = LoopThread::new(); + loop_thread.arm(); + let held = loop_thread.with(|_| loop_thread.0.try_lock().is_err()); + assert_eq!(held, Some(true), + "the slot is held for the whole send, so `disarm` waits for it and none follows it"); + assert!(loop_thread.0.try_lock().is_ok(), "and is free again once the send ends"); + } + + #[test] + fn the_process_watchdog_arms_disarms_and_rearms() { + let _serial = crate::testlock::serial(); + disarm(); + assert!(!is_armed()); + arm(); + assert!(is_armed()); + assert_eq!(SIGNALS.loop_thread.with(|thread| thread), Some(this_thread())); + disarm(); + assert!(!is_armed(), "disarmed before a hosted stop is reported"); + } } diff --git a/rust-modules/gfx/src/gfx.rs b/rust-modules/gfx/src/gfx.rs index 6eae044146..da67d32133 100644 --- a/rust-modules/gfx/src/gfx.rs +++ b/rust-modules/gfx/src/gfx.rs @@ -1192,7 +1192,7 @@ fn gl_is_es() -> bool { // and therefore the safe default — a wrong guess there changes nothing. // `starts_with`, not a substring scan: the ES spec mandates this exact prefix, while a // desktop vendor string containing "ES" anywhere would otherwise skip the preamble and - // hard-exit at the first shader compile. + // fail the boot at the first shader compile. v.is_null() || CStr::from_ptr(v).to_bytes().starts_with(b"OpenGL ES") }) } @@ -1228,12 +1228,53 @@ unsafe fn supersample_aa(src: *const c_char) -> Option { std::ffi::CString::new(text.replace(EDGE, &format!("smoothstep(-{w:.6}, {w:.6}, d)"))).ok() } -pub fn gfx_compile(ty: c_uint, src: *const c_char) -> c_uint { - try_compile(ty, src).unwrap_or_else(|| plx_base::process::exit_now(1)) +/// A required shader program the driver refused: the typed form of the two `exit_now(1)` calls +/// this module made (a compile rejection inside `gfx_compile`, the base program's link failure in +/// `init_gl`). [`init_gl`], [`init_text`](crate::text::init_text) and [`init_image`] return it and +/// the application's entry turns it into its exit, so a process that hosts the app is told instead +/// of being killed under its host. What each refusal costs is unchanged: a compile rejection of +/// any program linked through [`link_program`] is a fault; a link failure is one only for the base +/// program, and the others degrade ([`degrade_on_link_failure`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GfxFault { + /// The driver rejected a shader's source (the compile log is already in the event log). + Compile, + /// The driver compiled both shaders and refused to link them. + Link, } -/// Optional programs may degrade on a driver's compile rejection; required shaders keep the -/// existing exit policy through `gfx_compile` above. +impl std::fmt::Display for GfxFault { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + GfxFault::Compile => f.write_str("a required shader failed to compile"), + GfxFault::Link => f.write_str("a required shader program failed to link"), + } + } +} + +/// The two driver steps a program's bring-up takes, so what a refusal costs is decided in +/// [`link_required`] and graded without a GL context (`fault_tests`). +trait ProgramDriver { + /// Compile one shader; `None` is the driver's rejection. + fn compile(&self, ty: c_uint, src: *const c_char) -> Option; + /// Link a program from two compiled shaders; `None` is the driver's refusal. + fn link(&self, vs: c_uint, fs: c_uint) -> Option; +} + +/// The GLES driver. +struct Gles; + +impl ProgramDriver for Gles { + fn compile(&self, ty: c_uint, src: *const c_char) -> Option { + try_compile(ty, src) + } + fn link(&self, vs: c_uint, fs: c_uint) -> Option { + link_shaders(vs, fs) + } +} + +/// Optional programs may degrade on a driver's compile rejection; required shaders report it as a +/// [`GfxFault`] through [`link_required`]. fn try_compile(ty: c_uint, src: *const c_char) -> Option { unsafe { let s = glCreateShader(ty); @@ -1276,10 +1317,33 @@ fn try_compile(ty: c_uint, src: *const c_char) -> Option { } /// Shared program bring-up for every shader pair: create → attach VS/FS → bind `a_pos` -/// (attrib 0, the shared unit quad) → link. `None` = link failure; each caller keeps its -/// own failure policy (hard-exit, degrade to 0, or early-return). -pub fn link_program(vs: *const c_char, fs: *const c_char) -> Option { - link_shaders(gfx_compile(GL_VERTEX_SHADER, vs), gfx_compile(GL_FRAGMENT_SHADER, fs)) +/// (attrib 0, the shared unit quad) → link. A compile rejection is `Err(GfxFault::Compile)` for +/// every caller; a link failure is `Err(GfxFault::Link)` and each caller keeps its own policy +/// (return the fault, degrade to 0 through [`degrade_on_link_failure`], or early-return). +/// +/// **Boot only.** The frame loop must not link a required program: it would have to end the loop +/// with a fault where boot returns one. The program a frame links on demand takes +/// [`link_optional_program`] (`blur_lazy_init`) and degrades on either refusal. +pub fn link_program(vs: *const c_char, fs: *const c_char) -> Result { + link_required(&Gles, vs, fs) +} + +fn link_required(driver: &dyn ProgramDriver, vs: *const c_char, fs: *const c_char) -> Result { + let vs = driver.compile(GL_VERTEX_SHADER, vs).ok_or(GfxFault::Compile)?; + let fs = driver.compile(GL_FRAGMENT_SHADER, fs).ok_or(GfxFault::Compile)?; + driver.link(vs, fs).ok_or(GfxFault::Link) +} + +/// The policy of a required program that the frame can do without: a link failure is logged with +/// `note` and answered `0` ("no program"), a compile rejection stays a fault. +pub(crate) fn degrade_on_link_failure(program: Result, note: &str) -> Result { + program.or_else(|fault| match fault { + GfxFault::Link => { + log(note); + Ok(0) + } + GfxFault::Compile => Err(fault), + }) } fn link_optional_program(vs: *const c_char, fs: *const c_char) -> Option { @@ -1433,7 +1497,7 @@ fn bind_core_profile_vao() { } } -pub fn init_gl() { +pub fn init_gl() -> Result<(), GfxFault> { unsafe { WARM_TARGET = None; // Before any buffer or attribute state is touched — in a core profile the calls below are @@ -1441,15 +1505,17 @@ pub fn init_gl() { #[cfg(feature = "hostsim")] bind_core_profile_vao(); - PROG = link_program(VS_SRC.as_ptr(), FS_SRC.as_ptr()).unwrap_or_else(|| { - // Logged for the same reason as the compile failure in `gfx_compile`: stderr is not the - // event log and a clean exit is not a crash, so this line is the only trace the death - // leaves. The base program is the one every draw needs, hence the exit where the - // ambient/shadow/image programs below merely degrade. - log("base prog link FAILED — exiting"); - eprintln!("link failed"); - plx_base::process::exit_now(1); - }); + PROG = link_program(VS_SRC.as_ptr(), FS_SRC.as_ptr()).map_err(|fault| { + // A compile rejection logged itself in `try_compile`. A link failure is logged here, + // for the same reason: stderr is not the event log and a clean exit is not a crash, so + // this line is the only trace the death leaves. The base program is the one every draw + // needs, hence the fault where the ambient/shadow/image programs below merely degrade. + if fault == GfxFault::Link { + log("base prog link FAILED — exiting"); + eprintln!("link failed"); + } + fault + })?; use_prog(PROG); RECT_UNIFORMS = RectUniforms::of(PROG); glUniform2f(RECT_UNIFORMS.screen, SCR_W, SCR_H); @@ -1488,10 +1554,11 @@ pub fn init_gl() { glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, std::ptr::null()); - APROG = link_program(VS_AMBIENT_DITHERED.as_ptr(), FS_AMBIENT.as_ptr()).unwrap_or_else(|| { - log("ambient prog link failed"); - 0 // draw_ambient then binds program 0 and draws nothing — the corner wash is a nicety - }); + APROG = degrade_on_link_failure( + link_program(VS_AMBIENT_DITHERED.as_ptr(), FS_AMBIENT.as_ptr()), + // draw_ambient then binds program 0 and draws nothing — the corner wash is a nicety + "ambient prog link failed", + )?; if APROG != 0 { AL_RECT = glGetUniformLocation(APROG, c"u_rect".as_ptr()); AL_SCREEN = glGetUniformLocation(APROG, c"u_screen".as_ptr()); @@ -1505,10 +1572,10 @@ pub fn init_gl() { AL_SCRIM = ScrimLoc::of(APROG); } SCRIM_SENT = [scrim::GroundShade::NONE; 3]; - SCRIM_PROG = link_program(VS_SCRIM_LAYER.as_ptr(), FS_AMBIENT_PLAIN.as_ptr()).unwrap_or_else(|| { - log("scrim layer prog link failed — a layered hero draws no scrim over its art"); - 0 - }); + SCRIM_PROG = degrade_on_link_failure( + link_program(VS_SCRIM_LAYER.as_ptr(), FS_AMBIENT_PLAIN.as_ptr()), + "scrim layer prog link failed — a layered hero draws no scrim over its art", + )?; if SCRIM_PROG != 0 { SCL_RECT = glGetUniformLocation(SCRIM_PROG, c"u_rect".as_ptr()); SCL_INK = glGetUniformLocation(SCRIM_PROG, c"u_ink".as_ptr()); @@ -1518,10 +1585,10 @@ pub fn init_gl() { } bind_dither_tile(); - APROG_PLAIN = link_program(VS_AMBIENT.as_ptr(), FS_AMBIENT_PLAIN.as_ptr()).unwrap_or_else(|| { - log("ambient (plain) prog link failed — the dithered program serves every frame"); - 0 - }); + APROG_PLAIN = degrade_on_link_failure( + link_program(VS_AMBIENT.as_ptr(), FS_AMBIENT_PLAIN.as_ptr()), + "ambient (plain) prog link failed — the dithered program serves every frame", + )?; if APROG_PLAIN != 0 { PL_RECT = glGetUniformLocation(APROG_PLAIN, c"u_rect".as_ptr()); PL_TL = glGetUniformLocation(APROG_PLAIN, c"u_atl".as_ptr()); @@ -1533,10 +1600,11 @@ pub fn init_gl() { } // Soft-shadow program (own program so the hot FS_SRC pays nothing; mirrors init_image). - SPROG = link_program(VS_SRC.as_ptr(), FS_SHADOW.as_ptr()).unwrap_or_else(|| { - log("shadow prog link failed"); - 0 // draw_shadow no-ops → cards simply lose the drop-shadow, nothing else breaks - }); + SPROG = degrade_on_link_failure( + link_program(VS_SRC.as_ptr(), FS_SHADOW.as_ptr()), + // draw_shadow no-ops → cards simply lose the drop-shadow, nothing else breaks + "shadow prog link failed", + )?; if SPROG != 0 { SL_RECT = glGetUniformLocation(SPROG, c"u_rect".as_ptr()); SL_SCREEN = glGetUniformLocation(SPROG, c"u_screen".as_ptr()); @@ -1549,10 +1617,10 @@ pub fn init_gl() { SL_COL = glGetUniformLocation(SPROG, c"u_col".as_ptr()); } - FPROG = link_program(VS_SRC.as_ptr(), FS_FLAT.as_ptr()).unwrap_or_else(|| { - log("flat prog link failed — uniform rects take the fill program's flat path"); - 0 - }); + FPROG = degrade_on_link_failure( + link_program(VS_SRC.as_ptr(), FS_FLAT.as_ptr()), + "flat prog link failed — uniform rects take the fill program's flat path", + )?; if FPROG != 0 { FL_RECT = glGetUniformLocation(FPROG, c"u_rect".as_ptr()); FL_COL = glGetUniformLocation(FPROG, c"u_col".as_ptr()); @@ -1560,8 +1628,8 @@ pub fn init_gl() { glUniform2f(glGetUniformLocation(FPROG, c"u_screen".as_ptr()), SCR_W, SCR_H); } - // Optional on purpose: `link_program` exits the process on a compile rejection - // (`gfx_compile`), which would make `draw_ramp`'s fallback unreachable for the failure a + // Optional on purpose: `link_program` makes a compile rejection a fault boot returns + // (`link_required`), which would make `draw_ramp`'s fallback unreachable for the failure a // driver is likeliest to give a new program. `try_compile` logs the compile error itself. RPROG = link_optional_program(VS_SRC.as_ptr(), FS_RAMP.as_ptr()).unwrap_or_else(|| { log("ramp prog compile/link failed — square gradients take the fill program's flat path"); @@ -1579,10 +1647,10 @@ pub fn init_gl() { // unit quad IS the texture coordinate and there is nothing for a `u_uvrect` to express. // DITHERED: `fs_field.frag` is built with `glsl_dithered!`, so its paired vertex source // must be the `PLX_DITHER_NC` variant that supplies `v_dither_nc` (cost rule 4). - UPROG = link_program(VS_SRC_DITHERED.as_ptr(), FS_FIELD.as_ptr()).unwrap_or_else(|| { - log("field prog link failed — an underlay field draws nothing"); - 0 - }); + UPROG = degrade_on_link_failure( + link_program(VS_SRC_DITHERED.as_ptr(), FS_FIELD.as_ptr()), + "field prog link failed — an underlay field draws nothing", + )?; if UPROG != 0 { UL_RECT = glGetUniformLocation(UPROG, c"u_rect".as_ptr()); UL_TINT = glGetUniformLocation(UPROG, c"u_tint".as_ptr()); @@ -1595,10 +1663,10 @@ pub fn init_gl() { // The same field as a popover's material — `draw_field_panel`. DITHERED, same contract as // `UPROG` above: `fs_field_panel.frag` is built with `glsl_dithered!`, so it must link // against the `PLX_DITHER_NC` vertex variant. - PPROG = link_program(VS_SRC_DITHERED.as_ptr(), FS_FIELD_PANEL.as_ptr()).unwrap_or_else(|| { - log("field-panel prog link failed — popover panels fall back to the flat sheet"); - 0 - }); + PPROG = degrade_on_link_failure( + link_program(VS_SRC_DITHERED.as_ptr(), FS_FIELD_PANEL.as_ptr()), + "field-panel prog link failed — popover panels fall back to the flat sheet", + )?; if PPROG != 0 { FP_RECT = glGetUniformLocation(PPROG, c"u_rect".as_ptr()); FP_TINT = glGetUniformLocation(PPROG, c"u_tint".as_ptr()); @@ -1681,6 +1749,7 @@ pub fn init_gl() { // Last: it reads GL's extension string and links against the context just built. straighten::init(); } + Ok(()) } /// The CAPSULE OUTLINE's solved geometry as the shader takes it — `[R, f, r, big centre y, end @@ -2725,14 +2794,15 @@ pub fn draw_number(mut n: i32, right_x: f32, y: f32, s: f32, col: *const f32) { } // ---- image program: RGBA textures (posters/logos/backdrop) with rounded corners ---- -pub fn init_image() { +pub fn init_image() -> Result<(), GfxFault> { unsafe { IPROG = match link_program(VS_IMG.as_ptr(), FS_IMG.as_ptr()) { - Some(p) => p, - None => { + Ok(p) => p, + Err(GfxFault::Link) => { log("image prog link failed"); - return; + return Ok(()); } + Err(fault) => return Err(fault), }; IL_RECT = glGetUniformLocation(IPROG, c"u_trect".as_ptr()); IL_SCREEN = glGetUniformLocation(IPROG, c"u_tscreen".as_ptr()); @@ -2836,6 +2906,7 @@ pub fn init_image() { use_prog(PROG); } + Ok(()) } /// Can the wash carry its artwork in one pass? `false` means the caller draws [`draw_ambient`] and @@ -6222,7 +6293,10 @@ fn blur_lazy_init() -> bool { if (*std::ptr::addr_of!(BLURST)).is_some() { return true; } - BPROG = match link_program(VS_IMG.as_ptr(), FS_BLUR.as_ptr()) { + // OPTIONAL, both programs: this runs from the frame (`draw_blur_backdrop`) as well as from + // boot, and a frame has no way to return a fault, so a compile rejection degrades exactly + // as a link failure does (`link_program` is boot-only). + BPROG = match link_optional_program(VS_IMG.as_ptr(), FS_BLUR.as_ptr()) { Some(p) => p, None => { log("blur: prog link failed — backdrop blur off"); @@ -6243,7 +6317,7 @@ fn blur_lazy_init() -> bool { glUniform4f(BL_RECT, 0.0, 0.0, SCR_W, SCR_H); glUniform4f(BL_UVRECT, 0.0, 0.0, 1.0, 1.0); - GPROG = match link_program(VS_IMG_DITHERED.as_ptr(), FS_GLASS.as_ptr()) { + GPROG = match link_optional_program(VS_IMG_DITHERED.as_ptr(), FS_GLASS.as_ptr()) { Some(p) => p, None => { log("blur: glass prog link failed — backdrop blur off"); @@ -10221,8 +10295,8 @@ mod tests { /// overdraw ledger BEFORE choosing a program, and fall back to the fill program rather than /// draw nothing when the ramp program did not compile or link. Each arm of the routing must call /// ITS program (a swap would still contain both calls), and the ramp program must be built from - /// `VS_SRC` + `FS_RAMP` through `link_optional_program`: `link_program` exits the process on a - /// compile rejection, so the fallback above would never be reached for it. + /// `VS_SRC` + `FS_RAMP` through `link_optional_program`: `link_program` makes a compile rejection a + /// boot fault, so the fallback above would never be reached for it. #[test] fn the_ramp_program_is_the_fill_programs_flat_path_in_a_smaller_shader() { let ramp = shader_code(FS_RAMP); @@ -13328,3 +13402,92 @@ mod frost_tests { assert_eq!(FROST_TAPS.iter().map(|d| d * d + 0.25).sum::(), 9.0, "sigma 3 texels = 24 px at 1/8"); } } + +/// What a driver's refusal costs a required program, graded without a GL context: the decision is +/// [`link_required`] / [`degrade_on_link_failure`], which take the driver as a parameter. +#[cfg(test)] +mod fault_tests { + use super::*; + use std::cell::RefCell; + + /// A driver that rejects what it is told to and records the steps it was asked for. + struct Refusing { + reject_compile_of: Option, + refuse_link: bool, + steps: RefCell>, + } + + impl Refusing { + fn new(reject_compile_of: Option, refuse_link: bool) -> Self { + Self { reject_compile_of, refuse_link, steps: RefCell::new(Vec::new()) } + } + } + + impl ProgramDriver for Refusing { + fn compile(&self, ty: c_uint, _src: *const c_char) -> Option { + self.steps.borrow_mut().push(if ty == GL_VERTEX_SHADER { "compile vs" } else { "compile fs" }); + (self.reject_compile_of != Some(ty)).then_some(ty) + } + fn link(&self, _vs: c_uint, _fs: c_uint) -> Option { + self.steps.borrow_mut().push("link"); + (!self.refuse_link).then_some(7) + } + } + + #[test] + fn an_injected_compile_rejection_is_a_fault_for_either_shader() { + let vertex = Refusing::new(Some(GL_VERTEX_SHADER), false); + assert_eq!(link_required(&vertex, std::ptr::null(), std::ptr::null()), Err(GfxFault::Compile)); + assert_eq!(*vertex.steps.borrow(), ["compile vs"], "the first rejection ends it, as the exit did"); + let fragment = Refusing::new(Some(GL_FRAGMENT_SHADER), false); + assert_eq!(link_required(&fragment, std::ptr::null(), std::ptr::null()), Err(GfxFault::Compile)); + assert_eq!(*fragment.steps.borrow(), ["compile vs", "compile fs"], "and nothing is linked after it"); + } + + #[test] + fn an_injected_link_refusal_is_a_link_fault() { + let driver = Refusing::new(None, true); + assert_eq!(link_required(&driver, std::ptr::null(), std::ptr::null()), Err(GfxFault::Link)); + assert_eq!(*driver.steps.borrow(), ["compile vs", "compile fs", "link"]); + } + + #[test] + fn a_program_the_driver_accepts_comes_back() { + let driver = Refusing::new(None, false); + assert_eq!(link_required(&driver, std::ptr::null(), std::ptr::null()), Ok(7)); + } + + /// The split the exits had: a link failure costs the base program the boot and every other + /// required program only itself; a compile rejection costs the boot whichever program it was. + #[test] + fn a_link_fault_degrades_a_program_and_a_compile_fault_never_does() { + assert_eq!(degrade_on_link_failure(Ok(5), "kept"), Ok(5)); + assert_eq!(degrade_on_link_failure(Err(GfxFault::Link), "a fault test's degraded program"), Ok(0), + "no program: the draw that needs it does nothing or falls back"); + assert_eq!(degrade_on_link_failure(Err(GfxFault::Compile), "unused"), Err(GfxFault::Compile)); + } + + #[test] + fn a_fault_names_what_failed() { + assert_eq!(GfxFault::Compile.to_string(), "a required shader failed to compile"); + assert_eq!(GfxFault::Link.to_string(), "a required shader program failed to link"); + } + + /// `blur_lazy_init` runs from the frame, which cannot return a fault: it links only optional + /// programs, so a driver's rejection degrades it exactly as its link failure did. Reads the + /// source for the reason the neighbouring tests do (no host test has a GL context). + #[test] + fn the_frames_lazy_link_is_optional_so_the_loop_never_owes_a_fault() { + let source = include_str!("gfx.rs"); + let body = source + .split_once(concat!("\nfn blur_lazy_", "init() -> bool {")) + .expect("blur_lazy_init") + .1 + .split_once("\n}\n") + .expect("the end of blur_lazy_init") + .0; + assert!(!body.contains(concat!("link_", "program(")), "a required program linked from the frame"); + assert_eq!(body.matches(concat!("link_optional_", "program(")).count(), 3, + "the blur, the glass and the frost programs are all optional"); + } +} diff --git a/rust-modules/gfx/src/text.rs b/rust-modules/gfx/src/text.rs index 282b151703..269e8ec623 100644 --- a/rust-modules/gfx/src/text.rs +++ b/rust-modules/gfx/src/text.rs @@ -89,6 +89,7 @@ use std::ptr::{addr_of, addr_of_mut}; use std::rc::Rc; use plx_base::surface::{LOGICAL_H as SCR_H, LOGICAL_W as SCR_W}; +use crate::gfx::{degrade_on_link_failure, GfxFault}; use crate::overdraw::{gate, Class}; /// Last resort only. Reaching this is a DEFECT, not a graceful degradation — see `font_at`. @@ -1646,20 +1647,21 @@ unsafe fn publish_text_ok() -> bool { true } -pub fn init_text() { +pub fn init_text() -> Result<(), GfxFault> { FITTED_LINES.with(|cache| cache.borrow_mut().entries.clear()); MEASURED_BOUNDS.with(|cache| cache.borrow_mut().entries.clear()); unsafe { if !ttf_init() { log("TTF_Init failed"); - return; + return Ok(()); } TPROG = match crate::gfx::link_program(VS_TEXT.as_ptr(), FS_TEXT.as_ptr()) { - Some(p) => p, - None => { + Ok(p) => p, + Err(GfxFault::Link) => { log("text prog link failed"); - return; + return Ok(()); } + Err(fault) => return Err(fault), }; TL_RECT = glGetUniformLocation(TPROG, c"u_trect".as_ptr()); TL_SCREEN = glGetUniformLocation(TPROG, c"u_tscreen".as_ptr()); @@ -1667,12 +1669,10 @@ pub fn init_text() { TL_TEX = glGetUniformLocation(TPROG, c"u_tex".as_ptr()); // the fade program shares VS_TEXT; a link failure leaves TPROGF=0 and draw_text_fade // falls back to the plain path (the fade is a nicety, not load-bearing) - TPROGF = crate::gfx::link_program(VS_TEXT.as_ptr(), FS_TEXT_FADE.as_ptr()).unwrap_or_else( - || { - log("text fade prog link failed"); - 0 - }, - ); + TPROGF = degrade_on_link_failure( + crate::gfx::link_program(VS_TEXT.as_ptr(), FS_TEXT_FADE.as_ptr()), + "text fade prog link failed", + )?; if TPROGF != 0 { TLF_RECT = glGetUniformLocation(TPROGF, c"u_trect".as_ptr()); TLF_SCREEN = glGetUniformLocation(TPROGF, c"u_tscreen".as_ptr()); @@ -1685,12 +1685,10 @@ pub fn init_text() { } // the ink program shares VS_TEXT too; without it a label crossed by a capsule's rounded end // is painted plain (a nicety again: the stretches' ink is still chosen, only the edge is square) - TPROGI = crate::gfx::link_program(VS_TEXT.as_ptr(), FS_TEXT_INK.as_ptr()).unwrap_or_else( - || { - log("text ink prog link failed"); - 0 - }, - ); + TPROGI = degrade_on_link_failure( + crate::gfx::link_program(VS_TEXT.as_ptr(), FS_TEXT_INK.as_ptr()), + "text ink prog link failed", + )?; if TPROGI != 0 { TLI_RECT = glGetUniformLocation(TPROGI, c"u_trect".as_ptr()); TLI_SCREEN = glGetUniformLocation(TPROGI, c"u_tscreen".as_ptr()); @@ -1723,6 +1721,7 @@ pub fn init_text() { // which is a shared reference to a `static mut` (`static_mut_refs`, a future hard error) log(&format!("init_text ok={}", *addr_of!(TEXT_OK))); } + Ok(()) } /// **The fonts without the renderer.** [`init_text`] opens the fonts AND links the text shaders, so it diff --git a/rust-modules/src/app/boot.rs b/rust-modules/src/app/boot.rs index b002896f88..3a2cbea1cd 100644 --- a/rust-modules/src/app/boot.rs +++ b/rust-modules/src/app/boot.rs @@ -531,73 +531,6 @@ mod seam_order_tests { ); } - /// **No exit of the app process returns into libc's `exit`.** `exit` runs libcrypto's - /// `OPENSSL_cleanup`, which frees and NULLs its global locks while the detached curl workers - /// still run (#1115). The run-and-shutdown sequence and the entry point are typed `-> !` (a - /// path that returns does not compile): these consts are the compile-time proof, and the - /// source scan below finds any other `exit` call, which would sidestep - /// `plx_base::process::exit_now`. - const _: unsafe fn(&mut super::super::App) -> ! = super::super::run_and_shutdown; - const _: fn(*const std::os::raw::c_char, std::os::raw::c_int) -> ! = - super::super::run_application; - - #[test] - fn no_production_code_calls_libc_exit_outside_the_shared_helper() { - // The app process links every crate under rust-modules except `storage` (the separate - // `plxstorage` helper binary, no OpenSSL workers) and the os layer's `storage_service/` (that - // helper's body). `base/src/process.rs` is the helper itself. - let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); - let mut files = Vec::new(); - collect_rs(&root.join("src"), &mut files); - for entry in std::fs::read_dir(root).expect("rust-modules") { - let dir = entry.expect("entry").path(); - let name = dir.file_name().and_then(|n| n.to_str()).unwrap_or("").to_string(); - if matches!(name.as_str(), "storage" | "target" | "tests") - || name.starts_with("target-") - || !dir.join("src").is_dir() - { - continue; - } - collect_rs(&dir.join("src"), &mut files); - } - assert!(files.len() > 100, "the scan must see the whole tree"); - let (a, b) = (concat!("process::", "exit("), concat!("libc::", "exit(")); - let mut hits = Vec::new(); - for f in files { - let path = f.to_string_lossy().replace('\\', "/"); - if path.ends_with("base/src/process.rs") - || path.contains("/storage_service/") - || path.contains("/tests/") - || path.ends_with("_tests.rs") - { - continue; - } - let text = std::fs::read_to_string(&f).expect("read"); - let prod = text.split("#[cfg(test)]").next().unwrap_or(""); - for (n, line) in prod.lines().enumerate() { - let code = line.split("//").next().unwrap_or(""); - if code.contains(a) || code.contains(b) { - hits.push(format!("{path}:{}", n + 1)); - } - } - } - assert!( - hits.is_empty(), - "exit through plx_base::process::exit_now, never libc exit (#1115): {hits:?}" - ); - } - - fn collect_rs(dir: &std::path::Path, out: &mut Vec) { - for entry in std::fs::read_dir(dir).expect("read_dir").flatten() { - let p = entry.path(); - if p.is_dir() { - collect_rs(&p, out); - } else if p.extension().is_some_and(|e| e == "rs") { - out.push(p); - } - } - } - /// `enter_application` installs the player's error-trace eraser before telemetry first loads a /// decision (`pre_boot_diagnostics` -> `telemetry::boot`, which already erases through it) and /// before anything can play. It was installed by `player::report::requested`, which a @@ -1439,7 +1372,8 @@ pub(super) fn install_pms_owned( /// Everything before the loop: SDL and the window, GL, text, the poster workers, the boot gate /// (login / token / session / picker), every dev trigger read once, and the `App` literal — /// `plex_run`'s former body up to `while app.running`, moved verbatim in phase 1b-ii. An early -/// exit ends the process through `plx_base::process::exit_now` (the caller maps `Err(code)` to it). +/// refusal returns its `Exit` (the entry ends the process with its code, `port::plex_run`; a hosted +/// entry reports it and stays alive). /// /// `mt`, THE main-thread token, is minted once by `plex_run` itself (`plx_base::task::MainThread:: /// assume()` — that function IS the SDL main thread) and MOVES into `App.adapters.player` here, @@ -1451,7 +1385,7 @@ pub(crate) unsafe fn boot( pms_port: c_int, mt: plx_base::task::MainThread, preflight: super::bootstrap::Preflight, -) -> Result { +) -> Result { // 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); @@ -1466,7 +1400,7 @@ pub(crate) unsafe fn boot( let host = std::ffi::CStr::from_ptr(pms_host).to_string_lossy(); match super::bootstrap::Initial::capture_home(&host, pms_port) { Ok(initial) => Some(initial), - Err(reason) => { log(&format!("rec: REFUSED — {reason}")); return Err(1); } + Err(reason) => { log(&format!("rec: REFUSED — {reason}")); return Err(Exit::refused(1)); } } } super::bootstrap::Preflight::Replay { initial, .. } => Some((initial.clone(), None)), @@ -1522,12 +1456,12 @@ pub(crate) unsafe fn construct( pms_host: *const c_char, pms_port: c_int, mt: plx_base::task::MainThread, preflight: super::bootstrap::Preflight, initial: Option, deferred: Option, -) -> Result { +) -> Result { let controlled = preflight.controlled(); if let Some(initial) = &initial { plx_data::stores::tape::init(initial.person_credits(), preflight.replay()); - initial.home.restore(&mt).map_err(|_| 1)?; - plx_plex::plex::Client::restore_generation_seed(initial.primary_client).map_err(|_| 1)?; + initial.home.restore(&mt).map_err(|_| Exit::refused(1))?; + plx_plex::plex::Client::restore_generation_seed(initial.primary_client).map_err(|_| Exit::refused(1))?; } SDL_SetMainReady(); // DEAD END, measured 2026-07-31 — do not re-try this. The obvious answer to "a parked TV @@ -1546,7 +1480,7 @@ pub(crate) unsafe fn construct( webos3_cursor_sleep_hint(); if SDL_Init(SDL_INIT_VIDEO) != 0 { log("SDL_Init failed"); - return Err(1); + return Err(Exit::refused(1)); } tap_relaunch_payloads(); { @@ -1656,7 +1590,7 @@ pub(crate) unsafe fn construct( log(&format!("GL ctx failed at {ww_try}x{wh_try}")); SDL_DestroyWindow(win); } - let Some((w, h)) = fallback.take() else { return Err(1); }; + let Some((w, h)) = fallback.take() else { return Err(Exit::refused(1)); }; log(&format!("surface: retrying the window at the native {w}x{h}")); (ww_try, wh_try) = (w, h); }; @@ -1727,9 +1661,11 @@ pub(crate) unsafe fn construct( // 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(); - plx_gfx::gfx::init_gl(); - plx_gfx::text::init_text(); - plx_gfx::gfx::init_image(); + // 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()?; + plx_gfx::text::init_text()?; + plx_gfx::gfx::init_image()?; plx_gfx::gfx::init_blur(); // The transport takes the client's `User-Agent` as a value (it names no Plex layer): hand it // over before any request can be made, so the first one already carries it. @@ -2518,6 +2454,8 @@ pub(crate) unsafe fn construct( rec: super::recorder::Recplay::Off, boot_initial: initial, telemetry_guard: None, + #[cfg(test)] + drop_probe: Default::default(), glass, // **The application's page stack runs the route DIP** (§6.2). It ran `Immediate` until @@ -2639,16 +2577,16 @@ pub(crate) unsafe fn construct( plx_plex::plex::account::announce_discover(); if controlled { let initial = app.snapshot_init().expect("controlled constructor retains initial inputs"); - initial.validate().map_err(|reason| { log(&format!("rec: REFUSED — {reason}")); 1 })?; + initial.validate().map_err(|reason| { log(&format!("rec: REFUSED — {reason}")); Exit::refused(1) })?; let replay = preflight.replay(); app.rec = super::recorder::Recplay::controlled(preflight, &initial) - .map_err(|reason| { log(&format!("rec: REFUSED — {reason}")); 1 })?; + .map_err(|reason| { log(&format!("rec: REFUSED — {reason}")); Exit::refused(1) })?; let mut bridge = app.runtime.bridge(&mut app.bridge); app.rec.arm_landgate(bridge.landgate()); log("bootstrap: captured pre-effect initial state"); if let Some(deferred) = deferred { apply_deferred_capture(&mut app.rec, bridge.landgate(), deferred) - .map_err(|reason| { log(&format!("rec: REFUSED — {reason}")); 1 })?; + .map_err(|reason| { log(&format!("rec: REFUSED — {reason}")); Exit::refused(1) })?; log("bootstrap: captured session persistence applied"); } if !replay { @@ -2659,13 +2597,13 @@ pub(crate) unsafe fn construct( app.rec.prepare_resources(&mut bridge); if !matches!(activate_session(&mut bridge, &mut app.pages, &mut app.rec), BootTo::Home) { log("bootstrap: controlled Home activation refused"); - return Err(1); + return Err(Exit::refused(1)); } let tree = app.pages.state_hash(); app.rec.resource_requests(bridge.take_resource_requests()); if let Some(reason) = app.rec.failure().or_else(|| bridge.controlled_failure()) { log(&format!("bootstrap: REFUSED — {reason}")); - return Err(1); + return Err(Exit::refused(1)); } super::run::recorder_end_frame(&mut app.rec, &bridge, "home", "", "bootstrap", tree); @@ -2698,7 +2636,7 @@ pub(crate) unsafe fn construct( // Preflight refuses the still-unsupported first-run surface before resource boot. if plx_screens::consent::should_show(&initial.consent, initial.automated) { log("bootstrap: REFUSED — unsupported initial consent route"); - return Err(1); + return Err(Exit::refused(1)); } } else { maybe_ask_consent(&mut app.pages, &mut app.runtime.consent.machine.ask); diff --git a/rust-modules/src/app/exit.rs b/rust-modules/src/app/exit.rs new file mode 100644 index 0000000000..786354c0fd --- /dev/null +++ b/rust-modules/src/app/exit.rs @@ -0,0 +1,622 @@ +//! How the application ends, and what it hands back to whatever started it. +//! +//! [`run_application`](super::run_application) RETURNS an [`Exit`]; it never ends the process. +//! An early-boot refusal returns its code, and a played session returns after `run::shutdown` and +//! the telemetry guard drop. Ending the process is the EXECUTABLE entry's: `port::plex_main` (the C +//! shim and the simulator both enter through `plex_run`, which only calls it) calls +//! `plx_base::process::exit_now(exit.code)` right after, in the order the app always ended in, so a +//! television behaves as before. A process that HOSTS the application never calls `exit_now` or +//! `exit`: libc's `exit` runs OpenSSL's cleanup under the detached curl workers (#1115), and a host +//! would be killed under its own runtime. No exit a hosted process can reach remains in the tree: +//! the graphics boot returns a [`GfxFault`](plx_gfx::gfx::GfxFault) ([`Exit::from`]) where it used +//! to call `exit_now(1)`, and `lifecycle_tests` below scans the production source for any +//! `exit_now(` outside the entries. `plex_main` is typed `-> !`, a const beside it proves it, and +//! the scan holds that the const is still there. +//! +//! # What is leaked, and why +//! +//! [`entry`] wraps the mounted value in `ManuallyDrop`, so returning drops nothing: the detached +//! workers (notification feed, metadata, watchlist, auth probes) are still running, and +//! `SessionAdapter::drop`, GL object drops (`QrCode::drop` deletes a texture) and the feed +//! `Engine` must never run under them (#1115). It is the same on both entry kinds. `App`'s +//! `drop_probe` (test builds) is the sentinel that proves it: dropping the `App` drops the probe, +//! whatever its other fields are. +//! +//! # What the release says +//! +//! [`Release`] is the one decision the teardown makes about the display: `Complete` is the arm of +//! [`release_of`] that ends with `SDL_Quit()` (`NativeExit::Clean`), `Retained` is the arm that logs +//! "SDL_Quit skipped" because a native worker is still inside firmware +//! (`NativeExit::WorkerInFirmware`) and, for a refusal, "nothing was torn down". The executable +//! ignores it; a hosted entry maps `Retained` to `clean = 0`. Until the shell crate lands, `SDL_Quit` +//! IS the release of the window and the GL context, so `Complete` already means both. +//! +//! # The host doorway +//! +//! [`HostGate`], [`Completion`] and [`Stopped`] are the hosted entry's half of the contract (the +//! Tizen host's callbacks, `plx_host_stop` and its deadline watchdog). They are plain values, not +//! statics, and decide nothing by themselves that a runner has to wait for: [`HostGate::report`] +//! answers "not yet" while a gated callback is running and the runner asks again. The C ABI that +//! drives them is the hosted platform's; `lifecycle_tests` drives them through a fake host. +//! +//! ```text +//! host callback ──enter──▶ gate ──(stopping? refused)──▶ runs ──drop──▶ inflight - 1 +//! loop thread returns ──report──▶ clean = Complete AND inflight == 0 ──deliver──▶ on_stopped (once) +//! deadline thread ──expire──▶ clean = 0 ──deliver──▶ on_stopped (once; the loser is suppressed) +//! ``` + +use plx_gfx::gfx::GfxFault; +use plx_media::player::NativeExit; +use std::mem::ManuallyDrop; +use std::os::raw::c_int; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +/// Whether the application gave back every native resource it held before it returned. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Release { + /// The teardown ran to its end and released the window and the GL context. + Complete, + /// Something is still held: a native worker is inside firmware, or the boot refused before any + /// teardown ran. Nothing may be released under it, and a host treats process exit as the + /// teardown. + Retained, +} + +/// What `run_application` returns to its entry. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Exit { + /// The process exit status: `1` after a failed recording or a refused boot, else `0`. + pub(crate) code: c_int, + pub(crate) release: Release, +} + +impl Exit { + /// An early-boot refusal. Nothing was torn down, so nothing is released. + pub(crate) const fn refused(code: c_int) -> Self { + Self { code, release: Release::Retained } + } + + /// A played session's end: `failed` is a recording that did not land or a controlled run that + /// refused, and `release` is what [`crate::app::run::shutdown`] returned. + pub(crate) fn played(failed: bool, release: Release) -> Self { + Self { code: c_int::from(failed), release } + } +} + +/// A required shader the driver refused ended the process with status 1 (`exit_now(1)`); it ends the +/// boot with the same status and no teardown, which is a refusal like any other. +impl From for Exit { + fn from(_: GfxFault) -> Self { + Self::refused(1) + } +} + +/// What [`crate::app::run::shutdown`] releases for a worker-exit verdict. The ONE `match` that +/// decides it, exhaustive with no `_` arm so a third [`NativeExit`] fails to compile here and in +/// [`crate::app::run::quits_sdl`], which is derived from it: the hosted report cannot say +/// `Complete` where the executable skipped `SDL_Quit`. +pub(crate) fn release_of(native_exit: NativeExit) -> Release { + match native_exit { + NativeExit::Clean => Release::Complete, + // A native worker is still inside firmware: the display must not be torn down under it. + NativeExit::WorkerInFirmware => Release::Retained, + } +} + +/// Construct, run, return, and leak: the whole of `run_application`'s body, with the two phases +/// passed in so a host test drives the same path with a refusal, a stand-in or a real `App`. +/// +/// A refusal returns its [`Exit`]. A mounted value is handed to `run` and then forgotten +/// (`ManuallyDrop`), never dropped: see the module note. `run` ends the session and says how. +pub(crate) fn entry( + enter: impl FnOnce() -> Result, + run: impl FnOnce(&mut T) -> Exit, +) -> Exit { + match enter() { + Ok(mounted) => run(&mut ManuallyDrop::new(mounted)), + Err(exit) => exit, + } +} + +/// The sentinel on `App` that shows the leak: a counter its `Drop` increments, shared with the test +/// that holds the other end. It is a FIELD, not a static, so dropping the `App` drops it whatever +/// the `App`'s other fields are (and no `statics` line is owed). +#[cfg(test)] +#[derive(Default)] +pub(crate) struct DropProbe(std::sync::Arc); + +#[cfg(test)] +impl DropProbe { + /// The counter, to be read after the `App` has gone wherever the test sent it. Only the + /// hostsim lifecycle tests build an `App` to read it from. + #[cfg_attr(not(all(feature = "hostsim", feature = "play-feed")), allow(dead_code))] + pub(crate) fn counter(&self) -> std::sync::Arc { + std::sync::Arc::clone(&self.0) + } +} + +#[cfg(test)] +impl Drop for DropProbe { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } +} + +/// One host-bound callback's admission. Every callback into the host (window, player request, log +/// sink) and every event from it (a player completion) enters through ONE of these, and is refused +/// once the stop was requested. +/// +/// `stopping` alone could only choose which sender reports; it cannot drain a callback that is +/// already running. `inflight` is that drain: [`HostGate::report`] answers `clean` only once it is +/// zero. +// The first caller is the hosted entry (the Tizen platform); `lifecycle_tests` grade it until then. +#[cfg_attr(not(test), allow(dead_code))] +pub(crate) struct HostGate { + stopping: AtomicBool, + inflight: AtomicUsize, +} + +/// A callback that was admitted by [`HostGate::enter`] and has not returned. Dropping it is the +/// return. +#[cfg_attr(not(test), allow(dead_code))] +pub(crate) struct InFlight<'a>(&'a HostGate); + +impl Drop for InFlight<'_> { + fn drop(&mut self) { + self.0.inflight.fetch_sub(1, Ordering::SeqCst); + } +} + +#[cfg_attr(not(test), allow(dead_code))] +impl HostGate { + pub(crate) const fn new() -> Self { + Self { stopping: AtomicBool::new(false), inflight: AtomicUsize::new(0) } + } + + /// Admit one callback, or refuse it (`None`) because the stop was requested: the caller drops a + /// late player completion and makes no further call into the host. + /// + /// The count goes up BEFORE `stopping` is read and comes back down on a refusal. The other + /// order lets a callback read "not stopping", lose the CPU while [`HostGate::stop`] and + /// [`HostGate::report`] run, and then start with the report already sent as clean. All four + /// operations are `SeqCst`, so either the callback sees the stop or `report` sees the callback. + pub(crate) fn enter(&self) -> Option> { + self.inflight.fetch_add(1, Ordering::SeqCst); + if self.stopping.load(Ordering::SeqCst) { + self.inflight.fetch_sub(1, Ordering::SeqCst); + return None; + } + Some(InFlight(self)) + } + + /// `plx_host_stop`: refuse every later callback. Answers whether THIS call is the one that + /// stopped (a second `stop` is harmless and answers `false`). + pub(crate) fn stop(&self) -> bool { + !self.stopping.swap(true, Ordering::SeqCst) + } + + pub(crate) fn stopping(&self) -> bool { + self.stopping.load(Ordering::SeqCst) + } + + /// Callbacks admitted and not yet returned. A refused [`HostGate::enter`] shows here for an + /// instant, which is why [`HostGate::report`] is asked again rather than trusted once. + pub(crate) fn in_flight(&self) -> usize { + self.inflight.load(Ordering::SeqCst) + } + + /// The loop thread's report once `run_application` returned `exit`: it stops the gate, and + /// answers `None` ("a callback is still running, ask again") until none is. `clean` is + /// `Complete` AND drained: a `Retained` loop is never clean, whatever the callbacks did. + pub(crate) fn report(&self, exit: &Exit) -> Option { + self.stop(); + (self.in_flight() == 0) + .then_some(Stopped { code: exit.code, clean: exit.release == Release::Complete }) + } + + /// The deadline thread's report, when the loop has not finished in time (a stalled swap): never + /// clean, because a loop that has not returned has released nothing. + pub(crate) fn expire(&self, code: c_int) -> Stopped { + self.stop(); + Stopped { code, clean: false } + } +} + +/// What `on_stopped(code, clean)` carries. With `clean` the host may release its callbacks and +/// surfaces; without it, it releases nothing and treats process exit as the teardown. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(not(test), allow(dead_code))] +pub(crate) struct Stopped { + pub(crate) code: c_int, + pub(crate) clean: bool, +} + +/// `on_stopped`'s exactly-once guard. The loop thread's report and the deadline thread's race for +/// it; the first delivers, and the loser's report is suppressed (`false`). +#[cfg_attr(not(test), allow(dead_code))] +pub(crate) struct Completion { + delivered: AtomicBool, +} + +#[cfg_attr(not(test), allow(dead_code))] +impl Completion { + pub(crate) const fn new() -> Self { + Self { delivered: AtomicBool::new(false) } + } + + /// Deliver `stopped` through `on_stopped`, unless a report was delivered already. The watchdog + /// is disarmed first: the loop thread is about to end (its id with it), and after `on_stopped` + /// the host may tear the process down around it. + pub(crate) fn deliver(&self, stopped: Stopped, on_stopped: impl FnOnce(Stopped)) -> bool { + if self.delivered.swap(true, Ordering::SeqCst) { + return false; + } + plx_base::task::watchdog::disarm(); + on_stopped(stopped); + true + } +} + +/// The host-doorway contract, through a fake host: the second implementation of the table the +/// hosted platform will fill, with threads standing in for its. +#[cfg(test)] +mod lifecycle_tests { + use super::*; + use std::sync::{mpsc, Mutex}; + + /// A host: the gate and the once-guard its table shares, and what `on_stopped` received. It + /// holds the process-global test lock for its whole life: `Completion::deliver` disarms the + /// process watchdog, which a test that arms it and reads it back must not race. + struct FakeHost { + _serial: plx_base::testlock::Serial, + gate: HostGate, + completion: Completion, + /// Each delivery, with whether the watchdog was still armed when the callback ran. + received: Mutex>, + } + + impl FakeHost { + fn new() -> Self { + Self { + _serial: plx_base::testlock::serial(), + gate: HostGate::new(), + completion: Completion::new(), + received: Mutex::new(Vec::new()), + } + } + + fn on_stopped(&self, stopped: Stopped) { + self.received.lock().unwrap().push((stopped, plx_base::task::watchdog::is_armed())); + } + + /// The loop thread's tail once `run_application` returned: ask until the gate drains. + fn loop_returned(&self, exit: &Exit) -> bool { + loop { + if let Some(stopped) = self.gate.report(exit) { + return self.completion.deliver(stopped, |stopped| self.on_stopped(stopped)); + } + std::thread::yield_now(); + } + } + + /// The watchdog thread `plx_host_stop` starts, once its deadline passed. + fn deadline(&self, code: c_int) -> bool { + let stopped = self.gate.expire(code); + self.completion.deliver(stopped, |stopped| self.on_stopped(stopped)) + } + + fn received(&self) -> Vec { + self.received.lock().unwrap().iter().map(|(stopped, _)| *stopped).collect() + } + } + + fn quit() -> Exit { + Exit::played(false, Release::Complete) + } + + #[test] + fn a_boot_refusal_returns_its_code_and_the_host_is_told_once() { + let exit = entry::<()>(|| Err(Exit::refused(7)), |_| unreachable!("nothing was mounted")); + assert_eq!(exit, Exit { code: 7, release: Release::Retained }); + let host = FakeHost::new(); + assert!(host.loop_returned(&exit)); + assert_eq!(host.received(), [Stopped { code: 7, clean: false }], + "a refusal tore nothing down, so the host is told not to release anything"); + } + + #[test] + fn a_shader_the_driver_refused_reaches_the_host_as_status_one_and_the_host_stays_alive() { + for fault in [GfxFault::Compile, GfxFault::Link] { + let exit = entry::<()>(|| Err(Exit::from(fault)), |_| unreachable!("nothing was mounted")); + assert_eq!(exit, Exit { code: 1, release: Release::Retained }, "{fault}"); + let host = FakeHost::new(); + assert!(host.loop_returned(&exit)); + assert_eq!(host.received(), [Stopped { code: 1, clean: false }], "{fault}"); + } + } + + #[test] + fn a_quit_during_playback_returns_after_the_teardown_and_reports_clean() { + let ended = Mutex::new(false); + let exit = entry(|| Ok(()), |_| { + *ended.lock().unwrap() = true; + quit() + }); + assert!(*ended.lock().unwrap(), "the session ran before the entry returned"); + assert_eq!(exit, Exit { code: 0, release: Release::Complete }); + let host = FakeHost::new(); + assert!(host.loop_returned(&exit)); + assert_eq!(host.received(), [Stopped { code: 0, clean: true }]); + } + + #[test] + fn a_failed_recording_is_status_one_and_still_a_complete_release() { + assert_eq!(Exit::played(true, Release::Complete), Exit { code: 1, release: Release::Complete }); + } + + #[test] + fn a_stop_with_a_player_request_outstanding_drops_its_late_completion() { + let host = FakeHost::new(); + // The loop asked the host to play; the host took the request and has not answered. + drop(host.gate.enter().expect("a request before the stop is admitted")); + assert!(host.gate.stop(), "plx_host_stop"); + assert!(host.loop_returned(&quit())); + // The completion arrives after the stop: dropped, and nothing is delivered for it. + assert!(host.gate.enter().is_none(), "a late player completion is refused"); + assert_eq!(host.gate.in_flight(), 0, "a refusal leaves nothing counted"); + assert_eq!(host.received(), [Stopped { code: 0, clean: true }]); + } + + #[test] + fn a_returning_loop_with_a_retained_worker_is_never_clean() { + let host = FakeHost::new(); + assert!(host.loop_returned(&Exit::played(false, Release::Retained))); + assert_eq!(host.received(), [Stopped { code: 0, clean: false }], + "a worker is still in firmware: the host releases nothing"); + } + + #[test] + fn a_callback_in_flight_at_stop_holds_the_clean_report_until_it_returns() { + let gate = HostGate::new(); + let running = gate.enter().expect("admitted"); + assert_eq!(gate.in_flight(), 1); + assert_eq!(gate.report(&quit()), None, "a flag alone cannot drain a callback already running"); + assert!(gate.stopping(), "and the report itself refuses every later one"); + assert!(gate.enter().is_none()); + drop(running); + assert_eq!(gate.report(&quit()), Some(Stopped { code: 0, clean: true })); + } + + #[test] + fn the_loop_thread_waits_for_a_running_callback_and_reports_exactly_once() { + let host = FakeHost::new(); + let running = host.gate.enter().expect("admitted"); + let (done, finished) = mpsc::channel(); + std::thread::scope(|scope| { + scope.spawn(|| done.send(host.loop_returned(&quit())).unwrap()); + while !host.gate.stopping() { + std::thread::yield_now(); + } + assert!(host.received().is_empty(), "the callback has not returned: nothing is reported"); + drop(running); + assert!(finished.recv().unwrap(), "the loop thread delivered"); + }); + assert_eq!(host.received(), [Stopped { code: 0, clean: true }]); + } + + /// Two senders, one flag: whichever reaches it first delivers, and the loser is suppressed. + #[test] + fn a_swap_that_stalls_and_wakes_after_the_deadline_reports_once_and_unclean() { + let host = FakeHost::new(); + assert!(host.deadline(1), "the deadline thread reports while the loop is still stuck"); + assert!(!host.loop_returned(&quit()), "the loop wakes, returns Complete, and is suppressed"); + assert_eq!(host.received(), [Stopped { code: 1, clean: false }]); + } + + #[test] + fn a_loop_that_returns_in_time_suppresses_the_deadline() { + let host = FakeHost::new(); + assert!(host.loop_returned(&quit())); + assert!(!host.deadline(1)); + assert_eq!(host.received(), [Stopped { code: 0, clean: true }]); + } + + #[test] + fn two_senders_racing_deliver_exactly_once() { + for _ in 0..200 { + let host = FakeHost::new(); + let delivered = std::thread::scope(|scope| { + let loop_thread = scope.spawn(|| host.loop_returned(&quit())); + let deadline = scope.spawn(|| host.deadline(1)); + [loop_thread.join().unwrap(), deadline.join().unwrap()] + }); + assert_eq!(delivered.iter().filter(|delivered| **delivered).count(), 1); + assert_eq!(host.received().len(), 1); + } + } + + #[test] + fn pause_then_stop_leaves_the_watchdog_disarmed_when_on_stopped_runs() { + let host = FakeHost::new(); + plx_base::task::watchdog::arm(); + // OnPause: nothing may signal the loop thread while the host is parked. + plx_base::task::watchdog::disarm(); + assert!(!plx_base::task::watchdog::is_armed()); + // OnResume re-captures the loop thread. + plx_base::task::watchdog::arm(); + assert!(plx_base::task::watchdog::is_armed()); + // Stop: the report disarms before the callback runs. + assert!(host.loop_returned(&quit())); + let received = host.received.lock().unwrap(); + assert_eq!(received.len(), 1); + assert!(!received[0].1, "the watchdog was disarmed before on_stopped"); + } + + #[test] + fn the_gate_refuses_after_stop_and_counts_what_it_admitted() { + let gate = HostGate::new(); + assert!(!gate.stopping()); + let (first, second) = (gate.enter().unwrap(), gate.enter().unwrap()); + assert_eq!(gate.in_flight(), 2); + drop(first); + assert_eq!(gate.in_flight(), 1); + assert!(gate.stop()); + assert!(!gate.stop(), "only the first stop is the one that stopped"); + assert!(gate.enter().is_none()); + drop(second); + assert_eq!(gate.in_flight(), 0); + } + + #[test] + fn release_follows_the_worker_exit_verdict_in_both_directions() { + assert_eq!(release_of(NativeExit::Clean), Release::Complete); + assert_eq!(release_of(NativeExit::WorkerInFirmware), Release::Retained); + } + + /// **No exit of the app process returns into libc's `exit`, and none a hosted process could + /// reach is left.** `exit` runs libcrypto's `OPENSSL_cleanup`, which frees and NULLs its global + /// locks while the detached curl workers still run (#1115), so every exit goes through + /// `plx_base::process::exit_now`; and that is the executable entries' to call, because a host + /// is killed under its own runtime by one. `run_application` and the graphics boot RETURN + /// (`Exit`, `GfxFault`), so the production `exit_now(` sites are the entries that own the + /// process end (`port::plex_main`, the simulator's `main`), the frame dump (`devtriggers`, off in + /// a release build) and the helper itself. A new exit anywhere else fails here. + #[test] + fn lifecycle_no_production_exit_is_reachable_from_a_hosted_process() { + // The app process links every crate under rust-modules except `storage` (the separate + // `plxstorage` helper binary, no OpenSSL workers) and os's `storage_service/` (that + // helper's body). `base/src/process.rs` is the helper itself. + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); + let mut files = Vec::new(); + collect_rs(&root.join("src"), &mut files); + for entry in std::fs::read_dir(root).expect("rust-modules") { + let dir = entry.expect("entry").path(); + let name = dir.file_name().and_then(|n| n.to_str()).unwrap_or("").to_string(); + if matches!(name.as_str(), "storage" | "target" | "tests") + || name.starts_with("target-") + || !dir.join("src").is_dir() + { + continue; + } + collect_rs(&dir.join("src"), &mut files); + } + assert!(files.len() > 100, "the scan must see the whole tree"); + let owns_process_end = ["src/port.rs", "src/bin/sim.rs", "src/dev/framedump.rs"].map(|p| root.join(p)); + for entry in &owns_process_end { + assert!(entry.is_file(), "{}: an entry the scan allows is gone; update the list", entry.display()); + } + let (libc_exit, std_exit, exit_now) = + (concat!("process::", "exit("), concat!("libc::", "exit("), concat!("exit_", "now(")); + let mut hits = Vec::new(); + for f in files { + let path = f.to_string_lossy().replace('\\', "/"); + if path.ends_with("base/src/process.rs") + || path.contains("/storage_service/") + || path.contains("/tests/") + || path.ends_with("_tests.rs") + { + continue; + } + let text = std::fs::read_to_string(&f).expect("read"); + let prod = production_prefix(&text); + if path.ends_with("src/app/mod.rs") { + 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)" + ); + } + for (n, line) in prod.lines().enumerate() { + let code = line.split("//").next().unwrap_or(""); + if code.contains(libc_exit) + || code.contains(std_exit) + || (code.contains(exit_now) && !owns_process_end.contains(&f)) + { + hits.push(format!("{path}:{}", n + 1)); + } + } + } + assert!( + hits.is_empty(), + "exit through plx_base::process::exit_now from an entry that owns the process end, \ + never libc exit (#1115) and never from library code a host runs: {hits:?}" + ); + } + + /// 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 { + let lines: Vec<&str> = text.split_inclusive('\n').collect(); + let mut offset = 0; + for pair in lines.windows(2) { + let attr = pair[0].trim(); + let test_only = attr == "#[cfg(test)]" || attr.starts_with("#[cfg(all(test"); + if test_only && pair[1].contains("mod ") && pair[1].trim_end().ends_with('{') { + return &text[..offset]; + } + offset += pair[0].len(); + } + text + } + + fn collect_rs(dir: &std::path::Path, out: &mut Vec) { + for entry in std::fs::read_dir(dir).expect("read_dir").flatten() { + let p = entry.path(); + if p.is_dir() { + collect_rs(&p, out); + } else if p.extension().is_some_and(|e| e == "rs") { + out.push(p); + } + } + } + + /// The `App` itself: the rig builds a real one, which only a hostsim build with the Feed has. + #[cfg(all(feature = "hostsim", feature = "play-feed"))] + mod app_leak { + use super::*; + use crate::app::run::lifecycle_regression_tests::app; + + #[test] + fn the_returning_exit_path_leaks_the_app_so_nothing_under_it_drops() { + let _serial = plx_base::testlock::serial(); + let app = app(); + let dropped = app.drop_probe.counter(); + let exit = entry(|| Ok(app), |_| quit()); + assert_eq!(exit, quit()); + assert_eq!(dropped.load(Ordering::SeqCst), 0, "the probe is a field: no field of the App dropped"); + } + + #[test] + fn control_an_app_dropped_the_ordinary_way_trips_the_probe() { + let _serial = plx_base::testlock::serial(); + let app = app(); + let dropped = app.drop_probe.counter(); + drop(app); + assert_eq!(dropped.load(Ordering::SeqCst), 1, "the probe detects a drop"); + } + } +} diff --git a/rust-modules/src/app/mod.rs b/rust-modules/src/app/mod.rs index 1996146a90..341e151c8d 100644 --- a/rust-modules/src/app/mod.rs +++ b/rust-modules/src/app/mod.rs @@ -2,7 +2,8 @@ //! event loop, input decode, the per-frame tick, draw orchestration, app lifecycle, //! the buffer-feed pump orchestration, and the dev triggers. The C boot shim //! (main.c) sets up the log and fallback crash tracer, calls the Rust image-marker and native-spool -//! entries when required, then calls `plex_run` (port.rs), which hands over to `run_application`. +//! entries when required, then calls `plex_run` (port.rs), which hands over to `run_application` +//! and, when it returns its `Exit` (`exit.rs`), ends the process. //! The only application subsystems left in C are the starfish.c C++ Feed seam and the video_plane.c //! ACB / exported-window display binding (the engine itself is Rust: plx_media::player). #![allow(non_upper_case_globals)] @@ -131,6 +132,8 @@ mod clock_notice; mod hint_taught; mod recorder; mod window_activity; +mod exit; +pub(crate) use exit::Exit; pub(crate) mod events; pub(crate) mod lifecycle; pub(crate) mod playback; @@ -368,6 +371,12 @@ pub(crate) struct App { pub(crate) rec: recorder::Recplay, pub(crate) boot_initial: Option, pub(crate) telemetry_guard: Option, + /// The sentinel that proves the returning exit leaks the `App` (`exit::entry`): a counter its + /// own drop increments, so dropping the `App` drops it whatever the other fields are. A field, + /// not a static. Read by the hostsim lifecycle tests, which build the `App` the rig needs. + #[cfg(test)] + #[cfg_attr(not(all(feature = "hostsim", feature = "play-feed")), allow(dead_code))] + drop_probe: exit::DropProbe, /// The frame plan's GLASS half (spec §8.3): the layer/region source registry, shared chrome /// material and dev load dial. The budget half lives on the `Dispatcher` (§2.2). @@ -434,7 +443,7 @@ impl App { /// 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, - deferred: Option) -> Result { + deferred: Option) -> Result { boot::construct(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. @@ -558,7 +567,11 @@ fn pre_boot_diagnostics() -> plx_telemetry::telemetry::native::Guard { /// The run+teardown sequence `run_application` hands the mounted `App` to, split out for the same /// reason as [`pre_boot_diagnostics`] (D4): `run_application` stays a ten-line skeleton naming only /// the THREE real phases (pre-boot diagnostics, `boot`, this), never the steps inside any one of them. -unsafe fn run_and_shutdown(app: &mut App) -> ! { +/// +/// It RETURNS how the session ended; ending the process is the executable entry's (`port::plex_run`). +/// The `App` is leaked by the caller (`exit::entry`), so the last thing this does is the one `Drop` +/// that persists something. +unsafe fn run_and_shutdown(app: &mut App) -> Exit { run::run(app); // The crash record's phase (`src/crashtrace.c`): from here a fault is in the teardown. plx_base::task::watchdog::set_crash_phase(plx_base::task::watchdog::CrashPhase::Shutdown); @@ -568,12 +581,11 @@ unsafe fn run_and_shutdown(app: &mut App) -> ! { let failed = finish_recording(&mut app.rec, bridge.landgate()) || bridge.controlled_failure().is_some(); app.glass.sources.borrow_mut().clear(); - let code = i32::from(failed); - run::shutdown(&mut app.player.session, &mut app.adapters.player); + let release = run::shutdown(&mut app.player.session, &mut app.adapters.player); // The crash-channel guard is the one `Drop` that persists something (it closes the capture // backend and removes its database), so it runs here explicitly: nothing drops the `App`. drop(app.telemetry_guard.take()); - plx_base::process::exit_now(code) + Exit::played(failed, release) } fn finish_recording(rec: &mut recorder::Recplay, gate: &plx_machine::landgate::Gate) -> bool { @@ -597,7 +609,7 @@ 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(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")); @@ -617,7 +629,7 @@ fn enter_application(pms_host: *const c_char, pms_port: c_int) -> Result mode, - Err(reason) => { log(&format!("replay: REFUSED — {reason}")); return Err(1); } + Err(reason) => { log(&format!("replay: REFUSED — {reason}")); return Err(Exit::refused(1)); } }; // The player's `…` menu draws the Stats for nerds switch from the read-out's own flag, which // this layer owns and `appkit` cannot name, so it is handed the reader on EVERY boot (a @@ -639,11 +651,11 @@ fn enter_application(pms_host: *const c_char, pms_port: c_int) -> Result ! { - // An early-boot refusal ends the same way: the workers it has already started (diagnostics, - // capability probe, telemetry) are as live as after a played session. - let mut app = match enter_application(pms_host,pms_port) { Ok(app) => app, Err(code) => plx_base::process::exit_now(code) }; - unsafe { run_and_shutdown(&mut app) } +pub(crate) fn run_application(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) }) } diff --git a/rust-modules/src/app/run.rs b/rust-modules/src/app/run.rs index 831fbe7943..61912e3956 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::exit::{release_of, Release}; /// One lazy product frame-tail hash path for recording and replay grading alike. pub(super) fn recorder_end_frame( @@ -3706,24 +3707,23 @@ pub(crate) unsafe fn heartbeat(app: &mut App, fr: &mut Frame) { } } -/// Whether [`shutdown`] quits SDL before the process ends. EVERY exit ends the process with `_exit` -/// (`plx_base::process::exit_now`), never by returning into libc's `exit` (#1115); this is the one decision -/// left in the teardown. +/// Whether [`shutdown`] quits SDL before the process ends. The executable entry ends the process with +/// `_exit` (`plx_base::process::exit_now`), never by returning into libc's `exit` (#1115); this is the one +/// decision left in the teardown, and it is [`release_of`]'s: `SDL_Quit` runs exactly when the +/// release is `Complete`, so the hosted entry's report cannot say `Complete` where the executable +/// skipped it. pub(crate) fn quits_sdl(native_exit: plx_media::player::NativeExit) -> bool { - match native_exit { - plx_media::player::NativeExit::Clean => true, - // A native worker is still inside firmware: the display must not be torn down under it. - plx_media::player::NativeExit::WorkerInFirmware => false, - } + release_of(native_exit) == Release::Complete } /// Teardown after the loop: abandon the pending report, stop the active backend, wait for the stop /// scrobble, close the capture stream and the poster workers, quit SDL (unless a worker is still -/// in firmware). The caller (`app::run_and_shutdown`) then ends the process with `_exit`. +/// in firmware). Answers what it released: the caller (`app::run_and_shutdown`) returns it in the +/// `Exit`, and the executable entry then ends the process with `_exit`. pub(crate) unsafe fn shutdown( ps: &mut plx_media::route::PlaybackSession, pa: &mut plx_media::player::adapter::PlayerAdapter, -) { +) -> Release { ps.finish_metric_request(plx_media::player::attempt_metrics::RequestOutcome::Cancelled); pa.sync_request_metrics(ps); plx_media::player::report::abandon_pending(ps); @@ -3734,7 +3734,7 @@ pub(crate) unsafe fn shutdown( // object it is releasing left undestroyed. The wait is bounded, and a worker still inside // firmware (an overdue `Unload`, or a timed-out Load's media thread) means the display must not // be torn down under it, and nothing may run the firmware libraries' destructors either: the - // caller (`app::run_and_shutdown`) ends the process with `_exit`. + // executable entry ends the process with `_exit`, and the `App` is leaked (`app::exit::entry`). let native_exit = plx_media::player::exit_native(ps, pa); // The stop scrobble is posted off-thread now, and this process is about to die with any // worker still running — so THIS is the one place its result has to be waited for, or the @@ -3751,6 +3751,7 @@ pub(crate) unsafe fn shutdown( } else { log("shutdown: a native worker is still inside firmware; SDL_Quit skipped, exiting without unwinding"); } + release_of(native_exit) } /// Re-inject one recorded input (`app::recorder`'s encodings) for the frame being replayed: SDL @@ -3912,14 +3913,21 @@ unsafe fn controlled_key_input(app: &mut App, event: plx_machine::machine::Input } #[cfg(all(test, feature = "hostsim", feature = "play-feed"))] -mod lifecycle_regression_tests { +pub(in crate::app) mod lifecycle_regression_tests { use super::*; + /// Both answers, pinned for both variants: `SDL_Quit` runs exactly when the release is + /// `Complete`, so the hosted report cannot say `Complete` where the executable skipped it. #[test] fn shutdown_quits_sdl_only_when_no_worker_is_in_firmware() { use plx_media::player::NativeExit; assert!(!quits_sdl(NativeExit::WorkerInFirmware)); assert!(quits_sdl(NativeExit::Clean)); + assert_eq!(release_of(NativeExit::WorkerInFirmware), Release::Retained); + assert_eq!(release_of(NativeExit::Clean), Release::Complete); + for exit in [NativeExit::Clean, NativeExit::WorkerInFirmware] { + assert_eq!(quits_sdl(exit), release_of(exit) == Release::Complete, "{exit:?}: one decision, two readings"); + } } use std::io::{BufRead, BufReader, Read, Write}; use std::sync::{ @@ -3967,7 +3975,7 @@ mod lifecycle_regression_tests { } // No boot, renderer or device: the real App/event/frame phases with Bridge's host rig. - fn app() -> App { + pub(in crate::app) fn app() -> App { 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 { @@ -4106,6 +4114,7 @@ mod lifecycle_regression_tests { rec: super::super::recorder::Recplay::Off, boot_initial: Default::default(), telemetry_guard: Default::default(), + drop_probe: Default::default(), glass: Default::default(), pages: plx_ui::dispatch::Dispatcher::new(), diff --git a/rust-modules/src/port.rs b/rust-modules/src/port.rs index 9c0ef1f871..89f91fbf8f 100644 --- a/rust-modules/src/port.rs +++ b/rust-modules/src/port.rs @@ -52,16 +52,35 @@ static PORT: plx_os::tv::Port = plx_os::tv::Port { uri_media: plx_os::webos::URI_MEDIA, }; -/// The C shim's entry (`src/main.c`) and the simulator's (`src/bin/sim.rs`): install the port, then -/// hand over to `app::run_application`. +/// 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] 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 +/// with the status it returned. +/// +/// 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. +/// +/// It is typed `-> !` rather than left to diverge through its last expression. `src/main.c` does +/// `return plex_run(..)`, so an entry that returned would fall into `__libc_start_main`, which calls +/// libc `exit` directly (the interposer in `src/exit.c` cannot catch that), and `OPENSSL_cleanup` +/// would then free libcrypto's locks under the live curl workers (#1115). The `const` below is the +/// compile-time proof that replaced the ones `app::boot`'s `seam_order_tests` held for +/// `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); #[cfg(target_os = "linux")] let _ = plx_os::storage::client::install_activator(plx_os::webos::activate_storage_helper); - crate::app::run_application(pms_host, pms_port) + plx_base::process::exit_now(crate::app::run_application(pms_host, pms_port).code) } +const _: fn(*const c_char, c_int) -> ! = plex_main; + /// `src/main.c` hands over SAM's launch payload (`argv[1]`) before `plex_run`. Kept raw in /// `tv::launch`; `app::deeplink` reads it once the app has a session to act in. /// From 73e828109e3566924be26ffad89e4fd483def071 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 09:42:22 +0300 Subject: [PATCH 04/26] Make: a PLATFORM axis (webos, desktop, tizen), with no build change yet (#1482) `PLATFORM` is now a make variable with three values, `webos`, `desktop` and `tizen` (step W1 of the platform plan, discussion #1460). Nothing reads it yet, so no build changes. Later steps hang the per-platform crates and packaging on it. - The values come from `ci/platform_axis.py --list`, and `PLATFORM ?= webos`. A value that is not exactly one listed word, such as `webos bogus` or `%`, stops make before the stamp reset deletes anything. The file is not `ci/platform.py`, because a module of that name would shadow the stdlib `platform` for `ci/mkmacapp.py`, `ci/build-libass.py` and `ci/test-compat.py`. - `sim`, `sim-%`, `macapp` and `macapp-zip` imply `desktop` when PLATFORM was not given. An explicit value wins. The other goals that build the simulator (`check-replay`, `screenshots`, `screenshots-sim`, `site-video-sim`) imply nothing yet; that waits for W4. - `print-platform` and `print-rust-target` are query targets in `QUERY_GOALS`. `RUST_TARGET` does not move with PLATFORM. - PLATFORM is not exported, is not part of `RUST_CFG` or `RUST_TDIR`, and adds no cargo-running target. Like `FLAVOR`, an environment value is read. - `ci/test_platform_axis.py` (22 tests, in `ci/check-python-steps.txt`) covers the list, each value and each refusal, and the desktop implication over 16 sim and macapp goals. It also checks that a refused value and both queries leave a seeded stamp and binary alone in a scratch tree, and the stdlib-shadow guard. - `make -n` is byte-identical to before for the default goal, `ipk`, `RELEASE=1 ipk`, `FLAVOR=stable RELEASE=1 ipk`, `sim-macos`, `sim-linux`, `macapp`, `lint`, `check-nodef` and `test-hostsim`. Each make pays one more python start, measured at +12 ms. --- Makefile | 39 ++++- ci/check-python-steps.txt | 6 + ci/platform_axis.py | 39 +++++ ci/test_platform_axis.py | 338 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 421 insertions(+), 1 deletion(-) create mode 100755 ci/platform_axis.py create mode 100644 ci/test_platform_axis.py diff --git a/Makefile b/Makefile index d63e98292b..c14578a7fd 100644 --- a/Makefile +++ b/Makefile @@ -128,6 +128,37 @@ $(if $(strip $(FLAVORS)),,$(error ci/flavor.py --list produced no flavours — i FLAVOR ?= debug $(if $(filter $(FLAVOR),$(FLAVORS)),,$(error unknown FLAVOR "$(FLAVOR)" — one of: $(FLAVORS))) +# --- WHICH OS: the PLATFORM axis ----------------------------------------------------------- +# +# `webos` (the television this file has always built for, and the default), `desktop` (the macOS and +# Windows/WSLg simulators and the macOS app) or `tizen` (a name only: no goal builds it yet). It is the +# TARGET OS and nothing else. FLAVOR stays the install identity, and the compatibility axis — the Rust +# target (`RUST_TARGET`), the sysroot (`SYSROOT`) and, once a platform needs them, a managed TFM, a +# firmware floor and the signing path — stays a set of separate variables that PLATFORM does not choose: +# `make -s print-rust-target` answers the same under every PLATFORM. Today the axis labels and validates; +# no recipe reads it, so the default `PLATFORM=webos` builds exactly what it built before the axis existed. +# +# The simulators and the macOS app are desktop builds, so `sim`, `sim-*`, `macapp` and `macapp-zip` imply +# PLATFORM=desktop when it was not given: `$(origin PLATFORM)` is `undefined` (not on the command line, +# not in the environment), and an explicit value wins. It is one value per invocation, read from the whole +# goal list. The target names themselves do not change. This sits ABOVE the `?=`, so the literal default +# line below stays the one place that says `webos`. +# +# Validated against `ci/platform_axis.py --list` the way FLAVOR is against `ci/flavor.py --list`, for the +# same reason: `make PLATFORM=webso ...` must be a message on a terminal, not a build of something nobody +# asked for. One word, exactly (a `filter` of the value against the list would also pass `webos bogus` +# and `%`). The script is NOT `ci/platform.py`: scripts run from ci/ `import platform` (`mkmacapp.py`, +# `build-libass.py`, `test-compat.py`), and a file of that name would shadow the standard library for them. +PLATFORMS := $(shell python3 ci/platform_axis.py --list) +$(if $(strip $(PLATFORMS)),,$(error ci/platform_axis.py --list produced no platforms — is python3 available and does ci/platform_axis.py run?)) +ifeq ($(origin PLATFORM),undefined) +ifneq ($(filter sim sim-% macapp macapp-zip,$(MAKECMDGOALS)),) +PLATFORM := desktop +endif +endif +PLATFORM ?= webos +$(if $(and $(filter 1,$(words $(PLATFORM))),$(filter $(PLATFORMS),$(PLATFORM))),,$(error unknown PLATFORM "$(PLATFORM)" — one of: $(PLATFORMS))) + # The id users get. Also `paths::STABLE_APP_ID` in the Rust half and `STABLE_ID` in ci/flavor.py — # three copies of one string, each in a language that cannot see the others, and ci/flavor.py's # selftest is what keeps them in step. @@ -185,7 +216,8 @@ APPPORT = $(if $(filter stable,$(FLAVOR)),8910,$(if $(filter nightly,$(FLAV QUERY_GOALS = print-flavor print-appid print-appdir print-rundir print-eventlog print-appport print-tv print-playback-config \ print-simbin print-app-files print-deploy-files print-sentry-handler print-ffmpeg-staged \ print-sentry-project print-bench-config print-disk-entries \ - print-subs-font-files print-rust-toolchain print-rust-codegen print-cargo-env + print-subs-font-files print-rust-toolchain print-rust-codegen print-cargo-env \ + print-platform print-rust-target print-flavor: ; @echo '$(FLAVOR)' print-appid: ; @echo '$(APPID)' print-appdir: ; @echo '$(APPDIR)' @@ -193,6 +225,11 @@ print-rundir: ; @echo '$(RUNDIR)' print-eventlog: ; @echo '$(EVENTLOG)' print-appport: ; @echo '$(APPPORT)' print-tv: ; @echo '$(TV)' +# The PLATFORM axis (above) and the Rust target the ARM recipes cross-compile for. They are two queries +# because they are two axes: PLATFORM does not choose the Rust target, so `print-rust-target` does not +# move with it. Both are in QUERY_GOALS, so asking resets nothing under `pkg/`. +print-platform: ; @echo '$(PLATFORM)' +print-rust-target: ; @echo '$(RUST_TARGET)' # Where `make sim` put the simulator. It is `$(SIM_TDIR)`-derived and `SIM_TDIR` is deliberately # overridable — agents running several simulators at once keep separate target dirs, and the # `macapp` build has its own — so a tool that restates the path silently runs another lane's diff --git a/ci/check-python-steps.txt b/ci/check-python-steps.txt index 438be11606..090455210f 100644 --- a/ci/check-python-steps.txt +++ b/ci/check-python-steps.txt @@ -438,3 +438,9 @@ python3 ci/test_runtime_ownership_borrows.py # systemMessage, under the 10,000 character cap), the settings.json registrations, and a real process with a stub standing in for # `build-gc.sh --auto` (detached, own session, output in the log). Never starts the real build-gc; temp dirs only; no sleeping on a timer. python3 .claude/hooks/disk-low-notify-test.py +# The PLATFORM build axis (Makefile `PLATFORM`, ci/platform_axis.py --list): default `webos`, the three names accepted from the command line +# and the environment, anything else refused at parse time, `sim`/`sim-*`/`macapp`/`macapp-zip` implying `desktop` (read from a dry run in a +# scratch tree, where an explicit value still wins), `print-rust-target` unmoved by it, both new queries leaving a built `pkg/` alone, and +# that the selector is not named `platform.py`: scripts in ci/ import the stdlib `platform`, so a probe from ci/, every existing consumer and +# a shadow control are run. No cargo; the scratch trees are private temp dirs. +python3 ci/test_platform_axis.py diff --git a/ci/platform_axis.py b/ci/platform_axis.py new file mode 100755 index 0000000000..146c0bb1ea --- /dev/null +++ b/ci/platform_axis.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""The PLATFORM build axis: which operating system a build targets. + +`PLATFORM` in the Makefile is one of the values below, and the Makefile reads them from `--list` +the way it reads FLAVOR's from `ci/flavor.py --list`, so a mistyped `make PLATFORM=webso ...` is +refused at parse time instead of building something nobody asked for: + + webos the LG webOS television (armv7, the `.ipk`): what every target built before the axis + existed, and the default. + desktop the macOS and Windows/WSLg simulators and the macOS app (`sim-*`, `macapp`): the Makefile + makes it the default for those goals. + tizen the Samsung Tizen television (the `.tpk`). Only the name exists yet; no goal builds it. + +The axis is the TARGET OS and nothing else. It does not choose the compatibility axis: the Rust +target (`RUST_TARGET`), the sysroot (`SYSROOT`), a managed TFM, a firmware floor and the signing +path stay separate variables, each recorded once per tested configuration, so adding a platform never +changes what another one links. FLAVOR stays the install identity (`debug`, `nightly`, `stable`) and +is orthogonal to it. + +THIS FILE IS NOT NAMED `platform.py`. Scripts in `ci/` (`mkmacapp.py`, `build-libass.py`, +`test-compat.py`) `import platform` for `system()` and `machine()`, and Python puts a script's own +directory first on `sys.path`, so a `ci/platform.py` would replace the standard library module for +every one of them. `ci/test_platform_axis.py` runs them from this directory to keep it that way. + +It imports nothing but `sys`: the Makefile spawns it on every `make` invocation, as it does +`ci/flavor.py`, and each import adds to that bill. +""" +import sys + +# Order is the order the Makefile's error message lists them in. The default is the Makefile's +# `PLATFORM ?= webos`, not a property of this list. +PLATFORMS = ("webos", "desktop", "tizen") + +if __name__ == "__main__": + if sys.argv[1:] == ["--list"]: + print(" ".join(PLATFORMS)) + sys.exit(0) + print(__doc__) + sys.exit(2) diff --git a/ci/test_platform_axis.py b/ci/test_platform_axis.py new file mode 100644 index 0000000000..cba11976a9 --- /dev/null +++ b/ci/test_platform_axis.py @@ -0,0 +1,338 @@ +#!/usr/bin/env python3 +"""The PLATFORM build axis (the Makefile's `PLATFORM`, `ci/platform_axis.py`): what it accepts, what it +implies, what it must not change, and that its script is not named after the standard library. + +* `ci/platform_axis.py --list` names `webos desktop tizen`, and the Makefile reads that list the way it + reads FLAVOR's from `ci/flavor.py --list`. +* `PLATFORM` defaults to `webos`, takes any of the three from the command line or the environment, and + refuses anything else at parse time: an unknown name, an empty one, two words, a `%` (a `filter` of the + value against the list would pass the last two). +* The refusal comes before the Makefile's stamp reset, whatever the goal: a mistyped `PLATFORM` beside a + goal that builds must not delete the last build's binary. That is read from a seeded scratch tree, by + the files surviving (a refusal below the reset would still print the same error). +* `sim`, `sim-*`, `macapp` and `macapp-zip` imply `desktop` when `PLATFORM` was not given and an explicit + value wins. That depends on the GOALS, and `make -s print-platform sim-macos` would BUILD the simulator, + so it is read from a dry run (`make -n`, which prints the recipe line `echo 'desktop'` instead of running + it) in a scratch tree: a dry run beside a goal that builds is not a pure query, so its parse-time reset + of `pkg/` (see ci/test_arm_profile.py) must not reach this checkout. +* The compatibility axis is not the platform axis: `print-rust-target` answers the same under every + `PLATFORM`. +* Both new query goals are in the Makefile's side-effect-free set: asking resets nothing under `pkg/`. A + control proves the seeded tree below would have been reset by a goal that builds. +* The script's name. Scripts in ci/ `import platform` and Python puts a script's own directory first on + `sys.path`, so a `ci/platform.py` would replace the standard library module for all of them. A probe run + from `ci/` must get the real one, each existing consumer must import it from there, and a control proves + the probe would notice a shadow. + +Pure queries run from the checkout. Everything that dry-runs a goal runs in a scratch tree that symlinks the +checkout's files but owns real `pkg/` and `vendor/` directories, and never dry-runs a goal whose recipe +re-enters make (`check`, `install`...): `$(MAKE)` lines run even under `-n`. +""" +from __future__ import annotations + +import ast +import importlib.util +import os +import re +import subprocess +import sys +import tempfile +import textwrap +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +CI = ROOT / "ci" +PLATFORMS = ("webos", "desktop", "tizen") +RUST_TARGET = "armv7-unknown-linux-gnueabi" +# What the Makefile reads the environment for, which a developer's shell or an outer make may have set. +SCRUBBED = ("MAKEFLAGS", "MFLAGS", "MAKELEVEL", "PLATFORM", "FLAVOR", "RELEASE", "SYMBOLS", "LAB", "CI", + "GITHUB_ACTIONS", "ARM_PROFILE", "TV", "PLAYBACK_BACKENDS", "SIM_TDIR", "MACAPP_TDIR") +# The goals the Makefile implies `desktop` for, one per kind of recipe: the simulators, their aliases and +# their helpers, and the macOS app. Every one is dry-run below; none of them re-enters make. +DESKTOP_GOALS = ("sim", "sim-macos", "sim-linux", "sim-wsl", "sim-run", "sim-macos-run", "sim-shot", + "sim-macos-shot", "sim-token", "sim-macos-token", "sim-play", "sim-macos-play", "sim-clean", + "sim-macos-clean", "macapp", "macapp-zip") +# Goals that build the television package: they stay on the default. (Not `check` or `install`, whose +# recipes run `$(MAKE)` even under `-n`.) +WEBOS_GOALS = ("all", "ipk") +STAMP = "pkg/.build-config" +BINARY = "pkg/plxnative" +SEEDED_STAMP = "seeded by test_platform_axis" + + +def environment(extra: dict[str, str] | None = None) -> dict[str, str]: + env = {k: v for k, v in os.environ.items() if k not in SCRUBBED} + env.update(extra or {}) + return env + + +def make(*args: str, cwd: Path = ROOT, dry: bool = False, env: dict[str, str] | None = None + ) -> subprocess.CompletedProcess: + cmd = ["make", "-n" if dry else "", "-s", "--no-print-directory", "-C", str(cwd), *args] + return subprocess.run([c for c in cmd if c], capture_output=True, text=True, env=environment(env), + timeout=120) + + +class PlatformList(unittest.TestCase): + def run_script(self, *args: str) -> subprocess.CompletedProcess: + return subprocess.run([sys.executable, str(CI / "platform_axis.py"), *args], capture_output=True, + text=True, timeout=30) + + def test_the_list_names_the_three_platforms(self): + proc = self.run_script("--list") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stdout, "webos desktop tizen\n") + + def test_anything_else_is_a_usage_error(self): + for args in ((), ("--bogus",), ("--list", "extra"), ("webos",)): + with self.subTest(args=args): + proc = self.run_script(*args) + self.assertEqual(proc.returncode, 2) + self.assertNotEqual(proc.stdout.splitlines()[:1], ["webos desktop tizen"]) + + def test_it_imports_nothing_but_sys(self): + """Every `make` invocation spawns it (it is the FLAVOR cost again), and each import adds to the bill.""" + tree = ast.parse((CI / "platform_axis.py").read_text()) + imported = {alias.name for node in ast.walk(tree) if isinstance(node, ast.Import) for alias in node.names} + imported |= {node.module for node in ast.walk(tree) if isinstance(node, ast.ImportFrom)} + self.assertEqual(imported, {"sys"}) + + def test_the_makefile_reads_the_list_the_way_it_reads_flavors(self): + text = (ROOT / "Makefile").read_text() + self.assertRegex(text, r"(?m)^PLATFORMS\s*:=\s*\$\(shell python3 ci/platform_axis\.py --list\)\s*$") + self.assertRegex(text, r"(?m)^PLATFORM\s*\?=\s*webos\s*$") + + +class PlatformVariable(unittest.TestCase): + def query(self, *args: str, env: dict[str, str] | None = None) -> str: + proc = make("print-platform", *args, env=env) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + return proc.stdout.strip() + + def test_the_default_is_webos(self): + self.assertEqual(self.query(), "webos") + + def test_every_listed_platform_is_accepted_from_the_command_line_and_the_environment(self): + for platform in PLATFORMS: + with self.subTest(platform=platform): + self.assertEqual(self.query(f"PLATFORM={platform}"), platform) + self.assertEqual(self.query(env={"PLATFORM": platform}), platform) + + def test_anything_else_is_refused_at_parse_time(self): + for value in ("webso", "WEBOS", "", "webos bogus", "webos webos", "%", "web%", "android"): + with self.subTest(value=value): + proc = make("print-platform", f"PLATFORM={value}") + self.assertNotEqual(proc.returncode, 0) + self.assertEqual(proc.stdout, "") + self.assertIn(f'unknown PLATFORM "{value}"', proc.stderr) + self.assertIn("one of: webos desktop tizen", proc.stderr) + + def test_the_rust_target_is_not_chosen_by_the_platform(self): + """The compatibility axis (Rust target, sysroot, TFM, firmware floor, signing) is separate.""" + for platform in PLATFORMS: + with self.subTest(platform=platform): + proc = make("print-rust-target", f"PLATFORM={platform}") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stdout.strip(), RUST_TARGET) + self.assertEqual(make("print-rust-target").stdout.strip(), RUST_TARGET) + + def test_the_existing_queries_do_not_move(self): + """`make -s print-flavor print-appid` is what every tool asks, and PLATFORM changes neither.""" + for platform in PLATFORMS: + with self.subTest(platform=platform): + proc = make("print-flavor", "print-appid", "print-appport", f"PLATFORM={platform}") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stdout.split(), ["debug", "com.beb.plxnative.debug", "8911"]) + + +class ScratchTree(unittest.TestCase): + """A scratch checkout to dry-run goals in. It holds symlinks to the checkout's own files (the Makefile + reads `ci/` and `tools/` while it parses) and REAL `pkg/` and `vendor/` directories, because the + parse-time reset removes paths under exactly those two and, through a symlink, would delete this + checkout's binary and its FFmpeg header sentinel (ci/test_arm_profile.py has the whole account).""" + + def setUp(self): + td = tempfile.TemporaryDirectory(prefix="plx-platform.") + self.addCleanup(td.cleanup) + self.tree = Path(td.name) + for entry in ROOT.iterdir(): + if entry.name not in (".git", "pkg", "vendor"): + (self.tree / entry.name).symlink_to(entry) + (self.tree / "pkg").mkdir() + (self.tree / "vendor").mkdir() + # The package's tracked inputs, so `ipk` has what it names; build outputs stay out. + (self.tree / "pkg/appinfo.json").write_text((ROOT / "pkg/appinfo.json").read_text()) + + def dry(self, *args: str, env: dict[str, str] | None = None) -> list[str]: + """The recipe lines a dry run printed. `-n` prints even an `@`-silenced line, minus the `@`.""" + proc = make(*args, cwd=self.tree, dry=True, env=env) + self.assertEqual(proc.returncode, 0, (args, proc.stderr[-400:])) + return proc.stdout.splitlines() + + def seed(self) -> None: + """The tree the way a finished build leaves it: a stamp that is not the current configuration's (so + the parse-time reset would rewrite it) and a built binary (which the reset would delete).""" + (self.tree / STAMP).write_text(SEEDED_STAMP) + (self.tree / BINARY).write_text("a built binary\n") + + def assert_untouched(self, what: str) -> None: + self.assertEqual((self.tree / STAMP).read_text(), SEEDED_STAMP, f"{what} rewrote the build stamp") + self.assertTrue((self.tree / BINARY).exists(), f"{what} deleted a built binary") + + +class ImpliedPlatform(ScratchTree): + def platform_of(self, *goals: str, env: dict[str, str] | None = None) -> str: + """The value `print-platform` would print beside these goals: its recipe line `echo ''`.""" + shown = [m.group(1) for line in self.dry("print-platform", *goals, env=env) + if (m := re.fullmatch(r"echo '(webos|desktop|tizen)'", line))] + self.assertEqual(len(shown), 1, (goals, shown)) + return shown[0] + + def test_the_simulators_and_the_macos_app_imply_desktop(self): + for goal in DESKTOP_GOALS: + with self.subTest(goal=goal): + self.assertEqual(self.platform_of(goal), "desktop") + + def test_goals_that_build_the_television_package_stay_on_the_default(self): + for goal in WEBOS_GOALS: + with self.subTest(goal=goal): + self.assertEqual(self.platform_of(goal), "webos") + self.assertEqual(self.platform_of(), "webos") + + def test_a_goal_that_is_not_one_of_them_does_not_imply_it(self): + self.assertEqual(self.platform_of("print-appid"), "webos") + self.assertEqual(self.platform_of("print-appid", "ipk"), "webos") + + def test_an_explicit_value_wins_over_the_implication(self): + self.assertEqual(self.platform_of("sim-macos", "PLATFORM=webos"), "webos") + self.assertEqual(self.platform_of("macapp", "PLATFORM=tizen"), "tizen") + self.assertEqual(self.platform_of("sim-macos", env={"PLATFORM": "webos"}), "webos") + self.assertEqual(self.platform_of("all", "PLATFORM=desktop"), "desktop") + + def test_asking_never_resets_a_built_tree_and_a_building_goal_does(self): + """Seed a tree the way a finished build leaves it, then ask the two new questions: nothing moves. The + control (a goal that builds, beside the same query) must reset the same files, or this proves nothing.""" + for goal in ("print-platform", "print-rust-target"): + with self.subTest(goal=goal): + self.seed() + for args in ((goal,), (goal, "PLATFORM=desktop"), (goal, "PLATFORM=tizen")): + proc = make(*args, cwd=self.tree) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assert_untouched(f"make {goal}") + self.seed() + self.dry("print-platform", "all") + self.assertFalse((self.tree / BINARY).exists(), "control: a building goal must reset the seeded tree") + self.assertNotEqual((self.tree / STAMP).read_text(), SEEDED_STAMP) + + def test_the_queries_are_registered_as_queries(self): + text = (ROOT / "Makefile").read_text().replace("\\\n", " ") + for goal in ("print-platform", "print-rust-target"): + with self.subTest(goal=goal): + self.assertRegex(text, rf"(?m)^QUERY_GOALS\s*=[^\n]*\b{goal}\b") + self.assertRegex(text, rf"(?m)^{goal}:") + + +class RefusedPlatform(ScratchTree): + def test_a_refused_value_is_refused_whatever_the_goal(self): + """The refusal is at parse time, above the stamp reset that deletes `pkg/plxnative` and the staged + libraries, so a mistyped value beside a goal that builds (`all`, `sim-macos`) leaves a built tree + alone. The error text alone cannot show that (a refusal moved below the reset prints the same line + after the reset ran), so the seeded stamp and binary must survive. The control in `ImpliedPlatform` + shows that a building goal does reset them.""" + for goal in ("all", "sim-macos", "print-appid"): + with self.subTest(goal=goal): + self.seed() + proc = make("PLATFORM=bogus", goal, cwd=self.tree, dry=True) + self.assertNotEqual(proc.returncode, 0) + self.assertIn('unknown PLATFORM "bogus"', proc.stderr) + self.assert_untouched(f"make PLATFORM=bogus {goal}") + + +def stdlib_names() -> frozenset[str]: + return frozenset(getattr(sys, "stdlib_module_names", ())) | {"platform"} + + +def imports_platform(path: Path) -> bool: + tree = ast.parse(path.read_text()) + return any(isinstance(node, ast.Import) and any(alias.name == "platform" for alias in node.names) + for node in ast.walk(tree)) + + +def consumers() -> list[Path]: + """The scripts in ci/ that import the standard library's `platform`.""" + return sorted(p for p in CI.glob("*.py") if p != Path(__file__).resolve() and imports_platform(p)) + + +# Imports a file the way a script run from its own directory sees its imports: that directory first on +# `sys.path`. Prints where `platform` came from and what `platform.system()` answered. +PROBE = textwrap.dedent("""\ + import importlib.util, pathlib, sys + here = pathlib.Path(sys.argv[1]) + sys.path.insert(0, str(here)) + if len(sys.argv) > 2: + spec = importlib.util.spec_from_file_location("consumer", sys.argv[2]) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + platform = module.platform + else: + import platform + print(platform.__file__) + print(platform.system() != "" and platform.machine() != "") + """) + + +class StandardLibraryIsNotShadowed(unittest.TestCase): + def probe(self, directory: Path, consumer: Path | None = None) -> tuple[Path, str]: + args = [sys.executable, "-B", "-c", PROBE, str(directory)] + ([str(consumer)] if consumer else []) + proc = subprocess.run(args, capture_output=True, text=True, timeout=60, cwd=directory) + self.assertEqual(proc.returncode, 0, proc.stderr) + where, works = proc.stdout.splitlines() + return Path(where).resolve(), works + + def test_there_are_consumers_to_protect(self): + self.assertGreaterEqual({p.name for p in consumers()}, + {"mkmacapp.py", "build-libass.py", "test-compat.py"}) + + def test_nothing_in_ci_is_named_like_a_standard_library_module(self): + shadows = sorted(p.name for p in CI.iterdir() + if (p.suffix == ".py" or (p / "__init__.py").exists()) and p.stem in stdlib_names()) + self.assertEqual(shadows, [], "a module in ci/ shadows the standard library for every script run from ci/") + + def test_a_probe_run_from_ci_gets_the_real_platform(self): + where, works = self.probe(CI) + self.assertNotEqual(where.parent, CI.resolve()) + self.assertEqual((where.name, works), ("platform.py", "True")) + + def test_every_existing_consumer_imports_the_real_platform_from_ci(self): + for script in consumers(): + with self.subTest(script=script.name): + where, works = self.probe(CI, script) + self.assertNotEqual(where.parent, CI.resolve()) + self.assertEqual((where.name, works), ("platform.py", "True")) + + def test_the_consumers_that_parse_arguments_still_start_from_ci(self): + for script in ("test-compat.py", "mkmacapp.py"): + with self.subTest(script=script): + proc = subprocess.run([sys.executable, script, "--help"], capture_output=True, text=True, + timeout=60, cwd=CI) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn("usage:", proc.stdout.lower()) + + def test_the_probe_notices_a_shadow(self): + """The control: with a `platform.py` beside the script the same probe must report that file, or the + tests above would pass whatever ci/ held.""" + with tempfile.TemporaryDirectory(prefix="plx-shadow.") as td: + fake = Path(td) + (fake / "platform.py").write_text('def system():\n return "shadow"\n\ndef machine():\n return "shadow"\n') + consumer = fake / "consumer.py" + consumer.write_text("import platform\n") + for use in (None, consumer): + with self.subTest(consumer=bool(use)): + where, _ = self.probe(fake, use) + self.assertEqual(where, (fake / "platform.py").resolve()) + + +if __name__ == "__main__": + unittest.main() From d6125c847d2261640be95eb52af79ca7424ea809 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 11:46:46 +0300 Subject: [PATCH 05/26] tv::Port becomes tv::Services; the shell and frame probes move to app::Platform (#1483) The bottom layer's hook table is split by who reads it (step W2 of the platform plan, discussion #1460). The lower layers keep `tv::Services`. The window, bus and frame-probe entries, which only the loop reads, move to an app-private `app::Platform` that `run_application` takes as a parameter. webOS and the simulator behave as before. - `plx_os::tv::Port` (27 fields) becomes `tv::Services` with the same function pointers in four groups: - `identity { probe_device, start_capability_probe, repair_sandbox, system_locale, sound_output }`; - `secure { seal, open, remove, mode }`, which absorbs W3a's separate once-set mode and `publish_mode`. `secure::mode()` keeps its signature and still reads the test override first; - `system { go_home, poll_home, deliver_toast }`; - `legacy_webos_media { sink, display_sink, uri_media }`. Every hook is required, and each group has a named `NONE`. `Services::HOST_TEST` replaces `ABSENT`. The install is still once-only. - The seven window and bus entries become the `Shell` trait and the six frame probes become `FrameProbe`. Both live in `app/platform.rs` beside the loop, and `tv/window.rs` is deleted. - `app::Platform { services, shell, diag }`. `Platform::new` builds it, and `install_services` is the only reader of the private `services`, so app code cannot call a raw hook past the guards in `tv`'s modules. - `run_application(platform, ..)` installs the services, and `App.platform` holds the platform at both construction sites. - Boot code that runs before `App` exists takes it as a parameter, and the bridge's opaque-region hooks read the shell from `BridgeRetained`. - `Platform::HOST_TEST` is `#[cfg(test)]`, so a production entry cannot boot with the no-op shell. - `port.rs` builds the webOS `SERVICES` and `PLATFORM` over the same `crate::system` functions as before. `plex_main` installs gfx's thread-local clear-probe hook. `plex_run` and the proof that `plex_main` never returns are unchanged. - The #1479 scan also asserts that `fn plex_run(` and `fn plex_main(` each occur exactly once in `port.rs`. A second, cfg-gated `plex_run` no longer passes it. - The `frame` gate in `ci/check-deps.sh` pins the call text of `pump_bus`, `opaque_route` and `clear_opaque_region` to `app/run.rs`. It matches the shell receiver, the trait path, and a chained call whose previous line ends in `shell`, so the bridge `Rig` trait's methods of the same name pass. Two self-tests in `tests/test_harness.py` cover both cases. On the dev set, three `--guest --mock` boots (this change, main, main) each reached idle Home and closed with `APP_CLOSED`, `exit_status: 0`. The logs match within the noise floor, apart from a race in the order of two lines and a one-block difference in the image cache's cap. --- ci/check-deps.sh | 43 +++- ci/module-layers.ini | 15 +- docs/agent-reference.md | 2 +- docs/module-layers.md | 28 +-- rust-modules/gfx/src/gfx.rs | 8 +- rust-modules/os/src/tv.rs | 220 ++++++++++++------ 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 | 30 ++- rust-modules/src/app/bootstrap/tests.rs | 12 +- rust-modules/src/app/bridge.rs | 40 ++-- .../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 | 114 ++++++--- rust-modules/src/app/home_admission_tests.rs | 2 +- .../app/metadata_alt_sources_bridge_tests.rs | 2 +- rust-modules/src/app/mod.rs | 22 +- rust-modules/src/app/notify_bridge_tests.rs | 2 +- rust-modules/src/app/platform.rs | 169 ++++++++++++++ rust-modules/src/app/recorder.rs | 4 +- .../src/app/recording_erasure_tests.rs | 2 +- rust-modules/src/app/run.rs | 58 ++--- .../src/app/session_dispatch_tests.rs | 2 +- .../src/app/viewstate_controlled_tests.rs | 2 +- rust-modules/src/port.rs | 140 +++++++---- tests/test_harness.py | 43 ++++ 36 files changed, 735 insertions(+), 350 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..f48a647e67 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,27 @@ 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`, 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, # 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` (`app.platform.shell.pump_bus()`, `p.shell.opaque_route(..)`), on the +# 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 # 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,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='(crate|plx_os)::tv::window::(pump_bus|opaque_route|clear_opaque_region)\(' +# `[.]` 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%%:*}" @@ -1119,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 @@ -1158,7 +1179,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/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/docs/agent-reference.md b/docs/agent-reference.md index 15db8fcdde..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 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 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 566838556b..4561d00c55 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 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 `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`, 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` | -`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` 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. @@ -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/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)))); } diff --git a/rust-modules/os/src/tv.rs b/rust-modules/os/src/tv.rs index adfeb02b4a..558ecb9aa0 100644 --- a/rust-modules/os/src/tv.rs +++ b/rust-modules/os/src/tv.rs @@ -9,107 +9,195 @@ 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, 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 /// 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..21acced293 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))] @@ -525,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" ); @@ -554,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" @@ -600,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); } @@ -1381,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, @@ -1389,11 +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( - plx_os::tv::window::frame_probe_waiting, - plx_os::tv::window::frame_probe_acquired, - ); let initial = match &preflight { super::bootstrap::Preflight::Live => None, super::bootstrap::Preflight::Record => { @@ -1406,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), } } @@ -1453,7 +1450,7 @@ pub(super) fn resume_stored(pages: &mut plx_ui::dispatch::Dispatcher, deferred: Option, ) -> Result { @@ -1647,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. - 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 +1653,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()?; @@ -1834,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); @@ -2408,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 391d0799c4..e08e35cfa1 100644 --- a/rust-modules/src/app/bridge.rs +++ b/rust-modules/src/app/bridge.rs @@ -32,9 +32,10 @@ //! 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 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 { @@ -3371,13 +3379,13 @@ 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); + 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 786354c0fd..0b9ed5ec6e 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(&PLATFORM, 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/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 341e151c8d..e6966f1e4c 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; @@ -405,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 { @@ -441,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. /// @@ -609,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")); @@ -645,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) }) + 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/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 new file mode 100644 index 0000000000..d9ffd985a5 --- /dev/null +++ b/rust-modules/src/app/platform.rs @@ -0,0 +1,169 @@ +//! The platform the application runs on, as only the loop reads it. +//! +//! [`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). +//! `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 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; + +/// 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 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). + 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 by the platform's entry (`port.rs` for +/// 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 { + services: &'static Services, + pub(crate) shell: &'static dyn Shell, + pub(crate) diag: &'static dyn FrameProbe, +} + +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) {} + 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. Test builds only. +#[cfg(test)] +struct HostProbe; + +#[cfg(test)] +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() + } +} + +#[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`. 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)] +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"); + } +} 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 61912e3956..4dc98fe9de 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::Shell; 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(); + 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(); @@ -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(); + app.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(); + 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()); } @@ -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(); + 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()); } @@ -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); + 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). @@ -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 -/// `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) { - plx_os::tv::window::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 `plx_os::tv::window::clear_opaque_region` was before the move. -pub(crate) fn rig_clear_opaque_region() { - plx_os::tv::window::clear_opaque_region(); +/// 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(shell: &dyn Shell) { + 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(); + app.platform.diag.request(); SDL_GL_SwapWindow(app.win); } app.window_activity.presented(fr.player); @@ -1171,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, @@ -3128,7 +3131,7 @@ pub(crate) unsafe fn draw(app: &mut App, fr: &mut Frame) -> (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 +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. - 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 +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), - plx_os::tv::window::frame_probe_fields() + app.platform.diag.fields() ) }) { log(&line); @@ -3979,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(), @@ -8263,7 +8267,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 +8570,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 +11194,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 +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 = " plx_os::tv::window::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 89f91fbf8f..060fad0397 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 hands them over. //! -//! 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 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}; #[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,90 @@ 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: 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::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. #[no_mangle] @@ -59,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 port, 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. @@ -73,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) -> ! { - let _ = plx_os::tv::install(&PORT); #[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; @@ -97,7 +154,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 +163,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..efb4c5d575 100644 --- a/tests/test_harness.py +++ b/tests/test_harness.py @@ -10381,6 +10381,49 @@ 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(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(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, 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" + " 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", + ) + 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 1adff841e5e6120c894cde34ab2ef84b854688cd Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 13:12:54 +0300 Subject: [PATCH 06/26] Lifecycle and quit reach the loop as a HostEvent (#1484) Quit and the four app-switch edges now reach the loop as an app-private `HostEvent` instead of raw SDL codes. This is step W5a of the platform plan, the first step of the event contract (discussion #1460). A hosted platform will deliver its stop as the same `HostEvent::Quit`. webOS and the simulator behave as before. - `app/events.rs` gains `HostEvent { Lifecycle(Lifecycle), Quit }` and `Lifecycle { WillBackground, DidBackground, WillForeground, DidForeground }`. `decode_host_event` maps SDL `0x100` and `0x103`-`0x106` to them. Every other event returns `None` and keeps today's raw path; keys, text and pointer are W5b and W5c. - In `app/run.rs`, the drain decodes first and hands a `HostEvent` to `ingest_host_event`, which routes both background edges to `host_background` and both foreground edges to `host_foreground`. The effects run in the base's order: 1. window activity and the window telemetry; 2. `session::lifecycle` on `0x106`; 3. the controlled-replay restore and refusal; 4. the presentation damage note; 5. the recorder; 6. the park or resume of playback, or the quit. `ingest_sdl_event_with_window` keeps its name, because `ci/list-caps.ini` keys an entry on it. - The recorder still writes the SDL code (`Lifecycle::sdl_code()`), so tapes are byte-equal, and a quit is still not recorded. - The source pin in `ui/src/fixture.rs`, which proves the loop delivers an app switch to every body, now finds `host_background` and `host_foreground`, bounded to each function's body. It also pins `ingest_host_event`'s arms, which send both edges of each pair to them. - The tests feed each event both ways, as SDL bytes and as a `HostEvent`, and compare what the loop leaves: - quit, during playback and during a controlled replay; - a full park and resume, including the crash-step trail; - a WILL edge sent alone, which must do its own work (the test fails if either arm is narrowed to its DID edge); - the recorded tape. --- rust-modules/src/app/events.rs | 117 ++++ rust-modules/src/app/recorder.rs | 25 + rust-modules/src/app/run.rs | 640 +++++++++++++----- .../telemetry/src/telemetry/window.rs | 4 +- rust-modules/ui/src/fixture.rs | 29 +- 5 files changed, 641 insertions(+), 174 deletions(-) diff --git a/rust-modules/src/app/events.rs b/rust-modules/src/app/events.rs index 4ba0f7cb7c..90a8530e6c 100644 --- a/rust-modules/src/app/events.rs +++ b/rust-modules/src/app/events.rs @@ -1,6 +1,9 @@ //! SDL event decoding and the remote-FIFO token synthesis — the raw-offset reads of LG's shifted //! `SDL_KeyboardEvent`, the synthetic key/pointer/wheel events, and `dispatch_remote_token`. //! Moved out of `app.rs` verbatim in phase 1a (a pure move; `pub(crate)` widening only). +//! +//! The one decode that yields a platform-neutral value is [`decode_host_event`]: SDL's quit and +//! application-lifecycle events become a [`HostEvent`], which the loop consumes in one function. use super::*; @@ -126,6 +129,73 @@ pub(crate) fn host_wcode(sym: u32) -> u32 { } } +/// SDL's application events (`SDL_APP_*`), the four the loop acts on: the compositor taking the +/// screen (WILL and DID enter background) and giving it back (WILL and DID enter foreground). +const SDL_APP_WILLENTERBACKGROUND: u32 = 0x103; +const SDL_APP_DIDENTERBACKGROUND: u32 = 0x104; +const SDL_APP_WILLENTERFOREGROUND: u32 = 0x105; +const SDL_APP_DIDENTERFOREGROUND: u32 = 0x106; + +/// What the platform tells the loop that is not a key, a text commit or a pointer: the window +/// leaving or returning to the screen, and the host asking the application to end. App-private, +/// like [`Shell`](super::platform::Shell): no platform reaches it by a type of its own until the +/// platform contract is settled (`docs/platform-ports.md`, Target shape 2). +/// +/// The SDL drain decodes SDL's events into it ([`decode_host_event`]) and the loop consumes it in +/// ONE function (`run::ingest_host_event`), so a host that stops the application without SDL +/// (the hosted entry's `plx_host_stop`) arrives as the same [`HostEvent::Quit`] an `SDL_QUIT` +/// does and takes the same path. Keys, text, pointer and wheel are not here yet: they keep their +/// raw path in `run::ingest_sdl_event_with_window` until their own steps (W5b, W5c) move them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum HostEvent { + /// The window left or came back to the screen. + Lifecycle(Lifecycle), + /// The host asks the application to end (`SDL_QUIT` on SDL platforms). + Quit, +} + +/// One edge of the window's visibility. Both background edges park the tree (the second finds +/// nothing left to park); WILL foreground un-parks the tree, and DID foreground alone reacquires the +/// window and restores playback. A platform that sends only DID background is enough on its own +/// (`WindowActivity`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Lifecycle { + WillBackground, + DidBackground, + WillForeground, + DidForeground, +} + +impl Lifecycle { + /// The SDL event type this edge arrives as, and so the code the SDL-coded readers take: the + /// recorder's tape (`enc_lifecycle`, whose recorded codes ARE the tape format), the window gate + /// and telemetry's crash steps and session. The inverse of [`decode_host_event`]'s table; + /// `host_event_tests` pins the four pairs. + pub(crate) const fn sdl_code(self) -> u32 { + match self { + Lifecycle::WillBackground => SDL_APP_WILLENTERBACKGROUND, + Lifecycle::DidBackground => SDL_APP_DIDENTERBACKGROUND, + Lifecycle::WillForeground => SDL_APP_WILLENTERFOREGROUND, + Lifecycle::DidForeground => SDL_APP_DIDENTERFOREGROUND, + } + } +} + +/// An SDL event decoded into a [`HostEvent`]: `SDL_QUIT` and the four application lifecycle types. +/// `None` for everything else, which the loop reads raw (keys, text, pointer, wheel, and the SDL +/// events nothing acts on). Beside [`decode_key`], the other place that knows SDL's event bytes. +#[inline] +pub(crate) fn decode_host_event(ev: &[u8]) -> Option { + Some(match rd_u32(ev, 0) { + SDL_QUIT => HostEvent::Quit, + SDL_APP_WILLENTERBACKGROUND => HostEvent::Lifecycle(Lifecycle::WillBackground), + SDL_APP_DIDENTERBACKGROUND => HostEvent::Lifecycle(Lifecycle::DidBackground), + SDL_APP_WILLENTERFOREGROUND => HostEvent::Lifecycle(Lifecycle::WillForeground), + SDL_APP_DIDENTERFOREGROUND => HostEvent::Lifecycle(Lifecycle::DidForeground), + _ => return None, + }) +} + /// The bytes a synthetic key event needs, in whichever layout [`decode_key`] reads. /// /// **The inverse of `decode_key`, and the pair is only correct together.** They already shipped @@ -770,3 +840,50 @@ mod key_layout_tests { ); } } + +/// SDL's quit and application events, decoded into the `HostEvent` the loop consumes (W5a). The SDL +/// codes are literals: the table is the contract with SDL and with the tape, so it is not read back +/// from the mapping it grades. +#[cfg(test)] +mod host_event_tests { + use super::{decode_host_event, encode_key, is_input_event, HostEvent, Lifecycle}; + + fn event_of(code: u32) -> [u8; 128] { + let mut ev = [0u8; 128]; + ev[..4].copy_from_slice(&code.to_ne_bytes()); + ev + } + + #[test] + fn quit_and_the_four_lifecycle_types_decode_and_the_lifecycle_codes_round_trip() { + for (code, event) in [ + (0x100, HostEvent::Quit), + (0x103, HostEvent::Lifecycle(Lifecycle::WillBackground)), + (0x104, HostEvent::Lifecycle(Lifecycle::DidBackground)), + (0x105, HostEvent::Lifecycle(Lifecycle::WillForeground)), + (0x106, HostEvent::Lifecycle(Lifecycle::DidForeground)), + ] { + assert_eq!(decode_host_event(&event_of(code)), Some(event), "{code:#x}"); + assert!(!is_input_event(code), "{code:#x}: a host event is the app's, never a modal's input"); + if let HostEvent::Lifecycle(edge) = event { + assert_eq!(edge.sdl_code(), code, "the code a decoded edge is read back as"); + } + } + } + + /// Everything the loop still reads raw stays raw: no key, text, pointer or wheel event decodes, + /// in either key layout, and neither do the SDL events nothing acts on (terminating and low + /// memory, which sit between quit and the background pair, and the window events). + #[test] + fn every_other_event_stays_on_the_raw_path() { + for code in [ + 0, 0x101, 0x102, 0x107, 0x200, 0x300, 0x301, 0x302, 0x303, 0x400, 0x401, 0x402, 0x403, + u32::MAX, + ] { + assert_eq!(decode_host_event(&event_of(code)), None, "{code:#x}"); + } + for down in [true, false] { + assert_eq!(decode_host_event(&encode_key(plx_ui::consts::SDLK_DOWN, 0, down)), None); + } + } +} diff --git a/rust-modules/src/app/recorder.rs b/rust-modules/src/app/recorder.rs index 51aaa3f49d..adf94aa1c5 100644 --- a/rust-modules/src/app/recorder.rs +++ b/rust-modules/src/app/recorder.rs @@ -1876,6 +1876,31 @@ mod tests { } } + /// W5a: the loop reads a `HostEvent`, and the tape still records each lifecycle edge as the SDL + /// code it arrived as, so every recorded tape replays as it did. Each pair is spelled as the + /// literal record an earlier build wrote. + #[test] + fn a_lifecycle_edge_is_recorded_as_the_sdl_code_it_arrived_as() { + use super::super::events::{decode_host_event, HostEvent, Lifecycle}; + for (code, edge, foreground) in [ + (0x103u32, Lifecycle::WillBackground, false), + (0x104, Lifecycle::DidBackground, false), + (0x105, Lifecycle::WillForeground, true), + (0x106, Lifecycle::DidForeground, true), + ] { + let mut event = [0u8; 128]; + event[..4].copy_from_slice(&code.to_ne_bytes()); + assert_eq!(decode_host_event(&event), Some(HostEvent::Lifecycle(edge)), "{code:#x}"); + let recorded = enc_lifecycle(edge.sdl_code()); + let legacy: Value = serde_json::from_str(&format!(r#"{{"kind":"lifecycle","code":{code}}}"#)).unwrap(); + assert_eq!(recorded, legacy, "{code:#x}"); + assert_eq!(recorded.to_string(), legacy.to_string(), "{code:#x}: byte-equal on the tape"); + assert_eq!(controlled_foreground(&recorded), + if foreground { Ok(Some(code)) } else { Err("unsupported controlled lifecycle") }, + "{code:#x}: only the foreground pair is in the controlled domain"); + } + } + #[test] fn product_mode_encoding_is_bounded_explicit_and_fail_closed() { assert_eq!(ReplayMode::parse("/tmp/synthetic"),Ok((ReplayMode::Targets,"/tmp/synthetic"))); diff --git a/rust-modules/src/app/run.rs b/rust-modules/src/app/run.rs index 4dc98fe9de..6c74655859 100644 --- a/rust-modules/src/app/run.rs +++ b/rust-modules/src/app/run.rs @@ -1171,6 +1171,212 @@ fn window_step(stage: plx_telemetry::telemetry::window::Stage, playing: Option restore_window(app.win), + HostEvent::Quit + | HostEvent::Lifecycle(Lifecycle::WillBackground | Lifecycle::DidBackground) => { + app.rec.refuse("live window exit interrupted controlled replay"); + app.running = false; + } + HostEvent::Lifecycle(Lifecycle::WillForeground) => {} + } + return; + } + // Lifecycle changes remain page damage. + app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); + match event { + // Nothing is torn down here: the loop ends, then `shutdown` releases what is held. + HostEvent::Quit => app.running = false, + HostEvent::Lifecycle(edge) => { + app.rec.input(super::recorder::enc_lifecycle(edge.sdl_code())); + match edge { + Lifecycle::WillBackground | Lifecycle::DidBackground => { + host_background(app, fr, edge, playing) + } + Lifecycle::WillForeground | Lifecycle::DidForeground => { + host_foreground(app, edge, playing, restore_window) + } + } + } + } +} + +/// WILL or DID enter background (`edge` says which): the OS took the screen. +unsafe fn host_background(app: &mut App, fr: &mut Frame, edge: Lifecycle, playing: bool) { + // The visit ends here: nothing is measured in the background, and the app may never come + // back (the system kills it). The event is only QUEUED to the spool on disk (see + // `diag::event_for_impl`), so it is sent by the next flush, this process's or the next + // launch's. The second edge (`DID`) finds an empty visit and emits nothing; the return to + // the foreground starts a fresh visit of the same screen. + end_route_visit(app, false); + app.instr.set_suspended(true); + log(&format!( + "LIFECYCLE: background (playing={})", + matches!(app.route(), AppArg::Player) as i32 + )); + // A freeze is only reported in the foreground (`watchdog::FREEZE_THRESHOLD_MS`): a parked + // app may idle or wait on the system for as long as the system keeps it there. + plx_base::task::watchdog::set_foreground(false); + // **The TELEVISION'S KEYBOARD goes with the panel, and it is not ours to keep.** + // The compositor tears its own IME down when it takes the screen away, and it + // tells the app nothing — so a field left `editing` comes back to the + // foreground drawing an editing layout and a blinking caret over a keyboard + // that is gone, and typing is dead in a way no press can recover: + // `textinput::start` early-returns while its own `STARTED` is set, so OK on the + // field would toggle our flag and raise nothing. This is the same DISMISSAL a + // navigation away from Search runs — there is no teardown table any more (D1 + // deleted `nav::leave_of`); the container delivers `WillLeave`/`Unmount`/`Cover` + // to `SearchScreen`, which drops the keyboard on all three, and the event pushed + // just below is that same drop asked for directly. Deliberately NOT the commit + // path `leave_field` takes: the OS moving the screen is not the user saying + // "that is the search I meant", and a half-typed term must not be filed in + // their recent searches by an app switch. Unconditional because `EDITING` is + // this screen's alone and both calls under it are guarded, so it costs a + // predictable nothing on every other route. Search is unconditionally owned, so + // there is no legacy fallback left to dispatch to. + // Keep dismissal after earlier text/keys in this input batch. The dispatcher + // releases both system ownership and the native start latch at delivery. + app.inputs.push(plx_machine::machine::InputEvent { + at: plx_machine::machine::Tick { ms: fr.now, dt_us: 0 }, source: plx_machine::machine::Source::Sdl, + kind: plx_machine::machine::InputKind::SystemKeyboard(false), + }); + // **The TREE hears it too** (spec §9, §12.1) — phase 9. `ScreenEvent::Suspend` down every + // mounted body at this frame's NAV COMMIT, and `Navigation.suspended` set. The vocabulary + // and the delivery have existed in `ui/containers` since the containers landed + // (`Navigation::suspend`, `Dispatcher::suspend`) and NOTHING CALLED THEM: the screens that + // handle the event — Settings, which forwards it down its own stack, and Search, which + // drops the television's keyboard — were answering an event that could not arrive. + // + // Outside the player guard below on purpose: this is the OS taking the screen from + // whatever is on it, not a fact about playback. + super::bridge::background(&mut app.pages); + app.ptr.sync_back_cursor(None, None); + // The notification feed is a live socket the OS will not keep: cancel it at the first edge + // that says the screen is going (idempotent on the second), reopened by DID foreground. + app.runtime.bridge(&mut app.bridge).notify_suspend(); + // Revoke our borrowed SDL proxies before another frame can use them while backgrounded. + // SDL owns their lifetime; foreground must query its current window again. + release_borrowed_window(|| app.platform.shell.release_surface()); + // A trailer preview is not parked: the OS taking the screen ends it, like any other way + // off its page (`content::halt_preview_off_its_page`). A Load that has not returned is + // left Abandoning, and a preview session is never parked for the foreground reload — + // that reload would bring the trailer back as ordinary playback. + super::content::halt_preview_now(&mut app.player.session, &mut app.adapters.player); + // A second background while the foreground restore waits on its flight (the resume's rebuild, + // an Original rollback): drop the flight — its landing is discarded and only the replacement + // it registered is stopped — and park the session back where the first suspend left it. + // The suspend below would otherwise be refused (`awaiting_load`) and the flight would run + // on, landing a Load on a backgrounded window. + if super::lifecycle::park_pending_foreground_flight( + &mut app.player.lifecycle, + &mut app.player.session, + &mut app.adapters.player, + ) { + app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); + } + // Playback owns its resolve and Engine before the queued Player page mounts. Page + // presence only governs the screen-local cleanup below, never resource suspension. + if !plx_media::route::preview_request(&app.player.session) + && (plx_media::route::play_pending() + || app.adapters.player.playback_needs_teardown(&app.player.session) + || plx_media::route::has_url(&app.player.session)) + && !app.player.lifecycle.awaiting_load() + { + park_playback(app); + // The OS took the screen; whatever the pointer was doing, its button-up is never + // going to arrive here. + app.ptr.button_down = false; + // **The PAGE STACK is deliberately not touched**, which is the whole of what a park + // is: the OS is taking the screen away, not the user navigating, and the foreground + // edge (`host_foreground`) reloads straight back into the player. It USED to write + // `route = Route::Home` here — a statement about the loop's mirror, which + // `bridge::sync_page` turned into a `Root(Home)` that retired the player entry AND + // the page it was launched from, so the foreground minted a fresh player over a + // stack that was just Home. Nothing noticed, because the playback session and + // `App.play_from` both lived outside the tree; the player's origin is an `EntryId` + // now, so destroying entries destroys the way back. See + // `an_app_switch_parks_the_page_stack_and_gives_the_same_entries_back`. + } + // The session ends only after the park above: a crash inside the buffer-feed suspend + // leaves it open, to be reported crashed or abnormal on the next boot. + plx_telemetry::telemetry::session::lifecycle(edge.sdl_code()); + // The DID edge finished its work (the WILL edge is only the notice): a crash after this + // crumb is not inside the background arm. + if edge == Lifecycle::DidBackground { + window_step(plx_telemetry::telemetry::window::Stage::BackgroundDone, Some(playing)); + } +} + +/// WILL or DID enter foreground (`edge` says which): the OS gave the screen back. +unsafe fn host_foreground(app: &mut App, edge: Lifecycle, playing: bool, + restore_window: impl FnOnce(*mut c_void)) { + app.instr.set_suspended(false); + log(&format!( + "LIFECYCLE: foreground (wasPlaying={})", + app.player.lifecycle.awaiting_load() as i32 + )); + plx_base::task::watchdog::set_foreground(true); + // The other half of the park (§12.1): `ScreenEvent::Resume` down the tree and + // `Navigation.suspended` cleared. On BOTH edges, matching `host_background` — webOS sends + // `will` and `did` and the app is told nothing about which of the two it will get first; + // `Navigation::resume` is idempotent, so the pair is safe and a lost one is not. + super::bridge::foreground(&mut app.pages); + if edge == Lifecycle::DidForeground { + // Nothing proves the television is still on the network the person allowed + // unencrypted connections on: every plaintext grant ends here, and each server that + // lost one is queued for a fresh discovery (requested by the upgrade retry's frame + // step) that re-proves eligibility before minting again (`plex::grant`). + plx_plex::plex::grant::network_changed(); + // …and the same doubt applies to the notification feed's open sockets: drop them, let + // the feed connect again (a backoff is forgiven). This is no feed gap: `reread.resume()` below + // re-reads every page, so the reconnect owes no second resync. + app.runtime.bridge(&mut app.bridge).notify_network_changed(); + app.runtime.bridge(&mut app.bridge).notify_resume(); + // The television may have been away long enough for every page to be stale. + app.reread.resume(); + // Reacquire only on DID foreground, before playback restoration and rendering. + restore_window(app.win); + app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); + // A decoder-release park is claimed by this edge like any other park. + app.decoder_parked = false; + let activation = did_foreground_with_link(app); + if matches!(activation, ForegroundActivation::Launched) { + finish_foreground_launch(app); + } else if app.player.lifecycle.claimable_clock().is_some() { + // The Load was refused: on a plaintext-granted server the grant `network_changed` + // just withdrew is re-proven a moment later, after this claim. Claim again then. + app.foreground_retry = Some((plx_plex::plex::grant::revision(), FOREGROUND_RETRIES)); + } + window_step(plx_telemetry::telemetry::window::Stage::ForegroundDone, Some(playing)); + } +} + /// One polled event. Shared by ordinary polling and ordered FIFO/replay ingestion. unsafe fn ingest_sdl_event(app: &mut App, fr: &mut Frame) { let shell = app.platform.shell; @@ -1179,30 +1385,25 @@ unsafe fn ingest_sdl_event(app: &mut App, fr: &mut Frame) { /// The window reacquisition is a platform operation, supplied separately so the /// recorded/live ingress boundary can be exercised without an SDL/GL context. +/// +/// Quit and the four lifecycle edges are decoded into a [`HostEvent`] and consumed by +/// [`ingest_host_event`]. What follows is the raw path: key, text, pointer and wheel events, read +/// from the event's bytes here until their own steps move them behind the decoder. unsafe fn ingest_sdl_event_with_window(app: &mut App, fr: &mut Frame, restore_window: impl FnOnce(*mut c_void)) { + if let Some(event) = decode_host_event(&app.ev) { + ingest_host_event(app, fr, event, restore_window); + return; + } let et = rd_u32(&app.ev, 0); - app.window_activity.event(et); - let playing = matches!(app.route(), AppArg::Player); - plx_telemetry::telemetry::window::lifecycle(et, playing); - // Release health: the foreground edge begins a session (the background edge ends it further - // down, after the player's park), and a key or pointer event is the activity that keeps one - // open (`telemetry::session`; consent-gated inside, a no-op while crash reports are off). - if et == 0x106 { plx_telemetry::telemetry::session::lifecycle(et); } + // A key or pointer event is the activity that keeps a release-health session open + // (`telemetry::session`; consent-gated inside, a no-op while crash reports are off). if is_input_event(et) { plx_telemetry::telemetry::session::input(); } if controlled_replay(app) { - // The tape owns logical ingress; real SDL startup notifications must not be - // counted a second time. The real compositor still owns window safety. - // Only its DID foreground reacquires native handles. Recorded notifications - // below never reacquire them, revoke grants or resume a native player. - if et == 0x106 { restore_window(app.win); } - if matches!(et, 0x103 | 0x104 | SDL_QUIT) { - app.rec.refuse("live window exit interrupted controlled replay"); - app.running = false; - } + // The tape owns logical ingress; real SDL events must not be counted a second time. return; } - // Attribute only the input repaint to its owner; lifecycle changes remain page damage. + // Attribute only the input repaint to its owner; other events remain page damage. if is_input_event(et) { app.note_input_damage(); } else { app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); } if et == SDL_KEYDOWN @@ -1237,157 +1438,7 @@ unsafe fn ingest_sdl_event_with_window(app: &mut App, fr: &mut Frame, clock::now() )); } - if (0x103..=0x106).contains(&et) { - app.rec.input(super::recorder::enc_lifecycle(et)); - } - if et == SDL_QUIT { - app.running = false; - } else if et == 0x103 || et == 0x104 { - // WILL/DID ENTER BACKGROUND - // The visit ends here: nothing is measured in the background, and the app may never come - // back (the system kills it). The event is only QUEUED to the spool on disk (see - // `diag::event_for_impl`), so it is sent by the next flush, this process's or the next - // launch's. The second edge (`DID`) finds an empty visit and emits nothing; the return to - // the foreground starts a fresh visit of the same screen. - end_route_visit(app, false); - app.instr.set_suspended(true); - log(&format!( - "LIFECYCLE: background (playing={})", - matches!(app.route(), AppArg::Player) as i32 - )); - // A freeze is only reported in the foreground (`watchdog::FREEZE_THRESHOLD_MS`): a parked - // app may idle or wait on the system for as long as the system keeps it there. - plx_base::task::watchdog::set_foreground(false); - // **The TELEVISION'S KEYBOARD goes with the panel, and it is not ours to keep.** - // The compositor tears its own IME down when it takes the screen away, and it - // tells the app nothing — so a field left `editing` comes back to the - // foreground drawing an editing layout and a blinking caret over a keyboard - // that is gone, and typing is dead in a way no press can recover: - // `textinput::start` early-returns while its own `STARTED` is set, so OK on the - // field would toggle our flag and raise nothing. This is the same DISMISSAL a - // navigation away from Search runs — there is no teardown table any more (D1 - // deleted `nav::leave_of`); the container delivers `WillLeave`/`Unmount`/`Cover` - // to `SearchScreen`, which drops the keyboard on all three, and the event pushed - // just below is that same drop asked for directly. Deliberately NOT the commit - // path `leave_field` takes: the OS moving the screen is not the user saying - // "that is the search I meant", and a half-typed term must not be filed in - // their recent searches by an app switch. Unconditional because `EDITING` is - // this screen's alone and both calls under it are guarded, so it costs a - // predictable nothing on every other route. Search is unconditionally owned, so - // there is no legacy fallback left to dispatch to. - // Keep dismissal after earlier text/keys in this input batch. The dispatcher - // releases both system ownership and the native start latch at delivery. - app.inputs.push(plx_machine::machine::InputEvent { - at: plx_machine::machine::Tick { ms: fr.now, dt_us: 0 }, source: plx_machine::machine::Source::Sdl, - kind: plx_machine::machine::InputKind::SystemKeyboard(false), - }); - // **The TREE hears it too** (spec §9, §12.1) — phase 9. `ScreenEvent::Suspend` down every - // mounted body at this frame's NAV COMMIT, and `Navigation.suspended` set. The vocabulary - // and the delivery have existed in `ui/containers` since the containers landed - // (`Navigation::suspend`, `Dispatcher::suspend`) and NOTHING CALLED THEM: the screens that - // handle the event — Settings, which forwards it down its own stack, and Search, which - // drops the television's keyboard — were answering an event that could not arrive. - // - // Outside the player guard below on purpose: this is the OS taking the screen from - // whatever is on it, not a fact about playback. - super::bridge::background(&mut app.pages); - app.ptr.sync_back_cursor(None, None); - // The notification feed is a live socket the OS will not keep: cancel it at the first edge - // that says the screen is going (idempotent on the second), reopened by DID foreground. - app.runtime.bridge(&mut app.bridge).notify_suspend(); - // Revoke our borrowed SDL proxies before another frame can use them while backgrounded. - // SDL owns their lifetime; foreground must query its current window again. - release_borrowed_window(|| app.platform.shell.release_surface()); - // A trailer preview is not parked: the OS taking the screen ends it, like any other way - // off its page (`content::halt_preview_off_its_page`). A Load that has not returned is - // left Abandoning, and a preview session is never parked for the foreground reload — - // that reload would bring the trailer back as ordinary playback. - super::content::halt_preview_now(&mut app.player.session, &mut app.adapters.player); - // A second background while the foreground restore waits on its flight (the resume's rebuild, - // an Original rollback): drop the flight — its landing is discarded and only the replacement - // it registered is stopped — and park the session back where the first suspend left it. - // The suspend below would otherwise be refused (`awaiting_load`) and the flight would run - // on, landing a Load on a backgrounded window. - if super::lifecycle::park_pending_foreground_flight( - &mut app.player.lifecycle, - &mut app.player.session, - &mut app.adapters.player, - ) { - app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); - } - // Playback owns its resolve and Engine before the queued Player page mounts. Page - // presence only governs the screen-local cleanup below, never resource suspension. - if !plx_media::route::preview_request(&app.player.session) - && (plx_media::route::play_pending() - || app.adapters.player.playback_needs_teardown(&app.player.session) - || plx_media::route::has_url(&app.player.session)) - && !app.player.lifecycle.awaiting_load() - { - park_playback(app); - // The OS took the screen; whatever the pointer was doing, its button-up is never - // going to arrive here. - app.ptr.button_down = false; - // **The PAGE STACK is deliberately not touched**, which is the whole of what a park - // is: the OS is taking the screen away, not the user navigating, and the foreground - // arm below reloads straight back into the player. It USED to write - // `route = Route::Home` here — a statement about the loop's mirror, which - // `bridge::sync_page` turned into a `Root(Home)` that retired the player entry AND - // the page it was launched from, so the foreground minted a fresh player over a - // stack that was just Home. Nothing noticed, because the playback session and - // `App.play_from` both lived outside the tree; the player's origin is an `EntryId` - // now, so destroying entries destroys the way back. See - // `an_app_switch_parks_the_page_stack_and_gives_the_same_entries_back`. - } - // The session ends only after the park above: a crash inside the buffer-feed suspend - // leaves it open, to be reported crashed or abnormal on the next boot. - plx_telemetry::telemetry::session::lifecycle(et); - // The DID edge finished its work (the WILL edge is only the notice): a crash after this - // crumb is not inside the background arm. - if et == 0x104 { - window_step(plx_telemetry::telemetry::window::Stage::BackgroundDone, Some(playing)); - } - } else if et == 0x105 || et == 0x106 { - // WILL/DID ENTER FOREGROUND - app.instr.set_suspended(false); - log(&format!( - "LIFECYCLE: foreground (wasPlaying={})", - app.player.lifecycle.awaiting_load() as i32 - )); - plx_base::task::watchdog::set_foreground(true); - // The other half of the park (§12.1): `ScreenEvent::Resume` down the tree and - // `Navigation.suspended` cleared. On BOTH edges, matching the suspend above — webOS sends - // `will` and `did` and the app is told nothing about which of the two it will get first; - // `Navigation::resume` is idempotent, so the pair is safe and a lost one is not. - super::bridge::foreground(&mut app.pages); - if et == 0x106 { - // Nothing proves the television is still on the network the person allowed - // unencrypted connections on: every plaintext grant ends here, and each server that - // lost one is queued for a fresh discovery (requested by the upgrade retry's frame - // step) that re-proves eligibility before minting again (`plex::grant`). - plx_plex::plex::grant::network_changed(); - // …and the same doubt applies to the notification feed's open sockets: drop them, let - // the feed connect again (a backoff is forgiven). This is no feed gap: `reread.resume()` below - // re-reads every page, so the reconnect owes no second resync. - app.runtime.bridge(&mut app.bridge).notify_network_changed(); - app.runtime.bridge(&mut app.bridge).notify_resume(); - // The television may have been away long enough for every page to be stale. - app.reread.resume(); - // Reacquire only on DID foreground, before playback restoration and rendering. - restore_window(app.win); - app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); - // A decoder-release park is claimed by this edge like any other park. - app.decoder_parked = false; - let activation = did_foreground_with_link(app); - if matches!(activation, ForegroundActivation::Launched) { - finish_foreground_launch(app); - } else if app.player.lifecycle.claimable_clock().is_some() { - // The Load was refused: on a plaintext-granted server the grant `network_changed` - // just withdrew is re-proven a moment later, after this claim. Claim again then. - app.foreground_retry = Some((plx_plex::plex::grant::revision(), FOREGROUND_RETRIES)); - } - window_step(plx_telemetry::telemetry::window::Stage::ForegroundDone, Some(playing)); - } - } else if et == SDL_KEYDOWN || et == SDL_KEYUP { + if et == SDL_KEYDOWN || et == SDL_KEYUP { let (state, wcode, sym) = decode_key(&app.ev); // The press's IDENTITY, resolved once from the two raw fields // (`ui::consts::classify`, which is where the spellings live and where they @@ -4506,6 +4557,259 @@ pub(in crate::app) mod lifecycle_regression_tests { } } + // ---- W5a: Quit and the lifecycle edges as a `HostEvent` ------------------------------------- + // + // The same event is delivered two ways: as the SDL event bytes the drain decodes (`event`, which + // is what every test above sends) and as the `HostEvent` a hosted stop or a future platform hands + // `ingest_host_event` directly. Each test runs both and compares what the loop left behind. + + /// The SDL event type each `HostEvent` arrives as, spelled as literals so these tests do not + /// borrow the mapping they grade. + fn sdl_event_of(event: HostEvent) -> u32 { + match event { + HostEvent::Quit => 0x100, + HostEvent::Lifecycle(Lifecycle::WillBackground) => 0x103, + HostEvent::Lifecycle(Lifecycle::DidBackground) => 0x104, + HostEvent::Lifecycle(Lifecycle::WillForeground) => 0x105, + HostEvent::Lifecycle(Lifecycle::DidForeground) => 0x106, + } + } + + /// Deliver `event` the SDL way (`hosted` false: its bytes through `ingest_sdl_event`) or the + /// host's (`hosted` true: the `HostEvent` itself through the one consumer). + fn deliver(app: &mut App, fr: &mut Frame, hosted: bool, event: HostEvent) { + if hosted { + unsafe { ingest_host_event(app, fr, event, |_| {}) }; + } else { + self::event(app, fr, sdl_event_of(event)); + } + } + + const EDGES: [Lifecycle; 4] = [ + Lifecycle::WillBackground, + Lifecycle::DidBackground, + Lifecycle::WillForeground, + Lifecycle::DidForeground, + ]; + + /// What a quit leaves behind, as far as this rig can see it: whether the loop goes on, the + /// `Exit` that `run_and_shutdown` builds from what the loop leaves (`failed` is a recording that + /// did not land or a controlled run that refused; the release is `shutdown`'s alone, and the rig + /// has no GL context or native worker to run it, so `Complete` is the clean verdict it would + /// return), and the state a park or a teardown would have changed. + fn after_quit(app: &mut App) -> (bool, Exit, String) { + let failed = app.rec.failure().is_some() + || app.runtime.bridge(&mut app.bridge).controlled_failure().is_some(); + let exit = Exit::played(failed, release_of(plx_media::player::NativeExit::Clean)); + let rest = format!( + "foreground={:?} awaiting_load={} suspended={} live={} present={} inputs={}", + std::mem::discriminant(&app.player.lifecycle.state()), + app.player.lifecycle.awaiting_load(), + app.pages.nav.suspended, + app.adapters.player.is_live(), + app.window_activity.allow_present(true), + app.inputs.len(), + ); + (app.running, exit, rest) + } + + /// **A hosted stop is the same `Quit` an `SDL_QUIT` is.** Both reach the one consumer, which + /// ends the loop and leaves every release to `shutdown`: nothing parks, nothing is torn down + /// here, and the `Exit` the entry returns is the clean one. + #[test] + fn a_host_quit_takes_the_path_an_sdl_quit_takes() { + let _serial = plx_base::testlock::serial(); + let mut seen = Vec::new(); + for hosted in [false, true] { + let mut app = app(); + let mut fr = Frame::begin(&app.player.session, app.runtime.metadata_view()); + app.running = true; + deliver(&mut app, &mut fr, hosted, HostEvent::Quit); + seen.push(after_quit(&mut app)); + } + assert!(!seen[0].0, "the loop ends"); + assert_eq!(seen[0].1, Exit { code: 0, release: Release::Complete }); + assert_eq!(seen[0], seen[1], "a host's Quit and an SDL_QUIT leave the same loop and the same Exit"); + } + + /// The same, while a film plays: the quit parks nothing (that is the lifecycle's, and a quit + /// is not one) and leaves the session for `shutdown` to end, whichever way it arrived. + #[test] + fn a_host_quit_during_playback_takes_the_path_an_sdl_quit_takes() { + let _serial = plx_base::testlock::serial(); + let mut seen = Vec::new(); + for hosted in [false, true] { + let Some(mut rig) = Rig::new() else { + eprintln!("SKIPPED a_host_quit_during_playback_takes_the_path_an_sdl_quit_takes: \ + lifecycle fixture worker thread could not be spawned"); + return; + }; + start_film(&mut rig); + assert!(super::super::bridge::player(&rig.app.pages).is_some() && rig.app.adapters.player.is_live(), + "premise: the film is playing"); + let mut fr = Frame::begin(&rig.app.player.session, rig.app.runtime.metadata_view()); + rig.app.running = true; + deliver(&mut rig.app, &mut fr, hosted, HostEvent::Quit); + assert!(rig.app.adapters.player.is_live(), "the quit tore nothing down: that is shutdown's"); + assert_eq!(rig.app.player.lifecycle.state(), ForegroundState::Idle, "a quit parks nothing"); + seen.push(after_quit(&mut rig.app)); + } + assert!(!seen[0].0, "the loop ends"); + assert_eq!(seen[0].1, Exit { code: 0, release: Release::Complete }); + assert_eq!(seen[0], seen[1], "a host's Quit and an SDL_QUIT leave the same loop and the same Exit"); + } + + /// A quit interrupts a controlled replay the way a live background does: the tape refuses and the + /// loop ends, so the `Exit` it feeds is a failed one. Delivered either way. + #[test] + fn a_host_quit_interrupts_a_controlled_replay_as_an_sdl_quit_does() { + use super::super::{bootstrap::{Initial, Preflight}, recorder::{Recplay, ReplayMode, state_fp}}; + use plx_ui::{dispatch::Tap, rec::{Header, Recording}}; + use plx_machine::machine::Tick; + let _serial = plx_base::testlock::serial(); + let mut seen = Vec::new(); + for hosted in [false, true] { + let mut app = app(); + let initial = Initial::synthetic_home(1, 32517, None).unwrap(); + let recording = Recording { + header: Header::new(state_fp(), &initial), + frames: vec![plx_ui::rec::Frame { f: 0, tick: Some(Tick { ms: 0, dt_us: 0 }), + st: Some(7), focus: Some(None), ..Default::default() }], + metrics: Default::default(), stopped_at: None, + }; + app.boot_initial = Some(initial.clone()); + app.rec = Recplay::controlled( + Preflight::Replay { initial: initial.clone(), recording, mode: ReplayMode::Targets }, + &initial).unwrap(); + Tap::focus(&mut app.rec, 0, None); + let mut fr = Frame::begin(&app.player.session, app.runtime.metadata_view()); + app.running = true; + deliver(&mut app, &mut fr, hosted, HostEvent::Quit); + assert_eq!(app.rec.failure(), Some("live window exit interrupted controlled replay")); + seen.push(after_quit(&mut app)); + } + assert!(!seen[0].0, "the loop ends"); + assert_eq!(seen[0].1, Exit { code: 1, release: Release::Complete }, "the refused tape is a failed run"); + assert_eq!(seen[0], seen[1]); + } + + /// **A `Lifecycle` sequence parks and resumes as the SDL codes do.** A film is playing; WILL and + /// DID background park it and take the window, WILL and DID foreground give both back. Whatever + /// the loop leaves after each edge, and the crash steps it records, are the same either way. + #[test] + fn a_host_lifecycle_sequence_parks_and_resumes_as_the_sdl_codes_do() { + let _serial = plx_base::testlock::serial(); + let _consent = CrashReports::granted(); + let mut traces = Vec::new(); + for hosted in [false, true] { + let Some(mut rig) = Rig::new() else { + eprintln!("SKIPPED a_host_lifecycle_sequence_parks_and_resumes_as_the_sdl_codes_do: \ + lifecycle fixture worker thread could not be spawned"); + return; + }; + start_film(&mut rig); + let _ = plx_telemetry::telemetry::window::take_recorded_for_test(); + let mut fr = Frame::begin(&rig.app.player.session, rig.app.runtime.metadata_view()); + let mut trace = Vec::new(); + for edge in EDGES { + deliver(&mut rig.app, &mut fr, hosted, HostEvent::Lifecycle(edge)); + trace.push((edge, after_quit(&mut rig.app).2)); + } + let steps = plx_telemetry::telemetry::window::take_recorded_for_test(); + traces.push((trace, steps)); + } + let (trace, steps) = &traces[1]; + let after = |edge: Lifecycle| &trace.iter().find(|(e, _)| *e == edge).unwrap().1; + assert!(after(Lifecycle::DidBackground).contains("awaiting_load=true") + && after(Lifecycle::DidBackground).contains("suspended=true") + && after(Lifecycle::DidBackground).contains("present=false"), + "the film is parked and the window taken: {}", after(Lifecycle::DidBackground)); + assert!(after(Lifecycle::DidForeground).contains("suspended=false") + && after(Lifecycle::DidForeground).contains("present=true"), + "the tree resumes and the window is given back: {}", after(Lifecycle::DidForeground)); + assert_eq!(steps.first(), Some(&"will_background")); + assert_eq!(steps.last(), Some(&"foreground_done")); + assert_eq!(traces[0], traces[1], "a host's Lifecycle edges and the SDL codes leave the same loop"); + } + + /// **Each WILL edge does its work on its own.** The sequence above sends all four edges, so a + /// dispatch that dropped a WILL edge (an arm narrowed to the DID edge it pairs with) would still + /// pass it: the DID edge repeats what WILL did. Here WILL background arrives ALONE and parks the + /// film and the tree (the base's `0x103` arm ran the whole background arm), and WILL foreground + /// arrives ALONE and gives the tree back but not the window or the film (the base's `0x105` arm + /// ran the foreground arm; only the DID edge restores). Either way of delivery leaves the same + /// loop. + #[test] + fn a_host_will_edge_does_its_arms_work_without_its_did_edge() { + let _serial = plx_base::testlock::serial(); + let mut seen = Vec::new(); + for hosted in [false, true] { + let Some(mut rig) = Rig::new() else { + eprintln!("SKIPPED a_host_will_edge_does_its_arms_work_without_its_did_edge: \ + lifecycle fixture worker thread could not be spawned"); + return; + }; + start_film(&mut rig); + let before = after_quit(&mut rig.app).2; + let inputs_before = rig.app.inputs.len(); + let mut fr = Frame::begin(&rig.app.player.session, rig.app.runtime.metadata_view()); + deliver(&mut rig.app, &mut fr, hosted, HostEvent::Lifecycle(Lifecycle::WillBackground)); + let will_background = after_quit(&mut rig.app).2; + let keyboard_dismissals = rig.app.inputs.len() - inputs_before; + deliver(&mut rig.app, &mut fr, hosted, HostEvent::Lifecycle(Lifecycle::WillForeground)); + let will_foreground = after_quit(&mut rig.app).2; + seen.push((before, will_background, keyboard_dismissals, will_foreground)); + } + let (before, will_background, keyboard_dismissals, will_foreground) = &seen[1]; + assert!(before.contains("awaiting_load=false") && before.contains("suspended=false"), + "premise: the film plays and the tree is live: {before}"); + assert!(will_background.contains("awaiting_load=true") + && will_background.contains("suspended=true"), + "WILL background alone parks the film and suspends the tree: {will_background}"); + assert_eq!(*keyboard_dismissals, 1, "WILL background alone dismisses the television's keyboard"); + assert!(will_foreground.contains("suspended=false"), + "WILL foreground alone resumes the tree: {will_foreground}"); + assert!(will_foreground.contains("awaiting_load=true") && will_foreground.contains("present=false"), + "...and only the DID edge restores the film and the window: {will_foreground}"); + assert_eq!(seen[0], seen[1], "a host's WILL edges and the SDL codes leave the same loop"); + } + + /// **The tape is the same whichever way an edge arrives.** The four edges are recorded as the SDL + /// codes `enc_lifecycle` always wrote, in order, and a quit records nothing. + #[test] + fn a_host_lifecycle_edge_is_recorded_as_the_sdl_code_it_arrives_as() { + use super::super::{bootstrap::Initial, recorder::{Recplay, state_fp}}; + use plx_ui::rec::{Header, MemSink, Recording}; + let _serial = plx_base::testlock::serial(); + let initial = Initial::synthetic_home(1, 32517, None).unwrap(); + let mut tapes = Vec::new(); + for hosted in [false, true] { + let mut app = app(); + let mut fr = Frame::begin(&app.player.session, app.runtime.metadata_view()); + let sink = MemSink::default(); + let segments = sink.segments.clone(); + let manifest = Header::new(state_fp(), &initial).to_json().to_string(); + app.rec = Recplay::recording_with_sink(&initial, Box::new(sink)).unwrap(); + app.rec.tick(initial.clock_start, 0.0); + for edge in EDGES { + deliver(&mut app, &mut fr, hosted, HostEvent::Lifecycle(edge)); + } + deliver(&mut app, &mut fr, hosted, HostEvent::Quit); + app.rec.end_frame(&|| 7); + std::mem::replace(&mut app.rec, Recplay::Off).finish(plx_machine::landgate::fixture_gate()); + let recording = Recording::parse(&manifest, + &segments.borrow().iter().map(Vec::as_slice).collect::>(), state_fp()).unwrap(); + tapes.push(recording.frames.iter().flat_map(|frame| frame.inputs.clone()).collect::>()); + } + let recorded: Vec<(String, u64)> = tapes[0].iter() + .map(|input| (input["kind"].as_str().unwrap().to_owned(), input["code"].as_u64().unwrap())) + .collect(); + assert_eq!(recorded, [("lifecycle".to_owned(), 0x103), ("lifecycle".to_owned(), 0x104), + ("lifecycle".to_owned(), 0x105), ("lifecycle".to_owned(), 0x106)], + "the four edges, as SDL codes, in order; the quit is not recorded"); + assert_eq!(tapes[0], tapes[1], "the tape is byte-equal whichever way an edge arrives"); + } + #[cfg(feature = "devtriggers")] #[test] #[should_panic(expected = "main-thread block: dev hang probe")] diff --git a/rust-modules/telemetry/src/telemetry/window.rs b/rust-modules/telemetry/src/telemetry/window.rs index 22bb8cae08..5c3bca5564 100644 --- a/rust-modules/telemetry/src/telemetry/window.rs +++ b/rust-modules/telemetry/src/telemetry/window.rs @@ -451,7 +451,7 @@ mod tests { } } - /// The run.rs background arm: both edges, the surface release, the teardown of a playing + /// `host_background` (`app/run.rs`): both edges, the surface release, the teardown of a playing /// engine, then the DID edge's `background_done`. fn background(playing: bool) { lifecycle(0x103, playing); @@ -465,7 +465,7 @@ mod tests { step(Stage::BackgroundDone); } - /// The run.rs foreground arm: both edges, the window grab, the restoring Load's window create, + /// `host_foreground` (`app/run.rs`): both edges, the window grab, the restoring Load's window create, /// then the DID edge's `foreground_done`. `first_frame` comes later, from the first present. fn foreground(playing: bool) { lifecycle(0x105, playing); diff --git a/rust-modules/ui/src/fixture.rs b/rust-modules/ui/src/fixture.rs index 88a57dfe64..247ba54a13 100644 --- a/rust-modules/ui/src/fixture.rs +++ b/rust-modules/ui/src/fixture.rs @@ -2582,24 +2582,45 @@ fn an_app_switch_suspends_every_body_and_the_loop_is_what_delivers_it() { assert_eq!(heard(&d, "resume"), 1, "every mounted body must hear `Resume`"); // The second claim: the LOOP calls them. No host test can drive `app::run` — it needs a live - // SDL window — so this is pinned from its source, in the two arms that own the question. + // SDL window — so this is pinned from its source, in the two functions that own the question + // (the loop's reaction to a `HostEvent::Lifecycle` edge: `host_background`, then + // `host_foreground`, in that order). let src = std::fs::read_to_string( std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../src/app/run.rs"), ) .expect("read run.rs"); let bg = src - .find("et == 0x103 || et == 0x104") + .find("unsafe fn host_background(") .expect("the background arm"); let fg = src - .find("et == 0x105 || et == 0x106") + .find("unsafe fn host_foreground(") .expect("the foreground arm"); + let fg_end = fg + src[fg..].find("\n}\n").expect("the end of the foreground arm"); assert!( src[bg..fg].contains("bridge::background(&mut app.pages);"), "the BACKGROUND arm must park the container tree, or Settings and Search answer an event \ that never arrives", ); assert!( - src[fg..].contains("bridge::foreground(&mut app.pages);"), + src[fg..fg_end].contains("bridge::foreground(&mut app.pages);"), "…and the FOREGROUND arm must un-park it, or the tree stays parked for the rest of the run", ); + + // …and the loop's one consumer sends BOTH edges of each pair to them. An arm narrowed to the + // DID edge would pass everything above: the WILL edge would reach `{}`, and webOS may send + // either edge of a pair first. + let host = src + .find("unsafe fn ingest_host_event(") + .expect("the loop's one HostEvent consumer"); + let host_end = host + src[host..].find("\n}\n").expect("the end of the consumer"); + let flat = src[host..host_end].split_whitespace().collect::>().join(" "); + for (edges, call) in [ + ("Lifecycle::WillBackground | Lifecycle::DidBackground", "host_background("), + ("Lifecycle::WillForeground | Lifecycle::DidForeground", "host_foreground("), + ] { + assert!( + flat.contains(&format!("{edges} => {{ {call}")) || flat.contains(&format!("{edges} => {call}")), + "the consumer must send both `{edges}` to `{call}`", + ); + } } From d166f5fcbac07a4b559ee5d9077f655624a6d0a4 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 13:16:07 +0300 Subject: [PATCH 07/26] The television's webOS-shaped types become neutral ones (#1485) The television seam's types no longer name webOS (step W3d of the platform plan, discussion #1460). The secure envelope's backend becomes an opaque tag, `sandbox` becomes `native_video`, and identity publishes a neutral `Platform`. webOS fills each with the values it carried before. The X-Plex headers, the `devjail:` log line, the telemetry fields and the session file's wire form are unchanged. - `tv::secure::Backend` is now an opaque tag: `Backend(Cow<'static, str>)`, serialized transparently, with `KEYMANAGER3` and `PALM_KEYMANAGER` as constants. - `keymanager::open` refuses any other tag without an LS2 call, and `remove` ignores it. The session layer reports Locked and leaves the file untouched, which is how an unknown tag ended before, when serde failed. Its log line now reads "device key is unavailable" rather than "unsupported or damaged secure envelope". - A fixture written from the old code pins both tags' wire form byte for byte. - `tv::sandbox` becomes `tv::native_video`, and its `Verdict` becomes `Available | Blocked(&'static str) | NotApplicable`. - `context()` still answers `ok`, `missing` or `n/a`. - `Services.identity.repair_sandbox` becomes `repair_native_video: Option`. `None` answers `Failure::Unsupported` as before. - `tv::device`: - `Info` moves webOS's codename, API and name into `Info.webos`. - A publish-once `Platform { name, version }` arrives. webOS publishes `("webOS", release or "4.5")`, and `plex::identity::platform()` reads it, defaulting to the old constant. - Device file reads go through `Files { read, exists }`. devcaps' parsing is split into `read_caps(&Files)`, and webOS supplies the fs-backed `DEVICE_FILES` through `Services.identity.device_files`. - The readers in media, appkit, screens, telemetry, the app's diagnostics, playback and lab snapshot follow the renames. `docs/module-layers.md` follows too, and marks L15c done. --- ci/module-layers.ini | 2 +- docs/module-layers.md | 32 ++-- docs/platform-ports.md | 5 +- rust-modules/appkit/src/player_hud/state.rs | 8 +- rust-modules/media/src/player/adapter.rs | 10 +- rust-modules/media/src/player/machine.rs | 14 +- rust-modules/media/src/player/mod.rs | 12 +- rust-modules/media/src/player/route_start.rs | 2 +- rust-modules/media/src/route/decision.rs | 6 +- rust-modules/os/src/devcaps.rs | 87 ++++++++- rust-modules/os/src/keymanager.rs | 60 ++++-- rust-modules/os/src/tv.rs | 31 ++- rust-modules/os/src/tv/device.rs | 80 +++++++- rust-modules/os/src/tv/native_video.rs | 181 ++++++++++++++++++ rust-modules/os/src/tv/sandbox.rs | 129 ------------- rust-modules/os/src/tv/secure.rs | 105 +++++++++- rust-modules/os/src/webos.rs | 117 ++++++++--- rust-modules/os/src/webos/jail_repair.rs | 2 +- rust-modules/plex/src/plex/account.rs | 2 +- rust-modules/plex/src/plex/client.rs | 4 +- rust-modules/plex/src/plex/identity.rs | 40 +++- .../src/plex/session_persistence_tests.rs | 49 ++++- rust-modules/screens/src/player/mod.rs | 10 +- rust-modules/src/app/diagnostics.rs | 15 +- rust-modules/src/app/playback.rs | 2 +- rust-modules/src/lab/snapshot.rs | 6 +- rust-modules/src/port.rs | 3 +- rust-modules/telemetry/src/diag/schema.rs | 8 +- .../telemetry/src/telemetry/native.rs | 10 +- .../telemetry/src/telemetry/sentry.rs | 8 +- 30 files changed, 754 insertions(+), 286 deletions(-) create mode 100644 rust-modules/os/src/tv/native_video.rs delete mode 100644 rust-modules/os/src/tv/sandbox.rs diff --git a/ci/module-layers.ini b/ci/module-layers.ini index e0dacdde5d..5bbf045998 100644 --- a/ci/module-layers.ini +++ b/ci/module-layers.ini @@ -59,7 +59,7 @@ members = machine present landgate landing job motion idle_regression_tests pres # the codec table, the artwork cache, the localization catalog, and the Cloud Lab session file # (`labcfg`: `lab.json` plus the trigger-key / menu-row answers `ui/` and `screens/` ask of it). # `webos` and `keymanager` are also in [platform webos]. `tv` holds the interfaces the webOS port fills -# at boot (step L15): device identity, the sandbox verdict, the key store, home, toast, the window +# at boot (step L15): device identity, the native-video verdict, the key store, home, toast, the window # and the video sink trait. uses = base machine members = webos storage keymanager devcaps imgcache i18n labcfg tv playback_trace diff --git a/docs/module-layers.md b/docs/module-layers.md index 4561d00c55..31ac64876e 100644 --- a/docs/module-layers.md +++ b/docs/module-layers.md @@ -330,10 +330,10 @@ 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}` (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). | +| **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, native_video, 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; 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. | +| **L15c** the platform value and the three contracts — **done** | — | Wave R (the rename that gave this page `os` and `[platform webos]`) landed as #1474; W2 landed (`tv::Port` became `tv::Services`, with four groups of hooks; the shell and the frame probes moved to `app::Platform`), and so did the three contracts, W3a to W3c: who may persist credentials (#1477), what evidence admits a URI player (#1478), who ends the process (#1479). See "L15c to L15h" below. | +| **L15d** neutral types and the simulator as its own platform (L15b item 2) — **W3d landed, W4 planned** | — | W3d has landed (the opaque `Backend` tag, `sandbox` to `native_video`, identity publishes a platform name and version, `device::Info` keeps its webOS fields in `WebosDetail`, and `devcaps` reads its files through the platform), and what is planned is 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. | | **L15g** the webOS facts and the remaining `hostsim` (L15b item 3) — **planned** | — | W8: the `target_arch = "arm"` and `target_os = "linux"` sites sorted into "is webOS" (a platform value or runner) and "is 32-bit ARM" or "is Linux" (stays), then the library name lists, `paths`, the packaging and the 363 `feature = "hostsim"` lines outside the fence (360 cfg lines and three doc comments). | @@ -363,16 +363,16 @@ Only `tv`'s own modules read the table. Two things leave it: the sink, through `play-uri` driver receives that transport and a shared `DisplaySink` as injected ports; it does not read the webOS port registry or the feed-only `VideoSink` itself. Lazily computed facts (device identity, the sandbox verdict, the Dolby Vision capability) are -published values rather than hooks: the webOS code writes them into `tv::device`, `tv::sandbox` and +published values rather than hooks: the webOS code writes them into `tv::device`, `tv::native_video` and `devcaps::dv` at the same boot moment as before, so readers keep their `OnceLock` semantics. | interface | where it went | named from | |---|---|---| -| 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` | +| device identity | `tv::device::{info, device, platform, files, Info, WebosDetail, Hardware, Platform, Files}`, published by `webos::probe` (`Info` is the release, build and major every platform states; `WebosDetail` is the codename, API version and name only a webOS firmware file has; `Platform` is the name and version the Plex headers report, which `plex::identity` defaults to `webOS` until one is published; `Files` is the reader `devcaps::probe` parses through, a field of `Services.identity`) | `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` | +| native-video availability and repair | `tv::native_video::{blocked, context, repair, Verdict, State, Failure, FORCE_BLOCKED}`, `Verdict` being `Available`, `Blocked(reason)` or `NotApplicable`; the verdict is published by `webos::probe` and the repair is an optional port hook (`Services.identity.repair_native_video`) | `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 `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` | +| secure store | `tv::secure::{seal, open, remove, Sealed, Backend}`; `Backend` is an opaque tag (a string on the wire, with constants for the two webOS spellings) | `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 `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) | @@ -441,18 +441,22 @@ still webOS's. Three things are left: simulator runs today (`launch_home`, `system_locale`, `sound_output`, `bind_window`, the keymanager client, `deliver`, `call_hbc` among them), and they stay compiled for tests and `test-support` with only their `hostsim` term gone (`docs/platform-ports.md`, W4). The - webOS-shaped types in `tv` also need neutral shapes then: `tv::secure::Backend` names the two - webOS key managers and is part of the on-disk envelope, and `tv::sandbox`'s verdict and repair - describe webOS's own device jail. + webOS-shaped types in `tv` needed neutral shapes then, and have them since W3d: `tv::secure::Backend` + is an opaque tag that stays a string on the wire (the two webOS spellings are constants, and a tag no + installed platform knows is refused on open), `tv::sandbox` is `tv::native_video` with a verdict that is + `Available`, `Blocked(reason)` or `NotApplicable` and an optional repair hook, and `tv::device::Info` + keeps the release, build and major while the codename, API version and name sit in a `WebosDetail`. 3. **The webOS facts the gate cannot see.** The gate sees names, not literals, and not modules that stay where they are. The port takes these too: - `devcaps` reads webOS's own table, `/etc/umediaserver/device_codec_capability_config.json`. - The parsed model stays and the reader moves. + The parsed model stays and the reader moved in W3d: `devcaps::probe` reads its files through + `tv::device::files()`, the `Files` that `Services.identity` states. - The libraries the app loads at run time are the television's: `libcurl` (`net`, `curlio`) and `libEGLfk` (`egl`). The bundled FFmpeg in `ff` is loaded by absolute path and is not one of them. - - `plex::identity`'s platform constant and client headers. + - `plex::identity`'s platform constant and client headers (W3d: the platform publishes its name and + version to `tv::device`, and `PLATFORM` is the default until it does). - The Magic Remote's key codes and pointer in `app::{input, boot, events}`. - `paths`'s fallback install prefix. - Outside `rust-modules/src`: `src/starfish.c`, `src/main.c`'s boot shim, the storage helper @@ -497,7 +501,7 @@ layer below it. Since L14 the first half holds for every layer and the second fo listed 134 such items after L14 (8 in `base`, 11 `machine`, 13 `os`, 8 `gfx`, 10 `net`, 21 `plex`, 8 `telemetry`, 12 `ui`, 25 `data`, 4 `session`, 6 `media`, 4 `appkit`, 4 `screens`). L15 replaced `webos::FORCE_JAIL_BLOCKED`, `webos::home_requests` and `keymanager::RPC_FOR_TEST` with -`cfg(test)` seams of `tv` (`sandbox::FORCE_BLOCKED`, `home::home_requests`, +`cfg(test)` seams of `tv` (`native_video::FORCE_BLOCKED`, `home::home_requests`, `secure::{STORE_FOR_TEST, TestStore}`) that other layers' tests still name, so `--report` listed 136 (15 in `os`, the rest as above) before Split 3 took the 15 with it; run it for the current count. The @@ -729,7 +733,7 @@ suite is 5603 tests before and after (157 + 66 + 218 + 5162). What it taught bey times alone before trusting them. - **No orphan-rule hazard, and nothing was dead because of a trait.** `os` defines traits (`tv::sink::VideoSink`) and the application implements them for its own types, which is legal; the - compiler is the checker, as in Split 2. `tv::sandbox::Failure::Timeout` had a + compiler is the checker, as in Split 2. `tv::native_video::Failure::Timeout` (then `tv::sandbox`) had a `cfg_attr(..., expect(dead_code))` that became an unfulfilled expectation once the enum was `pub`; it is gone. - **FFI moved byte for byte.** `webos.rs`'s `extern "C"` blocks and `storage_service/{auxv,bus}.rs` diff --git a/docs/platform-ports.md b/docs/platform-ports.md index c516f7c551..45f9329ffc 100644 --- a/docs/platform-ports.md +++ b/docs/platform-ports.md @@ -842,7 +842,10 @@ split by who reads it (critic M4): 1. `tv::Services` (`plx_os::tv`, installed once by `run_application`) holds what LOWER layers read through the private `tv::port()` (F5): - - `identity { probe_device, start_capability_probe, repair_sandbox, system_locale, sound_output }`; + - `identity { probe_device, start_capability_probe, repair_native_video: Option Result<(), Failure>>, + device_files: Files, system_locale, sound_output }` (`repair_native_video` is optional: `None` is a platform + with nothing to repair, and the repair then answers `Failure::Unsupported`; `device_files` is the reader + `devcaps` parses through, `Files::NONE` for a platform with none); - `secure { seal, open, remove, mode }` (Target shape 4; until W2 `mode` is W3a's own once-set value); - `system { go_home, poll_home, deliver_toast }`; - `legacy_webos_media { sink, display_sink, uri_media }`: the Starfish, ACB and `com.webos.media` verbs (F31), diff --git a/rust-modules/appkit/src/player_hud/state.rs b/rust-modules/appkit/src/player_hud/state.rs index 9acb821e25..d9da6e84d1 100644 --- a/rust-modules/appkit/src/player_hud/state.rs +++ b/rust-modules/appkit/src/player_hud/state.rs @@ -587,9 +587,9 @@ fn failure_glyph(kind: plx_media::player::FailureKind) -> plx_ui::icons::Icon { impl FailureReadout { /// Pure projection of the app's complete failure snapshot, including the repair status. pub fn captured(mut e: plx_media::player::ErrorShape, actions: Vec, - support: String, repair_status: plx_os::tv::sandbox::State) -> Self { + support: String, repair_status: plx_os::tv::native_video::State) -> Self { if e.kind == plx_media::player::FailureKind::JailMissingRtkmem { - use plx_os::tv::sandbox::State; + use plx_os::tv::native_video::State; match repair_status { State::Idle => {} State::Running => { @@ -726,8 +726,8 @@ pub fn failure_row_drawn(busy: Busy) -> bool { } /// Product copy is resolved here; the worker's technical error identity stays unchanged. -fn repair_failure_message(reason: plx_os::tv::sandbox::Failure) -> &'static str { - use plx_os::tv::sandbox::Failure; +fn repair_failure_message(reason: plx_os::tv::native_video::Failure) -> &'static str { + use plx_os::tv::native_video::Failure; match reason { Failure::StartFailed => plx_os::i18n::msg::widgets_repair_start_failed(), Failure::HbcUnavailable => plx_os::i18n::msg::widgets_repair_hbc_unavailable(), diff --git a/rust-modules/media/src/player/adapter.rs b/rust-modules/media/src/player/adapter.rs index 6388c782a4..0dcfcf7f17 100644 --- a/rust-modules/media/src/player/adapter.rs +++ b/rust-modules/media/src/player/adapter.rs @@ -507,7 +507,7 @@ pub struct PlayerAdapter { abr_inbox: Option<(crate::route::RouteStartAttempt, crate::adaptive::AbrInbox)>, /// Backend-independent periodic reporting resource for the current physical attempt. timeline: Option, - repair: Option<(u64, std::sync::mpsc::Receiver>)>, + repair: Option<(u64, std::sync::mpsc::Receiver>)>, release: super::release::NativeRelease, /// Effects produced by an addressed URI release while the backend poll has no session /// borrow. The release machine owns the sole queued transaction; these are only its IO work. @@ -1759,11 +1759,11 @@ impl PlayerAdapter { let Some(token) = owner.begin(supported) else { return; }; let (tx, rx) = std::sync::mpsc::channel(); if plx_base::task::spawn_small("jail repair", move || { - let _ = tx.send(plx_os::tv::sandbox::repair()); + let _ = tx.send(plx_os::tv::native_video::repair()); }) { self.repair = Some((token, rx)); } else { - owner.complete(token, Err(plx_os::tv::sandbox::Failure::StartFailed)); + owner.complete(token, Err(plx_os::tv::native_video::Failure::StartFailed)); } } @@ -1773,7 +1773,7 @@ impl PlayerAdapter { let result = match rx.try_recv() { Ok(result) => result, Err(std::sync::mpsc::TryRecvError::Empty) => return false, - Err(std::sync::mpsc::TryRecvError::Disconnected) => Err(plx_os::tv::sandbox::Failure::StartFailed), + Err(std::sync::mpsc::TryRecvError::Disconnected) => Err(plx_os::tv::native_video::Failure::StartFailed), }; let changed = owner.complete(*token, result); self.repair = None; @@ -2254,7 +2254,7 @@ impl PlayerAdapter { #[cfg(test)] mod repair_receipt_tests { use super::*; - use plx_os::tv::sandbox::{Failure, State}; + use plx_os::tv::native_video::{Failure, State}; #[test] fn local_metric_history_evicts_old_effects_after_real_reducer_results() { use super::super::attempt_metrics::{Origin, RequestOutcome, Tick, Fx}; diff --git a/rust-modules/media/src/player/machine.rs b/rust-modules/media/src/player/machine.rs index dc9ed736a9..b1aec7038b 100644 --- a/rust-modules/media/src/player/machine.rs +++ b/rust-modules/media/src/player/machine.rs @@ -130,21 +130,21 @@ impl Default for Player { /// Logical repair authority; resource handles live in PlayerAdapter. No reset-on-playback API. pub struct RepairAttempt { - state: plx_os::tv::sandbox::State, + state: plx_os::tv::native_video::State, } impl RepairAttempt { - pub const fn new() -> Self { Self { state: plx_os::tv::sandbox::State::Idle } } - pub fn state(&self) -> plx_os::tv::sandbox::State { self.state } + pub const fn new() -> Self { Self { state: plx_os::tv::native_video::State::Idle } } + pub fn state(&self) -> plx_os::tv::native_video::State { self.state } pub fn begin(&mut self, supported: bool) -> Option { - use plx_os::tv::sandbox::{State, Failure}; + use plx_os::tv::native_video::{State, Failure}; if self.state != State::Idle { return None; } if !supported { self.state = State::Failed(Failure::Unsupported); return None; } self.state = State::Running; Some(1) } /// The single issued token can land only once. Wrong/duplicate completions cannot rewrite it. - pub fn complete(&mut self, token: u64, result: Result<(), plx_os::tv::sandbox::Failure>) -> bool { - use plx_os::tv::sandbox::State; + pub fn complete(&mut self, token: u64, result: Result<(), plx_os::tv::native_video::Failure>) -> bool { + use plx_os::tv::native_video::State; if token != 1 || self.state != State::Running { return false; } self.state = match result { Ok(()) => State::Repaired, Err(e) => State::Failed(e) }; true @@ -154,7 +154,7 @@ impl RepairAttempt { #[cfg(test)] mod repair_tests { use super::*; - use plx_os::tv::sandbox::Failure; + use plx_os::tv::native_video::Failure; // `repair_survives_screen_and_session_recreation_and_rejects_stale_completions` builds a // `PlayerScreen`, which `player` may not name: it lives in `screens::player`'s // `repair_confirmation_tests`, beside the screen it recreates. diff --git a/rust-modules/media/src/player/mod.rs b/rust-modules/media/src/player/mod.rs index 06dcdf7bc7..a4335fd364 100644 --- a/rust-modules/media/src/player/mod.rs +++ b/rust-modules/media/src/player/mod.rs @@ -998,7 +998,7 @@ pub enum FailureKind { TvPipeline, /// This device's jail is missing `/dev/rtkmem` on a SoC where that is a known cause of /// native A/V crashes — the Load was never attempted. Community-tier finding: see - /// [`plx_os::tv::sandbox::blocks_native_video`]'s doc. + /// [`plx_os::tv::native_video::blocked`]'s doc. JailMissingRtkmem, /// Issue #74 D.1.4's `NATIVE_LOAD_BUDGET` fired — either the native `Load` call never /// returned, or it returned but `loadCompleted` never arrived. Distinct from @@ -1157,7 +1157,7 @@ pub fn failure_context_captured(ps: &crate::route::PlaybackSession, diagnostic_f FailureContext { forced: crate::route::forced_direct_play(ps) || diagnostic_forced, can_retry: crate::route::can_retry_current_play(ps), - repair_idle: ps.repair_status == plx_os::tv::sandbox::State::Idle, + repair_idle: ps.repair_status == plx_os::tv::native_video::State::Idle, } } @@ -1227,9 +1227,9 @@ fn live_runtime_failure(ps: &crate::route::PlaybackSession) -> RuntimeFailure { /// [`error_shape`], because it precedes route resolution entirely: it names a device finding, not /// a decision the server or the runtime made. Phrased as a FINDING throughout — "found... known /// to..." — never as a certain diagnosis, matching the community-tier evidence it is built on -/// (see [`plx_os::tv::sandbox::blocks_native_video`]'s doc). Caption and readout are kept short for +/// (see [`plx_os::tv::native_video::blocked`]'s doc). Caption and readout are kept short for /// legibility from a phone photograph, same bar as every other arm here; the remedy's detail goes -/// in `detail`. `Player.repair` (see `tv::sandbox`) can actually attempt the Homebrew +/// in `detail`. `Player.repair` (see `tv::native_video`) can actually attempt the Homebrew /// Channel service call that patches the jail profile, so the remedy text points at that confirmed /// in-app repair rather than at a bare reinstall. fn jail_error_shape() -> ErrorShape { @@ -4754,7 +4754,7 @@ mod native_failure_regressions { use super::*; struct JailGuard; impl Drop for JailGuard { - fn drop(&mut self) { plx_os::tv::sandbox::FORCE_BLOCKED.store(false, Relaxed); } + fn drop(&mut self) { plx_os::tv::native_video::FORCE_BLOCKED.store(false, Relaxed); } } #[test] fn jail_refusal_enters_error_without_engine_and_retires_on_exit() { @@ -4764,7 +4764,7 @@ mod native_failure_regressions { crate::route::reset_player_control_for_test(&ps); crate::player::reset_session_for_test(); let mut pa = adapter::PlayerAdapter::new_fed(unsafe { plx_base::task::MainThread::assume() }); - plx_os::tv::sandbox::FORCE_BLOCKED.store(true, Relaxed); + plx_os::tv::native_video::FORCE_BLOCKED.store(true, Relaxed); assert!(start_bufferfeed(&mut ps, &mut pa)); assert!(!pa.is_live()); assert_eq!(state(&ps), PlaybackState::Error); diff --git a/rust-modules/media/src/player/route_start.rs b/rust-modules/media/src/player/route_start.rs index e59eaa4e91..88ddfa2762 100644 --- a/rust-modules/media/src/player/route_start.rs +++ b/rust-modules/media/src/player/route_start.rs @@ -56,7 +56,7 @@ pub fn start_bufferfeed_tracked(ps: &mut crate::route::PlaybackSession, pa: &mut let uri_chosen = matches!(ps.backend_offer(), crate::route::backend_policy::Selection::Open(offer) if offer.backend == plx_playback_contract::BackendKind::Uri); - if !uri_chosen && plx_os::tv::sandbox::blocks_native_video() { + if !uri_chosen && plx_os::tv::native_video::blocked() { ps.jail_load_blocked = true; log("start_bufferfeed: refusing native video; affected chassis cannot read /dev/rtkmem"); if let Some(ticket) = crate::route::begin_route_start() { diff --git a/rust-modules/media/src/route/decision.rs b/rust-modules/media/src/route/decision.rs index b6dd22a25b..d150d6b920 100644 --- a/rust-modules/media/src/route/decision.rs +++ b/rust-modules/media/src/route/decision.rs @@ -196,7 +196,7 @@ pub struct PlaybackSession { /// and a scrobble on top would be a second view. Read and cleared by [`scrobble_stop`]. pub finished: bool, /// Read-only publication of Player.repair for the HUD. Never authorizes a resource effect. - pub repair_status: plx_os::tv::sandbox::State, + pub repair_status: plx_os::tv::native_video::State, /// The request which produced this attempt, retained for terminal Retry / Choose quality. /// Written synchronously by [`request_play`] rather than by [`apply_plan`], because the /// server can refuse before a playable plan exists. @@ -1690,7 +1690,7 @@ impl PlaybackSession { native_start_refused: None, engine_failure: None, finished: false, - repair_status: plx_os::tv::sandbox::State::Idle, + repair_status: plx_os::tv::native_video::State::Idle, request: None, requested_resume_ns: 0, url: String::new(), @@ -11540,7 +11540,7 @@ fn apply_plan(ps: &mut PlaybackSession, meta: &mut plx_data::stores::metadata::M native_start_refused: None, engine_failure: None, finished: false, - repair_status: plx_os::tv::sandbox::State::Idle, + repair_status: plx_os::tv::native_video::State::Idle, request, requested_resume_ns, url: plan.url, diff --git a/rust-modules/os/src/devcaps.rs b/rust-modules/os/src/devcaps.rs index dee51183de..f2c1934c65 100644 --- a/rust-modules/os/src/devcaps.rs +++ b/rust-modules/os/src/devcaps.rs @@ -39,6 +39,7 @@ //! before this module. Misreading the table must degrade to yesterday's behavior, not invent a //! weaker television: the issue-#22 lesson cuts both ways, and a client that suddenly transcodes //! everything on a healthy 4K panel is as wrong as one that direct-plays HEVC to a SoC without it. +use crate::tv::device::Files; use std::borrow::Cow; use std::sync::OnceLock; @@ -334,7 +335,7 @@ pub enum Limit { /// takes only an IDR first ([`Limit::DvFirstPictureIdr`]), which the player answers by withdrawing the /// declaration at a landing the splitter would skip. /// -/// The key is the firmware codename (`tv::device::Info::codename`, nyx's `webos_release_codename`), +/// The key is the firmware codename (`tv::device::WebosDetail::codename`, nyx's `webos_release_codename`), /// the one identity the app reads reliably on every set: it groups the sets that run the same /// build of the media stack, which is what decides the decoder's behaviour, where the retail model /// name (`product_id`, absent on some firmware) and the SoC class would split one stack or merge two. @@ -1525,11 +1526,12 @@ impl Drop for AudioStackGuard { } } -/// Read the table once and log what was derived. Called at boot right after `webos::probe`, -/// before anything can fail; safe when the file does not exist (older/odd firmware → assumed). -pub fn probe() { +/// The device table and `gstcool.conf` through `files`, parsed and logged: the caps this set +/// announces before the firmware exclusions, and whether they were READ ([`MEASURED`]) or are the +/// assumed fallback. Every failure to read or parse lands on [`Caps::assumed`], with its line. +fn read_caps(files: &Files) -> (Caps, bool) { let mut measured = false; - let caps = match std::fs::read_to_string(CAPS_TABLE) { + let caps = match (files.read)(CAPS_TABLE) { Ok(s) => match parse(&s) { Some(c) => { measured = true; @@ -1547,7 +1549,7 @@ pub fn probe() { plx_base::eventlog::log(&format!("devcaps: table audio rows: {}", table_audio_rows(&s))); c.vp9_bit_depth = vp9_bit_depth_for(crate::tv::device::info().major); // Before the exclusions: a codec the conf lists as switched off is not a candidate to limit. - let (gst_dropped, gst_unlisted) = match std::fs::read_to_string(GST_CONF) { + let (gst_dropped, gst_unlisted) = match (files.read)(GST_CONF) { Ok(conf) => apply_gst_decoders(&mut c, &conf), Err(_) => (Vec::new(), Vec::new()), }; @@ -1586,6 +1588,15 @@ pub fn probe() { Caps::assumed() } }; + (caps, measured) +} + +/// Read the table once and log what was derived. Called at boot right after `webos::probe`, +/// before anything can fail; safe when the file does not exist (older/odd firmware → assumed). +/// The files are read the platform's way (`tv::device::files`); this model only parses them. +pub fn probe() { + let files = crate::tv::device::files(); + let (caps, measured) = read_caps(&files); let _ = MEASURED.set(measured); let info = crate::tv::device::info(); let (wide, learn, forget) = ( @@ -1600,10 +1611,10 @@ pub fn probe() { // the AUDIO exclusions (a row's `dv_first_picture` stays, it is not an audio fact) and the learned // layer (`nativeaudiolearn` beside it keeps the layer), // `nativeaudioforget` the record. - let stack = audio_stack_from(|path| std::path::Path::new(path).exists()); + let stack = audio_stack_from(|path| (files.exists)(path)); let _ = AUDIO_STACK.set(stack); let mut boot = caps.clone(); - let excluded = apply_exclusions(&mut boot, &info.codename, wide, EXCLUSIONS); + let excluded = apply_exclusions(&mut boot, &info.webos.codename, wide, EXCLUSIONS); if plx_base::devtrig::flag("appdecodelossy") { boot = boot.with_app_lossy(); #[cfg(feature = "devtriggers")] @@ -1636,7 +1647,7 @@ pub fn probe() { )); plx_base::eventlog::log(&format!( "devcaps: firmware={:?} build={:?} audio stack={} audio layers: table+gst={} | exclusions: {} | -> audio={}{}{}", - info.codename, + info.webos.codename, info.build, stack.label(), caps.audio, @@ -1649,7 +1660,7 @@ pub fn probe() { }, if forget { " (nativeaudioforget: stored refusals ignored this run)" } else { "" }, )); - let _ = BOOT.set(Boot::new(boot, info.codename.clone(), info.build.clone(), (wide, learn, forget))); + let _ = BOOT.set(Boot::new(boot, info.webos.codename.clone(), info.build.clone(), (wide, learn, forget))); } /// Whether [`caps`] reflects THIS set's table or the assumed profile — see [`MEASURED`]. @@ -3184,4 +3195,60 @@ mod tests { let capped = Caps { video_ceiling: [("av1".to_owned(), (1280, 720))].into(), ..caps }; assert_eq!(capped.raster_bound("av1"), (1280, 720)); } + + /// A platform serving the real device table and a `gstcool.conf` with DTS switched off. + const SERVES_TABLE_AND_CONF: Files = Files { + read: |path| match path { + CAPS_TABLE => Ok(REAL.to_owned()), + GST_CONF => Ok(GST_C1.replace("dts_audiodec=290", "dts_audiodec=0")), + _ => Err(std::io::ErrorKind::NotFound.into()), + }, + exists: |path| path == LXAUDIOSINK_PLUGIN, + }; + + /// A platform serving the table and no `gstcool.conf` (the conf is optional: a set without it keeps + /// every codec the table lists). + const SERVES_TABLE_ONLY: Files = Files { + read: |path| match path { + CAPS_TABLE => Ok(REAL.to_owned()), + _ => Err(std::io::ErrorKind::NotFound.into()), + }, + exists: |_| false, + }; + + /// A platform whose table is not the JSON this model reads. + const SERVES_GARBAGE: Files = Files { + read: |_| Ok("not a device table".to_owned()), + exists: |_| false, + }; + + /// The model parses what the platform READ and performs no read of its own: a platform with no + /// files is the assumed profile, unmeasured, which is what a set whose table is absent answers. + #[test] + fn a_platform_with_no_device_files_gets_the_assumed_profile_unmeasured() { + assert_eq!(read_caps(&Files::NONE), (Caps::assumed(), false)); + } + + #[test] + fn a_table_the_model_cannot_parse_gets_the_assumed_profile_unmeasured() { + assert_eq!(read_caps(&SERVES_GARBAGE), (Caps::assumed(), false)); + } + + /// The caps are the table's, minus what the conf the platform served switches off, and measured. + #[test] + fn the_table_and_conf_the_platform_serves_are_parsed_into_measured_caps() { + let (caps, measured) = read_caps(&SERVES_TABLE_AND_CONF); + assert!(measured); + let mut expected = parse(REAL).unwrap(); + expected.vp9_bit_depth = vp9_bit_depth_for(crate::tv::device::info().major); + let conf = GST_C1.replace("dts_audiodec=290", "dts_audiodec=0"); + assert_eq!(apply_gst_decoders(&mut expected, &conf).0, ["dts"]); + assert_eq!(caps, expected); + assert!(!caps.audio_has("dts"), "the served conf switched DTS off"); + assert_eq!(caps.hevc_row, (4096, 2176, 60)); + + let (kept, measured) = read_caps(&SERVES_TABLE_ONLY); + assert!(measured, "a missing gstcool.conf does not make the table any less read"); + assert!(kept.audio_has("dts"), "without the conf nothing is dropped"); + } } diff --git a/rust-modules/os/src/keymanager.rs b/rust-modules/os/src/keymanager.rs index fad80c915c..0bf228480d 100644 --- a/rust-modules/os/src/keymanager.rs +++ b/rust-modules/os/src/keymanager.rs @@ -52,11 +52,14 @@ pub fn open(sealed: &Sealed) -> Option> { if sealed.key != KEY_NAME { return None; } - match sealed.backend { - Backend::Keymanager3 => modern_crypt(sealed.data.as_bytes(), Some(&sealed.iv)), - // Kept only so an interim/pre-release envelope deserializes as locked instead of being - // mistaken for plaintext. AES-CFB does not authenticate the file, so never open it. - Backend::PalmKeymanager => None, + if sealed.backend == Backend::KEYMANAGER3 { + modern_crypt(sealed.data.as_bytes(), Some(&sealed.iv)) + } else { + // `PALM_KEYMANAGER` is kept only so an interim/pre-release envelope deserializes as locked + // instead of being mistaken for plaintext: AES-CFB does not authenticate the file, so never + // open it. A tag this platform has no key manager for is refused the same way, and is never + // handed to keymanager3 on the strength of its key name alone. + None } .and_then(|s| b64::decode(&s.data)) } @@ -65,15 +68,20 @@ pub fn remove(backend: &Backend, key: &str) { if key != KEY_NAME { return; } - let _ = match backend { - Backend::Keymanager3 => call( + let _ = if *backend == Backend::KEYMANAGER3 { + call( "luna://com.webos.service.keymanager3/removeKey", &json!({"name": key}), - ), - Backend::PalmKeymanager => call( + ) + } else if *backend == Backend::PALM_KEYMANAGER { + call( "luna://com.palm.keymanager/remove", &json!({"keyname": key}), - ), + ) + } else { + // Not a store this platform has: no service is asked, and the backend cache below is left + // as it was (nothing was deleted). + return; }; // `clear()` deletes the key and the file in one sign-out. A later sign-in in the same process // must run key creation again rather than trusting the now-stale backend cache. @@ -166,7 +174,7 @@ fn modern_crypt(input: &[u8], iv: Option<&str>) -> Option { return None; } Some(Sealed { - backend: Backend::Keymanager3, + backend: Backend::KEYMANAGER3, key: KEY_NAME.to_string(), iv: generated_iv, data: finish.get("output")?.as_str()?.to_string(), @@ -298,14 +306,14 @@ mod tests { fn removing_the_key_invalidates_the_backend_cache() { let _guard = plx_base::testlock::serial(); SELECTED.store(MODERN, Ordering::Relaxed); - remove(&Backend::Keymanager3, super::KEY_NAME); + remove(&Backend::KEYMANAGER3, super::KEY_NAME); assert_eq!(SELECTED.load(Ordering::Relaxed), UNKNOWN); } #[test] fn unauthenticated_legacy_ciphertext_is_never_opened() { let sealed = Sealed { - backend: Backend::PalmKeymanager, + backend: Backend::PALM_KEYMANAGER, key: super::KEY_NAME.into(), iv: "legacy-iv".into(), data: b64::encode(b"attacker-controlled ciphertext"), @@ -313,6 +321,30 @@ mod tests { assert!(open(&sealed).is_none()); } + /// A tag this platform has no key manager for (another platform's, or one from the future) is + /// refused on open and ignored on remove, with the bus never asked: it must not be handed to + /// keymanager3 because its key name happens to match, and a sign-out must not delete the + /// keymanager3 key on the strength of a file some other store wrote. + #[test] + fn an_envelope_tagged_for_a_store_this_platform_lacks_is_refused_without_asking_a_service() { + let _guard = plx_base::testlock::serial(); + reset_for_test(); + RPC_FOR_TEST.with(|hook| hook.set(Some(|uri, _| panic!("a service was asked: {uri}")))); + let foreign = Backend::new("host_file"); + let sealed = Sealed { + backend: foreign.clone(), + key: super::KEY_NAME.into(), + iv: "iv".into(), + data: b64::encode(b"sealed by another platform"), + }; + assert!(open(&sealed).is_none()); + SELECTED.store(MODERN, Ordering::Relaxed); + remove(&foreign, super::KEY_NAME); + assert_eq!(SELECTED.load(Ordering::Relaxed), MODERN, "nothing was removed, so the cache is not stale"); + RPC_FOR_TEST.with(|hook| hook.set(None)); + reset_for_test(); + } + /// The protocol round trip, over a synthetic LS2 transport that returns what it was given: it /// does not claim to test cryptography or firmware availability, only that `seal` and `open` /// walk generateKey, begin and finish in order and agree on the envelope. @@ -332,7 +364,7 @@ mod tests { Ok(response.to_string()) }))); let sealed = seal(b"secret").expect("the synthetic transport seals"); - assert_eq!(sealed.backend, Backend::Keymanager3); + assert_eq!(sealed.backend, Backend::KEYMANAGER3); assert_eq!(sealed.key, super::KEY_NAME); assert_eq!(sealed.iv, "synthetic-iv"); assert_eq!(open(&sealed).as_deref(), Some(&b"secret"[..])); diff --git a/rust-modules/os/src/tv.rs b/rust-modules/os/src/tv.rs index 558ecb9aa0..752c3bc93c 100644 --- a/rust-modules/os/src/tv.rs +++ b/rust-modules/os/src/tv.rs @@ -2,8 +2,8 @@ pub mod device; pub mod home; pub mod launch; +pub mod native_video; pub mod plane; -pub mod sandbox; pub mod secure; pub mod sink; pub mod sound; @@ -35,7 +35,12 @@ pub struct Services { pub struct IdentityHooks { pub probe_device: fn(), pub start_capability_probe: fn(), - pub repair_sandbox: fn() -> Result<(), sandbox::Failure>, + /// The user-confirmed repair of a blocked native video path ([`native_video::repair`]), for a + /// platform that has one. `None` is a platform with nothing to repair: the repair then answers + /// [`native_video::Failure::Unsupported`]. + pub repair_native_video: Option Result<(), native_video::Failure>>, + /// The files the capability probe parses, read the platform's way ([`device::files`]). + pub device_files: device::Files, pub system_locale: fn() -> LocaleReply, pub sound_output: fn() -> sound::Reply, } @@ -71,12 +76,13 @@ pub struct LegacyWebosMedia { fn nothing() {} impl IdentityHooks { - /// A platform with no identity of its own to publish: nothing is probed, the sandbox cannot be + /// A platform with no identity of its own to publish: nothing is probed, native video 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), + repair_native_video: None, + device_files: device::Files::NONE, system_locale: || LocaleReply::NoPlatform, sound_output: || sound::Reply::NoPlatform, }; @@ -150,7 +156,7 @@ mod tests { #[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 }, + identity: IdentityHooks { probe_device, start_capability_probe, repair_native_video, device_files, 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 }, @@ -158,19 +164,26 @@ mod tests { probe_device(); start_capability_probe(); - assert_eq!(repair_sandbox(), Err(sandbox::Failure::Unsupported)); + assert!(repair_native_video.is_none(), "a platform with nothing to repair states no hook"); + assert_eq!(native_video::repair(), Err(native_video::Failure::Unsupported)); + assert_eq!( + (device_files.read)("/etc/umediaserver/device_codec_capability_config.json").unwrap_err().kind(), + std::io::ErrorKind::NotFound, + "no files: a read fails as a missing file does" + ); + assert!(!(device_files.exists)("/"), "and nothing exists"); assert!(matches!(system_locale(), LocaleReply::NoPlatform)); assert!(matches!(sound_output(), sound::Reply::NoPlatform)); let sealed = secure::Sealed { - backend: secure::Backend::Keymanager3, + 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"); + remove(&secure::Backend::PALM_KEYMANAGER, "k"); assert_eq!(mode, secure::StoreMode::Durable, "no key manager is not a memory-only platform"); go_home(); @@ -197,7 +210,7 @@ mod tests { // 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!(native_video::repair(), Err(native_video::Failure::Unsupported)); assert_eq!(uri::installed().open(uri::Shape::Anon), Err("no bus".into())); } } diff --git a/rust-modules/os/src/tv/device.rs b/rust-modules/os/src/tv/device.rs index a7474574cf..d9e824da7b 100644 --- a/rust-modules/os/src/tv/device.rs +++ b/rust-modules/os/src/tv/device.rs @@ -1,10 +1,14 @@ -//! Which television this is: the firmware ([`Info`]) and the set ([`Hardware`]). The webOS port -//! reads them at boot and publishes them here; everything else reads them from here. +//! Which television this is: the firmware ([`Info`]) and the set ([`Hardware`]), what the platform +//! calls itself to a Plex server ([`Platform`]) and the files its capability probe reads +//! ([`Files`]). The webOS port reads and publishes them at boot; everything else reads them from here. use std::sync::OnceLock; /// What the set said about itself. Owned strings rather than borrows into the file, because the /// file is read once and dropped; `OnceLock` because this is written exactly once, at boot, and /// read from the render thread every frame the diagnostics panel is up. +/// +/// `release`, `build` and `major` are the OS-version facts every platform states. What only a webOS +/// firmware file says is [`WebosDetail`], behind [`Info::webos`]. #[derive(Debug, Default, Clone)] pub struct Info { /// e.g. "4.10.2" — empty when unknown @@ -14,30 +18,38 @@ pub struct Info { /// when the release came from `/usr/lib/os-release`, which names no build). A /// patch within one release changes this and not `release`. pub build: String, + /// leading component of `release`, or 0 when unknown + pub major: u32, + /// What only a webOS firmware says about itself. All-empty on every other platform. + pub webos: WebosDetail, +} + +/// The firmware facts that are webOS's alone: three keys of nyx's `os_info.json`. The webOS +/// platform owns them: its probe is the only writer, no other platform has a value to put here, and +/// a reader that prints one prints a webOS fact (the codename is also the key the firmware +/// exclusions and the learned refusals are filed under). Empty when unknown, like [`Info`]'s own. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct WebosDetail { /// e.g. "goldilocks2-grampians" — webosbrew buckets firmware by this pub codename: String, /// e.g. "4.1.0" pub api: String, /// e.g. "webOS TV" pub name: String, - /// leading component of `release`, or 0 when unknown - pub major: u32, } static INFO: OnceLock = OnceLock::new(); static NO_INFO: Info = Info { release: String::new(), build: String::new(), - codename: String::new(), - api: String::new(), - name: String::new(), major: 0, + webos: WebosDetail { codename: String::new(), api: String::new(), name: String::new() }, }; /// What the set reported. All-empty with `major == 0` when neither `os_info.json` nor /// `/usr/lib/os-release` could be read — which is the honest answer and is what the panel prints. -/// A release that only `/usr/lib/os-release` named leaves the codename, API version, name and -/// build empty. A plain `get()` (never `get_or_init`), so a read +/// A release that only `/usr/lib/os-release` named leaves the [`WebosDetail`] (codename, API +/// version, name) and the build empty. A plain `get()` (never `get_or_init`), so a read /// that races ahead of the boot probe sees the empty answer for itself and leaves the cell open for /// [`publish_info`]. pub fn info() -> &'static Info { @@ -179,6 +191,56 @@ pub fn publish_probe(probe: Probe) { let _ = PROBE.set(probe); } +/// What the platform calls itself to a Plex server: the `X-Plex-Platform` and +/// `X-Plex-Platform-Version` every request carries. The platform states them once at boot +/// ([`publish_platform`]); `plex::identity` reports its own default until it does. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Platform { + /// e.g. "webOS" + pub name: &'static str, + /// The platform's version as a Plex server should read it, e.g. "6.5.2". + pub version: String, +} + +static PLATFORM: OnceLock = OnceLock::new(); + +/// What the platform published, or `None` before it has (a read racing ahead of the boot probe, or +/// a host test). A plain `get()` like [`info`], so an early read leaves the cell open for +/// [`publish_platform`]. +pub fn platform() -> Option<&'static Platform> { + PLATFORM.get() +} + +/// The boot probe's answer. First write wins, like the `OnceLock` it lands in. +pub fn publish_platform(platform: Platform) { + let _ = PLATFORM.set(platform); +} + +/// The files the capability probe (`devcaps::probe`) parses, read by the platform. The probe owns +/// what a file means and where the model looks for it; the platform owns reading it, so the model +/// performs no IO of its own. The platform states them as `Services.identity.device_files`. +#[derive(Clone, Copy)] +pub struct Files { + /// The text of the file at an absolute path, or why it could not be read: the error is logged + /// by the caller, verbatim. + pub read: fn(&str) -> std::io::Result, + /// Whether a file or directory exists at an absolute path (a stat, never an open). + pub exists: fn(&str) -> bool, +} + +impl Files { + /// A platform with no such files: every read fails as a missing file does, and nothing exists. + pub const NONE: Self = Self { + read: |_| Err(std::io::ErrorKind::NotFound.into()), + exists: |_| false, + }; +} + +/// The installed platform's [`Files`]. +pub fn files() -> Files { + super::services().identity.device_files +} + #[cfg(test)] mod tests { use super::*; diff --git a/rust-modules/os/src/tv/native_video.rs b/rust-modules/os/src/tv/native_video.rs new file mode 100644 index 0000000000..70cce9c83f --- /dev/null +++ b/rust-modules/os/src/tv/native_video.rs @@ -0,0 +1,181 @@ +//! Whether this set may start a native video Load, and the user-confirmed repair of a refusal. The +//! platform's boot probe publishes the verdict here and the player gates on it. webOS answers it +//! by probing `/dev/rtkmem`; a platform with nothing to ask publishes nothing, and the verdict is +//! then `NotApplicable`. +use std::sync::OnceLock; + +/// What the boot-time probe found, cached for the process. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Verdict { + /// The platform probed and the video path is there. On webOS: the SoC matched the affected + /// family and `/dev/rtkmem` is readable. + Available, + /// The platform probed and the video path is not usable here, so a Load must not be attempted. + /// The reason is a constant word the platform names; it is printed, in the log and as the + /// report's context ([`context`]), and no shared code branches on it. On webOS: the SoC matched + /// the affected family and `/dev/rtkmem` is missing (or unreadable) from this jail, reason + /// `"missing"`. + Blocked(&'static str), + /// There is nothing to ask: nothing was probed, or the platform's probe found the set outside + /// the family it asks about. On webOS: the SoC did not match, so `/dev/rtkmem` was never probed. + NotApplicable, +} + +static VERDICT: OnceLock = OnceLock::new(); + +/// The boot probe's verdict, once per boot. First write wins, like the `OnceLock` it lands in. +pub fn publish(verdict: Verdict) { + let _ = VERDICT.set(verdict); +} + +/// TEST ONLY: force [`blocked`] to report blocked, without touching the process-wide `VERDICT` +/// `OnceLock` — a real boot sets that exactly once via the platform's probe, and no test can +/// re-init it to exercise the blocked path. Mirrors `ffi_host.rs`'s `FORCE_*` controls. There is no +/// separate "release" call: `false` is the default, so a test that sets this to `true` must reset +/// it to `false` before returning, under `plx_base::testlock::serial()`. +#[cfg(any(test, feature = "test-support"))] +pub static FORCE_BLOCKED: std::sync::atomic::AtomicBool = + std::sync::atomic::AtomicBool::new(false); + +/// True only when this session must not attempt a native video Load: the platform's probe found +/// the video path unusable ([`Verdict::Blocked`]). On webOS that is the SoC matching the affected +/// family AND `/dev/rtkmem` missing from this jail; the community-tier evidence it is built on is +/// in the webOS port's `probe_jail` section doc. `player::mod` calls this before the first Load of +/// every session. +/// +/// Reads with a plain `get()` (never `get_or_init`) so a call that races ahead of the platform's +/// probe sees `NotApplicable` for itself but leaves the cell EMPTY — a later [`publish`] can still +/// `set()` the real verdict, and every subsequent call observes it. `get_or_init` would instead +/// latch `NotApplicable` permanently on that first early call, silently discarding the real +/// probe's `set()` and leaving the `devjail: … rtkmem=missing` log line contradicted by a gate +/// that reports not-blocked forever. +pub fn blocked() -> bool { + #[cfg(any(test, feature = "test-support"))] + if FORCE_BLOCKED.load(std::sync::atomic::Ordering::Relaxed) { + return true; + } + blocks(&VERDICT) +} + +/// PURE half of [`blocked`]'s verdict, taking the cell as a parameter — so the +/// early-read-vs-later-write race it exists to guard against can be tested against a throwaway +/// local `OnceLock`, rather than by writing into the real process-wide `VERDICT` (which a test can +/// never un-set, and which every later test's `blocked()` call also reads). +fn blocks(cell: &OnceLock) -> bool { + matches!(verdict_of(cell), Verdict::Blocked(_)) +} + +/// What `cell` holds, or [`Verdict::NotApplicable`] when nothing has been published: the one +/// fallback [`blocked`] and [`context`] share, so the gate and the report cannot disagree about a +/// call that raced ahead of the probe. +fn verdict_of(cell: &OnceLock) -> Verdict { + cell.get().copied().unwrap_or(Verdict::NotApplicable) +} + +/// The closed word for a verdict: `ok` for [`Verdict::Available`], `n/a` for +/// [`Verdict::NotApplicable`] and the platform's own reason for [`Verdict::Blocked`] (`missing` on +/// webOS). The vocabulary the telemetry schema and `PRIVACY.md` document. +fn word(verdict: Verdict) -> &'static str { + match verdict { + Verdict::Available => "ok", + Verdict::NotApplicable => "n/a", + Verdict::Blocked(reason) => reason, + } +} + +/// The closed native-video fact for every telemetry event — `ok` / `missing` / `n/a` on webOS — read +/// from the SAME cached verdict [`blocked`] gates playback on, never a second probe of the device. +/// An unset cell (a call racing ahead of boot's probe, the same race [`blocked`]'s doc describes) +/// reads as `n/a` — the same fallback that function uses, so a telemetry event and the gate it +/// would have been diagnosing this attempt's failure against can never disagree about what this +/// jail carries. +pub fn context() -> &'static str { + word(verdict_of(&VERDICT)) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Failure { + StartFailed, + HbcUnavailable, + NotRoot, + CommandFailed, + // The simulator has no LS2 timeout; development fixtures and tests still construct it. The + // enum is public to the application crate, so the variant is never dead in this crate. + Timeout, + Unreadable, + Unsupported, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum State { + Idle, + Running, + Repaired, + Failed(Failure), +} + +/// Called only by the PlayerAdapter worker after the owner accepts explicit confirmation. A platform +/// with no repair (`Services.identity.repair_native_video` is `None`) answers +/// [`Failure::Unsupported`]. +pub fn repair() -> Result<(), Failure> { + match super::services().identity.repair_native_video { + Some(hook) => hook(), + None => Err(Failure::Unsupported), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Regression for `rtkmem-verdict-defeated-by-get-or-init-default`: an early call to + /// `blocked()` (before the platform's probe has ever run) must NOT permanently latch + /// `NotApplicable` into the cell. With the old `get_or_init(|| NotApplicable)` reader this + /// first call would win the race and every later `VERDICT.set(Blocked(..))` from the real probe + /// would be silently dropped (`OnceLock::set` returns `Err` once already initialized) — the + /// gate would report "not blocked" forever while the boot log said `rtkmem=missing`. + /// + /// Exercised against a throwaway local cell via `blocks`, not the process-wide `VERDICT` + /// static — that `OnceLock` can never be un-set, so writing into the real one here would + /// permanently latch `blocked()` to `true` for every other test in this process, + /// un-serialized. See finding + /// `rtkmem-probe-test-permanently-sets-the-process-wide-oncelock`. + #[test] + fn early_read_does_not_defeat_a_later_blocked_verdict() { + let cell: OnceLock = OnceLock::new(); + assert!(!blocks(&cell), "cell must start empty/unset"); + cell.set(Verdict::Blocked("missing")) + .expect("cell was still empty, so this must be the first, winning set()"); + assert!( + blocks(&cell), + "a verdict set after an earlier read must still take effect" + ); + } + + /// The three verdicts, mapped: only a blocked one blocks, and an unpublished cell reads as not + /// applicable for both the gate and the report. + #[test] + fn only_a_blocked_verdict_blocks_and_an_unpublished_one_is_not_applicable() { + for (verdict, blocks_load) in [ + (Verdict::Available, false), + (Verdict::NotApplicable, false), + (Verdict::Blocked("missing"), true), + ] { + let cell = OnceLock::new(); + cell.set(verdict).unwrap(); + assert_eq!(blocks(&cell), blocks_load, "{verdict:?}"); + } + let unset: OnceLock = OnceLock::new(); + assert_eq!(verdict_of(&unset), Verdict::NotApplicable); + assert!(!blocks(&unset)); + } + + /// The words telemetry, the log and `PRIVACY.md` carry for the jail pre-flight. A blocked + /// verdict reads as the reason its platform named, which on webOS is `missing`. + #[test] + fn the_context_words_are_ok_missing_and_not_applicable() { + assert_eq!(word(Verdict::Available), "ok"); + assert_eq!(word(Verdict::Blocked("missing")), "missing"); + assert_eq!(word(Verdict::NotApplicable), "n/a"); + } +} diff --git a/rust-modules/os/src/tv/sandbox.rs b/rust-modules/os/src/tv/sandbox.rs deleted file mode 100644 index a23cad15db..0000000000 --- a/rust-modules/os/src/tv/sandbox.rs +++ /dev/null @@ -1,129 +0,0 @@ -//! The jail's verdict on the video path, and the user-confirmed repair of it. The webOS port -//! probes `/dev/rtkmem` at boot and publishes the verdict here; the player gates on it. -use std::sync::OnceLock; - -/// The three outcomes of the boot-time probe, cached for the process. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Verdict { - /// The SoC did not match the affected family — `/dev/rtkmem` was never probed. - NotApplicable, - /// The SoC matched and `/dev/rtkmem` is readable. - Ok, - /// The SoC matched and `/dev/rtkmem` is missing (or unreadable) from this jail. - Missing, -} - -static VERDICT: OnceLock = OnceLock::new(); - -/// The boot probe's verdict, once per boot. First write wins, like the `OnceLock` it lands in. -pub fn publish(verdict: Verdict) { - let _ = VERDICT.set(verdict); -} - -/// TEST ONLY: force [`blocks_native_video`] to report blocked, without touching the process-wide -/// `VERDICT` `OnceLock` — a real boot sets that exactly once via the port's probe, and no test can -/// re-init it to exercise the blocked path. Mirrors `ffi_host.rs`'s `FORCE_*` controls. There is no -/// separate "release" call: `false` is the default, so a test that sets this to `true` must reset -/// it to `false` before returning, under `plx_base::testlock::serial()`. -#[cfg(any(test, feature = "test-support"))] -pub static FORCE_BLOCKED: std::sync::atomic::AtomicBool = - std::sync::atomic::AtomicBool::new(false); - -/// True only when this session must not attempt a native video Load: the SoC matched the -/// affected family AND `/dev/rtkmem` was missing from this jail. The community-tier evidence it is -/// built on is in the webOS port's `probe_jail` section doc. `player::mod` calls this before the -/// first Load of every session. -/// -/// Reads with a plain `get()` (never `get_or_init`) so a call that races ahead of the port's -/// probe sees `NotApplicable` for itself but leaves the cell EMPTY — a later [`publish`] can still -/// `set()` the real verdict, and every subsequent call observes it. `get_or_init` would instead -/// latch `NotApplicable` permanently on that first early call, silently discarding the real -/// probe's `set()` and leaving the `devjail: … rtkmem=missing` log line contradicted by a gate -/// that reports not-blocked forever. -pub fn blocks_native_video() -> bool { - #[cfg(any(test, feature = "test-support"))] - if FORCE_BLOCKED.load(std::sync::atomic::Ordering::Relaxed) { - return true; - } - blocks(&VERDICT) -} - -/// PURE half of [`blocks_native_video`]'s verdict, taking the cell as a parameter — so the -/// early-read-vs-later-write race it exists to guard against can be tested against a throwaway -/// local `OnceLock`, rather than by writing into the real process-wide `VERDICT` (which a test can -/// never un-set, and which every later test's `blocks_native_video()` call also reads). -fn blocks(cell: &OnceLock) -> bool { - matches!( - cell.get().copied().unwrap_or(Verdict::NotApplicable), - Verdict::Missing - ) -} - -/// The closed-enum sandbox fact for every telemetry event — `ok` / `missing` / `n/a` — read from -/// the SAME cached verdict [`blocks_native_video`] gates playback on, never a second probe of -/// `/dev/rtkmem`. An unset cell (a call racing ahead of boot's probe, the same race -/// [`blocks_native_video`]'s doc describes) reads as `n/a` — the same fallback that function uses, -/// so a telemetry event and the gate it would have been diagnosing this attempt's failure against -/// can never disagree about what this jail carries. -pub fn context() -> &'static str { - match VERDICT.get().copied().unwrap_or(Verdict::NotApplicable) { - Verdict::NotApplicable => "n/a", - Verdict::Ok => "ok", - Verdict::Missing => "missing", - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Failure { - StartFailed, - HbcUnavailable, - NotRoot, - CommandFailed, - // The simulator has no LS2 timeout; development fixtures and tests still construct it. The - // enum is public to the application crate, so the variant is never dead in this crate. - Timeout, - Unreadable, - Unsupported, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum State { - Idle, - Running, - Repaired, - Failed(Failure), -} - -/// Called only by the PlayerAdapter worker after the owner accepts explicit confirmation. -pub fn repair() -> Result<(), Failure> { - (super::services().identity.repair_sandbox)() -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Regression for `rtkmem-verdict-defeated-by-get-or-init-default`: an early call to - /// `blocks_native_video()` (before the port's probe has ever run) must NOT permanently latch - /// `NotApplicable` into the cell. With the old `get_or_init(|| NotApplicable)` reader this - /// first call would win the race and every later `VERDICT.set(Missing)` from the real probe - /// would be silently dropped (`OnceLock::set` returns `Err` once already initialized) — the - /// gate would report "not blocked" forever while the boot log said `rtkmem=missing`. - /// - /// Exercised against a throwaway local cell via `blocks`, not the process-wide `VERDICT` - /// static — that `OnceLock` can never be un-set, so writing into the real one here would - /// permanently latch `blocks_native_video()` to `true` for every other test in this process, - /// un-serialized. See finding - /// `rtkmem-probe-test-permanently-sets-the-process-wide-oncelock`. - #[test] - fn early_read_does_not_defeat_a_later_missing_verdict() { - let cell: OnceLock = OnceLock::new(); - assert!(!blocks(&cell), "cell must start empty/unset"); - cell.set(Verdict::Missing) - .expect("cell was still empty, so this must be the first, winning set()"); - assert!( - blocks(&cell), - "a verdict set after an earlier read must still take effect" - ); - } -} diff --git a/rust-modules/os/src/tv/secure.rs b/rust-modules/os/src/tv/secure.rs index c961535490..c35d0b9667 100644 --- a/rust-modules/os/src/tv/secure.rs +++ b/rust-modules/os/src/tv/secure.rs @@ -4,12 +4,42 @@ //! Beside them, [`StoreMode`] says whether this platform keeps a credential across launches at //! all. use serde::{Deserialize, Serialize}; +use std::borrow::Cow; +/// Which key store sealed an envelope: an opaque tag, written to disk exactly as spelled. +/// +/// It is not a closed set. The tag is the only thing in the stored envelope that says which +/// platform's store can open it, and a platform names its own in its own code ([`Backend::new`]); +/// no shared code branches on one, but the legacy-migration decoder +/// (`plex::session::persistence::decode_legacy_at_depth`), which accepts only `keymanager3` from +/// the files earlier builds wrote. A tag that no installed platform knows is REFUSED when the +/// envelope is opened (the platform's `open` answers `None`, the session layer reports the file +/// locked) and is never read as another store's: the stored text is not ours to reinterpret. +/// +/// Serde-transparent, so the wire form is the bare string: an envelope written before this type +/// stopped being an enum reads back unchanged, and one written now reads in an older build. +/// `the_sealed_envelope_keeps_its_wire_form_for_every_backend_tag` pins both directions. #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum Backend { - Keymanager3, - PalmKeymanager, +#[serde(transparent)] +pub struct Backend(Cow<'static, str>); + +impl Backend { + /// webOS's public `com.webos.service.keymanager3`: AES-GCM under a key the service holds. + pub const KEYMANAGER3: Backend = Backend::new("keymanager3"); + /// webOS's archival `com.palm.keymanager`. Only ever READ from a file an interim build + /// wrote: nothing seals with it and nothing opens it (its AES-CFB does not authenticate). + pub const PALM_KEYMANAGER: Backend = Backend::new("palm_keymanager"); + + /// A tag a platform names for its own store. The spelling is a wire format: it is stored in + /// every sealed session, so it never changes once a build has written it. + pub const fn new(tag: &'static str) -> Self { + Self(Cow::Borrowed(tag)) + } + + /// The tag as stored. + pub fn as_str(&self) -> &str { + &self.0 + } } #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] @@ -141,6 +171,73 @@ pub fn set_mode_for_test(mode: StoreMode) -> ModeReset { mod tests { use super::*; + /// **The sealed envelope's wire form, pinned for every backend tag a TV may have written.** The + /// envelope is what `plex::session` stores on disk, so a changed spelling of a tag would leave + /// every saved session on every TV unreadable. The literals are what this type wrote when the + /// test was added; a refactor of `Backend` must keep them byte for byte, in both directions. + /// `tests/fixtures/persistence/v0.6.*/secure-envelope-v1.json` carries the `keymanager3` tag + /// inside the session file's wrapper, and nothing pinned `palm_keymanager` at all. + #[test] + fn the_sealed_envelope_keeps_its_wire_form_for_every_backend_tag() { + let sealed = |backend| Sealed { + backend, + key: "plxnative.session.v1".into(), + iv: "MDEyMzQ1Njc4OWFi".into(), + data: "Y2lwaGVydGV4dA==".into(), + }; + let cases = [ + ( + Backend::KEYMANAGER3, + r#"{"backend":"keymanager3","key":"plxnative.session.v1","iv":"MDEyMzQ1Njc4OWFi","data":"Y2lwaGVydGV4dA=="}"#, + ), + ( + Backend::PALM_KEYMANAGER, + r#"{"backend":"palm_keymanager","key":"plxnative.session.v1","iv":"MDEyMzQ1Njc4OWFi","data":"Y2lwaGVydGV4dA=="}"#, + ), + ]; + for (backend, literal) in cases { + let value = sealed(backend); + assert_eq!(serde_json::to_string(&value).unwrap(), literal, "{value:?} serializes to its literal"); + assert_eq!(serde_json::from_str::(literal).unwrap(), value, "{literal} reads back as {value:?}"); + } + } + + /// The 0.6.3 to 0.6.5 files carry an `identity` member the envelope has no field for: it is + /// ignored on read, and a rewrite no longer carries it. Pinned beside the tags above because + /// both are the same promise: a file an earlier build wrote still opens. + #[test] + fn an_envelope_with_a_member_this_type_no_longer_has_still_reads() { + let literal = r#"{"backend":"keymanager3","key":"plxnative.session.v1","iv":"MDEyMzQ1Njc4OWFi","data":"Y2lwaGVydGV4dA==","identity":"named"}"#; + let read: Sealed = serde_json::from_str(literal).unwrap(); + assert_eq!(read.backend, Backend::KEYMANAGER3); + assert_eq!(read.key, "plxnative.session.v1"); + assert_eq!(read.iv, "MDEyMzQ1Njc4OWFi"); + assert_eq!(read.data, "Y2lwaGVydGV4dA=="); + } + + /// A tag nobody here has a name for is carried through as written, and no constant equals it: + /// it is the platform's `open` that refuses it, never this type that reads it as another store. + #[test] + fn a_tag_no_platform_knows_is_kept_verbatim_and_equals_no_known_tag() { + let literal = r#"{"backend":"host_file","key":"plxnative.session.v1","iv":"aXY=","data":"ZGF0YQ=="}"#; + let read: Sealed = serde_json::from_str(literal).unwrap(); + assert_eq!(read.backend.as_str(), "host_file"); + assert_ne!(read.backend, Backend::KEYMANAGER3); + assert_ne!(read.backend, Backend::PALM_KEYMANAGER); + assert_eq!(serde_json::to_string(&read).unwrap(), literal, "written back as it was read"); + assert_eq!(read.backend, Backend::new("host_file")); + } + + /// With no platform installed nothing opens an envelope, whatever its tag: a refusal is the + /// absence of an answer, not a reinterpretation. + #[test] + fn no_installed_platform_opens_any_tag() { + for backend in [Backend::KEYMANAGER3, Backend::PALM_KEYMANAGER, Backend::new("host_file")] { + let sealed = Sealed { backend, key: "k".into(), iv: "i".into(), data: "d".into() }; + assert!(open(&sealed).is_none(), "{sealed:?}"); + } + } + #[test] fn the_default_mode_is_durable() { let _serial = plx_base::testlock::serial(); diff --git a/rust-modules/os/src/webos.rs b/rust-modules/os/src/webos.rs index 74d2c11cae..d8ff5013fe 100644 --- a/rust-modules/os/src/webos.rs +++ b/rust-modules/os/src/webos.rs @@ -40,7 +40,7 @@ //! for service replies: [`caps`] uses `serde_json` and strict types because uncertainty there is a //! playback-safety decision. The capability query deliberately does not fill a missing webOS //! version; no public version key or anonymous permission for one is evidenced. -use crate::tv::device::{Hardware, Info, NyxFile}; +use crate::tv::device::{Hardware, Info, NyxFile, Platform, WebosDetail}; pub mod jail_repair; pub mod caps; @@ -78,10 +78,12 @@ fn parse(s: &str) -> Info { Info { release, build, - codename: get("webos_release_codename"), - api: get("webos_api_version"), - name: get("webos_name"), major, + webos: WebosDetail { + codename: get("webos_release_codename"), + api: get("webos_api_version"), + name: get("webos_name"), + }, } } @@ -109,15 +111,43 @@ pub fn probe() { } else if info.major > 0 { plx_base::eventlog::log(&format!( "webos: {} release={} codename={} api={} major={}", - info.name, info.release, info.codename, info.api, info.major + info.webos.name, info.release, info.webos.codename, info.webos.api, info.major )); } crate::tv::device::publish_info(info); + // From what `publish_info` kept (the first write wins), so the platform's version and `info()` + // cannot name two releases. + crate::tv::device::publish_platform(plex_platform(&crate::tv::device::info().release)); let device_info = probe_hw(); crate::tv::device::publish_probe(crate::tv::device::Probe { os_info, device_info }); probe_jail(); } +/// What webOS calls itself to a Plex server: `X-Plex-Platform`. +const PLEX_PLATFORM: &str = "webOS"; + +/// The `X-Plex-Platform-Version` for a firmware that names no release: the literal every release +/// before the real version was read has reported, rather than an empty value no server has ever +/// been shown. +const PLEX_PLATFORM_VERSION_UNKNOWN: &str = "4.5"; + +/// PURE: the platform webOS publishes to `tv::device` for a firmware `release`: the real release, +/// or [`PLEX_PLATFORM_VERSION_UNKNOWN`] when the set did not name one. The values `plex::identity` +/// reported before the platform published them, byte for byte. +fn plex_platform(release: &str) -> Platform { + Platform { + name: PLEX_PLATFORM, + version: if release.is_empty() { PLEX_PLATFORM_VERSION_UNKNOWN.to_string() } else { release.to_string() }, + } +} + +/// The files `devcaps::probe` parses, read from the file system: webOS's own paths, named by the +/// model. The simulator's host has none of them and so answers "unreadable", as it always did. +pub const DEVICE_FILES: crate::tv::device::Files = crate::tv::device::Files { + read: |path| std::fs::read_to_string(path), + exists: |path| std::path::Path::new(path).exists(), +}; + // ---- which SET this is, as opposed to which webOS --------------------------------------------- /// nyx's other file. Same directory, same flat shape, written by the same platform component. @@ -147,9 +177,9 @@ fn os_info_from(text: Option<&str>) -> (Info, NyxFile) { }; let info = parse(text); let answered = !info.release.is_empty() - || !info.codename.is_empty() - || !info.api.is_empty() - || !info.name.is_empty(); + || !info.webos.codename.is_empty() + || !info.webos.api.is_empty() + || !info.webos.name.is_empty(); (info, if answered { NyxFile::Ok } else { NyxFile::NoKeys }) } @@ -323,20 +353,31 @@ pub fn is_realtek_k5lp_family(machine_name: &str) -> bool { /// [`probe`] and [`probe_hw`] already follow for their own unreadable files. fn probe_jail() { let name = read_machine_name(); - let result = if is_realtek_k5lp_family(&name) { - let readable = std::ffi::CString::new(RTKMEM_DEVICE) + let result = jail_verdict(&name, || { + std::ffi::CString::new(RTKMEM_DEVICE) .map(|path| unsafe { libc::access(path.as_ptr(), libc::R_OK) } == 0) - .unwrap_or(false); - if readable { - crate::tv::sandbox::Verdict::Ok - } else { - crate::tv::sandbox::Verdict::Missing - } + .unwrap_or(false) + }); + crate::tv::native_video::publish(result); + plx_base::eventlog::log(&format!("devjail: soc={name} rtkmem={}", crate::tv::native_video::context())); +} + +/// The reason webOS names for a blocked native video path, and so the word the `devjail:` line, the +/// telemetry `rtkmem` context and `PRIVACY.md` carry for it. +const RTKMEM_MISSING: &str = "missing"; + +/// PURE: the native-video verdict for a machine name. A name outside the affected family is never +/// probed (`rtkmem_readable` is not called); inside it, a readable `/dev/rtkmem` is `Available` and +/// an unreadable one is `Blocked` with [`RTKMEM_MISSING`]. +fn jail_verdict(machine_name: &str, rtkmem_readable: impl FnOnce() -> bool) -> crate::tv::native_video::Verdict { + use crate::tv::native_video::Verdict; + if !is_realtek_k5lp_family(machine_name) { + Verdict::NotApplicable + } else if rtkmem_readable() { + Verdict::Available } else { - crate::tv::sandbox::Verdict::NotApplicable - }; - crate::tv::sandbox::publish(result); - plx_base::eventlog::log(&format!("devjail: soc={name} rtkmem={}", crate::tv::sandbox::context())); + Verdict::Blocked(RTKMEM_MISSING) + } } // ---- the ROOT press: give the screen back, without ending the process ------------------------- @@ -1330,7 +1371,7 @@ mod tests { // No codename, API version or name is in the file, and none is invented. Nor is a build: // `core_os_release` ("6.5.3-47") carries a build id this file does not, and a build that // read "6.5.3" on this boot and "6.5.3-47" on a nyx boot would look like two builds. - assert!(i.codename.is_empty() && i.api.is_empty() && i.name.is_empty() && i.build.is_empty(), "{i:?}"); + assert!(i.webos == WebosDetail::default() && i.build.is_empty(), "{i:?}"); let i = os_release_info(OS_RELEASE_562).expect("5.6.2 firmware names its release"); assert_eq!((i.release.as_str(), i.major), ("5.6.2", 5)); } @@ -1397,7 +1438,7 @@ mod tests { fn a_nyx_file_that_was_read_is_never_second_guessed() { let fw = firmware_from(Some(REAL), Some(OS_RELEASE_653)); assert_eq!((fw.info.release.as_str(), fw.info.major), ("4.10.2", 4)); - assert_eq!(fw.info.codename, "goldilocks2-grampians"); + assert_eq!(fw.info.webos.codename, "goldilocks2-grampians"); assert_eq!(fw.info.build, "4.10.2-31"); assert_eq!(fw.os_info, NyxFile::Ok); assert!(!fw.from_os_release); @@ -1411,7 +1452,7 @@ mod tests { fn an_unreadable_nyx_file_falls_back_to_os_release_and_is_still_reported_unreadable() { let fw = firmware_from(None, Some(OS_RELEASE_653)); assert_eq!((fw.info.release.as_str(), fw.info.major), ("6.5.3", 6)); - assert!(fw.info.codename.is_empty() && fw.info.api.is_empty() && fw.info.build.is_empty()); + assert!(fw.info.webos == WebosDetail::default() && fw.info.build.is_empty()); // The verdict on nyx's own file (the event log line and the crash report's `hardware.probe` // field) stays `unreadable`; it is not a statement about whether the release is known. assert_eq!(fw.os_info, NyxFile::Unreadable); @@ -1437,8 +1478,9 @@ mod tests { fn parses_the_whole_record() { let i = parse(REAL); assert_eq!((i.release.as_str(), i.major), ("4.10.2", 4)); - assert_eq!(i.codename, "goldilocks2-grampians"); - assert_eq!(i.name, "webOS TV"); + assert_eq!(i.webos.codename, "goldilocks2-grampians"); + assert_eq!(i.webos.api, "4.1.0"); + assert_eq!(i.webos.name, "webOS TV"); } /// The unknown case must be EMPTY with major 0, never a plausible-looking default. A panel that @@ -1447,7 +1489,7 @@ mod tests { fn an_unreadable_file_yields_no_version_rather_than_a_guess() { let i = parse("not json at all"); assert_eq!(i.major, 0); - assert!(i.release.is_empty() && i.codename.is_empty()); + assert!(i.release.is_empty() && i.webos.codename.is_empty()); } /// A two-component release still yields its major — LG has shipped "6.0" as well as "4.10.2". @@ -1473,4 +1515,27 @@ mod tests { assert!(!is_realtek_k5lp_family("prefix-k5lp")); assert!(!is_realtek_k5lp_family("K5LP")); } + + /// What webOS tells a Plex server: the name it always sent, the real release when the set named + /// one and the old literal when it did not. + #[test] + fn the_published_platform_is_the_webos_the_headers_always_named() { + assert_eq!(plex_platform("6.5.2"), Platform { name: "webOS", version: "6.5.2".into() }); + assert_eq!(plex_platform(""), Platform { name: "webOS", version: "4.5".into() }); + } + + /// webOS's three answers on the neutral verdict, one per old one: a readable `/dev/rtkmem` on + /// the family is `Available` (was `Ok`), an unreadable one is `Blocked` with the word telemetry + /// has always carried (was `Missing`), and a set outside the family is not probed at all. + #[test] + fn the_jail_verdict_maps_each_old_answer_to_its_native_video_variant() { + use crate::tv::native_video::Verdict; + assert_eq!(jail_verdict("k5lp", || true), Verdict::Available); + assert_eq!(jail_verdict("k3lp.something", || false), Verdict::Blocked("missing")); + assert_eq!( + jail_verdict("o22", || panic!("a set outside the family is never probed")), + Verdict::NotApplicable + ); + assert_eq!(jail_verdict("", || panic!("an unreadable machine name is never probed")), Verdict::NotApplicable); + } } diff --git a/rust-modules/os/src/webos/jail_repair.rs b/rust-modules/os/src/webos/jail_repair.rs index a9d1c63425..324dc52dc4 100644 --- a/rust-modules/os/src/webos/jail_repair.rs +++ b/rust-modules/os/src/webos/jail_repair.rs @@ -4,7 +4,7 @@ //! explicit confirmation. That app-owned attempt survives every screen and session reset, //! including timeout: the remote shell may still run after LS2 gives up. -use crate::tv::sandbox::Failure; +use crate::tv::native_video::Failure; use serde_json::Value; use std::path::Path; #[cfg(all(not(feature = "hostsim"), not(any(test, feature = "test-support"))))] diff --git a/rust-modules/plex/src/plex/account.rs b/rust-modules/plex/src/plex/account.rs index a86d3c6e12..3d810a337b 100644 --- a/rust-modules/plex/src/plex/account.rs +++ b/rust-modules/plex/src/plex/account.rs @@ -440,7 +440,7 @@ impl AccountClient { "Accept: application/json".to_string(), format!("X-Plex-Product: {}", id::PRODUCT), format!("X-Plex-Version: {}", id::version()), - format!("X-Plex-Platform: {}", id::PLATFORM), + format!("X-Plex-Platform: {}", id::platform()), format!("X-Plex-Platform-Version: {}", id::platform_version()), format!("X-Plex-Device: {}", id::DEVICE), format!("X-Plex-Device-Name: {}", id::device_name()), diff --git a/rust-modules/plex/src/plex/client.rs b/rust-modules/plex/src/plex/client.rs index 4180647268..b7a241f39c 100644 --- a/rust-modules/plex/src/plex/client.rs +++ b/rust-modules/plex/src/plex/client.rs @@ -114,7 +114,6 @@ pub struct Client { pub(super) client_id: String, // X-Plex-Client-Identifier — stable device id (NEVER per-item) pub(super) product: String, // "PlxNative" pub(super) version: String, // "0.1.0" - pub(super) platform: String, // "webOS" // Token generation, PER SERVER. Bumped by `set_token`; read by caches keyed on a path that // bakes the token in (`app::adapters::poster::built_key`'s memo). This used to be a process-global // `static TOKEN_GEN`, which cannot express "server B's token changed" — with a registry that @@ -272,7 +271,6 @@ impl Client { client_id: client_id.to_owned(), product: super::identity::PRODUCT.into(), version: super::identity::version().into(), - platform: super::identity::PLATFORM.into(), token_gen: AtomicU32::new(generation), grant_epoch: AtomicU32::new(generation), instance_gen: generation, @@ -304,7 +302,7 @@ impl Client { ("X-Plex-Client-Identifier", &self.client_id), ("X-Plex-Product", &self.product), ("X-Plex-Version", &self.version), - ("X-Plex-Platform", &self.platform), + ("X-Plex-Platform", super::identity::platform()), ("X-Plex-Platform-Version", super::identity::platform_version()), ("X-Plex-Device", DEVICE), ("X-Plex-Device-Name", device_name()), diff --git a/rust-modules/plex/src/plex/identity.rs b/rust-modules/plex/src/plex/identity.rs index 316c63d477..f90c7f20de 100644 --- a/rust-modules/plex/src/plex/identity.rs +++ b/rust-modules/plex/src/plex/identity.rs @@ -83,19 +83,35 @@ pub fn version() -> &'static str { } } +/// The platform name this client reports until the platform states its own +/// ([`plx_os::tv::device::publish_platform`]). It is webOS's, which is the only name every release +/// so far has reported, so a build or a test that never publishes still sends exactly what it sent. pub const PLATFORM: &str = "webOS"; -/// The OS version — the REAL one, read off the set at boot ([`plx_os::tv::device`]), because the -/// app runs on webOS 4 through 11 now and a literal is wrong on every set but one. This was -/// `const … = "4.5"` while the app was packaged `>=4.0, <5.0`; the webosbrew reviewer flagged it -/// reporting 4.5 from a 6.5.2 television (issue #22). PMS augments our named Generic profile -/// from the X-Plex-Client-Profile-Extra we send, so the version is informational today — but it -/// is also how a server-side profile could ever distinguish firmware generations, and a false -/// one poisons that forever. The fallback when neither `os_info.json` nor `/usr/lib/os-release` names a release keeps the literal +/// `X-Plex-Platform`: the name the platform published at boot, else [`PLATFORM`]. Read per request, +/// like [`platform_version`], so a request built before the boot probe (a host test) still names a +/// platform and one built after it names the real one. +pub fn platform() -> &'static str { + plx_os::tv::device::platform().map_or(PLATFORM, |p| p.name) +} + +/// `X-Plex-Platform-Version`: the version the platform published at boot ([`platform`]'s +/// companion), else the OS version off the set ([`plx_os::tv::device`]). +/// +/// The platform states it because the app runs on webOS 4 through 11 now and a literal is wrong on +/// every set but one. This was `const … = "4.5"` while the app was packaged `>=4.0, <5.0`; the +/// webosbrew reviewer flagged it reporting 4.5 from a 6.5.2 television (issue #22). PMS augments +/// our named Generic profile from the X-Plex-Client-Profile-Extra we send, so the version is +/// informational today — but it is also how a server-side profile could ever distinguish +/// firmware generations, and a false one poisons that forever. The fallback when nothing was +/// published and neither `os_info.json` nor `/usr/lib/os-release` names a release keeps the literal /// this replaces — the exact claim every release so far has made — rather than inventing an /// empty-string case no server has ever been shown. Safe by boot order: `tv::probe_device()` runs /// before any PMS request, so none can precede the read. pub fn platform_version() -> &'static str { + if let Some(published) = plx_os::tv::device::platform() { + return &published.version; + } let r = &plx_os::tv::device::info().release; if r.is_empty() { "4.5" @@ -229,6 +245,16 @@ mod tests { assert_eq!(super::platform_version(), "4.5"); } + /// Until a platform publishes its own name (`plx_os::tv::device::publish_platform`, which only the + /// webOS boot probe calls) the client says what every release so far has said, so a request + /// built before the probe, or in a host test, is unchanged. + #[test] + fn an_unpublished_platform_names_webos() { + assert!(plx_os::tv::device::platform().is_none(), "no host test publishes a platform"); + assert_eq!(super::platform(), super::PLATFORM); + assert_eq!(super::platform(), "webOS"); + } + #[test] fn a_process_locale_becomes_a_safe_plex_language_tag() { assert_eq!( diff --git a/rust-modules/plex/src/plex/session_persistence_tests.rs b/rust-modules/plex/src/plex/session_persistence_tests.rs index a94c281dc6..779cfbcc69 100644 --- a/rust-modules/plex/src/plex/session_persistence_tests.rs +++ b/rust-modules/plex/src/plex/session_persistence_tests.rs @@ -766,7 +766,7 @@ fn an_unopenable_secure_session_is_preserved_without_plaintext_downgrade() { format: SECURE_FORMAT.to_string(), version: 1, sealed: plx_os::tv::secure::Sealed { - backend: plx_os::tv::secure::Backend::Keymanager3, + backend: plx_os::tv::secure::Backend::KEYMANAGER3, key: "plxnative.session.v1".to_string(), iv: "AAAAAAAAAAAAAAAAAAAAAA==".to_string(), data: "c2VjcmV0".to_string(), @@ -830,6 +830,49 @@ fn an_unknown_secure_envelope_version_is_locked_and_never_rewritten_as_plaintext ); } +/// A sealed envelope for `signed_in()` under `backend`, in the file format `save` writes. +fn envelope_for_signed_in(backend: plx_os::tv::secure::Backend) -> Vec { + serde_json::to_vec_pretty(&SecureEnvelope { + format: SECURE_FORMAT.to_string(), + version: 1, + sealed: plx_os::tv::secure::Sealed { + backend, + key: "plxnative.session.v1".to_string(), + iv: "synthetic-iv".to_string(), + data: plx_base::b64::encode(&serde_json::to_vec_pretty(&signed_in()).unwrap()), + }, + }) + .unwrap() +} + +/// The control for the test below: the same plaintext, sealed under the tag the synthetic +/// platform does know, opens. +#[test] +fn an_envelope_with_the_platforms_own_backend_tag_opens() { + let _g = plx_base::testlock::serial(); + let _keymanager = SyntheticKeymanager::new(); + let t = TempSession::new("secure-own-tag"); + std::fs::write(t.file(), envelope_for_signed_in(plx_os::tv::secure::Backend::KEYMANAGER3)).unwrap(); + assert_eq!(load().account_token, "acct"); +} + +/// The backend tag is an opaque string, so an envelope naming a store no installed platform knows +/// still parses. It is REFUSED on open and never reinterpreted as the platform's own store: the +/// file stays locked ciphertext and the run signs in again. +#[test] +fn an_envelope_with_a_backend_tag_no_platform_knows_is_locked_and_left_as_it_was() { + let _g = plx_base::testlock::serial(); + let _keymanager = SyntheticKeymanager::new(); + let t = TempSession::new("secure-foreign-tag"); + let foreign = envelope_for_signed_in(plx_os::tv::secure::Backend::new("host_file")); + std::fs::write(t.file(), &foreign).unwrap(); + + let loaded = load(); + assert!(loaded.account_token.is_empty(), "a tag nobody knows opens nothing"); + assert!(!loaded.client_id.is_empty(), "the run still gets an ephemeral id"); + assert_eq!(std::fs::read(t.file()).unwrap(), foreign, "reading it rewrites nothing"); +} + #[test] fn a_precreated_tmp_symlink_cannot_redirect_session_bytes() { use std::os::unix::fs::symlink; @@ -1721,13 +1764,13 @@ fn signout_sweeps_cannot_complete_while_a_recovery_flush_is_pending() { struct SyntheticKeymanager; static STORE: plx_os::tv::secure::TestStore = plx_os::tv::secure::TestStore { seal: |plain| Some(plx_os::tv::secure::Sealed { - backend: plx_os::tv::secure::Backend::Keymanager3, + backend: plx_os::tv::secure::Backend::KEYMANAGER3, key: "plxnative.session.v1".into(), iv: "synthetic-iv".into(), data: plx_base::b64::encode(plain), }), open: |sealed| { - if sealed.backend == plx_os::tv::secure::Backend::Keymanager3 && sealed.key == "plxnative.session.v1" { + if sealed.backend == plx_os::tv::secure::Backend::KEYMANAGER3 && sealed.key == "plxnative.session.v1" { plx_base::b64::decode(&sealed.data) } else { None diff --git a/rust-modules/screens/src/player/mod.rs b/rust-modules/screens/src/player/mod.rs index 049cedfb1c..301941bec7 100644 --- a/rust-modules/screens/src/player/mod.rs +++ b/rust-modules/screens/src/player/mod.rs @@ -1258,7 +1258,7 @@ impl PlayerScreen { A::TryAgain => Self::ask(fx, PlayerReq::RetryPlayback), A::ChangeQuality => Self::ask(fx, PlayerReq::OpenOverlay(overlay::OverlayKind::More { page: Some(plx_appkit::more_menu::MorePage::Quality) })), A::Repair => { - if ps.repair_status == plx_os::tv::sandbox::State::Idle && !self.repair_alert.visible() { + if ps.repair_status == plx_os::tv::native_video::State::Idle && !self.repair_alert.visible() { self.repair_scroll = 0; self.repair_alert.open_with_body(plx_os::i18n::msg::widgets_repair_question_c(), plx_os::i18n::msg::widgets_repair_body()); Self::repair_focus(fx, GROUP_REPAIR); @@ -5980,7 +5980,7 @@ mod repair_confirmation_tests { std::fs::write(&path, "jail").unwrap(); let mut ps = plx_media::route::PlaybackSession::IDLE; plx_media::route::reset_player_control_for_test(&ps); - let hardware_verdict = plx_os::tv::sandbox::blocks_native_video(); + let hardware_verdict = plx_os::tv::native_video::blocked(); plx_media::player::failure_fixture(&mut ps); let mut page = PlayerScreen::new(EntryId(1), plx_appkit::player_hud::loaded::classic_for_test()); assert!(deliver(&mut page, &ps, None, key_event(consts::SDLK_RETURN, 0)).is_empty()); @@ -5988,7 +5988,7 @@ mod repair_confirmation_tests { assert!(deliver(&mut page, &ps, Some(REPAIR_CANCEL), ScreenEvent::Tick(Tick { ms: 16, dt_us: 16_000 })).is_empty()); assert!(page.repair_alert.is_open(), "Tick must not retire the jail fixture confirmation"); assert!(ps.jail_load_blocked); - assert_eq!(plx_os::tv::sandbox::blocks_native_video(), hardware_verdict, "the fixture must not alter the cached hardware verdict"); + assert_eq!(plx_os::tv::native_video::blocked(), hardware_verdict, "the fixture must not alter the cached hardware verdict"); ps.jail_load_blocked = false; deliver(&mut page, &ps, None, ScreenEvent::Tick(Tick { ms: 32, dt_us: 16_000 })); assert!(!page.repair_alert.is_open(), "retiring the session still closes its confirmation"); @@ -6042,7 +6042,7 @@ mod repair_confirmation_tests { /// `player` may not name `screens`. The attempt is the `Player` machine's, not the screen's. #[test] fn repair_survives_screen_and_session_recreation_and_rejects_stale_completions() { - use plx_os::tv::sandbox::{Failure, State}; + use plx_os::tv::native_video::{Failure, State}; let mut player = plx_media::player::machine::Player::new(); let token = player.repair.begin(true).unwrap(); assert!(!player.repair.complete(token + 1, Ok(()))); @@ -6058,7 +6058,7 @@ mod repair_confirmation_tests { #[test] fn accepted_attempt_hides_forward_action_after_screen_recreation() { let _g = plx_base::testlock::serial(); - for state in [plx_os::tv::sandbox::State::Running, plx_os::tv::sandbox::State::Repaired, plx_os::tv::sandbox::State::Failed(plx_os::tv::sandbox::Failure::Timeout)] { + for state in [plx_os::tv::native_video::State::Running, plx_os::tv::native_video::State::Repaired, plx_os::tv::native_video::State::Failed(plx_os::tv::native_video::Failure::Timeout)] { let mut ps = blocked(); ps.repair_status = state; plx_media::route::reset_player_control_for_test(&ps); let row = super::overlay_tests::failure_fixture(&ps).actions().to_vec(); diff --git a/rust-modules/src/app/diagnostics.rs b/rust-modules/src/app/diagnostics.rs index 6df2e71e9f..e7d157768f 100644 --- a/rust-modules/src/app/diagnostics.rs +++ b/rust-modules/src/app/diagnostics.rs @@ -462,10 +462,10 @@ impl Diagnostics { /// no API version, and the line must not end in an `api` label with nothing after it. fn firmware_head(w: &plx_os::tv::device::Info) -> String { let release = plx_os::i18n::webos_release_line(w); - if w.major == 0 || w.api.is_empty() { + if w.major == 0 || w.webos.api.is_empty() { release } else { - format!("{release} · api {}", w.api) + format!("{release} · api {}", w.webos.api) } } @@ -593,7 +593,7 @@ fn device_rows() -> Vec { // image somebody else can go and look at. v.push(Field::new( plx_os::i18n::msg::browse_diagnostics_field_firmware(), - match (i.name.as_str(), i.codename.as_str()) { + match (i.webos.name.as_str(), i.webos.codename.as_str()) { // Bare "unknown": with neither file read the head line above already carries the REASON // ("webOS unknown — os_info.json unreadable"). When `/usr/lib/os-release` named the // release instead, the head line reads `webOS 6.5.3` and this row is the codename, @@ -3523,9 +3523,14 @@ mod tests { /// line must not end in an `api` label with nothing after it. #[test] fn the_firmware_text_names_the_api_only_when_it_is_known() { - use plx_os::tv::device::Info; + use plx_os::tv::device::{Info, WebosDetail}; let _g = plx_base::testlock::serial(); - let nyx = Info { release: "4.10.2".into(), api: "4.1.0".into(), major: 4, ..Info::default() }; + let nyx = Info { + release: "4.10.2".into(), + major: 4, + webos: WebosDetail { api: "4.1.0".into(), ..WebosDetail::default() }, + ..Info::default() + }; assert_eq!(firmware_head(&nyx), "webOS 4.10.2 · api 4.1.0", "the nyx spelling is unchanged"); let os_release = Info { release: "6.5.3".into(), major: 6, ..Info::default() }; assert_eq!(firmware_head(&os_release), "webOS 6.5.3"); diff --git a/rust-modules/src/app/playback.rs b/rust-modules/src/app/playback.rs index c54ddcec07..c8196e575a 100644 --- a/rust-modules/src/app/playback.rs +++ b/rust-modules/src/app/playback.rs @@ -835,7 +835,7 @@ pub(crate) fn player_requests( } PlayerReq::RepairSandbox => { if player.session.jail_load_blocked { - pa.repair_sandbox(&mut player.repair, plx_os::tv::sandbox::blocks_native_video()); + pa.repair_sandbox(&mut player.repair, plx_os::tv::native_video::blocked()); player.session.repair_status = player.repair.state(); pages.present.note_in_scope(plx_machine::present::Scope::Page, plx_machine::present::PresentEvent::Damage(plx_machine::present::Provenance::Input)); } diff --git a/rust-modules/src/lab/snapshot.rs b/rust-modules/src/lab/snapshot.rs index e992eab511..7d27d2e31a 100644 --- a/rust-modules/src/lab/snapshot.rs +++ b/rust-modules/src/lab/snapshot.rs @@ -276,9 +276,9 @@ fn device() -> Device { let d = plx_os::tv::device::device(); Device { webos_release: i.release.clone(), - webos_codename: i.codename.clone(), - webos_api: i.api.clone(), - webos_name: i.name.clone(), + webos_codename: i.webos.codename.clone(), + webos_api: i.webos.api.clone(), + webos_name: i.webos.name.clone(), model: d.model.clone(), board: d.board.clone(), hw_revision: d.hw_revision.clone(), diff --git a/rust-modules/src/port.rs b/rust-modules/src/port.rs index 060fad0397..6214eecef0 100644 --- a/rust-modules/src/port.rs +++ b/rust-modules/src/port.rs @@ -30,7 +30,8 @@ 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, + repair_native_video: Some(plx_os::webos::jail_repair::execute), + device_files: plx_os::webos::DEVICE_FILES, system_locale: plx_os::webos::system_locale, sound_output: plx_os::webos::sound_output, }, diff --git a/rust-modules/telemetry/src/diag/schema.rs b/rust-modules/telemetry/src/diag/schema.rs index 0cf2e32f2a..3b8b6cf207 100644 --- a/rust-modules/telemetry/src/diag/schema.rs +++ b/rust-modules/telemetry/src/diag/schema.rs @@ -316,7 +316,7 @@ pub struct UsageContext { #[serde(default, skip_serializing_if = "Option::is_none")] pub ip_version: Option, /// issue #74: the k5lp/k3lp `/dev/rtkmem` sandbox pre-flight — `ok` / `missing` / `n/a` — the - /// SAME closed enum [`plx_os::tv::sandbox::context`] reports, never a free-text probe result. + /// SAME closed enum [`plx_os::tv::native_video::context`] reports, never a free-text probe result. /// Present on every event so a chassis's crash-at-start rate is queryable by sandbox rather /// than only discoverable from a single reported issue. #[serde(default = "rtkmem_default")] @@ -397,14 +397,14 @@ impl UsageContext { Self { app_version: dimension(crate::telemetry::app_version()), webos_release: dimension(&os.release), - webos_api: dimension(&os.api), - webos_codename: dimension(&os.codename), + webos_api: dimension(&os.webos.api), + webos_codename: dimension(&os.webos.codename), device_model: dimension(&hw.model), soc: dimension(&hw.board), hardware_revision: dimension(&hw.hw_revision), server_connection: connection.map(|(c, _)| c.to_string()), ip_version: connection.map(|(_, ip)| ip.to_string()), - rtkmem: plx_os::tv::sandbox::context().into(), + rtkmem: plx_os::tv::native_video::context().into(), install: plx_base::paths::install_kind().into(), } } diff --git a/rust-modules/telemetry/src/telemetry/native.rs b/rust-modules/telemetry/src/telemetry/native.rs index b2df49ab46..766e1bda63 100644 --- a/rust-modules/telemetry/src/telemetry/native.rs +++ b/rust-modules/telemetry/src/telemetry/native.rs @@ -289,7 +289,7 @@ pub(super) const OS_FIELDS: &[&str] = &["type", "name", "version", "build", "ker /// `sentry::attach_hardware_context` builds, and [`preview_event`] leaves it out because a real /// native crash event does not carry it. pub(super) const WEBOS_FIELDS: &[&str] = &["type", "name", "release", "build", "codename", "api"]; -/// issue #74: `rtkmem` (`ok`/`missing`/`n/a`, from [`plx_os::tv::sandbox::context`]) and `install` +/// issue #74: `rtkmem` (`ok`/`missing`/`n/a`, from [`plx_os::tv::native_video::context`]) and `install` /// (`devmode`/`homebrew`/`unknown`, from [`plx_base::paths::install_kind`]) ride on every native /// crash report beside the existing hardware compatibility class — the same two closed-enum /// sandbox facts PostHog's usage envelope carries as super-properties (`telemetry::posthog`'s @@ -890,17 +890,17 @@ mod sdk { return; }; let webos = plx_os::tv::device::info(); - let webos_name = cstring(webos.name.as_bytes()); + let webos_name = cstring(webos.webos.name.as_bytes()); let webos_release = cstring(webos.release.as_bytes()); - let webos_codename = cstring(webos.codename.as_bytes()); - let webos_api = cstring(webos.api.as_bytes()); + let webos_codename = cstring(webos.webos.codename.as_bytes()); + let webos_api = cstring(webos.webos.api.as_bytes()); let hardware = plx_os::tv::device::device(); let model = cstring(hardware.model.as_bytes()); let soc = cstring(hardware.board.as_bytes()); let hardware_revision = cstring(hardware.hw_revision.as_bytes()); // issue #74: the same two closed-enum sandbox facts the PostHog envelope carries, so a // native crash report can be graded by chassis AND sandbox without a second dashboard. - let rtkmem = cstring(plx_os::tv::sandbox::context().as_bytes()); + let rtkmem = cstring(plx_os::tv::native_video::context().as_bytes()); let install = cstring(plx_base::paths::install_kind().as_bytes()); let ptr = |value: &Option| { value diff --git a/rust-modules/telemetry/src/telemetry/sentry.rs b/rust-modules/telemetry/src/telemetry/sentry.rs index 91b0d2e2c8..d758b54053 100644 --- a/rust-modules/telemetry/src/telemetry/sentry.rs +++ b/rust-modules/telemetry/src/telemetry/sentry.rs @@ -545,13 +545,13 @@ pub fn attach_hardware_context(body: &mut serde_json::Value) { .or_insert_with(|| serde_json::json!({})); contexts["webos"] = serde_json::json!({ "type": "webos", - "name": webos.name, + "name": webos.webos.name, "release": webos.release, // The exact firmware build (nyx's `core_os_release`, e.g. `6.5.3-47`), which a patch within // one release changes and `release` does not: what a refusal is learned against. "build": webos.build, - "codename": webos.codename, - "api": webos.api, + "codename": webos.webos.codename, + "api": webos.webos.api, }); contexts["hardware"] = serde_json::json!({ "type": "hardware", @@ -562,7 +562,7 @@ pub fn attach_hardware_context(body: &mut serde_json::Value) { // two files (`/`, each `ok` / `no_keys` / `unreadable`, or // `unprobed`). Four fixed words, never free text. "probe": plx_os::tv::device::probe().code(), - "rtkmem": plx_os::tv::sandbox::context(), + "rtkmem": plx_os::tv::native_video::context(), "install": plx_base::paths::install_kind(), }); } From ca7653146a03a44ee9e14583b74ff5125af02af3 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 15:19:39 +0300 Subject: [PATCH 08/26] Keys and text reach the loop as a HostEvent with a canonical Action (#1487) Keys and text reach the loop as `HostEvent`s (step W5b of the platform plan, discussion #1460). They sit beside W5a's lifecycle and quit. A key carries a canonical `Action` where one is defined, and the raw pair it arrived as where there is one, so a platform with no SDL key codes can deliver an `Action` alone. webOS and the simulator behave as before. The replay tapes, `tests/keytable.json` and the machine's `InputKind::Key` are unchanged. - `plx_ui::consts` gains `Action` (19 variants), `raw_pair(Action)` (the one pair the app builds for an action) and `action_of(sym, wcode)`. - `action_of` reads `classify`, then paging, then the edit keys, then digits by `sym`. - `is_remote_bound` is now `action_of(..).is_some()`, checked against the old predicate over the whole grid. - The PIN screen's `digit_of` moves down unchanged as `pin_digit`. - `HostEvent` gains `Key(KeyPress)` and `Text(String)`. - `KeyPress` keeps an action and its pair consistent: with a pair, the action is `action_of` of it; without one, the action must round-trip; a press with neither is refused. - `decode_host_event` decodes SDL `KEYDOWN`, `KEYUP` and `TEXTINPUT` at both layouts' offsets. - The named remote-FIFO tokens build their pair through `raw_pair`. - `run.rs`'s drain hands keys and text to `ingest_key` and `ingest_text_commit`, unchanged in order and effect. - A press with no action takes today's raw path. - The pointer-hide early return reads `classify` of the pair. - The `key type=0x300 raw=` log line stays in the SDL drain. - `textinput.rs` splits `queue(String)` out of `on_event`, so a hosted `Text` and the FIFO's `txt:` share it. Tests feed the pairs the set and the simulator really send and assert the consumer's effect: - transport (Play is not Pause; Rewind and FF commit a seek, a plain Left or Right does not); - paging, Search editing and the PIN keypad; - pointer hide, unknown pairs and the lab-trigger pin; - the decode table and `KeyPress`'s refusals. A mutation matrix shows which guard catches each swapped table entry. `make check-replay` reports `SAME=4 REFUSED_EXPECTED=8 unexpected=0`. On the dev set, a `--guest --mock` key script ran against main and against this change. The 38 raw key lines were byte-identical once the SDL timestamp was masked, and the 20 state snapshots were equal. --- ci/list-caps.ini | 4 +- docs/remote-keys.md | 18 +- rust-modules/screens/src/profiles.rs | 14 +- .../screens/src/profiles_pin_tests.rs | 44 +- rust-modules/src/app/bridge.rs | 2 +- rust-modules/src/app/events.rs | 518 ++++++- rust-modules/src/app/input.rs | 60 +- rust-modules/src/app/mod.rs | 5 +- rust-modules/src/app/run.rs | 1214 ++++++++++++----- rust-modules/src/app/search_owned_tests.rs | 44 + rust-modules/src/textinput.rs | 17 +- rust-modules/ui/src/consts.rs | 420 +++++- 12 files changed, 1891 insertions(+), 469 deletions(-) diff --git a/ci/list-caps.ini b/ci/list-caps.ini index 008ada04a2..1972afd6ce 100644 --- a/ci/list-caps.ini +++ b/ci/list-caps.ini @@ -1072,9 +1072,9 @@ reason = SDL_WINDOW_FLAGS: application/dev tooling bound (scenario period, text class = not-a-list reason = SDL_WINDOW_INPUT_FOCUS: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. -[src/app/run.rs::ingest_sdl_event_with_window] +[src/app/run.rs::log_raw_input_event] class = not-a-list -reason = ingest_sdl_event_with_window: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. +reason = log_raw_input_event: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. [src/capture.rs::caplisten] class = not-a-list diff --git a/docs/remote-keys.md b/docs/remote-keys.md index aca301317f..8f13c51fc6 100644 --- a/docs/remote-keys.md +++ b/docs/remote-keys.md @@ -121,7 +121,7 @@ before `SDL_Init` (§5). | `301` | `wcode` | `page_dir`, Library route only | CH▼ pages down (evdev 403 `KEY_CHANNELDOWN`) | | `8` | `sym` | `screens::search::SearchScreen::step`, while editing | backspace | | `156 \| 1<<30` | `sym` | `screens::search::SearchScreen::step`, while editing | the panel's **Clear all**. **Not producible from the evdev table** — it reaches us through the fork's own text/IME path, which is why it is measured but has no evdev provenance. | -| `48..=57` | `sym` | `screens::profiles`, PIN keypad | type that digit into the PIN. `screens::profiles::digit_of` also reads the range out of `wcode`, where it is **not** a digit — §9. | +| `48..=57` | `sym` | `screens::profiles`, PIN keypad | type that digit into the PIN. `consts::pin_digit` (moved from `screens::profiles::digit_of`) also reads the range out of `wcode`, where it is **not** a digit — §9. | ### Swallowed @@ -201,10 +201,10 @@ change rather than a tidy-up, and the sibling codes (`402`, `415`, `413`) come f `linux/input.h` does not name — so unlike `33`/`34` there is no positive evidence about them in either direction. **Settle all four together, with the §7 capture plus a USB keyboard, in one pass.** -### 4.3 and 4.4 — `SDLK_SELECT`, and `digit_of`'s `wcode` arm +### 4.3 and 4.4 — `SDLK_SELECT`, and `pin_digit`'s `wcode` arm The other two are written up in §9, whose first and third bullets they are: `SDLK_SELECT` is -`SDL_SCANCODE_END`, and `screens::profiles::digit_of` reads ASCII digits out of the scancode field. Both are +`SDL_SCANCODE_END`, and `consts::pin_digit` (the old `screens::profiles::digit_of`) reads ASCII digits out of the scancode field. Both are misreadings of the same field, both are recorded rather than changed, and the reasons are there. `is_bound` (§6) declines to inherit the second of them. @@ -282,11 +282,11 @@ host's SDL rather than the press. The bare player samples the HUD for bound keys delivery. A second Back in the same SDL batch sees the first one's dismissal, and an intervening bound press spends any exit arming. The LG pointer-hidden notification only stops edge scrolling. -**The digit term reads `sym` and not `wcode`, diverging from `screens::profiles::digit_of`, on purpose.** +**The digit term reads `sym` and not `wcode`, diverging from `consts::pin_digit` (the old `screens::profiles::digit_of`), on purpose.** 48–57 in the scancode field are `]` `\` `#` `;` `'` `` ` `` `,` `.` `/` and CapsLock (the digits' scancodes are 30–39, which is how 33/34 turned out to be `4` and `5` in the first place). Mirroring -`digit_of` would have put the retired mis-reading straight back inside the gate that exists to stop -it. The consequence is that `is_bound` is not a strict superset of `digit_of` for a wcode-only +`pin_digit` would have put the retired mis-reading straight back inside the gate that exists to stop +it. The same term is `action_of`'s `Action::Digit`, which `is_bound` is now defined by. The consequence is that `is_bound` is not a strict superset of `pin_digit` for a wcode-only punctuation press — which is harmless, because the PIN pad has neither a HUD nor an armed click. Three things stay unconditional, each for its own reason. `held.down_sym` is bookkeeping about the @@ -432,10 +432,10 @@ reproduce rather than a rule to obey by quitting. `SDL_SCANCODE_RETURN`, captured and bound. * **§4.2** — `19` is `SDL_SCANCODE_P` and is bound to PLAY. Untested on a device; needs a USB keyboard as well as §7. -* **`screens::profiles`' `digit_of` reads the digit range in `wcode` too**, where 48–57 are not digits at +* **`consts::pin_digit` (moved from `screens::profiles::digit_of`) reads the digit range in `wcode` too**, where 48–57 are not digits at all but `]` `\` `#` `;` `'` `` ` `` `,` `.` `/` and CapsLock — and its own test asserts - `digit_of(0, 55) == Some(b'7')`, where scancode 55 is a full stop. No remote has those keys, so it - is harmless in practice and `screens/profiles.rs` is left alone here; a USB keyboard on the PIN screen + `pin_digit(0, 55) == Some(b'7')`, where scancode 55 is a full stop. No remote has those keys, so it + is harmless in practice and the reader moved down to `consts` unchanged; a USB keyboard on the PIN screen would type digits from punctuation. `is_bound` deliberately does **not** mirror it (§6). The same capture settles both. * **`461` and `156` are not producible from the evdev table.** 156 is explained — the panel's *Clear diff --git a/rust-modules/screens/src/profiles.rs b/rust-modules/screens/src/profiles.rs index b7388c7af1..76d42bd71c 100644 --- a/rust-modules/screens/src/profiles.rs +++ b/rust-modules/screens/src/profiles.rs @@ -44,7 +44,8 @@ //! **The digits are handled in `step`; no raw `key(sym)` function survives** (spec open question //! 2). A number key types straight into the PIN without moving the visual cursor (the remote's //! digit buttons carry the same 48-57 ASCII range in `sym`/`wcode` the legacy `digit_of` read, and -//! that pure function is unchanged); OK on a keypad cell presses whatever cell the cursor is on, +//! that pure function is unchanged and now lives in `plx_ui::consts` as `pin_digit`); OK on a keypad +//! cell presses whatever cell the cursor is on, //! delivered as an ordinary `ScreenEvent::Activate` — the keys are `ElemKind::Bare`, so the engine //! fires that on the key-DOWN edge with no press arm at all, exactly as a `Card`/`Control` MUST //! NOT (see the next paragraph). @@ -335,15 +336,6 @@ fn pin_flash(error_s: f32) -> Option { (error_s > 0.0).then(|| (((PIN_ERR_S - error_s) / PIN_ERR_HALF_S) as i32) % 2 == 0) } -/// Remote number key → keypad digit, ported verbatim: SDL gives a printable key its ASCII sym and -/// the webOS remote's number buttons carry the same 48-57 ('0'-'9') range in `wcode`. -fn digit_of(sym: u32, wcode: u32) -> Option { - [sym, wcode] - .into_iter() - .find(|v| (48..=57).contains(v)) - .map(|v| v as u8) -} - /// Avatar-row geometry: (first tile's left x before scroll, per-tile stride). Centred when the /// roster fits, else left-aligned so `CardRow` can scroll it. No `Measure` needed — every input is /// a fixed style constant or the roster count. Ported verbatim from `ui/profiles.rs::row_geom`. @@ -1773,7 +1765,7 @@ impl Machine for ProfilesScreen { // own `pad_key` return Handled::Yes; } - if let Some(d) = digit_of(*sym, *wcode) { + if let Some(d) = plx_ui::consts::pin_digit(*sym, *wcode) { self.press(d, fx); return Handled::Yes; } diff --git a/rust-modules/screens/src/profiles_pin_tests.rs b/rust-modules/screens/src/profiles_pin_tests.rs index 89809248e7..c38126a010 100644 --- a/rust-modules/screens/src/profiles_pin_tests.rs +++ b/rust-modules/screens/src/profiles_pin_tests.rs @@ -40,21 +40,11 @@ fn closing_pin_publishes_the_closed_state_before_the_next_tick() { } // --------------------------------------------------------------------------------------- -// pin_flash / digit_of — pure, ported verbatim from `ui/profiles.rs` +// pin_flash — pure, ported verbatim from `ui/profiles.rs`. The digit reader that used to sit beside +// it, `digit_of`, is now `plx_ui::consts::pin_digit`, and its table is graded there +// (`consts::action_tests`); the keypad's own reading of a wcode-only press is graded below. // --------------------------------------------------------------------------------------- -#[test] -fn a_pin_digit_is_read_from_either_field() { - assert_eq!(digit_of(b'7' as u32, 0), Some(b'7'), "a dev keyboard's sym"); - assert_eq!( - digit_of(0, 55), - Some(b'7'), - "the remote's wcode, same digit" - ); - assert_eq!(digit_of(b'0' as u32, 0), Some(b'0')); - assert_eq!(digit_of(999, 0), None, "not a digit in either field"); -} - /// A 1.4s error window reads as several distinct red pulses, not one — the assertion a static /// tint fails no matter how red it is. Ported from `ui/profiles.rs`'s own property test, /// minus the `plx_machine::idle` half (this screen reports through `Effects` instead — see the next @@ -329,10 +319,36 @@ fn a_digit_key_types_into_the_entry_and_backspace_removes_one() { None, ); assert_eq!(s.pad.entry, "127"); - // backspace via the delete cell's OWN digit path is not reachable through `digit_of` (it + // backspace via the delete cell's OWN digit path is not reachable through `pin_digit` (it // is not in 48..=57) — `press` handles it directly, exercised below through `Activate`. } +/// **Each number key types its own digit, and a wcode-only press keeps typing it.** The pairs are +/// the ones the keypad is sent as `InputKind::Key { sym, wcode }`, written out as literals: a +/// printable key's ASCII sym with or without the television's scancode beside it (the number +/// buttons are sym `'5'` with scancode 34: the sym is the digit and the scancode is not), and the +/// pair with NO digit sym and a wcode in 48..=57, which `pin_digit` still reads (the keypad's +/// reading, deliberately wider than `is_remote_bound`'s: `docs/remote-keys.md` section 9). Nothing +/// else types: the neighbours of both ranges, an unbound key, and a press that names no key. +#[test] +fn native_key_effect_pin_digits_type_their_own_digit() { + for digit in 0u32..=9 { + let typed = |sym: u32, wcode: u32| { + let mut s = bare(Pad::opened(0)); + step_ev(&mut s, &key_down(Key::Other, sym, wcode), None); + s.pad.entry + }; + assert_eq!(typed(48 + digit, 0), digit.to_string(), "sym '{digit}'"); + assert_eq!(typed(48 + digit, 30 + digit), digit.to_string(), "sym '{digit}' with its scancode beside it"); + assert_eq!(typed(0, 48 + digit), digit.to_string(), "wcode {} alone", 48 + digit); + } + for (sym, wcode) in [(47, 0), (58, 0), (0, 47), (0, 58), (0, 0), (0, 504), (0x4000_0051, 0), (0, 450), (0, 72)] { + let mut s = bare(Pad::opened(0)); + step_ev(&mut s, &key_down(Key::Other, sym, wcode), None); + assert_eq!(s.pad.entry, "", "({sym}, {wcode}) types nothing"); + } +} + /// Backspace and typing-again both cancel a running wrong-PIN flash — `press`'s own first /// line, ported from `ui/profiles.rs`. #[test] diff --git a/rust-modules/src/app/bridge.rs b/rust-modules/src/app/bridge.rs index e08e35cfa1..80a25c53eb 100644 --- a/rust-modules/src/app/bridge.rs +++ b/rust-modules/src/app/bridge.rs @@ -5325,7 +5325,7 @@ pub(crate) fn search_owns_input(d: &Dispatcher) -> bool { /// television's own keyboard through `SDL_TEXTINPUT`, a replayed text input). True while the system keyboard is /// up for whichever page or surface raised it (`Dispatcher::system_keyboard_up`: Settings > Player HUD's address /// field, and Search's), and while Search is on top, whose field takes text even when the dispatcher's record of -/// the panel disagrees with the OS (the `SDL_TEXTINPUT` branch of `run::ingest_sdl_event` says why). Text that +/// the panel disagrees with the OS (`run::ingest_text_commit` says why). Text that /// arrives while this is false goes to `textinput`'s bounded queue, which nothing reads. pub(crate) fn text_owner(d: &Dispatcher) -> bool { d.system_keyboard_up() || search_owns_input(d) diff --git a/rust-modules/src/app/events.rs b/rust-modules/src/app/events.rs index 90a8530e6c..3aaa5ce67e 100644 --- a/rust-modules/src/app/events.rs +++ b/rust-modules/src/app/events.rs @@ -2,10 +2,13 @@ //! `SDL_KeyboardEvent`, the synthetic key/pointer/wheel events, and `dispatch_remote_token`. //! Moved out of `app.rs` verbatim in phase 1a (a pure move; `pub(crate)` widening only). //! -//! The one decode that yields a platform-neutral value is [`decode_host_event`]: SDL's quit and -//! application-lifecycle events become a [`HostEvent`], which the loop consumes in one function. +//! The one decode that yields a platform-neutral value is [`decode_host_event`]: SDL's quit, +//! application-lifecycle, key and text events become a [`HostEvent`], which the loop consumes in one +//! function. A key carries its canonical [`Action`] (`ui::consts`) beside the raw pair. use super::*; +use plx_machine::machine::Edge; +use plx_ui::consts::{action_of, raw_pair, Action}; /// Preserve one IME commit and its place among key events. Desktop text does not imply an /// on-screen panel; the owning field decides whether it is editing when delivery reaches it. @@ -136,22 +139,135 @@ const SDL_APP_DIDENTERBACKGROUND: u32 = 0x104; const SDL_APP_WILLENTERFOREGROUND: u32 = 0x105; const SDL_APP_DIDENTERFOREGROUND: u32 = 0x106; -/// What the platform tells the loop that is not a key, a text commit or a pointer: the window -/// leaving or returning to the screen, and the host asking the application to end. App-private, -/// like [`Shell`](super::platform::Shell): no platform reaches it by a type of its own until the +/// What the platform tells the loop: a key press, a text commit, the window leaving or returning to +/// the screen, and the host asking the application to end. App-private, like +/// [`Shell`](super::platform::Shell): no platform reaches it by a type of its own until the /// platform contract is settled (`docs/platform-ports.md`, Target shape 2). /// /// The SDL drain decodes SDL's events into it ([`decode_host_event`]) and the loop consumes it in /// ONE function (`run::ingest_host_event`), so a host that stops the application without SDL /// (the hosted entry's `plx_host_stop`) arrives as the same [`HostEvent::Quit`] an `SDL_QUIT` -/// does and takes the same path. Keys, text, pointer and wheel are not here yet: they keep their -/// raw path in `run::ingest_sdl_event_with_window` until their own steps (W5b, W5c) move them. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// does and takes the same path, and a host with no SDL key pair sends a [`HostEvent::Key`] that +/// carries an [`Action`]. Pointer and wheel are not here yet: they keep their raw path in +/// `run::ingest_sdl_event_with_window` until their own step (W5c) moves them. +/// +/// There is no `Edit` event: nothing produces one. `SDL_TEXTEDITING` (the IME pre-edit) is read by +/// nothing and stays a log-only raw event, and the system keyboard's edit keys (caret, backspace, +/// clear-all) are ordinary [`HostEvent::Key`] actions. `Edit` arrives with its first producer (W9). +#[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum HostEvent { /// The window left or came back to the screen. Lifecycle(Lifecycle), /// The host asks the application to end (`SDL_QUIT` on SDL platforms). Quit, + /// One edge of a key. + Key(KeyPress), + /// One commit from the platform's text input (the television's own keyboard): the decoded + /// string, possibly empty (SDL delivers a commit for the IME's own bookkeeping too, and the + /// loop ignores an empty one as it always has). The platform's own text layout is decoded + /// before it gets here (`textinput::decode`, the one place that knows the offsets). + Text(String), +} + +/// The raw `(sym, wcode)` pair a key arrived as. Kept beside the [`Action`] because three things +/// still read it: a press with no action (an unsupported key flows on as exactly the pair it was), +/// the lab trigger key (named by `lab.json`, not by an action), and the recorder's tape, whose +/// format IS the pair. A platform with no SDL pair sends none, and the loop builds +/// [`raw_pair`] for its action. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct RawKey { + pub sym: c_uint, + pub wcode: c_uint, +} + +/// One edge of one key, as a platform hands it to the loop: the canonical [`Action`] where the key +/// has one, the [`Edge`], and the raw pair where the platform has one. +/// +/// **A press is self-consistent, and that is a type's guarantee, not a convention:** the fields are +/// private to this module and [`KeyPress::new`] makes the action and the pair one key. It refuses a +/// press that carries neither field, a stated action that is not what [`action_of`] makes of the raw +/// pair beside it, and an action alone whose [`raw_pair`] does not read back as that action +/// (`Digit(10)` names no key); a raw pair with no stated action has the action [`action_of`] reads +/// out of it. So the loop never reads a key it cannot name, and the action and the pair can never +/// disagree about which key was pressed. An SDL press always has a raw pair (its action is what +/// [`action_of`] makes of it, `None` for an unbound key); a host that knows only the meaning sends +/// the action alone and [`KeyPress::pair`] expands it with [`raw_pair`], which is the pair a +/// remote's press of that key would have been. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct KeyPress { + action: Option, + edge: Edge, + raw: Option, +} + +impl KeyPress { + /// A press of `action` and/or `raw`, or `None` when they do not make one key: + /// * with a raw pair, the action is [`action_of`] of it (`None` for a pair no action names: an + /// unsupported key still flows on as the pair it was), and an `action` that is stated and + /// differs is refused; + /// * with no raw pair, `action` must be set and its [`raw_pair`] must read back as it, which + /// refuses `Digit(10..=255)`, an action no pair spells. + pub(crate) fn new(action: Option, edge: Edge, raw: Option) -> Option { + let action = match raw { + Some(RawKey { sym, wcode }) => { + let read = action_of(sym, wcode); + if action.is_some() && action != read { + return None; + } + read + } + None => { + let named = action?; + let (sym, wcode) = raw_pair(named); + if action_of(sym, wcode) != Some(named) { + return None; + } + Some(named) + } + }; + Some(KeyPress { action, edge, raw }) + } + + /// The press an SDL key event is: the raw pair as `decode_key` reads it, its action, and the + /// edge the fork's packed `state` names (low byte 1 is down, bit 0x100 is the auto-repeat; the + /// same reading `bridge::key_input` makes of it). A key-up never carries the repeat bit here. + pub(crate) fn from_sdl(ev: &[u8]) -> Option { + let (state, wcode, sym) = decode_key(ev); + let edge = if (state & 0xff) != 1 { + Edge::Up + } else if state & 0x100 != 0 { + Edge::Repeat + } else { + Edge::Down + }; + KeyPress::new(action_of(sym, wcode), edge, Some(RawKey { sym, wcode })) + } + + /// What the press means. Read by the tests only for now: the loop's ladder reads [`pair`](Self::pair), + /// which every platform's press has, and the screens that move onto the action (W5d) make this + /// a production accessor then. + #[cfg(test)] + pub(crate) fn action(&self) -> Option { + self.action + } + + /// The pair the loop reads: the raw one a platform sent, else the one [`raw_pair`] gives the action. + pub(crate) fn pair(&self) -> RawKey { + self.raw.unwrap_or_else(|| { + let (sym, wcode) = raw_pair(self.action.expect("a KeyPress carries an action or a raw pair")); + RawKey { sym, wcode } + }) + } + + /// The fork's packed key state for this edge, the form `bridge::key_input` and the recorder read: + /// low byte 1 for a press, 0x100 on an auto-repeat. + pub(crate) fn state(&self) -> u32 { + match self.edge { + Edge::Down => 1, + Edge::Repeat => 1 | 0x100, + Edge::Up => 0, + } + } } /// One edge of the window's visibility. Both background edges park the tree (the second finds @@ -181,13 +297,17 @@ impl Lifecycle { } } -/// An SDL event decoded into a [`HostEvent`]: `SDL_QUIT` and the four application lifecycle types. -/// `None` for everything else, which the loop reads raw (keys, text, pointer, wheel, and the SDL -/// events nothing acts on). Beside [`decode_key`], the other place that knows SDL's event bytes. +/// An SDL event decoded into a [`HostEvent`]: `SDL_QUIT`, the four application lifecycle types, a +/// key edge (`SDL_KEYDOWN`/`SDL_KEYUP`, through [`decode_key`], so both layouts) and a text commit +/// (`SDL_TEXTINPUT`, through `textinput::decode`). `None` for everything else, which the loop reads +/// raw (pointer, wheel, the IME's pre-edit, and the SDL events nothing acts on). Beside +/// [`decode_key`], the other place that knows SDL's event bytes. #[inline] pub(crate) fn decode_host_event(ev: &[u8]) -> Option { Some(match rd_u32(ev, 0) { SDL_QUIT => HostEvent::Quit, + SDL_KEYDOWN | SDL_KEYUP => HostEvent::Key(KeyPress::from_sdl(ev)?), + SDL_TEXTINPUT => HostEvent::Text(crate::textinput::decode(ev)), SDL_APP_WILLENTERBACKGROUND => HostEvent::Lifecycle(Lifecycle::WillBackground), SDL_APP_DIDENTERBACKGROUND => HostEvent::Lifecycle(Lifecycle::DidBackground), SDL_APP_WILLENTERFOREGROUND => HostEvent::Lifecycle(Lifecycle::WillForeground), @@ -245,6 +365,21 @@ pub(crate) fn encode_key_repeat(sym: c_uint, wcode: c_uint) -> [u8; 128] { ev } +/// **One native key edge as the loop hands it to the tree**, for the effect-level guards (W5b): the +/// SDL bytes a television or the simulator delivers for the pair `(sym, wcode)` (the literals a +/// test writes down, never an `Action`'s `raw_pair`), decoded by [`decode_host_event`], and the +/// `InputEvent` that `run::ingest_key` pushes for that press (`bridge::key_input` of the press's +/// pair and its packed state). A consumer fed this event answers what it answers a real key. +#[cfg(test)] +pub(crate) fn native_key_input(sym: c_uint, wcode: c_uint, down: bool, at: plx_machine::machine::Tick) + -> (KeyPress, plx_machine::machine::InputEvent) { + let Some(HostEvent::Key(press)) = decode_host_event(&encode_key(sym, wcode, down)) else { + panic!("SDL key bytes decode to a key press"); + }; + let RawKey { sym, wcode } = press.pair(); + (press, super::bridge::key_input(sym, wcode, press.state(), at, plx_machine::machine::Source::Sdl)) +} + #[inline] /// An SDL pointer event's position, converted from window pixels to the authored 1920x1080 canvas. /// @@ -283,39 +418,44 @@ pub(crate) fn remote_token_key(tok: &str) -> Option<(c_uint, c_uint)> { let (s, w) = rest.split_once(',')?; return Some((s.parse().ok()?, w.parse().ok()?)); } - Some(match tok { - "up" => (SDLK_UP, 0), - "down" => (SDLK_DOWN, 0), - "left" => (SDLK_LEFT, 0), - "right" => (SDLK_RIGHT, 0), - "ok" | "enter" | "select" => (SDLK_RETURN, 0), // is_ok() - "back" | "esc" => (SDLK_ESCAPE, 0), // is_back() - // The pager's two spellings, and they are two tokens now rather than one pair carrying - // both: a PAGE key is a keyboard's and arrives as a sym alone, the rocker is the remote's - // and arrives as a wcode alone. The single pair they shared was `(SDLK_PAGEUP, 33)` — a + // Every named token is an `Action` and its pair is `raw_pair`'s, the ONE place a pair is built + // from a key's meaning (`ui::consts`), so what the FIFO presses and what a platform that sends + // an action presses cannot drift. The channel rocker is the one named token that is not an + // action's pair: it is the remote's CH key, a wcode alone, where `PageUp` is a keyboard's sym. + let action = match tok { + "up" => Action::Up, + "down" => Action::Down, + "left" => Action::Left, + "right" => Action::Right, + "ok" | "enter" | "select" => Action::Ok, // is_ok() + "back" | "esc" => Action::Back, // is_back() + // The pager's two spellings, and they are two tokens rather than one pair carrying both: a + // PAGE key is a keyboard's and arrives as a sym alone, the rocker is the remote's and + // arrives as a wcode alone. The single pair they once shared was `(SDLK_PAGEUP, 33)` — a // shape no real press has, since 33 is the digit `4` (`ui::consts`, where they were // retired), so half of what it drove was never the pager answering the rocker at all. - "pageup" => (SDLK_PAGEUP, 0), - "pagedown" => (SDLK_PAGEDOWN, 0), - "chup" => (0, WCODE_CH_UP_KEY), - "chdown" => (0, WCODE_CH_DOWN_KEY), - "play" => (0, WCODE_PLAY), - "pause" => (0, WCODE_PAUSE), - "stop" => (0, WCODE_STOP), + "pageup" => Action::PageUp, + "pagedown" => Action::PageDown, + "chup" => return Some((0, WCODE_CH_UP_KEY)), + "chdown" => return Some((0, WCODE_CH_DOWN_KEY)), + "play" => Action::Play, + "pause" => Action::Pause, + "stop" => Action::Stop, // The transport keys settled from LG's own scancode table (`ui::consts`' WCODE_REWIND doc). // Here for the same reason the edit keys below are: nothing else can press them headlessly. - "ff" | "fastforward" => (0, plx_ui::consts::WCODE_FASTFORWARD), - "rew" | "rewind" => (0, plx_ui::consts::WCODE_REWIND), - "playpause" => (0, plx_ui::consts::WCODE_PLAYPAUSE), - "exit" => (0, plx_ui::consts::WCODE_EXIT), + "ff" | "fastforward" => Action::FastForward, + "rew" | "rewind" => Action::Rewind, + "playpause" => Action::PlayPause, + "exit" => Action::Exit, // The system keyboard's own two edit keys (`ui::consts`' doc has the protocol). They are // here because they are otherwise UNREACHABLE without a human at the panel: no trigger // raises the keyboard and `SDL_PushEvent` cannot carry a text event on the simulator, so // without these the only grader for backspace and Clear all is somebody's thumb. - "backspace" | "del" => (plx_ui::consts::SDLK_BACKSPACE, 42), - "clear" => (plx_ui::consts::SDLK_CLEAR, 156), + "backspace" | "del" => Action::Backspace, + "clear" => Action::ClearAll, _ => return None, - }) + }; + Some(raw_pair(action)) } /// **`focus:`, `press:` and `press:@`**, the by-id tokens of the remote FIFO and @@ -846,7 +986,7 @@ mod key_layout_tests { /// from the mapping it grades. #[cfg(test)] mod host_event_tests { - use super::{decode_host_event, encode_key, is_input_event, HostEvent, Lifecycle}; + use super::{decode_host_event, is_input_event, HostEvent, Lifecycle}; fn event_of(code: u32) -> [u8; 128] { let mut ev = [0u8; 128]; @@ -863,7 +1003,7 @@ mod host_event_tests { (0x105, HostEvent::Lifecycle(Lifecycle::WillForeground)), (0x106, HostEvent::Lifecycle(Lifecycle::DidForeground)), ] { - assert_eq!(decode_host_event(&event_of(code)), Some(event), "{code:#x}"); + assert_eq!(decode_host_event(&event_of(code)), Some(event.clone()), "{code:#x}"); assert!(!is_input_event(code), "{code:#x}: a host event is the app's, never a modal's input"); if let HostEvent::Lifecycle(edge) = event { assert_eq!(edge.sdl_code(), code, "the code a decoded edge is read back as"); @@ -871,19 +1011,309 @@ mod host_event_tests { } } - /// Everything the loop still reads raw stays raw: no key, text, pointer or wheel event decodes, - /// in either key layout, and neither do the SDL events nothing acts on (terminating and low - /// memory, which sit between quit and the background pair, and the window events). + /// Everything the loop still reads raw stays raw: no pointer or wheel event decodes (0x400 to + /// 0x403, until W5c), nor the IME's pre-edit (0x302, which nothing reads), nor the SDL events + /// nothing acts on (terminating and low memory, which sit between quit and the background pair, + /// and the window events). Keys (0x300, 0x301) and text (0x303) are decoded: `key_event_tests`. #[test] fn every_other_event_stays_on_the_raw_path() { for code in [ - 0, 0x101, 0x102, 0x107, 0x200, 0x300, 0x301, 0x302, 0x303, 0x400, 0x401, 0x402, 0x403, - u32::MAX, + 0, 0x101, 0x102, 0x107, 0x200, 0x302, 0x400, 0x401, 0x402, 0x403, u32::MAX, ] { assert_eq!(decode_host_event(&event_of(code)), None, "{code:#x}"); } - for down in [true, false] { - assert_eq!(decode_host_event(&encode_key(plx_ui::consts::SDLK_DOWN, 0, down)), None); + } +} + +/// A key edge and a text commit as a [`HostEvent`] (W5b): what the SDL decoder makes of the bytes, +/// the pairs the FIFO's named tokens press, and the one guarantee the constructor gives. +#[cfg(test)] +mod key_event_tests { + use super::{ + decode_host_event, encode_key, encode_key_repeat, remote_token_key, Action, Edge, HostEvent, + KeyPress, RawKey, + }; + use plx_ui::consts::{raw_pair, SDLK_CLEAR, SDLK_DOWN, SDLK_RETURN, SDLK_UP, WCODE_BACK, WCODE_PLAY}; + + fn press(action: Option, edge: Edge, sym: u32, wcode: u32) -> HostEvent { + HostEvent::Key(KeyPress::new(action, edge, Some(RawKey { sym, wcode })).expect("a raw pair names a press")) + } + + /// An SDL key event decodes to its edge, its raw pair (always kept) and its action (`None` for a + /// press the app does not bind), for the layout this build reads. The press is built with + /// `encode_key`/`encode_key_repeat`, so this is the round trip; the byte-literal test below pins + /// the layout itself. + #[test] + fn an_sdl_key_decodes_to_its_edge_its_raw_pair_and_its_action() { + let table: [(u32, u32, Option); 9] = [ + (SDLK_UP, 0, Some(Action::Up)), + (SDLK_RETURN, 0, Some(Action::Ok)), + (0, WCODE_BACK, Some(Action::Back)), + (0, WCODE_PLAY, Some(Action::Play)), + (b'4' as u32, 33, Some(Action::Digit(4))), + (8, 42, Some(Action::Backspace)), + (SDLK_CLEAR, 156, Some(Action::ClearAll)), + (0, 504, None), + (0, 0, None), + ]; + for (sym, wcode, action) in table { + assert_eq!(decode_host_event(&encode_key(sym, wcode, true)), Some(press(action, Edge::Down, sym, wcode)), "({sym},{wcode}) down"); + assert_eq!(decode_host_event(&encode_key(sym, wcode, false)), Some(press(action, Edge::Up, sym, wcode)), "({sym},{wcode}) up"); + assert_eq!(decode_host_event(&encode_key_repeat(sym, wcode)), Some(press(action, Edge::Repeat, sym, wcode)), "({sym},{wcode}) repeat"); + } + } + + /// The layout, byte for byte and written out a second time rather than through `encode_key`. + /// LG's fork: `state` u32 at +16, wcode at +20, sym at +24. Stock SDL (the simulator): `state` u8 + /// at +12, `repeat` u8 at +13, sym at +20, and a synthetic press carries its wcode in `mod` at + /// +24 under the `SYNTH_WINDOW` marker at +8 (`decode_key`'s doc has the measurement). + #[test] + fn the_key_layout_is_pinned_byte_for_byte() { + // UP (0x40000052) with no wcode, and PLAY (wcode 450 = 0x1c2) with no sym. + let (up_sym, play_wcode) = ([0x52, 0x00, 0x00, 0x40], [0xc2, 0x01, 0x00, 0x00]); + let mut up = [0u8; 128]; + let mut play = [0u8; 128]; + let mut repeat = [0u8; 128]; + for ev in [&mut up, &mut play, &mut repeat] { + ev[0..4].copy_from_slice(&0x300u32.to_ne_bytes()); } + if cfg!(feature = "hostsim") { + for ev in [&mut up, &mut play, &mut repeat] { + ev[12] = 1; + ev[8..12].copy_from_slice(&0x504c_584bu32.to_ne_bytes()); + } + up[20..24].copy_from_slice(&up_sym); + play[24..26].copy_from_slice(&450u16.to_ne_bytes()); + repeat[20..24].copy_from_slice(&up_sym); + repeat[13] = 1; + } else { + for ev in [&mut up, &mut play, &mut repeat] { + ev[16] = 1; + } + up[24..28].copy_from_slice(&up_sym); + play[20..24].copy_from_slice(&play_wcode); + repeat[24..28].copy_from_slice(&up_sym); + repeat[17] = 1; // state 0x101 + } + assert_eq!(decode_host_event(&up), Some(press(Some(Action::Up), Edge::Down, SDLK_UP, 0))); + assert_eq!(decode_host_event(&play), Some(press(Some(Action::Play), Edge::Down, 0, 450))); + assert_eq!(decode_host_event(&repeat), Some(press(Some(Action::Up), Edge::Repeat, SDLK_UP, 0))); + } + + /// A release never carries the auto-repeat bit into the event: `Edge::Up` is `Edge::Up`, and the + /// tape's `repeat` for it is false (the SDL drivers only stamp 0x100 on a press). + #[test] + fn a_release_is_an_up_edge_whatever_else_is_stamped() { + let mut ev = encode_key(SDLK_DOWN, 0, false); + if cfg!(feature = "hostsim") { + ev[13] = 1; + } else { + ev[17] = 1; + } + let Some(HostEvent::Key(key)) = decode_host_event(&ev) else { panic!("a key event") }; + assert_eq!(key.state(), 0); + assert_eq!(key, KeyPress::new(Some(Action::Down), Edge::Up, Some(RawKey { sym: SDLK_DOWN, wcode: 0 })).unwrap()); + } + + /// The constructor's guarantee: a press names an action or a raw pair, and an action-only press + /// reads as the pair `raw_pair` gives it, which is what a remote's press of that key would be. + /// A raw pair that came with an action keeps being the pair read. + #[test] + fn a_press_names_an_action_or_a_raw_pair_and_reads_back_as_a_pair() { + assert!(KeyPress::new(None, Edge::Down, None).is_none(), "a press that names nothing is refused"); + for action in [Action::Up, Action::Pause, Action::Rewind, Action::PageDown, Action::Backspace, Action::Digit(3)] { + let only = KeyPress::new(Some(action), Edge::Down, None).unwrap(); + let (sym, wcode) = raw_pair(action); + assert_eq!(only.pair(), RawKey { sym, wcode }, "{action:?}"); + assert_eq!(only.action(), Some(action)); + } + let both = KeyPress::new(Some(Action::Back), Edge::Down, Some(RawKey { sym: 8, wcode: 482 })).unwrap(); + assert_eq!(both.pair(), RawKey { sym: 8, wcode: 482 }, "the simulator's desktop Backspace stays the pair it was"); + let raw_only = KeyPress::new(None, Edge::Repeat, Some(RawKey { sym: 0, wcode: 504 })).unwrap(); + assert_eq!((raw_only.action(), raw_only.pair()), (None, RawKey { sym: 0, wcode: 504 })); + assert_eq!( + [Edge::Down, Edge::Repeat, Edge::Up] + .map(|edge| KeyPress::new(Some(Action::Ok), edge, None).unwrap().state()), + [1, 0x101, 0] + ); + } + + /// **A press is one key: its action and its pair cannot disagree.** An action alone must read + /// back from its own `raw_pair` (`Digit(10)`, which `raw_pair` spells as `(0, 0)`, does not and + /// is refused, whatever else rides beside it); a stated action must be what `action_of` reads + /// out of the pair it comes with (the pairs below are real keys, each beside another key's + /// action); and a pair with no stated action has the action `action_of` reads out of it, + /// `PointerHidden` for the LG remote's pointer-hide wcode included. + #[test] + fn a_press_is_one_key_and_its_action_and_pair_cannot_disagree() { + for n in [10u8, 11, 100, 255] { + assert!(KeyPress::new(Some(Action::Digit(n)), Edge::Down, None).is_none(), "Digit({n}) names no key"); + assert!(KeyPress::new(Some(Action::Digit(n)), Edge::Down, Some(RawKey { sym: 0, wcode: 0 })).is_none(), + "Digit({n}) is no action of the unbound pair (0, 0)"); + } + assert!(KeyPress::new(Some(Action::Digit(9)), Edge::Down, None).is_some(), "9 is a number key"); + assert_eq!(Action::digit(10), None); + for (action, sym, wcode, why) in [ + (Action::Play, 0, 72, "PAUSE's wcode"), + (Action::Pause, 0, 450, "PLAY's wcode"), + (Action::PageUp, 0x4000_004e, 0, "PAGE DOWN's sym"), + (Action::PageDown, 0x4000_004b, 0, "PAGE UP's sym"), + (Action::Left, 0, 452, "REWIND, which is not a plain LEFT"), + (Action::Rewind, 0x4000_0050, 0, "LEFT, which is not REWIND"), + (Action::Digit(4), b'5' as u32, 0, "the digit 5"), + (Action::Ok, 0, 504, "an unbound colour button"), + (Action::PointerHidden, 0, 504, "an unbound colour button"), + ] { + assert!(KeyPress::new(Some(action), Edge::Down, Some(RawKey { sym, wcode })).is_none(), + "{action:?} beside {why} is two keys"); + } + // Agreeing, in either spelling, is accepted: the simulator's desktop Backspace carries BACK's wcode. + assert!(KeyPress::new(Some(Action::Back), Edge::Down, Some(RawKey { sym: 8, wcode: 482 })).is_some()); + assert!(KeyPress::new(Some(Action::Play), Edge::Down, Some(RawKey { sym: 0, wcode: 450 })).is_some()); + // A pair with no stated action has the action it reads as, so a raw-only press is the press an SDL event is. + for (sym, wcode, action) in [ + (0, 0x1e4, Some(Action::PointerHidden)), + (0, 450, Some(Action::Play)), + (0x4000_004b, 0, Some(Action::PageUp)), + (0, 300, Some(Action::PageUp)), + (0, 504, None), + ] { + let press = KeyPress::new(None, Edge::Down, Some(RawKey { sym, wcode })).unwrap(); + assert_eq!((press.action(), press.pair()), (action, RawKey { sym, wcode }), "({sym}, {wcode})"); + } + } + + /// **A native key decodes to the action it means.** Every pair here is what a television or the + /// simulator sends, written out as a LITERAL (no `raw_pair`, no constant), so a wrong `action_of` + /// reading cannot agree with itself: PLAY is not PAUSE, REWIND is not a plain LEFT, PAGE UP and + /// CH+ are not PAGE DOWN and CH-, the number keys read from the sym alone, and a wcode-only + /// number press is no action (the PIN pad reads it through `pin_digit` instead). No production + /// reader of the loop reads the action before W5d, so a wrong `action_of` leaves every native + /// effect test green: this table, `input.rs`'s decode literals and the hosted door's round trip + /// (`KeyPress::new`) are what see it. `native_key_effect_*` in `run.rs` grade what the consumers + /// do with the pair. + #[test] + fn native_key_effect_the_native_pairs_decode_to_the_actions_they_mean() { + let table: &[(u32, u32, Option)] = &[ + (0x4000_0052, 0, Some(Action::Up)), + (0x4000_0051, 0, Some(Action::Down)), + (0x4000_0050, 0, Some(Action::Left)), + (0x4000_004f, 0, Some(Action::Right)), + (13, 0, Some(Action::Ok)), + (0, 482, Some(Action::Back)), + (27, 0, Some(Action::Back)), + (8, 482, Some(Action::Back)), + (0, 450, Some(Action::Play)), + (0, 72, Some(Action::Pause)), + (0, 261, Some(Action::PlayPause)), + (415, 0, Some(Action::Pause)), + (0, 415, Some(Action::Pause)), + (19, 0, Some(Action::Play)), + (0, 402, Some(Action::Play)), + (0, 413, Some(Action::Stop)), + (0, 505, Some(Action::Exit)), + (0, 452, Some(Action::Rewind)), + (0, 451, Some(Action::FastForward)), + (0x4000_004b, 0, Some(Action::PageUp)), + (0, 300, Some(Action::PageUp)), + (0x4000_004e, 0, Some(Action::PageDown)), + (0, 301, Some(Action::PageDown)), + (8, 42, Some(Action::Backspace)), + (0x4000_009c, 156, Some(Action::ClearAll)), + (0, 0x1e4, Some(Action::PointerHidden)), + (48, 0, Some(Action::Digit(0))), + (49, 0, Some(Action::Digit(1))), + (50, 0, Some(Action::Digit(2))), + (51, 0, Some(Action::Digit(3))), + (52, 0, Some(Action::Digit(4))), + (53, 0, Some(Action::Digit(5))), + (54, 0, Some(Action::Digit(6))), + (55, 0, Some(Action::Digit(7))), + (56, 0, Some(Action::Digit(8))), + (57, 0, Some(Action::Digit(9))), + (57, 33, Some(Action::Digit(9))), + (0, 48, None), + (0, 53, None), + (0, 57, None), + (47, 0, None), + (58, 0, None), + (0, 504, None), + (0, 269, None), + (0, 270, None), + (97, 4, None), + (0, 0, None), + (0, 299, None), + (0, 302, None), + (0x4000_004c, 0, None), + ]; + for &(sym, wcode, action) in table { + let Some(HostEvent::Key(press)) = decode_host_event(&encode_key(sym, wcode, true)) else { + panic!("({sym}, {wcode}) decodes to a key press"); + }; + assert_eq!(press.action(), action, "({sym}, {wcode}) means {action:?}"); + assert_eq!(press.pair(), RawKey { sym, wcode }, "({sym}, {wcode}) keeps the pair it arrived as"); + } + } + + /// **The pairs the FIFO's named tokens press are the ones they have always pressed**, written out + /// as literals: they are what `tests/keytable.json` and the recorded tapes carry, and the fold + /// through `raw_pair` must not move one. The rocker's two tokens and `k:` are not actions' pairs + /// and stay literal. + #[test] + fn the_fifo_tokens_press_the_pairs_they_always_pressed() { + let (up, down, left, right) = (0x4000_0052u32, 0x4000_0051u32, 0x4000_0050u32, 0x4000_004fu32); + let (pageup, pagedown, clear) = (0x4000_004bu32, 0x4000_004eu32, 0x4000_009cu32); + for (tok, pair) in [ + ("up", (up, 0)), + ("down", (down, 0)), + ("left", (left, 0)), + ("right", (right, 0)), + ("ok", (13, 0)), + ("enter", (13, 0)), + ("select", (13, 0)), + ("back", (27, 0)), + ("esc", (27, 0)), + ("pageup", (pageup, 0)), + ("pagedown", (pagedown, 0)), + ("chup", (0, 300)), + ("chdown", (0, 301)), + ("play", (0, 450)), + ("pause", (0, 72)), + ("stop", (0, 413)), + ("ff", (0, 451)), + ("fastforward", (0, 451)), + ("rew", (0, 452)), + ("rewind", (0, 452)), + ("playpause", (0, 261)), + ("exit", (0, 505)), + ("backspace", (8, 42)), + ("del", (8, 42)), + ("clear", (clear, 156)), + ("k:0,504", (0, 504)), + ("k:53,34", (53, 34)), + ] { + assert_eq!(remote_token_key(tok), Some(pair), "{tok}"); + } + assert_eq!(remote_token_key("home"), None, "an unknown token names no key"); + assert_eq!(remote_token_key("k:1"), None, "`k:` needs both fields"); + } + + /// `SDL_TEXTINPUT` decodes to its string at THIS build's offset (LG's fork, +16; stock SDL, +12), + /// written out as literals: ASCII, a CJK commit (3 bytes a character), a full unterminated + /// 32-byte array, and the empty commit SDL sends for the IME's bookkeeping, which is still a + /// `Text` (the loop ignores it). + #[test] + fn a_text_commit_decodes_at_this_builds_offset() { + let off = if cfg!(feature = "hostsim") { 12 } else { 16 }; + let text = |bytes: &[u8]| { + let mut ev = [0u8; 128]; + ev[0..4].copy_from_slice(&0x303u32.to_ne_bytes()); + ev[off..off + bytes.len()].copy_from_slice(bytes); + decode_host_event(&ev) + }; + assert_eq!(text(b"wal"), Some(HostEvent::Text("wal".into()))); + assert_eq!(text("星球".as_bytes()), Some(HostEvent::Text("星球".into()))); + assert_eq!(text(&[b'a'; 32]), Some(HostEvent::Text("a".repeat(32)))); + assert_eq!(text(b""), Some(HostEvent::Text(String::new()))); } } diff --git a/rust-modules/src/app/input.rs b/rust-modules/src/app/input.rs index 5af3dd5035..1dd299ca33 100644 --- a/rust-modules/src/app/input.rs +++ b/rust-modules/src/app/input.rs @@ -1323,7 +1323,7 @@ mod unsupported_key_tests { fn a_bound_key_still_wakes_the_hud_without_owning_the_press() { let ps = plx_media::route::PlaybackSession::IDLE; let _g = plx_base::testlock::serial(); - let (armed, dismissed) = press(&ps, SDLK_ESCAPE, 0); + let (armed, dismissed) = press(&ps, plx_ui::consts::SDLK_ESCAPE, 0); assert!(armed, "physical bookkeeping must leave press ownership to the dispatcher"); assert!(!dismissed, "…and any key un-dismisses the transport"); } @@ -1358,6 +1358,64 @@ mod unsupported_key_tests { assert!(armed, "physical bookkeeping leaves cancellation to the input owner"); assert!(!dismissed); } + + /// The native pair as the loop reads it: decoded from the SDL bytes a television sends, then + /// handed to [`press`]. Returns the decoded action too. + fn native(ps: &plx_media::route::PlaybackSession, sym: c_uint, wcode: c_uint) + -> (Option, (bool, bool)) { + let (key, _) = crate::app::events::native_key_input(sym, wcode, true, plx_machine::machine::Tick::default()); + let pair = key.pair(); + assert_eq!((pair.sym, pair.wcode), (sym, wcode), "the decoder keeps the raw pair"); + (key.action(), press(ps, pair.sym, pair.wcode)) + } + + /// **A native key that no action names wakes nothing and abandons nothing, and a bound one still + /// wakes the HUD.** Both halves through the decoder, each pair a literal, in one test so the bound + /// keys are the positive control for the unbound ones: the colour button (504), HOME (269), + /// and the wcode-only press in 48..=57. That last one is the keypad's: `pin_digit` reads the + /// wcode, `is_remote_bound` reads the sym only (`action_of`'s number-key arm), so a scancode that + /// is punctuation (`;` is 51) is no number key to this predicate and has no action. + #[test] + fn native_key_effect_an_unbound_press_wakes_nothing_and_a_bound_one_wakes_the_hud() { + use plx_ui::consts::Action; + let ps = plx_media::route::PlaybackSession::IDLE; + let _g = plx_base::testlock::serial(); + let mut unbound: Vec<(c_uint, c_uint)> = vec![(0, 504), (0, 269), (0, 270), (b'a' as c_uint, 4), (0, 0)]; + unbound.extend((48..=57).map(|wcode| (0, wcode))); + for (sym, wcode) in unbound { + let (action, (armed, dismissed)) = native(&ps, sym, wcode); + assert_eq!(action, None, "({sym}, {wcode}) names no action"); + assert!(armed, "({sym}, {wcode}) must not cancel the armed click"); + assert!(dismissed, "({sym}, {wcode}) must not un-dismiss the HUD"); + } + for (sym, wcode, action) in [ + (0x4000_0051, 0, Action::Down), (13, 0, Action::Ok), (27, 0, Action::Back), + (0, 450, Action::Play), (0, 72, Action::Pause), (0, 452, Action::Rewind), + (0x4000_004e, 0, Action::PageDown), (0, 300, Action::PageUp), + (8, 42, Action::Backspace), (53, 34, Action::Digit(5)), + ] { + let (decoded, (_, dismissed)) = native(&ps, sym, wcode); + assert_eq!(decoded, Some(action), "({sym}, {wcode}) decodes to its action"); + assert!(!dismissed, "{action:?} is bound, so it un-dismisses the HUD"); + } + } + + /// **The lab trigger is not a key this build has.** `labcfg::is_trigger_key` is `false` at + /// compile time without `lab-diagnostics` (every build the suite runs: the hostsim and default + /// feature sets), so no test here can arm one; the type-check of `lab-diagnostics` is `make + /// check`'s third feature set and compiles no test. What this build does is pinned instead: no + /// native pair is a trigger, and `is_bound` is exactly "has an action" for all of them, so the + /// fifth source of `is_bound`'s doc contributes nothing and the lab arm of the loop's ladder + /// never takes a key. + #[cfg(not(feature = "lab-diagnostics"))] + #[test] + fn native_key_effect_no_lab_trigger_exists_without_lab_diagnostics() { + for (sym, wcode) in [(0, 504), (0, 450), (0, 72), (0x4000_0051, 0), (13, 0), (0, 300), (8, 42), (53, 34), (0, 55), (0, 0)] { + let (key, _) = crate::app::events::native_key_input(sym, wcode, true, plx_machine::machine::Tick::default()); + assert!(!plx_os::labcfg::is_trigger_key(sym, wcode), "({sym}, {wcode}) is no trigger here"); + assert_eq!(plx_ui::consts::is_bound(sym, wcode), key.action().is_some(), "({sym}, {wcode}) is bound iff it has an action"); + } + } } /// What the root press does once `auth::cancel` has answered. diff --git a/rust-modules/src/app/mod.rs b/rust-modules/src/app/mod.rs index e6966f1e4c..78370d23e3 100644 --- a/rust-modules/src/app/mod.rs +++ b/rust-modules/src/app/mod.rs @@ -90,9 +90,8 @@ pub(crate) const SDL_TEXTINPUT: u32 = 0x303; // keysyms, the OK/BACK predicates and `classify` — the key VOCABULARY the ladder below dispatches // on — live in ui::consts (the single keycode home) use plx_ui::consts::{ - classify, is_bound, is_ok, Key, SDLK_DOWN, SDLK_ESCAPE, SDLK_LEFT, SDLK_PAGEDOWN, - SDLK_PAGEUP, SDLK_RETURN, SDLK_RIGHT, SDLK_UP, WCODE_CH_DOWN_KEY, WCODE_CH_UP_KEY, WCODE_PAUSE, - WCODE_PLAY, WCODE_POINTER_HIDDEN, WCODE_STOP, + classify, is_bound, is_ok, Key, SDLK_RETURN, WCODE_CH_DOWN_KEY, WCODE_CH_UP_KEY, + WCODE_POINTER_HIDDEN, }; // The window we ASK SDL for. `surface::probe` then reads back what we actually got. const SCR_W: c_int = plx_base::surface::LOGICAL_W as c_int; diff --git a/rust-modules/src/app/run.rs b/rust-modules/src/app/run.rs index 6c74655859..c0d8025e34 100644 --- a/rust-modules/src/app/run.rs +++ b/rust-modules/src/app/run.rs @@ -1178,9 +1178,16 @@ fn window_step(stage: plx_telemetry::telemetry::window::Stage, playing: Option {} + // The tape owns logical ingress; a real key or text commit must not be counted a second time. + HostEvent::Key(_) | HostEvent::Text(_) => {} } return; } - // Lifecycle changes remain page damage. - app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); + // Attribute only the input repaint to its owner; lifecycle changes remain page damage. + if matches!(event, HostEvent::Key(_) | HostEvent::Text(_)) { app.note_input_damage(); } + else { app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); } match event { + HostEvent::Key(press) => ingest_key(app, press), + HostEvent::Text(text) => ingest_text_commit(app, text), // Nothing is torn down here: the loop ends, then `shutdown` releases what is held. HostEvent::Quit => app.running = false, HostEvent::Lifecycle(edge) => { @@ -1377,325 +1389,292 @@ unsafe fn host_foreground(app: &mut App, edge: Lifecycle, playing: bool, } } -/// One polled event. Shared by ordinary polling and ordered FIFO/replay ingestion. -unsafe fn ingest_sdl_event(app: &mut App, fr: &mut Frame) { - let shell = app.platform.shell; - ingest_sdl_event_with_window(app, fr, |win| shell.grab_surface(win)); -} - -/// The window reacquisition is a platform operation, supplied separately so the -/// recorded/live ingress boundary can be exercised without an SDL/GL context. +/// One key edge, and the loop's whole reaction to it: the ladder every press goes through. /// -/// Quit and the four lifecycle edges are decoded into a [`HostEvent`] and consumed by -/// [`ingest_host_event`]. What follows is the raw path: key, text, pointer and wheel events, read -/// from the event's bytes here until their own steps move them behind the decoder. -unsafe fn ingest_sdl_event_with_window(app: &mut App, fr: &mut Frame, - restore_window: impl FnOnce(*mut c_void)) { - if let Some(event) = decode_host_event(&app.ev) { - ingest_host_event(app, fr, event, restore_window); +/// The ladder reads the key's raw `(sym, wcode)` pair, as it always has: a press with no [`Action`] +/// (an unsupported key) flows on as exactly the pair it was, the lab trigger is a pair `lab.json` +/// names, and the tape records the pair. `press.pair()` is the raw pair an SDL event carried or, for +/// a host that sent only an action, the pair `raw_pair` gives it, so a platform with no SDL key +/// reaches the same arms a real remote does. Every arm reads the pair, the pointer-hide +/// notification included (`classify` of the pair, as it always was): the press's own `action()` is +/// the same answer by construction (`KeyPress::new` refuses a press whose action is not the pair's), +/// and the pair is the one thing every platform's press has. +unsafe fn ingest_key(app: &mut App, press: KeyPress) { + let RawKey { sym, wcode } = press.pair(); + // The fork's packed state (low byte 1 is down, 0x100 an auto-repeat), re-derived from the edge + // so the arms below, `bridge::key_input` and the tape read it exactly as they read the event. + let state = press.state(); + // The press's IDENTITY, resolved once from the two raw fields + // (`ui::consts::classify`, which is where the spellings live and where they + // are tested). `sym` and `wcode` are still read raw by the arms below — the + // ones that forward them to a screen's own `move_focus`/`key`, and the modal + // panels and the CH▲/CH▼ pager, which still spell their own key tests. + let key = classify(sym, wcode); + // LG can report its own pointer hide as a key-shaped SDL event. It is + // a notification, so it must not wake the HUD or spend Back's exit latch. + if key == Key::PointerHidden { + app.ptr.edge.stop(); return; } - let et = rd_u32(&app.ev, 0); - // A key or pointer event is the activity that keeps a release-health session open - // (`telemetry::session`; consent-gated inside, a no-op while crash reports are off). - if is_input_event(et) { plx_telemetry::telemetry::session::input(); } - if controlled_replay(app) { - // The tape owns logical ingress; real SDL events must not be counted a second time. + if app.boot_initial.is_some() { + let event = super::bridge::key_input(sym, wcode, state, + plx_machine::machine::Tick { ms: clock::now(), dt_us: 0 }, plx_machine::machine::Source::Sdl); + controlled_key_input(app, event); return; } - // Attribute only the input repaint to its owner; other events remain page damage. - if is_input_event(et) { app.note_input_damage(); } - else { app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); } - if et == SDL_KEYDOWN - || et == SDL_KEYUP - || et == SDL_TEXTINPUT - || et == SDL_TEXTEDITING - { - // 48 bytes, not 32: a TEXTINPUT event's `text[32]` starts at +16 on the - // television (LG's `inputSource` shifts it), so it ENDS at exactly +48. At the - // old width the one event whose payload the offsets are most easily wrong - // about would have left a forensic trail that stopped just before the payload. - let mut hex = String::with_capacity(96); - for b in &app.ev[..48] { - hex.push_str(&format!("{b:02x}")); - } - let what = match et { - SDL_TEXTINPUT => "text", - // **The IME's PRE-EDIT, and the reason it is logged at all.** The panel's - // word prediction is a REPLACE — tapping "summer" under a typed "summ" - // means *delete what I was predicting on, then commit this* — and the app - // sees only the commit, so the field reads "summsummer" (reported from the - // couch 2026-08-15). Whether the delete half reaches us as `SDL_TEXTEDITING` - // (`text_model.delete_surrounding_text` mapped onto SDL's pre-edit) or as - // nothing at all decides whether the fix can be exact or has to be a - // heuristic — and this arm is the only way to find out, since nothing in - // the app has ever read this event. - SDL_TEXTEDITING => "edit", - _ => "key", - }; - log(&format!( - "[{}] {what} type=0x{et:x} raw={hex}", - clock::now() - )); - } - if et == SDL_KEYDOWN || et == SDL_KEYUP { - let (state, wcode, sym) = decode_key(&app.ev); - // The press's IDENTITY, resolved once from the two raw fields - // (`ui::consts::classify`, which is where the spellings live and where they - // are tested). `sym` and `wcode` are still read raw by the arms below — the - // ones that forward them to a screen's own `move_focus`/`key`, and the modal - // panels and the CH▲/CH▼ pager, which still spell their own key tests. - let key = classify(sym, wcode); - // LG can report its own pointer hide as a key-shaped SDL event. It is - // a notification, so it must not wake the HUD or spend Back's exit latch. - if key == Key::PointerHidden { - app.ptr.edge.stop(); - return; - } - if app.boot_initial.is_some() { - let event = super::bridge::key_input(sym, wcode, state, - plx_machine::machine::Tick { ms: clock::now(), dt_us: 0 }, plx_machine::machine::Source::Sdl); - controlled_key_input(app, event); - return; + app.rec.input(super::recorder::enc_key( + sym, + wcode, + (state & 0xff) == 1, + state & 0x100 != 0, + )); + // **Does the TREE own this key?** (phase 5b, `app/bridge.rs`'s coexistence + // contract.) Asked once, here, above all three edges — because the dispatcher's + // press machine wants ALL of them: `Edge::Down` arms, `Edge::Repeat` is the + // dropped-key-up net's liveness beat, and `Edge::Up` is the release. Handing it + // only the fresh presses would leave a dipped control committing a second later + // at `press::MAX_HOLD_MS` instead of on the button coming up. + let tree_owns_key = super::bridge::owns_input(&app.pages); + // `clock::now()`, not `fr.now`: INGEST runs before the frame stamps its own time + // (see `run`'s phase order), so `fr.now` is still 0 here — the same reason the + // ladder below reaches for the clock to fill `app.last_input`. `dt_us` is 0 + // because an event's `at` is a stamp, not a timestep: every machine the + // dispatcher steps is driven by the FRAME's tick, which `bridge::frame` supplies. + let tree_tick = plx_machine::machine::Tick { + ms: clock::now(), + dt_us: 0, + }; + if (state & 0xff) != 1 { + if tree_owns_key { + app.inputs.push(super::bridge::key_input(sym, wcode, state, tree_tick, plx_machine::machine::Source::Sdl)); } - app.rec.input(super::recorder::enc_key( - sym, - wcode, - (state & 0xff) == 1, - state & 0x100 != 0, - )); - // **Does the TREE own this key?** (phase 5b, `app/bridge.rs`'s coexistence - // contract.) Asked once, here, above all three edges — because the dispatcher's - // press machine wants ALL of them: `Edge::Down` arms, `Edge::Repeat` is the - // dropped-key-up net's liveness beat, and `Edge::Up` is the release. Handing it - // only the fresh presses would leave a dipped control committing a second later - // at `press::MAX_HOLD_MS` instead of on the button coming up. - let tree_owns_key = super::bridge::owns_input(&app.pages); - // `clock::now()`, not `fr.now`: INGEST runs before the frame stamps its own time - // (see `run`'s phase order), so `fr.now` is still 0 here — the same reason the - // ladder below reaches for the clock to fill `app.last_input`. `dt_us` is 0 - // because an event's `at` is a stamp, not a timestep: every machine the - // dispatcher steps is driven by the FRAME's tick, which `bridge::frame` supplies. - let tree_tick = plx_machine::machine::Tick { - ms: clock::now(), - dt_us: 0, - }; - if (state & 0xff) != 1 { - if tree_owns_key { + // …and the loop's own key-up bookkeeping runs either way: it retires the sym + // from the physically-down slot and releases a deferred press, both of which are + // state about the PHYSICAL key rather than about whoever read it. Skipping it + // while a surface is up would leave a key the ladders never saw go down looking + // held the moment the surface closes. + // + // **It no longer touches the scrub** (restructure phase 12, PX-PLAYER). It used to + // commit, cancel or debounce `PlayerScreen::scrub` from here — a field the page + // itself has owned since it began answering `HitSource::Engine`, and which arms its + // own `TAP_COMMIT_MS` debounce on the very same `Edge::Up` — so one tap of RIGHT + // issued two seeks. The publish that followed went with it: nothing here moves a + // published field any more. + on_key_up(sym, &mut app.down_sym); + return; + } + // A repeat is only a repeat if we watched the key go down. See `App::down_sym`: + // the system keyboard eats key-ups, so the driver stamps 0x100 on presses that are + // the FIRST of their own gesture, and dropping those loses one press in two. + if state & 0x100 != 0 && sym == app.down_sym { + if tree_owns_key { + // **Item 13 survives the migration, and only the DIRECTIONS are gated.** + // A held key repeats every ~50 ms; a settings row or a line of reading + // text per beat is a blur nobody can track, and the focus engine has no + // cadence of its own — so `RepeatGate` still throttles the moves. The OK + // edges go through UNGATED, deliberately: `dispatch`'s ingest reads an OK + // `Edge::Repeat` as `press.note_alive`, so a swallowed beat is a hold that + // looks like a lost key-up and springs back without activating. + let ok = is_ok(sym); + if ok || app.modal_repeat.ready(tree_tick.ms) { app.inputs.push(super::bridge::key_input(sym, wcode, state, tree_tick, plx_machine::machine::Source::Sdl)); } - // …and the loop's own key-up bookkeeping runs either way: it retires the sym - // from the physically-down slot and releases a deferred press, both of which are - // state about the PHYSICAL key rather than about whoever read it. Skipping it - // while a surface is up would leave a key the ladders never saw go down looking - // held the moment the surface closes. - // - // **It no longer touches the scrub** (restructure phase 12, PX-PLAYER). It used to - // commit, cancel or debounce `PlayerScreen::scrub` from here — a field the page - // itself has owned since it began answering `HitSource::Engine`, and which arms its - // own `TAP_COMMIT_MS` debounce on the very same `Edge::Up` — so one tap of RIGHT - // issued two seeks. The publish that followed went with it: nothing here moves a - // published field any more. - on_key_up(sym, &mut app.down_sym); return; } - // A repeat is only a repeat if we watched the key go down. See `App::down_sym`: - // the system keyboard eats key-ups, so the driver stamps 0x100 on presses that are - // the FIRST of their own gesture, and dropping those loses one press in two. - if state & 0x100 != 0 && sym == app.down_sym { - if tree_owns_key { - // **Item 13 survives the migration, and only the DIRECTIONS are gated.** - // A held key repeats every ~50 ms; a settings row or a line of reading - // text per beat is a blur nobody can track, and the focus engine has no - // cadence of its own — so `RepeatGate` still throttles the moves. The OK - // edges go through UNGATED, deliberately: `dispatch`'s ingest reads an OK - // `Edge::Repeat` as `press.note_alive`, so a swallowed beat is a hold that - // looks like a lost key-up and springs back without activating. - let ok = is_ok(sym); - if ok || app.modal_repeat.ready(tree_tick.ms) { - app.inputs.push(super::bridge::key_input(sym, wcode, state, tree_tick, plx_machine::machine::Source::Sdl)); - } - return; - } - // All that is left of the legacy repeat path is the deferred press's liveness - // beat: the player's continuous scrub, its last direct consumer, engages from - // `PlayerScreen`'s own `Edge::Repeat` (phase 12, PX-PLAYER). + // All that is left of the legacy repeat path is the deferred press's liveness + // beat: the player's continuous scrub, its last direct consumer, engages from + // `PlayerScreen`'s own `Edge::Repeat` (phase 12, PX-PLAYER). - return; - } - // From here down this IS a fresh press, whatever the driver stamped on it. - app.last_input = clock::now(); - // The press that pays for a decoder-release restore also says which clock it restores - // (`wake_input`): PLAY plays, the PLAYPAUSE toggle plays a park saved Paused, and every - // other key — OK included — is only a wake and keeps the saved clock. - let wake = match key { - Key::Play => WakePress::Play, - Key::PlayPause => WakePress::Toggle, - _ => WakePress::Wake, - }; - if claim_press_after_decoder_release(app, wake) { - // `down_sym` is unconditional for every fresh press (`begin_fresh_press`'s own - // doc), and this press never reaches that function: skipping it here left a key - // still physically held after the restore read as a FRESH press on its next - // hardware auto-repeat, firing the input ladder for real a tick after the restore. - app.down_sym = sym; - return; - } - let viewer_paused = viewer_paused_for(&app.player.session, &app.adapters.player); - // The bare player samples its HUD in delivery order. The lab trigger is - // consumed here, so it keeps the loop's fresh-press bookkeeping. - let ordered_player_key = tree_owns_key && !app.pages.surface_up() - && matches!(app.route(), AppArg::Player) && !plx_os::labcfg::is_trigger_key(sym, wcode); - begin_fresh_press(&mut app.player.session, - key, - sym, - wcode, - app.last_input, - viewer_paused, - &mut app.down_sym, - None, // The mounted player samples fresh presses in its own input delivery. - &mut app.ptr, + return; + } + // From here down this IS a fresh press, whatever the driver stamped on it. + app.last_input = clock::now(); + // The press that pays for a decoder-release restore also says which clock it restores + // (`wake_input`): PLAY plays, the PLAYPAUSE toggle plays a park saved Paused, and every + // other key — OK included — is only a wake and keeps the saved clock. + let wake = match key { + Key::Play => WakePress::Play, + Key::PlayPause => WakePress::Toggle, + _ => WakePress::Wake, + }; + if claim_press_after_decoder_release(app, wake) { + // `down_sym` is unconditional for every fresh press (`begin_fresh_press`'s own + // doc), and this press never reaches that function: skipping it here left a key + // still physically held after the restore read as a FRESH press on its next + // hardware auto-repeat, firing the input ladder for real a tick after the restore. + app.down_sym = sym; + return; + } + let viewer_paused = viewer_paused_for(&app.player.session, &app.adapters.player); + // The bare player samples its HUD in delivery order. The lab trigger is + // consumed here, so it keeps the loop's fresh-press bookkeeping. + let ordered_player_key = tree_owns_key && !app.pages.surface_up() + && matches!(app.route(), AppArg::Player) && !plx_os::labcfg::is_trigger_key(sym, wcode); + begin_fresh_press(&mut app.player.session, + key, + sym, + wcode, + app.last_input, + viewer_paused, + &mut app.down_sym, + None, // The mounted player samples fresh presses in its own input delivery. + &mut app.ptr, - ); - if !ordered_player_key { - super::bridge::send_player_message(&mut app.pages, - plx_screens::registry::AppMsg::PlayerExtendHud { now: app.last_input, duration_ms: HUD_LINGER_MS }); - } + ); + if !ordered_player_key { + super::bridge::send_player_message(&mut app.pages, + plx_screens::registry::AppMsg::PlayerExtendHud { now: app.last_input, duration_ms: HUD_LINGER_MS }); + } - // LAB BUILDS ONLY, and above every arm below including the modals: the - // diagnostics trigger. It has to outrank the chain because the screen a tester - // most needs a snapshot of is the playback failure read-out, whose own arm - // `continue`s on every key — and because a snapshot changes no app state, so - // there is nothing for a later arm to have wanted first. Compiles to `false` - // in every other build (`crate::lab::key_press`). - if crate::lab::key_press(sym, wcode, &app.player.session, &app.adapters.player) { - return; - } + // LAB BUILDS ONLY, and above every arm below including the modals: the + // diagnostics trigger. It has to outrank the chain because the screen a tester + // most needs a snapshot of is the playback failure read-out, whose own arm + // `continue`s on every key — and because a snapshot changes no app state, so + // there is nothing for a later arm to have wanted first. Compiles to `false` + // in every other build (`crate::lab::key_press`). + if crate::lab::key_press(sym, wcode, &app.player.session, &app.adapters.player) { + return; + } - // ---- the route-scoped arms, each of which `continue`s once it has taken the - // press. That makes the chain itself the priority statement: an earlier guard - // subsumes each later one it overlaps with, which the playback-failure guard - // below does deliberately. Keep it a chain — a `match` over the same routes - // compiles and keeps the suite green while silently reordering it, because - // exhaustiveness cannot see subsumption. - // - // **THE DISPATCHER'S ARM, and it is one line because that is the whole point** - // (phase 5b). Three hand-written arms stood here — consent above legal above the - // settings root — and the height of each in this chain WAS its modality: each - // `continue`d on every key, and the ordering was load-bearing because BACK out of - // the privacy notice would otherwise have been read as Home's ROOT PRESS and - // handed the screen to the television. That ordering is now a container's: the - // Settings family is a modal SURFACE on the app's `ModalStack`, whose inner - // `NavStack` walks itself on BACK and only then lets the container dismiss it, so - // "which of the four answers this key" is a tree walk rather than a chain the next - // editor has to keep in order. `owns_input` is the same question the pointer, - // click and wheel arms below ask, which is what stops the four drifting apart. + // ---- the route-scoped arms, each of which `continue`s once it has taken the + // press. That makes the chain itself the priority statement: an earlier guard + // subsumes each later one it overlaps with, which the playback-failure guard + // below does deliberately. Keep it a chain — a `match` over the same routes + // compiles and keeps the suite green while silently reordering it, because + // exhaustiveness cannot see subsumption. + // + // **THE DISPATCHER'S ARM, and it is one line because that is the whole point** + // (phase 5b). Three hand-written arms stood here — consent above legal above the + // settings root — and the height of each in this chain WAS its modality: each + // `continue`d on every key, and the ordering was load-bearing because BACK out of + // the privacy notice would otherwise have been read as Home's ROOT PRESS and + // handed the screen to the television. That ordering is now a container's: the + // Settings family is a modal SURFACE on the app's `ModalStack`, whose inner + // `NavStack` walks itself on BACK and only then lets the container dismiss it, so + // "which of the four answers this key" is a tree walk rather than a chain the next + // editor has to keep in order. `owns_input` is the same question the pointer, + // click and wheel arms below ask, which is what stops the four drifting apart. + // + // It stays HIGH in the chain for the reason the old arms did: an owned surface is + // modal over whatever route is behind it, and every route arm below would + // otherwise act on a page the user cannot see. + // + // **The fourth root is closed here** (`app/input.rs`'s `back_at_root`). BACK at + // the FIRST consent stage used to be swallowed — the step behind it is sign-in, + // which cannot be undone — and the old comment recorded why the 2026-09-03 root + // rule could not reach it: `ui::consent::on_back` reported `true` for both the + // stepped-back and the swallowed case, so a BACK arm could not tell them apart + // without changing that module's return type. The owned screen simply says which + // it is: `ConsentPage` answers `Handled::No` at a Settings BACK and pushes + // `LoopReq::BackAtRoot` at the first stage, and the request drain below performs + // it. Nothing is stranded by going to the television's Home — the question is + // neither answered nor dismissed, and selecting the tile again comes back to it. + if tree_owns_key { + // Ingress already resolved the driver's repeat-marked fresh press. + let state = if ordered_player_key { state & !0x100 } else { state }; + app.inputs.push(super::bridge::key_input(sym, wcode, state, tree_tick, plx_machine::machine::Source::Sdl)); + return; + } + // `Route::Login | Route::Profiles` is deliberately absent here (phase 6, mirroring + // `Route::Onboard`'s own removal in 5b): both are OWNED screens now, so a key on + // either was already taken by `tree_owns_key` above and never reaches this chain. + // (`Route::ItemMenu`'s arm stood here, above every route-scoped one — it was MODAL, so it + // took every key. The item menu is a `ModalStack` surface since phase 10, so its keys were + // already claimed by `tree_owns_key` well above this chain and it can never be reached.) + // (The failure read-out's own key arm stood here — OK to the quality ladder, BACK out of + // the playback, everything else swallowed, and its guard deliberately subsuming every + // player arm below it. It was already unreachable when phase 12 found it, having grown a + // `!matches!(app.route, Route::Player)` term that can never hold beside the + // `Route::Player` test above it; what it was FOR is `PlayerScreen::handle_key`'s own + // `transport_hidden` gate, which asks `failed_key_action` — the same pure policy — before + // any ordinary transport arm.) + // (Four arms stood here — the track menu, the `…` popover, the Info card and the + // Chapters strip, each gated on `overlay_swallows_key` so that a transport key FELL + // THROUGH to the ordinary Pause/Play arms below while everything else was swallowed. The + // panels are SURFACES on the player page's own `ModalStack` since restructure phase + // 9, so `tree_owns_key` at the top of this chain has already handed the key to the one + // that is open and returned; the fall-through, which a surface cannot perform, is + // `PlayerReq::Transport` — see `screens::player::overlay`'s module doc.) + // (The player's UP/DOWN arm stood here. It walked the HUD ring on the mounted + // `PlayerScreen`'s own `hud`/`scrub` — which the page also does, through `Screen::links`, the + // groups' edge rules and `answer_edge`, for the same key — and was unreachable behind `tree_owns_key` above from the moment the page + // answered `FocusSource::Engine`. Deleted in phase 12, PX-PLAYER.) + // `Route::Search` is deliberately absent here (phase 6/7 Search cutover, mirroring + // `Route::Login | Route::Profiles` above): Search is unconditionally an OWNED screen + // now, so `tree_owns_key` above already took every key on this route and returned — + // this chain can never see one. + // ---- and the arms on key IDENTITY, which the routes above have already had + // their pick of. Still one `else if` chain, still in this order: four of its + // nine tests carry a route term as well as a key one (this first arm, Stop, the + // player's LEFT/RIGHT and the Library pager), so the order is behaviour too. + // + // The plain syms only (`alt: false`) — the alternate D-pad codes reach no arm + // that navigates a non-player screen. See `Key::Left`, which carries that + // asymmetry between this test and the player's scrub arm below. + if !matches!(app.route(), AppArg::Player) + && matches!( + key, + Key::Up + | Key::Down + | Key::Left { alt: false } + | Key::Right { alt: false } + ) + { + // Every non-player route reaching this far down the ladder is an OWNED page + // (Home/Library/Search included, since the Search cutover), and an owned page's + // directions are taken by `tree_owns_key`'s arm well above this chain — this branch + // is reached by nothing and does nothing (`key_move_focus`, the function that used + // to live here, was itself already an unconditional no-op and is retired). The + // condition stays so this arm keeps its PRECEDENCE over `wcode == WCODE_POINTER_HIDDEN` + // below for the documented direction+wcode-hidden combination noted there; removing + // the branch instead of its body would let that combination fall through to it. + } else if wcode == WCODE_POINTER_HIDDEN { + // LG pointer auto-hidden: nothing else to do, but a hidden pointer resting at an + // edge no longer scrolls the page (`input::EdgeScroll`). + app.ptr.edge.stop(); // - // It stays HIGH in the chain for the reason the old arms did: an owned surface is - // modal over whatever route is behind it, and every route arm below would - // otherwise act on a page the user cannot see. + // THE RAW `wcode`, not `Key::PointerHidden`, and this is the one arm in the + // ladder that cannot use the classified value. Its precedence here is + // ROUTE-DEPENDENT: the nav arm above it is `!Player && `, so for + // an event carrying BOTH a direction sym and this wcode, Home moves focus + // (the nav arm wins, being higher) while the player swallows it (the nav arm + // is skipped, and this one catches it before the scrub arm below). // - // **The fourth root is closed here** (`app/input.rs`'s `back_at_root`). BACK at - // the FIRST consent stage used to be swallowed — the step behind it is sign-in, - // which cannot be undone — and the old comment recorded why the 2026-09-03 root - // rule could not reach it: `ui::consent::on_back` reported `true` for both the - // stepped-back and the swallowed case, so a BACK arm could not tell them apart - // without changing that module's return type. The owned screen simply says which - // it is: `ConsentPage` answers `Handled::No` at a Settings BACK and pushes - // `LoopReq::BackAtRoot` at the first stage, and the request drain below performs - // it. Nothing is stranded by going to the television's Home — the question is - // neither answered nor dismissed, and selecting the tile again comes back to it. - if tree_owns_key { - // Ingress already resolved the driver's repeat-marked fresh press. - let state = if ordered_player_key { state & !0x100 } else { state }; - app.inputs.push(super::bridge::key_input(sym, wcode, state, tree_tick, plx_machine::machine::Source::Sdl)); - return; - } - // `Route::Login | Route::Profiles` is deliberately absent here (phase 6, mirroring - // `Route::Onboard`'s own removal in 5b): both are OWNED screens now, so a key on - // either was already taken by `tree_owns_key` above and never reaches this chain. - // (`Route::ItemMenu`'s arm stood here, above every route-scoped one — it was MODAL, so it - // took every key. The item menu is a `ModalStack` surface since phase 10, so its keys were - // already claimed by `tree_owns_key` well above this chain and it can never be reached.) - // (The failure read-out's own key arm stood here — OK to the quality ladder, BACK out of - // the playback, everything else swallowed, and its guard deliberately subsuming every - // player arm below it. It was already unreachable when phase 12 found it, having grown a - // `!matches!(app.route, Route::Player)` term that can never hold beside the - // `Route::Player` test above it; what it was FOR is `PlayerScreen::handle_key`'s own - // `transport_hidden` gate, which asks `failed_key_action` — the same pure policy — before - // any ordinary transport arm.) - // (Four arms stood here — the track menu, the `…` popover, the Info card and the - // Chapters strip, each gated on `overlay_swallows_key` so that a transport key FELL - // THROUGH to the ordinary Pause/Play arms below while everything else was swallowed. The - // panels are SURFACES on the player page's own `ModalStack` since restructure phase - // 9, so `tree_owns_key` at the top of this chain has already handed the key to the one - // that is open and returned; the fall-through, which a surface cannot perform, is - // `PlayerReq::Transport` — see `screens::player::overlay`'s module doc.) - // (The player's UP/DOWN arm stood here. It walked the HUD ring on the mounted - // `PlayerScreen`'s own `hud`/`scrub` — which the page also does, through `Screen::links`, the - // groups' edge rules and `answer_edge`, for the same key — and was unreachable behind `tree_owns_key` above from the moment the page - // answered `FocusSource::Engine`. Deleted in phase 12, PX-PLAYER.) - // `Route::Search` is deliberately absent here (phase 6/7 Search cutover, mirroring - // `Route::Login | Route::Profiles` above): Search is unconditionally an OWNED screen - // now, so `tree_owns_key` above already took every key on this route and returned — - // this chain can never see one. - // ---- and the arms on key IDENTITY, which the routes above have already had - // their pick of. Still one `else if` chain, still in this order: four of its - // nine tests carry a route term as well as a key one (this first arm, Stop, the - // player's LEFT/RIGHT and the Library pager), so the order is behaviour too. + // `classify` is a pure function of the pair and cannot express that — it has + // one linear order and no route. Ordering it directions-first reproduces + // Home and makes the player SEEK on a pointer notification; ordering it + // pointer-first reproduces the player and freezes Home's navigation. So the + // classifier keeps directions first (Home correct) and the raw test stays + // here, at the position that was always the player's answer. // - // The plain syms only (`alt: false`) — the alternate D-pad codes reach no arm - // that navigates a non-player screen. See `Key::Left`, which carries that - // asymmetry between this test and the player's scrub arm below. - if !matches!(app.route(), AppArg::Player) - && matches!( - key, - Key::Up - | Key::Down - | Key::Left { alt: false } - | Key::Right { alt: false } - ) - { - // Every non-player route reaching this far down the ladder is an OWNED page - // (Home/Library/Search included, since the Search cutover), and an owned page's - // directions are taken by `tree_owns_key`'s arm well above this chain — this branch - // is reached by nothing and does nothing (`key_move_focus`, the function that used - // to live here, was itself already an unconditional no-op and is retired). The - // condition stays so this arm keeps its PRECEDENCE over `wcode == WCODE_POINTER_HIDDEN` - // below for the documented direction+wcode-hidden combination noted there; removing - // the branch instead of its body would let that combination fall through to it. - } else if wcode == WCODE_POINTER_HIDDEN { - // LG pointer auto-hidden: nothing else to do, but a hidden pointer resting at an - // edge no longer scrolls the page (`input::EdgeScroll`). - app.ptr.edge.stop(); - // - // THE RAW `wcode`, not `Key::PointerHidden`, and this is the one arm in the - // ladder that cannot use the classified value. Its precedence here is - // ROUTE-DEPENDENT: the nav arm above it is `!Player && `, so for - // an event carrying BOTH a direction sym and this wcode, Home moves focus - // (the nav arm wins, being higher) while the player swallows it (the nav arm - // is skipped, and this one catches it before the scrub arm below). - // - // `classify` is a pure function of the pair and cannot express that — it has - // one linear order and no route. Ordering it directions-first reproduces - // Home and makes the player SEEK on a pointer notification; ordering it - // pointer-first reproduces the player and freezes Home's navigation. So the - // classifier keeps directions first (Home correct) and the raw test stays - // here, at the position that was always the player's answer. - // - // Whether any real event carries that pair is unrecorded: nothing in the - // tree names the sym beside wcode 0x1e4, `remote_token_key` never emits it, - // and the simulator cannot produce one — so `tools/keytable.py` is blind to - // this by construction. Settling it needs a `key` line off the television. - } else if matches!(key, Key::Ok) { - // OK is no arm of this chain. Its one occupant was the player's, and a mounted player - // page owns input (`bridge::owns_input`, pinned by - // `a_mounted_player_page_owns_input_so_the_ladder_never_sees_ok`), so `tree_owns_key` - // above took the key; the row's press is the engine's, `PlayerScreen::row_pressed`. - // The arm stays, empty, so OK keeps its place in front of the arms below. - } else if matches!(key, Key::Pause) { - key_pause(&mut app.player.session, &mut app.adapters.player, app.last_input, &mut app.pages); - } else if matches!(key, Key::Play) { + // Whether any real event carries that pair is unrecorded: nothing in the + // tree names the sym beside wcode 0x1e4, `remote_token_key` never emits it, + // and the simulator cannot produce one — so `tools/keytable.py` is blind to + // this by construction. Settling it needs a `key` line off the television. + } else if matches!(key, Key::Ok) { + // OK is no arm of this chain. Its one occupant was the player's, and a mounted player + // page owns input (`bridge::owns_input`, pinned by + // `a_mounted_player_page_owns_input_so_the_ladder_never_sees_ok`), so `tree_owns_key` + // above took the key; the row's press is the engine's, `PlayerScreen::row_pressed`. + // The arm stays, empty, so OK keeps its place in front of the arms below. + } else if matches!(key, Key::Pause) { + key_pause(&mut app.player.session, &mut app.adapters.player, app.last_input, &mut app.pages); + } else if matches!(key, Key::Play) { + key_play(&mut app.player.session, + &mut app.adapters.player, + app.last_input, + &mut app.player.lifecycle, + &mut app.repause_at, + &mut app.ptr, + &mut app.pages, + &mut app.runtime.bridge(&mut app.bridge), + ); + } else if matches!(key, Key::PlayPause) { + // ONE key, both directions. `key_play`/`key_pause` are each half of the + // toggle, so this arm picks; off the player route `key_play` is what starts + // playback, which is the right answer for a PLAYPAUSE press on a card. + if viewer_paused_for(&app.player.session, &app.adapters.player) + || super::bridge::player(&app.pages).is_none() { key_play(&mut app.player.session, &mut app.adapters.player, app.last_input, @@ -1705,45 +1684,130 @@ unsafe fn ingest_sdl_event_with_window(app: &mut App, fr: &mut Frame, &mut app.pages, &mut app.runtime.bridge(&mut app.bridge), ); - } else if matches!(key, Key::PlayPause) { - // ONE key, both directions. `key_play`/`key_pause` are each half of the - // toggle, so this arm picks; off the player route `key_play` is what starts - // playback, which is the right answer for a PLAYPAUSE press on a card. - if viewer_paused_for(&app.player.session, &app.adapters.player) - || super::bridge::player(&app.pages).is_none() { - key_play(&mut app.player.session, - &mut app.adapters.player, - app.last_input, - &mut app.player.lifecycle, - &mut app.repause_at, - &mut app.ptr, - &mut app.pages, - &mut app.runtime.bridge(&mut app.bridge), - ); - } else { - key_pause(&mut app.player.session, &mut app.adapters.player, app.last_input, &mut app.pages); - } - } else if matches!(key, Key::Exit) { - // The remote's EXIT key — LG's checklist item 38 wants the app terminated, - // and unlike BACK at Home's root there is nothing ambiguous about a key - // labelled EXIT, so unlike BACK it really does end the process — and it - // is now the only key that does. - log("EXIT key: terminating"); - app.running = false; - // (Two player arms stood here — STOP's `exit_player`, and LEFT/RIGHT's `key_scrub`. Both - // are `PlayerScreen`'s: `Key::Stop` asks for `PlayerReq::Exit` and reaches the very same - // ritual through `player_requests`, and the scrub ladder is the page's three edges. Their - // route terms were two of the four that made this chain's ORDER behaviour, which is why - // they are recorded rather than silently dropped. Phase 12, PX-PLAYER.) - } else if matches!(key, Key::Back) { - key_back(&mut app.player, - &mut app.adapters.player, - &mut app.repause_at, - &mut app.refresh_hubs, - &mut app.pages, - ); + } else { + key_pause(&mut app.player.session, &mut app.adapters.player, app.last_input, &mut app.pages); + } + } else if matches!(key, Key::Exit) { + // The remote's EXIT key — LG's checklist item 38 wants the app terminated, + // and unlike BACK at Home's root there is nothing ambiguous about a key + // labelled EXIT, so unlike BACK it really does end the process — and it + // is now the only key that does. + log("EXIT key: terminating"); + app.running = false; + // (Two player arms stood here — STOP's `exit_player`, and LEFT/RIGHT's `key_scrub`. Both + // are `PlayerScreen`'s: `Key::Stop` asks for `PlayerReq::Exit` and reaches the very same + // ritual through `player_requests`, and the scrub ladder is the page's three edges. Their + // route terms were two of the four that made this chain's ORDER behaviour, which is why + // they are recorded rather than silently dropped. Phase 12, PX-PLAYER.) + } else if matches!(key, Key::Back) { + key_back(&mut app.player, + &mut app.adapters.player, + &mut app.repause_at, + &mut app.refresh_hubs, + &mut app.pages, + ); + } +} + +/// A text commit from the platform's keyboard (`HostEvent::Text`). +/// +/// The television's own keyboard committing text. Gated on `bridge::text_owner`, +/// and the gate is deliberate. Search on top takes every commit whatever our own +/// record of the panel says: a panel the OS raised or kept behind our back must +/// not eat REAL typing, so Search adopts it (`textinput::adopt`, via +/// `Bridge::adopt_system_keyboard`), and only Search's commit carries that +/// adoption edge (`bridge::text_panel_edge`). Any other page takes text only while +/// `Dispatcher::system_keyboard_up()` says it raised the keyboard. Everything +/// else goes to `textinput::queue`, which queues without checking and which +/// nothing drains, so for a non-Search field our own flag decides: text that +/// arrives while it is down is not delivered. The leaks of that queue are closed +/// downstream, where they can be closed completely: `textinput::start` clears +/// it, so nothing typed before a field opened can arrive in it, and +/// `MAX_PENDING` bounds a queue nobody drains. An empty commit is ignored by both. +fn ingest_text_commit(app: &mut App, text: String) { + if super::bridge::text_owner(&app.pages) { + let panel = super::bridge::text_panel_edge(&app.pages, crate::textinput::available()); + ingest_text(app, &text, panel, plx_machine::machine::Source::Sdl); + } else { + crate::textinput::queue(text); + } +} + +/// The SDL event's raw bytes as a log line, before anything acts on them: `key`, `text` or `edit` +/// (the IME's pre-edit, read by nothing else), 48 bytes of hex. The television's byte layouts have +/// moved under this app before, and this line is what settles which one a press arrived in +/// (`docs/remote-keys.md`). Nothing for any other event type. +fn log_raw_input_event(ev: &[u8]) { + let et = rd_u32(ev, 0); + if !(et == SDL_KEYDOWN || et == SDL_KEYUP || et == SDL_TEXTINPUT || et == SDL_TEXTEDITING) { + return; + } + // 48 bytes, not 32: a TEXTINPUT event's `text[32]` starts at +16 on the + // television (LG's `inputSource` shifts it), so it ENDS at exactly +48. At the + // old width the one event whose payload the offsets are most easily wrong + // about would have left a forensic trail that stopped just before the payload. + let mut hex = String::with_capacity(96); + for b in &ev[..48] { + hex.push_str(&format!("{b:02x}")); + } + let what = match et { + SDL_TEXTINPUT => "text", + // **The IME's PRE-EDIT, and the reason it is logged at all.** The panel's + // word prediction is a REPLACE — tapping "summer" under a typed "summ" + // means *delete what I was predicting on, then commit this* — and the app + // sees only the commit, so the field reads "summsummer" (reported from the + // couch 2026-08-15). Whether the delete half reaches us as `SDL_TEXTEDITING` + // (`text_model.delete_surrounding_text` mapped onto SDL's pre-edit) or as + // nothing at all decides whether the fix can be exact or has to be a + // heuristic — and this arm is the only way to find out, since nothing in + // the app has ever read this event. + SDL_TEXTEDITING => "edit", + _ => "key", + }; + log(&format!( + "[{}] {what} type=0x{et:x} raw={hex}", + clock::now() + )); +} + +/// One polled event. Shared by ordinary polling and ordered FIFO/replay ingestion. +unsafe fn ingest_sdl_event(app: &mut App, fr: &mut Frame) { + let shell = app.platform.shell; + ingest_sdl_event_with_window(app, fr, |win| shell.grab_surface(win)); +} + +/// The window reacquisition is a platform operation, supplied separately so the +/// recorded/live ingress boundary can be exercised without an SDL/GL context. +/// +/// Quit, the four lifecycle edges, a key edge and a text commit are decoded into a [`HostEvent`] +/// and consumed by [`ingest_host_event`]. What follows is the raw path: pointer and wheel events, +/// and the IME's pre-edit, read from the event's bytes here until their own step (W5c) moves the +/// pointer and wheel behind the decoder. +unsafe fn ingest_sdl_event_with_window(app: &mut App, fr: &mut Frame, + restore_window: impl FnOnce(*mut c_void)) { + if let Some(event) = decode_host_event(&app.ev) { + // A key or text event's raw bytes are logged before anything acts on them. A controlled + // replay owns logical ingress and logs nothing for a real event. + if matches!(event, HostEvent::Key(_) | HostEvent::Text(_)) && !controlled_replay(app) { + log_raw_input_event(&app.ev); } - } else if et == SDL_MOUSEMOTION { + ingest_host_event(app, fr, event, restore_window); + return; + } + let et = rd_u32(&app.ev, 0); + // A key or pointer event is the activity that keeps a release-health session open + // (`telemetry::session`; consent-gated inside, a no-op while crash reports are off). + if is_input_event(et) { plx_telemetry::telemetry::session::input(); } + if controlled_replay(app) { + // The tape owns logical ingress; real SDL events must not be counted a second time. + return; + } + // Attribute only the input repaint to its owner; other events remain page damage. + if is_input_event(et) { app.note_input_damage(); } + else { app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); } + // The raw bytes of what is left on this path: the IME's pre-edit, which nothing else reads. + log_raw_input_event(&app.ev); + if et == SDL_MOUSEMOTION { app.last_input = clock::now(); app.ptr.last_motion = app.last_input; app.ptr.note_cursor_motion(); @@ -1965,27 +2029,6 @@ unsafe fn ingest_sdl_event_with_window(app: &mut App, fr: &mut Frame, // `Route::Search` is deliberately absent here: `search_owns_input()` above // already took every wheel tick on this route and returned. } - } else if et == SDL_TEXTINPUT { - // The television's own keyboard committing text. Gated on `bridge::text_owner`, - // and the gate is deliberate. Search on top takes every commit whatever our own - // record of the panel says: a panel the OS raised or kept behind our back must - // not eat REAL typing, so Search adopts it (`textinput::adopt`, via - // `Bridge::adopt_system_keyboard`), and only Search's commit carries that - // adoption edge (`bridge::text_panel_edge`). Any other page takes text only while - // `Dispatcher::system_keyboard_up()` says it raised the keyboard. Everything - // else goes to `textinput::on_event`, which queues without checking and which - // nothing drains, so for a non-Search field our own flag decides: text that - // arrives while it is down is not delivered. The leaks of that queue are closed - // downstream, where they can be closed completely: `textinput::start` clears - // it, so nothing typed before a field opened can arrive in it, and - // `MAX_PENDING` bounds a queue nobody drains. - if super::bridge::text_owner(&app.pages) { - let text = crate::textinput::decode(&app.ev); - let panel = super::bridge::text_panel_edge(&app.pages, crate::textinput::available()); - ingest_text(app, &text, panel, plx_machine::machine::Source::Sdl); - } else { - crate::textinput::on_event(&app.ev); - } } } @@ -4572,6 +4615,9 @@ pub(in crate::app) mod lifecycle_regression_tests { HostEvent::Lifecycle(Lifecycle::DidBackground) => 0x104, HostEvent::Lifecycle(Lifecycle::WillForeground) => 0x105, HostEvent::Lifecycle(Lifecycle::DidForeground) => 0x106, + HostEvent::Key(_) | HostEvent::Text(_) => { + panic!("a key or a text commit arrives as its own bytes (`encode_key`, `encode_event`), not as a type code") + } } } @@ -4810,6 +4856,438 @@ pub(in crate::app) mod lifecycle_regression_tests { assert_eq!(tapes[0], tapes[1], "the tape is byte-equal whichever way an edge arrives"); } + // ---- W5b: a key edge as a `HostEvent` ------------------------------------------------------- + // + // As above, each key is delivered two ways: as the SDL bytes the drain decodes, and as the + // `HostEvent::Key` a platform with no SDL key sends. The hosted press carries the ACTION alone + // (`raw: None`), so the loop expands it with `raw_pair`, the pair a remote's press would be. + + /// One edge of `action`, either way. + fn deliver_key(app: &mut App, fr: &mut Frame, hosted: bool, action: plx_ui::consts::Action, + edge: plx_machine::machine::Edge) { + use plx_machine::machine::Edge; + if hosted { + let press = KeyPress::new(Some(action), edge, None).expect("an action names a press"); + unsafe { ingest_host_event(app, fr, HostEvent::Key(press), |_| {}) }; + } else { + let (sym, wcode) = plx_ui::consts::raw_pair(action); + app.ev = match edge { + Edge::Down => encode_key(sym, wcode, true), + Edge::Repeat => encode_key_repeat(sym, wcode), + Edge::Up => encode_key(sym, wcode, false), + }; + event(app, fr, if edge == Edge::Up { SDL_KEYUP } else { SDL_KEYDOWN }); + } + } + + /// What a key edge left for the next frame (the owned inputs, as the tape would carry them) and + /// the physically-down slot a repeat is judged against. + fn key_aftermath(app: &mut App) -> (Vec, u32) { + let inputs = app.inputs.drain(..) + .map(|e| super::super::bootstrap::effects::input(&e).unwrap()) + .collect(); + (inputs, app.down_sym) + } + + /// **A hosted key is the key an SDL event is.** On a page that owns the keys (Settings), every + /// edge of a spread of actions (a direction, OK, BACK, PAUSE, the pager, the edit key, a digit and + /// REWIND) leaves the same inputs and the same down slot whichever way it arrives. + #[test] + fn a_host_key_takes_the_path_an_sdl_key_takes() { + use plx_machine::machine::Edge; + use plx_ui::consts::Action; + let _serial = plx_base::testlock::serial(); + let actions = [Action::Down, Action::Ok, Action::Back, Action::Pause, Action::PageDown, + Action::Backspace, Action::Digit(5), Action::Rewind]; + let mut seen = Vec::new(); + for hosted in [false, true] { + let mut app = app(); + super::super::bridge::show_page(&mut app.pages, + AppArg::Settings(plx_screens::family::SettingsPage::Root)); + frame(&mut app, 0); + let mut fr = Frame::begin(&app.player.session, app.runtime.metadata_view()); + let mut steps = Vec::new(); + for action in actions { + for edge in [Edge::Down, Edge::Repeat, Edge::Up] { + clock::set_replay(100); + deliver_key(&mut app, &mut fr, hosted, action, edge); + steps.push(key_aftermath(&mut app)); + } + } + seen.push(steps); + } + assert!(seen[0].iter().any(|(inputs, _)| !inputs.is_empty()), "premise: the page takes the keys"); + assert_eq!(seen[0], seen[1], "a host's key and an SDL key leave the same inputs and the same down slot"); + } + + /// **A press with no action flows on as the pair it was.** An unsupported key (the colour + /// buttons: `docs/remote-keys.md` section 9's 504) has no `Action`; sent raw-only by a host it + /// reaches the loop exactly as the SDL bytes do, and the physically-down slot keeps its sym. + #[test] + fn an_unbound_host_key_flows_on_as_the_raw_pair_it_was() { + use plx_machine::machine::Edge; + let _serial = plx_base::testlock::serial(); + let mut seen = Vec::new(); + for hosted in [false, true] { + let mut app = app(); + super::super::bridge::show_page(&mut app.pages, + AppArg::Settings(plx_screens::family::SettingsPage::Root)); + frame(&mut app, 0); + let mut fr = Frame::begin(&app.player.session, app.runtime.metadata_view()); + let mut steps = Vec::new(); + for (edge, down) in [(Edge::Down, true), (Edge::Repeat, true), (Edge::Up, false)] { + clock::set_replay(100); + if hosted { + let press = KeyPress::new(None, edge, Some(RawKey { sym: 0, wcode: 504 })).unwrap(); + unsafe { ingest_host_event(&mut app, &mut fr, HostEvent::Key(press), |_| {}) }; + } else { + app.ev = if edge == Edge::Repeat { encode_key_repeat(0, 504) } + else { encode_key(0, 504, down) }; + event(&mut app, &mut fr, if down { SDL_KEYDOWN } else { SDL_KEYUP }); + } + steps.push(key_aftermath(&mut app)); + } + seen.push(steps); + } + assert_eq!(seen[0], seen[1], "a raw-only host key and its SDL bytes leave the same loop"); + } + + /// **The tape is the same whichever way a key arrives**, and it is today's: one `key` row per + /// edge carrying the raw pair, `down` and `repeat`, as `enc_key` always wrote them. + #[test] + fn a_host_key_is_recorded_as_the_pair_it_arrives_as() { + use super::super::{bootstrap::Initial, recorder::{Recplay, state_fp}}; + use plx_machine::machine::Edge; + use plx_ui::consts::Action; + use plx_ui::rec::{Header, MemSink, Recording}; + let _serial = plx_base::testlock::serial(); + let initial = Initial::synthetic_home(1, 32517, None).unwrap(); + let mut tapes = Vec::new(); + for hosted in [false, true] { + let mut app = app(); + let mut fr = Frame::begin(&app.player.session, app.runtime.metadata_view()); + let sink = MemSink::default(); + let segments = sink.segments.clone(); + let manifest = Header::new(state_fp(), &initial).to_json().to_string(); + app.rec = Recplay::recording_with_sink(&initial, Box::new(sink)).unwrap(); + app.rec.tick(initial.clock_start, 0.0); + for (action, edge) in [(Action::Down, Edge::Down), (Action::Down, Edge::Repeat), (Action::Down, Edge::Up), + (Action::Ok, Edge::Down), (Action::Ok, Edge::Up), (Action::Pause, Edge::Down), (Action::Pause, Edge::Up)] { + deliver_key(&mut app, &mut fr, hosted, action, edge); + } + app.rec.end_frame(&|| 7); + std::mem::replace(&mut app.rec, Recplay::Off).finish(plx_machine::landgate::fixture_gate()); + let recording = Recording::parse(&manifest, + &segments.borrow().iter().map(Vec::as_slice).collect::>(), state_fp()).unwrap(); + tapes.push(recording.frames.iter().flat_map(|frame| frame.inputs.clone()).collect::>()); + } + let rows: Vec<(String, u64, u64, bool, bool)> = tapes[0].iter() + .map(|r| (r["kind"].as_str().unwrap().to_owned(), r["sym"].as_u64().unwrap(), r["wcode"].as_u64().unwrap(), + r["down"].as_bool().unwrap(), r["repeat"].as_bool().unwrap())) + .collect(); + let key = |sym, wcode, down, repeat| ("key".to_owned(), sym, wcode, down, repeat); + assert_eq!(rows, [ + key(0x4000_0051, 0, true, false), key(0x4000_0051, 0, true, true), key(0x4000_0051, 0, false, false), + key(13, 0, true, false), key(13, 0, false, false), + key(0, 72, true, false), key(0, 72, false, false), + ], "one `key` row per edge, in `enc_key`'s shape"); + assert_eq!(tapes[0], tapes[1], "the tape is byte-equal whichever way a key arrives"); + } + + // ---- W5b guard: a NATIVE key reaches the real consumer's effect ------------------------------ + // + // The tests above show that a hosted key and an SDL key agree. They cannot show that either is + // RIGHT: both doors carry one pair, whatever `raw_pair` says. These feed the pair a television + // or the simulator really sends, written out here as LITERALS (never `raw_pair`, never an + // `Action`), through the real decoder and loop, and grade what the real consumer did with it. + // Each case is a pair of tests, one per door (`native_key_effect_*`, so `T=native_key_effect` + // runs them all), and which of them a break of the mapping turns red depends on where it is: + // * the NATIVE door's effect reads the pair the consumers read today. A wrong `classify` / + // `page_dir` reading turns it red, and, because `action_of` is built on them, the hosted door + // and the decode table below with it. A wrong `raw_pair` or `action_of` leaves it GREEN. + // * the HOSTED door names the action and not the pair, so it goes through `raw_pair` and + // `KeyPress::new`'s round trip. A wrong `raw_pair` alone turns ONLY this door red, as the + // constructor's refusal (the `.expect` panics). A wrong `raw_pair` and `action_of` that agree + // with each other pass the round trip and turn it red as the effect of another key. + // * the DECODED action (`events::key_event_tests`' table of native pairs) is what a wrong + // `action_of` turns red, with `input.rs`'s decode literals and the hosted door's round + // trip. No production reader of the loop reads the action before W5d (the screens move onto + // it there), so no native effect test can see that one yet. + // The hostsim build feeds the STOCK SDL byte layout; LG's fork layout is graded in the default-feature + // run (`events::key_event_tests::the_key_layout_is_pinned_byte_for_byte`). + + /// How a key is delivered to a guard test: as the native SDL bytes (the pair, as literals) or as + /// the hosted press that names only the action. + enum Door { + Native(u32, u32), + Hosted(plx_ui::consts::Action), + } + + impl Door { + /// The door of a table row: the native pair, or (`hosted`) the action alone. + fn of(hosted: bool, sym: u32, wcode: u32, action: plx_ui::consts::Action) -> Door { + if hosted { Door::Hosted(action) } else { Door::Native(sym, wcode) } + } + } + + /// One edge of `door`'s key, through the real ingress. + fn door_edge(app: &mut App, fr: &mut Frame, door: &Door, down: bool) { + use plx_machine::machine::Edge; + match door { + Door::Native(sym, wcode) => { + app.ev = encode_key(*sym, *wcode, down); + event(app, fr, if down { SDL_KEYDOWN } else { SDL_KEYUP }); + } + Door::Hosted(action) => { + let edge = if down { Edge::Down } else { Edge::Up }; + let press = KeyPress::new(Some(*action), edge, None).expect("an action names a press"); + unsafe { ingest_host_event(app, fr, HostEvent::Key(press), |_| {}) }; + } + } + } + + /// The frame that delivers what the key edges left to the tree. + fn deliver_inputs(app: &mut App, ms: u32) { + let inputs = std::mem::take(&mut app.inputs); + super::super::bridge::app_frame(app, plx_machine::machine::Tick { ms, dt_us: 16_000 }, inputs); + } + + /// The bare player page, mounted with no engine behind it, and the frame the loop would hold. The + /// loop's clock is pinned, as the other key tests pin it. + fn mounted_player() -> (App, Frame) { + clock::set_replay(100); + let mut app = app(); + super::super::bridge::show_page(&mut app.pages, AppArg::Player); + frame(&mut app, 0); + let fr = Frame::begin(&app.player.session, app.runtime.metadata_view()); + (app, fr) + } + + /// What the player page asked the performer for, less the HUD's own housekeeping. + fn asked_of_the_player(app: &mut App) -> Vec { + app.runtime.bridge(&mut app.bridge).take_observed_player_commands().into_iter() + .filter(|req| !matches!(req, plx_screens::registry::PlayerReq::ExtendHud(_))).collect() + } + + /// A tap of `door`'s key on a mounted player, then the frames the page needs to answer it. + fn tap_the_player(app: &mut App, fr: &mut Frame, door: &Door) { + for (down, ms) in [(true, 120), (false, 136)] { + door_edge(app, fr, door, down); + deliver_inputs(app, ms); + } + for ms in [152, 168, 184, 200] { + frame(app, ms); + } + } + + /// A mounted player with the film at 60 s of 100 s and the transport up, the frame the loop would + /// hold, and the seek mailboxes the page's seeks write (restored when the last of these drops). + fn mounted_player_at_60s() -> (App, Frame, SeekGlobals) { + let (mut app, fr) = mounted_player(); + let seek = SeekGlobals::set(&mut app, 60_000_000_000, 100_000_000_000); + super::publish_frame(&mut app.runtime.bridge(&mut app.bridge), &app.player.session, true, + app.adapters.player.backend_viewer_paused()); + pin_headless_hud(&mut app, 100, None); + frame(&mut app, 100); + (app, fr, seek) + } + + /// **Play is not Pause, and neither is a toggle.** The player reads the key through + /// `classify_input`, so each transport key must reach it as the request it has always made: PLAY + /// (wcode 450) asks to play, PAUSE (wcode 72) asks to pause, PLAYPAUSE (261) asks for the toggle, + /// and their alternate spellings (415, 19 and 402, in either field) ask the same. + fn check_transport(hosted: bool) { + use plx_screens::registry::PlayerReq; + use plx_ui::consts::Action; + let _serial = plx_base::testlock::serial(); + let (pause, play, toggle) = (PlayerReq::Transport(Some(false)), PlayerReq::Transport(Some(true)), PlayerReq::Transport(None)); + for (sym, wcode, action, want, what) in [ + (0, 72, Action::Pause, &pause, "PAUSE"), + (0, 450, Action::Play, &play, "PLAY"), + (0, 261, Action::PlayPause, &toggle, "PLAYPAUSE"), + (415, 0, Action::Pause, &pause, "PAUSE, the alternate in the sym"), + (0, 415, Action::Pause, &pause, "PAUSE, the alternate in the wcode"), + (19, 0, Action::Play, &play, "PLAY, the first alternate in the sym"), + (0, 402, Action::Play, &play, "PLAY, the second alternate in the wcode"), + ] { + let (mut app, mut fr) = mounted_player(); + tap_the_player(&mut app, &mut fr, &Door::of(hosted, sym, wcode, action)); + assert_eq!(asked_of_the_player(&mut app), [want.clone()], "{what}: ({sym}, {wcode}), hosted={hosted}"); + } + } + + #[test] + fn native_key_effect_transport_native_keys_ask_what_they_mean() { + check_transport(false); + } + + #[test] + fn native_key_effect_transport_hosted_actions_ask_what_their_native_key_asks() { + check_transport(true); + } + + /// **REWIND seeks back, and a plain LEFT does not.** The player reads REWIND (wcode 452) as + /// `Left { alt: true }`, the transport's seek, and the D-pad's LEFT as `Left { alt: false }`, which + /// only moves a pending target: with the transport up at 60 s of 100 s a REWIND tap asks the + /// performer to seek to 50 s, and a plain LEFT asks nothing and leaves 50 s as the target for OK + /// to take. FAST-FORWARD (451) and RIGHT are the same pair the other way. + fn check_rewind(hosted: bool) { + use plx_screens::registry::PlayerReq; + use plx_ui::consts::Action; + let _serial = plx_base::testlock::serial(); + const S: i64 = 1_000_000_000; + for (sym, wcode, action, asked, target, what) in [ + (0, 452, Action::Rewind, vec![PlayerReq::CommitSeek(50 * S)], -1, "REWIND"), + (0, 451, Action::FastForward, vec![PlayerReq::CommitSeek(70 * S)], -1, "FAST-FORWARD"), + (0x4000_0050, 0, Action::Left, vec![], 50 * S, "LEFT"), + (0x4000_004f, 0, Action::Right, vec![], 70 * S, "RIGHT"), + ] { + let (mut app, mut fr, _seek) = mounted_player_at_60s(); + tap_the_player(&mut app, &mut fr, &Door::of(hosted, sym, wcode, action)); + let reached = super::super::bridge::player(&app.pages).expect("the player page is mounted").scrub.ns; + assert_eq!(reached, target, "{what}: the pending target, hosted={hosted}"); + assert_eq!(asked_of_the_player(&mut app), asked, "{what}: what the player asked, hosted={hosted}"); + } + } + + #[test] + fn native_key_effect_rewind_native_keys_seek_back_where_left_only_moves_a_target() { + check_rewind(false); + } + + #[test] + fn native_key_effect_rewind_hosted_actions_do_what_their_native_key_does() { + check_rewind(true); + } + + /// The Library grid's focused cell `(row, col)`, read off the page on top. + fn grid_cell(app: &App) -> Option<(usize, usize)> { + app.pages.nav.top_page()?.inst.as_ref()?.screen.as_any()? + .downcast_ref::()?.grid_position(app.pages.focus()) + } + + /// **The pager pages the grid the way its key says.** PAGE DOWN (sym `0x4000_004e`) and the channel + /// rocker's CH- (wcode 301) move the focus two rows down the Library grid and PAGE UP (sym + /// `0x4000_004b`) and CH+ (300) two rows up, in the same column, on a grid of 120 items. The + /// walk goes down past where it started and back, so each key is graded by the cell it leaves: + /// rows 2, 4, 6 and then 4, 2, 0. This is the real loop on the real Library, with the focus + /// seated on the first cell by the page's own command. + fn check_paging(hosted: bool) { + use plx_machine::machine::{Delivery, Fx, MachineId}; + use plx_screens::registry::{AppMsg, LibraryCmd}; + use plx_ui::consts::Action; + let _serial = plx_base::testlock::serial(); + let Some(mut rig) = Rig::new() else { + eprintln!("SKIPPED the paging guard: lifecycle fixture worker thread could not be spawned"); + return; + }; + let mut t = product_transition(&mut rig.app); + settle(&mut rig.app, &mut t); + library_with_grid(&mut rig, &mut t, 120); + let page = rig.app.pages.nav.top_page().unwrap(); + let instance = rig.app.pages.nav.instance_of(page.id).unwrap(); + rig.app.pages.emit(MachineId::Nav, Fx::Deliver(MachineId::Instance(instance), Delivery::Screen( + plx_ui::screen::ScreenEvent::App(AppMsg::Library(LibraryCmd::FocusGrid { row: 0, col: 0 }))))); + for _ in 0..40 { step(&mut rig.app, &mut t, vec![]); } + assert_eq!(grid_cell(&rig.app), Some((0, 0)), "premise: the first cell is focused"); + let mut fr = Frame::begin(&rig.app.player.session, rig.app.runtime.metadata_view()); + let (page_down, page_up) = ((0x4000_004e, 0), (0x4000_004b, 0)); + for (what, (sym, wcode), action, row) in [ + ("PAGE DOWN", page_down, Action::PageDown, 2), + ("PAGE DOWN", page_down, Action::PageDown, 4), + ("CH-", (0, 301), Action::PageDown, 6), + ("PAGE UP", page_up, Action::PageUp, 4), + ("CH+", (0, 300), Action::PageUp, 2), + ("PAGE UP", page_up, Action::PageUp, 0), + ] { + for down in [true, false] { + door_edge(&mut rig.app, &mut fr, &Door::of(hosted, sym, wcode, action), down); + step(&mut rig.app, &mut t, vec![]); + } + for _ in 0..30 { step(&mut rig.app, &mut t, vec![]); } + assert_eq!(grid_cell(&rig.app), Some((row, 0)), "{what}: ({sym}, {wcode}) leaves row {row}, hosted={hosted}"); + } + } + + #[test] + fn native_key_effect_paging_native_keys_page_the_grid_the_way_each_key_says() { + check_paging(false); + } + + #[test] + fn native_key_effect_paging_hosted_actions_page_the_grid_the_way_their_native_key_does() { + check_paging(true); + } + + /// **A pointer hide is a notification, however it arrives, and an unbound key still flows on.** + /// LG's pointer auto-hide is the pair (sym 0, wcode `0x1e4`). As the SDL bytes, as the hosted + /// press that carries that pair and no stated action (a raw-only press: the action is the one + /// `action_of` reads out of it), or as the hosted action alone, it stops the pointer's glide and + /// does nothing else: no input reaches the tree and no physically-down key is booked. The + /// unbound colour button (wcode 504) is the control on every count: an input for the tree, its + /// sym booked, the pointer left alone. + #[test] + fn native_key_effect_a_pointer_hide_is_a_notification_and_an_unbound_key_flows_on() { + use plx_machine::machine::Edge; + use plx_ui::consts::Action; + let _serial = plx_base::testlock::serial(); + clock::set_replay(100); + let booted = || { + let mut app = app(); + super::super::bridge::show_page(&mut app.pages, AppArg::Settings(plx_screens::family::SettingsPage::Root)); + frame(&mut app, 0); + let fr = Frame::begin(&app.player.session, app.runtime.metadata_view()); + app.ptr.edge.moved(900.0, 40.0, false); + app.down_sym = 77; + (app, fr) + }; + for door in ["the SDL bytes", "a raw-only hosted press", "a hosted action alone"] { + for down in [true, false] { + let (mut app, mut fr) = booted(); + let edge = if down { Edge::Down } else { Edge::Up }; + match door { + "the SDL bytes" => door_edge(&mut app, &mut fr, &Door::Native(0, 0x1e4), down), + "a raw-only hosted press" => { + let press = KeyPress::new(None, edge, Some(RawKey { sym: 0, wcode: 0x1e4 })) + .expect("a raw pair names a press"); + unsafe { ingest_host_event(&mut app, &mut fr, HostEvent::Key(press), |_| {}) }; + } + _ => door_edge(&mut app, &mut fr, &Door::Hosted(Action::PointerHidden), down), + } + assert_eq!(app.ptr.edge.at(), None, "{door} (down={down}): the glide's pointer is gone"); + assert!(app.inputs.is_empty(), "{door} (down={down}): no input reaches the tree"); + assert_eq!(app.down_sym, 77, "{door} (down={down}): no physically-down key is booked"); + } + } + let (mut app, mut fr) = booted(); + door_edge(&mut app, &mut fr, &Door::Native(0, 504), true); + assert!(app.ptr.edge.at().is_some(), "an unbound key leaves the pointer alone"); + assert_eq!(app.inputs.len(), 1, "an unbound key still flows on to the tree"); + assert!(matches!(app.inputs[0].kind, + plx_machine::machine::InputKind::Key { key: plx_machine::machine::Key::Other, sym: 0, wcode: 504, edge: Edge::Down, .. }), + "…as the raw pair it was"); + assert_eq!(app.down_sym, 0, "…and its sym is the physically-down key"); + } + + /// **An unbound native key leaves a dismissed transport dismissed, and a bound one raises it.** On + /// the mounted player (no engine) with the transport hidden by hand (the UP-hide's dismissal): the + /// colour button (wcode 504) is no key the app acted on, so it asks nothing and un-dismisses + /// nothing, and a D-pad DOWN, the positive control in the same rig, un-dismisses it. + #[test] + fn native_key_effect_an_unbound_key_does_not_wake_the_transport() { + let _serial = plx_base::testlock::serial(); + let dismissed = |app: &App| super::super::bridge::player(&app.pages) + .expect("the player page is mounted").hud.dismissed; + for (sym, wcode, wakes, what) in [(0, 504, false, "the colour button"), (0x4000_0051, 0, true, "DOWN")] { + let (mut app, mut fr) = mounted_player(); + super::super::bridge::player_mut(&mut app.pages).expect("the player page is mounted").hud.dismissed = true; + assert!(dismissed(&app), "premise: the transport was hidden by hand"); + tap_the_player(&mut app, &mut fr, &Door::Native(sym, wcode)); + assert_eq!(dismissed(&app), !wakes, "{what}: the transport is {}", if wakes { "raised" } else { "left down" }); + assert!(asked_of_the_player(&mut app).is_empty(), "{what} asks the performer for nothing"); + } + } + #[cfg(feature = "devtriggers")] #[test] #[should_panic(expected = "main-thread block: dev hang probe")] @@ -5246,9 +5724,11 @@ pub(in crate::app) mod lifecycle_regression_tests { fn drop(&mut self) { unsafe { SDL_Quit(); } } } let _events = Events; - for fifo in [true, false] { + // Three doors: the FIFO's token, the television's keyboard as the SDL bytes the drain decodes, + // and the same commit as the `HostEvent::Text` a platform with no SDL hands the loop (W5b). + for (fifo, hosted) in [(true, false), (false, false), (false, true)] { DIALLED.lock().unwrap().clear(); - let dir = HudDir::new(&fifo.to_string()); + let dir = HudDir::new(&format!("{fifo}-{hosted}")); let (mut app, mut fr, mut now) = hud_address_field_up(&dir.0, record); // Type it as each door delivers it: the FIFO in one token, the television's keyboard one key, one commit. @@ -5259,13 +5739,15 @@ pub(in crate::app) mod lifecycle_regression_tests { for chunk in commits { if fifo { assert!(unsafe { ingress_token(&mut app, &mut fr, &format!("txt:{chunk}")) }); + } else if hosted { + unsafe { ingest_host_event(&mut app, &mut fr, HostEvent::Text(chunk.to_owned()), |_| {}) }; } else { app.ev = crate::textinput::encode_event(chunk); event(&mut app, &mut fr, SDL_TEXTINPUT); } assert!(matches!(app.inputs.last().map(|input| &input.kind), Some(InputKind::Text(TextEdit::Commit(text))) if &**text == chunk), - "the text reaches the app's input queue (fifo={fifo}), not textinput's"); + "the text reaches the app's input queue (fifo={fifo}, hosted={hosted}), not textinput's"); let inputs = std::mem::take(&mut app.inputs); now += 16; super::super::bridge::app_frame(&mut app, Tick { ms: now, dt_us: 16_000 }, inputs); diff --git a/rust-modules/src/app/search_owned_tests.rs b/rust-modules/src/app/search_owned_tests.rs index 590b724118..ca27952723 100644 --- a/rust-modules/src/app/search_owned_tests.rs +++ b/rust-modules/src/app/search_owned_tests.rs @@ -475,6 +475,50 @@ fn owned_search_opens_edits_and_closes_in_one_input_batch_in_order() { assert_eq!(rig.retained.keyboard_calls, [true, false]); } +/// **The television keyboard's edit keys edit the field, as they always did.** The native pairs +/// (written out as literals: Backspace is sym 8 with scancode 42, Clear is `SDLK_CLEAR` with scancode +/// 156, and the simulator's desktop Backspace is sym 8 beside BACK's wcode 482) go through the real +/// decoder, and the input the loop hands the tree for each reaches the real Search screen, whose +/// store is what the viewer's query is. The simulator's Backspace decodes as `Back` and still +/// deletes: the screen reads the raw `sym` for the edit before it reads the key. +/// The narrowest rig that reaches Search's key arm is this Dispatcher tier: the loop's `app()` cannot +/// raise Search's keyboard on a host (`textinput::available()` is false there). +#[test] +fn native_key_effect_search_edit_keys_edit_the_field() { + use plx_ui::consts::Action; + let _serial = plx_base::testlock::serial(); + let session = plx_plex::plex::session::TempSession::new("native-key-effect-search"); + session.watching("synthetic-native-key-effect"); + plx_plex::plex::reset_servers_for_test(); + let mut d = Dispatcher::::new(); + let mut harness = crate::app::runtime_owners::Harness::new(|| 0); + let mut rig = harness.bridge(); + frame(&mut d, &mut rig, AppArg::Search, tick(0), vec![]); + let text = |s: &str, at| InputEvent { at, source: Source::Script, + kind: InputKind::Text(plx_machine::machine::TextEdit::Commit(s.into())) }; + let mut events = script_key(Key::Ok, tick(1)); + events.push(text("abcd", tick(1))); + frame(&mut d, &mut rig, AppArg::Search, tick(1), events); + assert_eq!(rig.stores.search.query(), "abcd", "premise: the field is editing and holds the text"); + for (n, (sym, wcode, action, query)) in [ + (8, 42, Action::Backspace, "abc"), + (8, 482, Action::Back, "ab"), // the simulator's Backspace: BACK's wcode beside the edit key's sym + (0x4000_009c, 156, Action::ClearAll, ""), + ].into_iter().enumerate() { + let (press, down) = crate::app::events::native_key_input(sym, wcode, true, tick(2 + n as u32)); + let (_, up) = crate::app::events::native_key_input(sym, wcode, false, tick(2 + n as u32)); + assert_eq!(press.action(), Some(action), "({sym}, {wcode}) decodes to its action"); + frame(&mut d, &mut rig, AppArg::Search, tick(2 + n as u32), vec![down, up]); + assert_eq!(rig.stores.search.query(), query, "native ({sym}, {wcode}) edits the field"); + assert!(d.input.keyboard, "an edit key does not close the keyboard"); + } + // An edit key with nothing to edit changes nothing and still keeps the field. + let (_, down) = crate::app::events::native_key_input(8, 42, true, tick(9)); + frame(&mut d, &mut rig, AppArg::Search, tick(9), vec![down]); + assert_eq!(rig.stores.search.query(), ""); + assert!(d.input.keyboard); +} + #[test] fn an_old_search_keyboard_request_cannot_close_the_new_instances_keyboard() { let _serial = plx_base::testlock::serial(); diff --git a/rust-modules/src/textinput.rs b/rust-modules/src/textinput.rs index 8f521ff47a..20b4f58fff 100644 --- a/rust-modules/src/textinput.rs +++ b/rust-modules/src/textinput.rs @@ -153,11 +153,11 @@ thread_local! { /// Nothing drains it in production: while a field owns text input (`bridge::text_owner`), typed text (the /// television's keyboard and the `txt:` remote token alike) goes through `app/run.rs`'s /// `ingest_text` into the app's input queue (`app.inputs`) and never reaches this one. - /// [`on_event`] fills it only on every other route, where it is a bounded buffer + /// [`queue`] fills it only on every other route, where it is a bounded buffer /// ([`MAX_PENDING`]) that [`start`] clears, and [`drain`] is read by the tests and nothing else. /// - /// Main-thread-only by construction: [`on_event`] is called from the SDL event loop in - /// `app/run.rs` and from the `txt:` remote token in `app/events.rs`, both on the frame thread. A + /// Main-thread-only by construction: [`queue`] is called from the event loop in + /// `app/run.rs` and (through [`on_event`]) from the `txt:` remote token in `app/events.rs`, both on the frame thread. A /// `thread_local!` for that reason and not a `static mut`: /// the queue owns `String`s that `on_event` trims and `start`/`drain` clear, so one process-wide /// queue lets two threads free each other's commits, which is how `cargo test`'s parallel threads @@ -359,9 +359,16 @@ pub(crate) fn decode(ev: &[u8]) -> String { decode_text_at(ev, TEXT_OFF) } -/// One `SDL_TEXTINPUT` event, straight off the wire. Called from `app.rs`'s event ladder. +/// One `SDL_TEXTINPUT` event, straight off the wire: [`decode`], then [`queue`]. Called by the +/// `txt:` remote token (`app/events.rs`), which has the bytes [`encode_event`] built. The event +/// loop gets its text already decoded (`HostEvent::Text`) and calls [`queue`] itself. pub(crate) fn on_event(ev: &[u8]) { - let s = decode(ev); + queue(decode(ev)); +} + +/// One committed string, queued for [`drain`] and bounded by [`MAX_PENDING`]. The loop's route for a +/// commit no field owns (`app/run.rs`'s `ingest_text_commit`). +pub(crate) fn queue(s: String) { // An empty commit is not a commit. SDL delivers `SDL_TEXTINPUT` for the IME's own bookkeeping // as well as for text, and a caller that reads "drain returned something" as "the query moved" // would spend a round trip re-asking the server the same question. diff --git a/rust-modules/ui/src/consts.rs b/rust-modules/ui/src/consts.rs index 8fe4c73800..fe4d104344 100644 --- a/rust-modules/ui/src/consts.rs +++ b/rust-modules/ui/src/consts.rs @@ -461,19 +461,18 @@ pub fn page_dir(sym: c_uint, wcode: c_uint) -> Option { /// 4. [`SDLK_BACKSPACE`] / [`SDLK_CLEAR`] — the television keyboard's own edit keys, read inside /// the owned Search screen (`screens::search`'s key match), which the classifier never sees. /// 5. An ASCII digit **in `sym`** — the who's-watching PIN keypad types straight from the remote's -/// number buttons (`ui::profiles`' own `digit_of`, which owns that behaviour). +/// number buttons ([`pin_digit`], which owns that behaviour). /// -/// **The `sym` field ONLY, and that is a deliberate divergence from `digit_of`, which also reads +/// **The `sym` field ONLY, and that is a deliberate divergence from [`pin_digit`], which also reads /// the range out of `wcode`.** `wcode` is a SCANCODE (`app.rs::decode_key`), and 48–57 there are /// not digits at all: they are `]` `\` `#` `;` `'` `` ` `` `,` `.` `/` and CapsLock. The digits' /// scancodes are 30–39 — which is exactly why 33/34 turned out to be `4` and `5` a few dozen lines -/// up. Mirroring `digit_of` would put the retired mis-reading straight back into the gate this +/// up. Mirroring [`pin_digit`] would put the retired mis-reading straight back into the gate this /// function exists to be, so this takes the spelling the evidence supports: a remote's number key /// arrives with its ASCII keycode in `sym` (evdev 5 -> scancode 33 -> `SDLK_4` = 52). The cost is -/// that `is_bound` is no longer a strict superset of `digit_of` for a wcode-only punctuation press -/// — which reaches no HUD and no armed click, because the PIN pad has neither. `profiles` is not -/// this module's to edit; `docs/remote-keys.md` §9 carries it as an open finding for the capture -/// that settles both. +/// that `is_bound` is no longer a strict superset of [`pin_digit`] for a wcode-only punctuation press +/// — which reaches no HUD and no armed click, because the PIN pad has neither. `docs/remote-keys.md` +/// §9 carries it as an open finding for the capture that settles both. /// /// **It still OVER-approximates in one place** and the alternative is worse. A digit is bound only /// on the PIN pad, so a number press on Home or during playback answers `true` here and still wakes @@ -484,13 +483,164 @@ pub fn is_bound(sym: c_uint, wcode: c_uint) -> bool { is_remote_bound(sym, wcode) || plx_os::labcfg::is_trigger_key(sym, wcode) } -/// The fixed key map, independent of a lab build's runtime diagnostics configuration. +/// The fixed key map, independent of a lab build's runtime diagnostics configuration: a press is +/// bound exactly when it has an [`Action`]. The four fixed sources [`is_bound`] lists (all but the +/// lab trigger) are the four arms [`action_of`] reads, so there is one spelling of the map and +/// this is its predicate. pub fn is_remote_bound(sym: c_uint, wcode: c_uint) -> bool { - classify(sym, wcode) != Key::Other - || page_dir(sym, wcode).is_some() - || sym == SDLK_BACKSPACE - || sym == SDLK_CLEAR - || (b'0' as c_uint..=b'9' as c_uint).contains(&sym) + action_of(sym, wcode).is_some() +} + +/// **A key press by what it MEANS, with no SDL in it** — the vocabulary a platform that has no SDL +/// key pair hands the loop (`HostEvent::Key`'s `action`), and the one the screens move onto when +/// they stop reading `(sym, wcode)` themselves. +/// +/// It is the union of the four fixed sources [`is_bound`] documents (everything but the lab +/// trigger, which `lab.json` names at run time), one variant per distinct press the app acts on: [`classify`]'s named keys (with [`Key::Left`]/[`Key::Right`]'s `alt: true` spelling +/// split out as [`Action::Rewind`]/[`Action::FastForward`], which is what it is), [`page_dir`]'s +/// two, the system keyboard's two edit keys and the number keys. [`Key::Other`] has no variant: a +/// press with no action is a press the app does not bind. +/// +/// **`Action` and the raw pair are two spellings of one fact and each has exactly one function.** +/// [`raw_pair`] is the ONLY place a `(sym, wcode)` is built from an action, and [`action_of`] the +/// only place one is read back into it; `action_of(raw_pair(a)) == Some(a)` for every action +/// (`action_tests`). So a platform that sends an action reaches the loop's raw readers through the +/// same pair a real remote would have sent. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Action { + Up, + Down, + Left, + Right, + Ok, + Back, + Play, + Pause, + PlayPause, + Stop, + /// The transport's REWIND key: [`classify`]'s `Left { alt: true }`. It is not a plain + /// [`Action::Left`], and a platform that cannot tell them apart would make the player's scrub + /// and Home's navigation one key. + Rewind, + /// [`classify`]'s `Right { alt: true }`; see [`Action::Rewind`]. + FastForward, + Exit, + /// The Library grid's pager, up: [`page_dir`]'s `-1`. + PageUp, + /// The Library grid's pager, down: [`page_dir`]'s `1`. + PageDown, + /// The system keyboard's delete key ([`SDLK_BACKSPACE`]). + Backspace, + /// The system keyboard's Clear-all button ([`SDLK_CLEAR`]). + ClearAll, + /// A number key, `0..=9`. Build one with [`Action::digit`]; a value above 9 names no key and + /// [`raw_pair`] gives it a pair no action reads back. + Digit(u8), + /// The Magic Remote reporting that its pointer auto-hid; a notification, not a press. + PointerHidden, +} + +impl Action { + /// The number key for `n`, or `None` above 9. + pub const fn digit(n: u8) -> Option { + if n <= 9 { Some(Action::Digit(n)) } else { None } + } +} + +/// The ONE `(sym, wcode)` pair the app builds for `action` when no SDL event carries one, and the +/// pair the remote FIFO's named tokens (`app/events.rs::remote_token_key`) press. +/// +/// Each is the pair a press of that key already reaches the app as in the synthetic path — the +/// pager is `sym` alone, the transport keys `wcode` alone — so a recorded tape and +/// `tests/keytable.json` read the same pairs they always did. Where a key has several real +/// spellings the one chosen is the one the FIFO has always sent ([`Action::Back`] is ESC, not +/// `wcode` 482; [`Action::Stop`] is [`WCODE_STOP`], not the LG-table 120/260), and [`action_of`] +/// still accepts every spelling. +pub const fn raw_pair(action: Action) -> (c_uint, c_uint) { + match action { + Action::Up => (SDLK_UP, 0), + Action::Down => (SDLK_DOWN, 0), + Action::Left => (SDLK_LEFT, 0), + Action::Right => (SDLK_RIGHT, 0), + Action::Ok => (SDLK_RETURN, 0), + Action::Back => (SDLK_ESCAPE, 0), + Action::Play => (0, WCODE_PLAY), + Action::Pause => (0, WCODE_PAUSE), + Action::PlayPause => (0, WCODE_PLAYPAUSE), + Action::Stop => (0, WCODE_STOP), + Action::Rewind => (0, WCODE_REWIND), + Action::FastForward => (0, WCODE_FASTFORWARD), + Action::Exit => (0, WCODE_EXIT), + Action::PageUp => (SDLK_PAGEUP, 0), + Action::PageDown => (SDLK_PAGEDOWN, 0), + // The keyboard's backspace arrives with scancode 42 beside its sym (device-measured; see + // `SDLK_BACKSPACE`), and Clear with 156; neither is read as anything else. + Action::Backspace => (SDLK_BACKSPACE, 42), + Action::ClearAll => (SDLK_CLEAR, 156), + Action::Digit(n) if n <= 9 => (b'0' as c_uint + n as c_uint, 0), + Action::Digit(_) => (0, 0), + Action::PointerHidden => (0, WCODE_POINTER_HIDDEN), + } +} + +/// The [`Action`] a raw `(sym, wcode)` press is, or `None` for a press the app does not bind +/// (an unsupported key: the colour buttons, GUIDE, INFO). The ONE decode. +/// +/// **The order is the precedence, and it is [`classify`]'s first.** [`classify`] settles every +/// named key exactly as the ladder has always read it (directions by `sym` before the transport +/// codes, `PAUSE` and `PLAY` by `wcode` alone, the alternates in either field), so a pair carrying +/// two keys' fields resolves as it always did. Only a press `classify` calls `Other` reaches the +/// rest, in this order: the Library pager ([`page_dir`]), then the system keyboard's edit keys and +/// the number keys, read from `sym`. That is why the simulator's `(8, 482)` (a desktop Backspace +/// with the BACK `wcode`) is [`Action::Back`] here and Backspace to a screen that reads `sym` for +/// itself: the loop keeps the raw pair beside the action, so both readings survive. +/// +/// **A number key is read from `sym` ONLY**, as [`is_remote_bound`] has always read it, because +/// `wcode` is a SCANCODE and 48–57 there are punctuation, not digits (`docs/remote-keys.md` §9). +/// [`pin_digit`], which the PIN keypad still types from, ALSO reads `wcode`; the two differ for a +/// press that carries a digit-range scancode and no digit `sym`. That press keeps typing a digit +/// while the PIN keypad reads the raw pair, and W5d, which moves the keypad onto [`Action::Digit`], +/// decides whether it still should. +pub fn action_of(sym: c_uint, wcode: c_uint) -> Option { + match classify(sym, wcode) { + Key::Up => return Some(Action::Up), + Key::Down => return Some(Action::Down), + Key::Left { alt: false } => return Some(Action::Left), + Key::Left { alt: true } => return Some(Action::Rewind), + Key::Right { alt: false } => return Some(Action::Right), + Key::Right { alt: true } => return Some(Action::FastForward), + Key::Ok => return Some(Action::Ok), + Key::Back => return Some(Action::Back), + Key::Play => return Some(Action::Play), + Key::Pause => return Some(Action::Pause), + Key::PlayPause => return Some(Action::PlayPause), + Key::Stop => return Some(Action::Stop), + Key::Exit => return Some(Action::Exit), + Key::PointerHidden => return Some(Action::PointerHidden), + Key::Other => {} + } + match page_dir(sym, wcode) { + Some(dir) if dir < 0 => return Some(Action::PageUp), + Some(_) => return Some(Action::PageDown), + None => {} + } + match sym { + SDLK_BACKSPACE => Some(Action::Backspace), + SDLK_CLEAR => Some(Action::ClearAll), + s if (b'0' as c_uint..=b'9' as c_uint).contains(&s) => Some(Action::Digit((s - b'0' as c_uint) as u8)), + _ => None, + } +} + +/// Remote number key → keypad digit, moved unchanged from `screens::profiles` (it was `digit_of`): SDL gives +/// a printable key its ASCII sym and the webOS remote's number buttons carry the same 48-57 +/// ('0'-'9') range in `wcode`. The PIN keypad types from it, and it reads BOTH fields, which +/// [`action_of`]'s number-key arm deliberately does not (see there). +pub fn pin_digit(sym: u32, wcode: u32) -> Option { + [sym, wcode] + .into_iter() + .find(|v| (48..=57).contains(v)) + .map(|v| v as u8) } // spring stiffnesses (from ui_home.c, redistributed 1:1 to their owning views) @@ -769,3 +919,247 @@ mod tests { } } } + +/// **The `Action` map, graded** (W5b): `action_of` is the one decode of a raw pair, `raw_pair` the one +/// builder, and `is_remote_bound` is `action_of(..).is_some()`. The pairs below are spelled as +/// literals where the key has LG-table or alternate spellings, so the table is not read back from +/// the functions it grades. +#[cfg(test)] +mod action_tests { + use super::*; + + const ALL: [Action; 28] = [ + Action::Up, + Action::Down, + Action::Left, + Action::Right, + Action::Ok, + Action::Back, + Action::Play, + Action::Pause, + Action::PlayPause, + Action::Stop, + Action::Rewind, + Action::FastForward, + Action::Exit, + Action::PageUp, + Action::PageDown, + Action::Backspace, + Action::ClearAll, + Action::PointerHidden, + Action::Digit(0), + Action::Digit(1), + Action::Digit(2), + Action::Digit(3), + Action::Digit(4), + Action::Digit(5), + Action::Digit(6), + Action::Digit(7), + Action::Digit(8), + Action::Digit(9), + ]; + + /// Every pair a press can carry, as far as the app has ever seen or built one: each named + /// sym and code, the FIFO's pairs, the simulator's stand-ins, every ASCII sym, and every wcode + /// to 600 (past the LG-private 450-505 block). + fn grid() -> impl Iterator { + let named = [ + SDLK_UP, SDLK_DOWN, SDLK_LEFT, SDLK_RIGHT, SDLK_RETURN, SDLK_KP_ENTER, SDLK_SELECT, + SDLK_ESCAPE, SDLK_PAGEUP, SDLK_PAGEDOWN, SDLK_BACKSPACE, SDLK_CLEAR, + WCODE_PAUSE, WCODE_STOP, WCODE_PAUSE_ALT, WCODE_PLAY_ALT_A, WCODE_PLAY_ALT_B, + WCODE_POINTER_HIDDEN, WCODE_BACK, WCODE_PLAY, WCODE_REWIND, WCODE_FASTFORWARD, + WCODE_STOP_KEY, WCODE_STOP_CD, WCODE_PLAYPAUSE, WCODE_EXIT, WCODE_CH_UP_KEY, + WCODE_CH_DOWN_KEY, + ]; + (0..256).chain(named).flat_map(|sym| (0..600).map(move |wcode| (sym, wcode))) + } + + /// The four-term expression `is_remote_bound` was before it became `action_of(..).is_some()`, + /// kept here verbatim as the oracle the new one is graded against. + fn old_is_remote_bound(sym: c_uint, wcode: c_uint) -> bool { + classify(sym, wcode) != Key::Other + || page_dir(sym, wcode).is_some() + || sym == SDLK_BACKSPACE + || sym == SDLK_CLEAR + || (b'0' as c_uint..=b'9' as c_uint).contains(&sym) + } + + /// `raw_pair` and `action_of` are inverses, for every action: a platform that sends an action + /// reaches the loop's raw readers through a pair that decodes back to it. + #[test] + fn every_action_reads_back_from_its_own_pair() { + for action in ALL { + let (sym, wcode) = raw_pair(action); + assert_eq!(action_of(sym, wcode), Some(action), "{action:?} via ({sym}, {wcode})"); + } + } + + /// The pair table, key by key, with the spellings a real remote or the simulator sends. + #[test] + fn every_spelling_maps_to_its_action() { + let table: [(c_uint, c_uint, Action); 40] = [ + (SDLK_UP, 0, Action::Up), + (SDLK_DOWN, 0, Action::Down), + (SDLK_LEFT, 0, Action::Left), + (SDLK_RIGHT, 0, Action::Right), + (SDLK_RETURN, 0, Action::Ok), + (SDLK_KP_ENTER, 0, Action::Ok), + (SDLK_SELECT, 0, Action::Ok), + (SDLK_ESCAPE, 0, Action::Back), + (b'q' as c_uint, 0, Action::Back), + (0, 461, Action::Back), + (0, 482, Action::Back), + (0, 450, Action::Play), + (0, 19, Action::Play), + (19, 0, Action::Play), + (0, 402, Action::Play), + (402, 0, Action::Play), + (0, 72, Action::Pause), + (0, 415, Action::Pause), + (415, 0, Action::Pause), + (0, 261, Action::PlayPause), + (261, 0, Action::PlayPause), + (0, 413, Action::Stop), + (0, 120, Action::Stop), + (0, 260, Action::Stop), + (413, 0, Action::Stop), + (0, 452, Action::Rewind), + (452, 0, Action::Rewind), + (0, 451, Action::FastForward), + (451, 0, Action::FastForward), + (0, 505, Action::Exit), + (505, 0, Action::Exit), + (SDLK_PAGEUP, 0, Action::PageUp), + (0, 300, Action::PageUp), + (SDLK_PAGEDOWN, 0, Action::PageDown), + (0, 301, Action::PageDown), + (8, 42, Action::Backspace), + (SDLK_CLEAR, 156, Action::ClearAll), + (0, 0x1e4, Action::PointerHidden), + (b'4' as c_uint, 33, Action::Digit(4)), + (b'0' as c_uint, 0, Action::Digit(0)), + ]; + for (sym, wcode, action) in table { + assert_eq!(action_of(sym, wcode), Some(action), "({sym}, {wcode})"); + } + } + + /// Rewind and FastForward are `Left`/`Right { alt: true }` and never the plain directions, and + /// the plain `sym` still wins the pair that carries both (the precedence `classify` documents). + #[test] + fn transport_is_not_a_direction_and_a_plain_sym_wins() { + assert_eq!(action_of(0, WCODE_REWIND), Some(Action::Rewind)); + assert_eq!(action_of(0, WCODE_FASTFORWARD), Some(Action::FastForward)); + assert_eq!(action_of(SDLK_LEFT, WCODE_REWIND), Some(Action::Left)); + assert_eq!(action_of(SDLK_RIGHT, WCODE_FASTFORWARD), Some(Action::Right)); + assert_ne!(action_of(0, WCODE_PLAY), action_of(0, WCODE_PAUSE), "Play is not Pause"); + assert_ne!(action_of(SDLK_PAGEUP, 0), action_of(SDLK_PAGEDOWN, 0), "PageUp is not PageDown"); + } + + /// The simulator's desktop Backspace is `(8, 482)`: BACK to `classify`, so Back here, with the + /// raw pair kept beside the action so a screen that reads `sym` still sees a Backspace. The + /// FIFO's `backspace` token, `(8, 42)`, and a bare sym 8 are Backspace. + #[test] + fn the_simulators_backspace_is_back_and_the_fifos_is_backspace() { + assert_eq!(action_of(8, 482), Some(Action::Back)); + assert_eq!(action_of(8, 42), Some(Action::Backspace)); + assert_eq!(action_of(8, 0), Some(Action::Backspace)); + } + + /// A press the app does not bind has no action: the colour buttons (the real remote's never + /// reach us, and 504 is the code `docs/remote-keys.md` §9 records for KEY_GREEN), GUIDE-class + /// codes, and a wcode-only number-range scancode. + #[test] + fn an_unbound_press_has_no_action() { + for (sym, wcode) in [(0, 0), (0, 504), (0, 403), (0, 412), (0, 417), (0, 1), (b'a' as c_uint, 4), (0, 50)] { + assert_eq!(action_of(sym, wcode), None, "({sym}, {wcode})"); + assert!(!is_remote_bound(sym, wcode), "({sym}, {wcode})"); + } + } + + /// `is_remote_bound` became `action_of(..).is_some()`: over every pair the grid names it + /// answers what the four-term expression it replaced answered. + #[test] + fn the_bound_predicate_is_unchanged_over_the_whole_grid() { + for (sym, wcode) in grid() { + assert_eq!( + is_remote_bound(sym, wcode), + old_is_remote_bound(sym, wcode), + "({sym}, {wcode})" + ); + } + } + + /// The pager and the edit keys read back as `page_dir` and the sym tests did. + #[test] + fn paging_and_editing_agree_with_their_own_readers() { + for (sym, wcode) in grid().filter(|&(s, w)| classify(s, w) == Key::Other) { + let paged = match page_dir(sym, wcode) { + Some(-1) => Some(Action::PageUp), + Some(1) => Some(Action::PageDown), + _ => None, + }; + if paged.is_some() { + assert_eq!(action_of(sym, wcode), paged, "({sym}, {wcode})"); + } else if sym == SDLK_BACKSPACE { + assert_eq!(action_of(sym, wcode), Some(Action::Backspace), "({sym}, {wcode})"); + } else if sym == SDLK_CLEAR { + assert_eq!(action_of(sym, wcode), Some(Action::ClearAll), "({sym}, {wcode})"); + } + } + } + + /// Every `classify`-named key has its own action and the action's pair classifies back to it: + /// the pair a platform's action expands to drives the ladder as the real key would. + #[test] + fn an_action_pair_drives_the_ladder_as_its_key() { + let expect = [ + (Action::Up, Key::Up), + (Action::Down, Key::Down), + (Action::Left, Key::Left { alt: false }), + (Action::Right, Key::Right { alt: false }), + (Action::Rewind, Key::Left { alt: true }), + (Action::FastForward, Key::Right { alt: true }), + (Action::Ok, Key::Ok), + (Action::Back, Key::Back), + (Action::Play, Key::Play), + (Action::Pause, Key::Pause), + (Action::PlayPause, Key::PlayPause), + (Action::Stop, Key::Stop), + (Action::Exit, Key::Exit), + (Action::PointerHidden, Key::PointerHidden), + ]; + for (action, key) in expect { + let (sym, wcode) = raw_pair(action); + assert_eq!(classify(sym, wcode), key, "{action:?}"); + } + for action in [Action::PageUp, Action::PageDown, Action::Backspace, Action::ClearAll, Action::Digit(7)] { + let (sym, wcode) = raw_pair(action); + assert_eq!(classify(sym, wcode), Key::Other, "{action:?} is taken by hand, not by the ladder"); + } + } + + /// The pad's digit reader moved here unchanged and still reads BOTH fields (so a wcode-only + /// press types a digit on the PIN keypad), while `action_of` reads `sym` only, as the bound + /// predicate always has. The two disagree on a digit-range scancode with no digit sym; the + /// keypad still reads the raw pair, and W5d decides what the Action does. + #[test] + fn the_pin_digit_reads_both_fields_and_the_action_reads_sym() { + assert_eq!(pin_digit(b'7' as u32, 0), Some(b'7'), "a dev keyboard's sym"); + assert_eq!(pin_digit(0, 55), Some(b'7'), "the remote's wcode, same digit"); + assert_eq!(pin_digit(b'0' as u32, 0), Some(b'0')); + assert_eq!(pin_digit(999, 0), None, "not a digit in either field"); + assert_eq!(action_of(0, 55), None, "scancode 55 is a full stop, not a digit"); + assert_eq!(action_of(b'7' as c_uint, 0), Some(Action::Digit(7))); + assert!(!is_remote_bound(0, 55)); + } + + /// A digit above 9 is no key: no constructor makes one, and a hand-built one has a pair nothing reads. + #[test] + fn a_digit_above_nine_names_no_key() { + assert_eq!(Action::digit(9), Some(Action::Digit(9))); + assert_eq!(Action::digit(10), None); + assert_eq!(raw_pair(Action::Digit(10)), (0, 0)); + assert_eq!(action_of(0, 0), None); + } +} From 8f55751826997fb60f4cd049bb611031f72a4043 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 15:28:32 +0300 Subject: [PATCH 09/26] The simulator runs on its own platform (#1486) The simulator becomes its own platform (step W4 of the platform plan, discussion #1460). It no longer runs the television's service tables through `hostsim` arms in `system.rs`, `port.rs`, `webos*.rs` and `keymanager.rs`. Those 102 gated lines fall to 0. The television's code is now always compiled, and the linker strips it from the simulator because nothing reaches it. webOS is unchanged, and the replay fixtures replay identically. - `src/platform_desktop.rs` (`[platform desktop]`) never names `port`, `system`, `webos` or `keymanager`. - It supplies its own `tv::Services`. The hooks a desktop host has nothing for are named `NONE` groups: the device probe, native-video repair, device files, locale, sound output, home polling, URI media and the secure store. - It has its own bodies for the capability probe (which publishes the DV answer), `go_home`, toasts and the sink. - Its `Shell` and `FrameProbe` are explicit no-ops. - Its entry returns the exit code, and `bin/sim.rs` ends the process. - The dev-trigger DV override moves from `webos/caps.rs` to the neutral `os/src/devcaps/dv.rs`, which both probes end in. - CI: `simulators.yml`'s macOS job also links the macOS app's feature set in debug, which guards the dead-strip reliance until W7 takes `webos` out of the desktop build. `ci/check-deps.sh`'s sink rule follows the moved arms. - The prose that put the simulator on the television's tables or on `port::plex_run` now says it has its own platform. The exception is `rust-modules/Cargo.toml`'s `hostsim` comment. The `ci/proofs` certificates pin that file, so W7 rewords it when it re-seals. What the simulator does differently, all in its own log and none read by a test, tool or fixture: - The webOS device-probe lines are gone, and the Sentry `probe` context reads `unprobed`. - The surface grab's `FB bits` and `wm sdl` lines and its `wm_query` crash step are gone. - The first `devcaps:` line's error text reads `entity not found`. - The keymanager stand-in's sign-in line is gone. The session is still stored in plaintext, as the harnesses expect. - The toast line has new wording, with the same `NoBus` outcome. - The DV probe runs synchronously, with the same answer and the dev triggers intact. - `X-Plex-Platform` stays `webOS`. Tests, base against head: the app hostsim suite ran 1726 passed on both (the two macOS-only no-GL tests skipped), `plx_media` hostsim 2478 on both, and `plx_os` 460 on both. No test was lost; two moved with their code. `make check-replay` was unchanged. The simulator boots to Home against `tests/mock_pms.py`, and `make macapp` builds. `nm -u` shows no Wayland, LS2, ACB, Starfish or luna symbol in any simulator binary. fw-compat-reviewer: SAFE. --- .github/workflows/ci.yml | 5 +- .github/workflows/simulators.yml | 22 ++- .gitignore | 3 + ci/check-deps.sh | 10 +- ci/mkmacapp.py | 5 +- ci/module-layers.ini | 11 ++ ci/test_sim_backend.py | 25 ++-- docs/agent-reference.md | 2 +- docs/macos-app.md | 6 +- docs/module-layers.md | 61 +++++---- fuzz/Cargo.toml | 8 +- rust-modules/os/src/devcaps/dv.rs | 97 ++++++++++++- rust-modules/os/src/keymanager.rs | 10 +- rust-modules/os/src/tv.rs | 2 +- rust-modules/os/src/webos.rs | 55 ++++---- rust-modules/os/src/webos/caps.rs | 118 +++------------- rust-modules/os/src/webos/jail_repair.rs | 10 +- rust-modules/os/src/webos/toast.rs | 8 +- rust-modules/os/src/webos/video_sink.rs | 9 +- rust-modules/play-feed/src/ffi_host.rs | 2 +- rust-modules/src/app/adapters/backends.rs | 2 +- rust-modules/src/app/adapters/hostsim.rs | 6 +- rust-modules/src/app/boot.rs | 5 +- rust-modules/src/app/exit.rs | 5 +- rust-modules/src/app/mod.rs | 9 +- rust-modules/src/bin/sim.rs | 13 +- rust-modules/src/lib.rs | 20 +-- rust-modules/src/platform_desktop.rs | 157 ++++++++++++++++++++++ rust-modules/src/port.rs | 40 ++---- rust-modules/src/system.rs | 117 +++++----------- 30 files changed, 497 insertions(+), 346 deletions(-) create mode 100644 rust-modules/src/platform_desktop.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4e7882e75f..3e220bbe9d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -273,8 +273,9 @@ jobs: - name: Type-check the simulator feature set # The host simulator is a real build configuration with real users (the `ui-sim` skill, and # `make macapp`, which ships `--release --no-default-features --features hostsim,play-feed` to - # somebody who has none of this installed). Nothing else in CI compiles it, so a change that - # only breaks the Mac side merges green and is found by a person trying to demo the app. + # somebody who has none of this installed). `simulators.yml` builds, links and launches it on + # macOS and Linux, in jobs that need a macOS runner and the host FFmpeg; this is the cheap early + # answer for the same feature sets, so a change that only breaks the Mac side fails here first. run: | cd rust-modules cargo "+$RUST_TOOLCHAIN" check --lib --features hostsim diff --git a/.github/workflows/simulators.yml b/.github/workflows/simulators.yml index a953ac2210..185d527aa0 100644 --- a/.github/workflows/simulators.yml +++ b/.github/workflows/simulators.yml @@ -188,10 +188,30 @@ jobs: uses: ./.github/actions/deps-cache - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 with: - workspaces: rust-modules -> target-sim-ci + workspaces: | + rust-modules -> target-sim-ci + rust-modules -> target-sim-ci-macapp key: simulator-macos - name: Build native macOS simulator run: make sim-macos SIM_TDIR=rust-modules/target-sim-ci + - name: Link the macOS app's feature set + # What `make macapp` ships: `--no-default-features --features hostsim,play-feed` (the + # release build in `ci/mkmacapp.py`, linked here in DEBUG: the harder case for the reliance + # below, and cheaper than a release build). The desktop platform (`platform_desktop`) never + # names the television's code, but the crate still COMPILES it (`system.rs`'s Wayland and + # SDL-private externs, `webos`, `keymanager`): a host executable links only because nothing + # references those items and the linker drops them (`-dead_strip` here, `--gc-sections` on + # Linux). A change that makes one reachable from the desktop entry fails this link on + # libwayland, glib or luna-service2, which the default-features build above may not show. This + # step guards that reliance until the platform crates split and the desktop build no longer + # contains `webos` (docs/platform-ports.md, W7). It has its own target dir because cargo does + # not hash its output: in `target-sim-ci` it would overwrite the binary the steps below run. + # The host FFmpeg and libass it links were staged by the step above. + run: | + CARGO_INCREMENTAL=0 cargo "+$(make -s print-rust-toolchain)" build \ + --manifest-path rust-modules/Cargo.toml \ + --target-dir rust-modules/target-sim-ci-macapp \ + --no-default-features --features hostsim,play-feed --bin plxnative-sim - name: Replay all committed product recordings # 960x540, not the driver's 1920x1080 default. The runner has no GPU (the log says `GL: # Apple Software Renderer`), so a replay is CPU-bound in the rasteriser and costs what the diff --git a/.gitignore b/.gitignore index 591a3e4aa0..6ef59224f8 100644 --- a/.gitignore +++ b/.gitignore @@ -68,6 +68,9 @@ rust-modules/target-sim-lab/ # `make screenshots-sim` — the documentation-screenshot simulator (hostsim + devtriggers). rust-modules/target-sim-shots/ rust-modules/target-sim-video/ +# `simulators.yml` builds into `target-sim-ci` (`make sim-macos SIM_TDIR=...`) and `target-sim-ci-macapp` +# (the macapp feature set's link), in the checkout; a lane reproducing that job gets the same trees. +rust-modules/target-sim-ci*/ # pkg/plxnative-storage's own target dir, deliberately separate from $(RUST_TDIR) — see the # Makefile's STORAGE_TDIR comment. One glob for every RELEASE/LAB/SYMBOLS combination. rust-modules/target*-storage/ diff --git a/ci/check-deps.sh b/ci/check-deps.sh index f48a647e67..8ebbf38ce1 100755 --- a/ci/check-deps.sh +++ b/ci/check-deps.sh @@ -14,7 +14,7 @@ # present — the present gate's worker door: ONE atomic static in machine/src/present.rs and ONE # `wake_from_worker`. # effect — `Effect::` spelled nowhere (the enum is `Fx::`, the app's `AppFx::`). -# sink — `tv::sink::installed` and `VideoSink` only under player/, tv/, tv.rs, port.rs and app/adapters/backends.rs +# sink — `tv::sink::installed` and `VideoSink` only under player/, tv/, tv.rs, port.rs, platform_desktop.rs and app/adapters/backends.rs # (step L15: the Starfish/ACB verbs are the player's alone). # # Phase 4 rule (D3 rewrite, phase 12): @@ -1140,8 +1140,8 @@ 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 names one) -# and `tv.rs` with `tv/` (which hold it) name `tv::sink::installed` or `VideoSink`; so does +# `player/`, `play-uri/`, the native `webos/` port, and `port.rs` and `platform_desktop.rs` (which +# name one each) 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 # driver set is built). Every other module reaches the television through the narrower `tv` interfaces. Wholly-test files are skipped like inline @@ -1156,12 +1156,12 @@ while IFS= read -r line; do case "$p" in "$SRC_PLAY_FEED"/*|"$SRC_PLAY_URI"/*) case "$line" in *tv::sink::installed*|*tv::sink::display_installed*) ;; *) continue ;; esac ;; esac - case "$p" in "$SRC_MEDIA"/player/*|"$SRC_OS"/tv/*|"$SRC_OS"/tv.rs|"$SRC_OS"/webos/*|"$SRC"/port.rs|"$SRC"/app/adapters/backends.rs) continue ;; esac + case "$p" in "$SRC_MEDIA"/player/*|"$SRC_OS"/tv/*|"$SRC_OS"/tv.rs|"$SRC_OS"/webos/*|"$SRC"/port.rs|"$SRC"/platform_desktop.rs|"$SRC"/app/adapters/backends.rs) continue ;; esac if is_wholly_test "$p"; then continue; fi echo " $line"; sink_bad=$((sink_bad+1)) done < <(grep_code 'tv::sink::(installed|display_installed)|\b(VideoSink|DisplaySink)\b' "$SRC" "$SRC_OS" "$SRC_UI" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP") if [ "$sink_bad" -eq 0 ]; then ok "sink" -else fail "sink: $sink_bad line(s) naming the video sink outside playback execution, port.rs, tv.rs and tv/"; fi +else fail "sink: $sink_bad line(s) naming the video sink outside playback execution, port.rs, platform_desktop.rs, tv.rs and tv/"; fi fi # sink # route: `Route::` in app/ = 0, and `enum Route` gone from the whole tree (D1/D4). No allowlist: diff --git a/ci/mkmacapp.py b/ci/mkmacapp.py index 7fae3c4987..a8df0451de 100755 --- a/ci/mkmacapp.py +++ b/ci/mkmacapp.py @@ -1,8 +1,9 @@ #!/usr/bin/env python3 """Build `PlxNative.app` — the app core as a SELF-CONTAINED macOS application. -This is the `hostsim` build (`rust-modules/src/bin/sim.rs`): the same UI, the same Plex data layer -and the same event loop the television runs, wrapped in a bundle that carries its own SDL, its own +This is the desktop platform's build (`rust-modules/src/platform_desktop.rs`, entered by +`rust-modules/src/bin/sim.rs`, feature `hostsim`): the same UI, the same Plex data layer and the same +event loop the television runs, booted on the desktop's own platform and wrapped in a bundle that carries its own SDL, its own fonts and its own copy of every non-system library it links, so it starts on a Mac that has none of this repo's build environment installed. What it is NOT is a television — there is no video pipeline off-device (`play-feed/src/ffi_host.rs`), so Play lands on the app's real failure read-out. diff --git a/ci/module-layers.ini b/ci/module-layers.ini index 5bbf045998..00325a7bd3 100644 --- a/ci/module-layers.ini +++ b/ci/module-layers.ini @@ -191,6 +191,7 @@ members = screens uses = base machine os gfx net plex telemetry ui data session media appkit screens playback_contract play_uri play_feed media_codecs members = crate app dev lab capture remote focusprobe hud_cli hud_tools shot coldstart textinput system release_line port + platform_desktop [platform webos] # Not a layer: the modules that exist only because the target is webOS. Identity, capability and @@ -207,3 +208,13 @@ members = # `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 + +[platform desktop] +# Not a layer, like [platform webos]: the simulator's and the macOS app's own platform. Its tables +# (`SERVICES`, the shell, the frame probe, `PLATFORM`) and its entry (`run`, which `src/bin/sim.rs` +# calls) are written for a host, from the shared `NONE` groups of `os`'s `tv` wherever a host has +# nothing to say, so nothing outside it needs to name it and it names none of [platform webos]: the +# gate fails a reference from here to `webos`, `keymanager`, `system` or `port` like any other +# reference from outside that port. It stays a module of the application crate until the platform +# crates split (docs/platform-ports.md, W7). +members = platform_desktop diff --git a/ci/test_sim_backend.py b/ci/test_sim_backend.py index b063c51342..b218b443c8 100644 --- a/ci/test_sim_backend.py +++ b/ci/test_sim_backend.py @@ -1,14 +1,15 @@ #!/usr/bin/env python3 """Every simulator build that drops the default features still selects the Feed backend. -`hostsim` swaps the television's native video sink for the simulator's (`plx_play_feed::ffi_host`), -but that stand-in is the Feed backend's, so it exists only when `play-feed` is built. A simulator -built `--no-default-features --features hostsim` selects NO backend: its app installs `NoSink`, so -Play can only ever reach the failure read-out and the clock sink (`plxnative-clocksink`) has nothing -to arm. Three builds drift into that state because they drop `devtools` and `devtriggers` with -`--no-default-features` and then list `hostsim` alone: the `.app` bundle (`ci/mkmacapp.py`), the -screenshot simulator (`make screenshots-sim`) and the demo-video simulator (`make site-video-sim`); -so does the CI step that type-checks the simulator feature set, which then proves nothing about the +The simulator is its own platform (`platform_desktop`, which `hostsim` compiles), and the video sink +it hands the application is the Feed backend's host sink (`plx_play_feed::ffi_host`), which exists +only when `play-feed` is built. A simulator built `--no-default-features --features hostsim` selects +NO backend: its platform installs `NoSink`, so Play can only ever reach the failure read-out and the +clock sink (`plxnative-clocksink`) has nothing to arm. Three builds drift into that state because +they drop `devtools` and `devtriggers` with `--no-default-features` and then list `hostsim` alone: +the `.app` bundle (`ci/mkmacapp.py`), the screenshot simulator (`make screenshots-sim`) and the +demo-video simulator (`make site-video-sim`); so do the CI steps that type-check +(`ci.yml`) and link (`simulators.yml`) the simulator feature set, which then prove nothing about the configuration the other three ship. The scan finds every cargo command line in the files that can hold one, joins its continuations and @@ -26,6 +27,7 @@ MAKEFILE = "Makefile" MKMACAPP = "ci/mkmacapp.py" CI_YML = ".github/workflows/ci.yml" +SIMULATORS_YML = ".github/workflows/simulators.yml" def feature_flags(tokens): @@ -91,7 +93,7 @@ def python_cargo_commands(path): def scan(): commands = [] - for path in (MAKEFILE, CI_YML): + for path in (MAKEFILE, CI_YML, SIMULATORS_YML): commands += text_cargo_commands(path) for path in sorted(p.relative_to(ROOT).as_posix() for p in (ROOT / "ci").glob("*.py")): commands += python_cargo_commands(path) @@ -106,7 +108,7 @@ class SimulatorBackend(unittest.TestCase): def test_the_scan_reaches_the_builds_it_exists_for(self): sims = sim_commands(scan()) reached = {(path, bool(no_default)) for path, _, _, no_default, _ in sims} - for site in (MKMACAPP, MAKEFILE, CI_YML): + for site in (MKMACAPP, MAKEFILE, CI_YML, SIMULATORS_YML): with self.subTest(site): self.assertIn((site, True), reached, f"no `--no-default-features --features hostsim` build found in {site}") makefile_lines = " ".join(line for path, _, line, _, _ in sims if path == MAKEFILE) @@ -126,10 +128,11 @@ def test_a_simulator_without_default_features_selects_the_feed_backend(self): ) def test_each_scripted_simulator_build_is_pinned_to_its_features(self): - """The three bundle/screenshot/video builds and the CI type-check, spelled out.""" + """The three bundle/screenshot/video builds and the CI type-check and link, spelled out.""" pinned = { MKMACAPP: {"hostsim", "play-feed"}, CI_YML: {"hostsim", "play-feed"}, + SIMULATORS_YML: {"hostsim", "play-feed"}, } sims = sim_commands(scan()) for site, expected in pinned.items(): diff --git a/docs/agent-reference.md b/docs/agent-reference.md index 2207261422..c1b2787593 100644 --- a/docs/agent-reference.md +++ b/docs/agent-reference.md @@ -345,7 +345,7 @@ the pinned Sentry Native cross-build), and `sshpass` (Homebrew; deploy/run use y asserts only what its code promises (no panic, the documented bounds, round trips) and a crash fails the run, with the input in `fuzz/artifacts//`. The package is a top-level `fuzz/` with its own `[workspace]`, so no shipped `Cargo.toml` names it and no shipped build changes; it depends on the layer - crates by path, with `plx_media/hostsim` (the one configuration that links on a host), and `fuzz/build.rs` + crates by path, with `plx_media/hostsim` (the host configuration: the Feed backend's host sink and the layers' host stand-ins), and `fuzz/build.rs` reuses `rust-modules/build_support/host_link.rs`. `tools/fuzz-hud.py` is the whole workflow (`list | seed | lock | build | run`): it copies `rust-modules/Cargo.lock` to the gitignored `fuzz/Cargo.lock` (the shared crates are exactly the shipped versions), builds with the nightly named by `FUZZ_TOOLCHAIN` diff --git a/docs/macos-app.md b/docs/macos-app.md index 6f513fcd65..735dd796ef 100644 --- a/docs/macos-app.md +++ b/docs/macos-app.md @@ -7,9 +7,9 @@ television runs, packaged so it starts on a Mac that has none of this repo's bui no Homebrew, no SDL, no toolchain. `ci/mkmacapp.py` is the whole recipe; this note is why it looks the way it does and what the result is and is not. -It is **not a new build of the app**. It is `--features hostsim,play-feed` — the desktop simulator -(`docs/…`/`rust-modules/src/bin/sim.rs`, and the `ui-sim` skill) — with the dev features off and a -bundle around it. (`play-feed` is named because `--no-default-features` drops it, and the simulator's +It is **not a new build of the app**. It is `--features hostsim,play-feed` — the desktop simulator, +which boots the app on the desktop's own platform (`rust-modules/src/platform_desktop.rs`, entered by +`rust-modules/src/bin/sim.rs`; the `ui-sim` skill) — with the dev features off and a bundle around it. (`play-feed` is named because `--no-default-features` drops it, and the simulator's video sink belongs to that backend.) Every UI change, every Plex data-layer change, is the same code the ipk ships. ## What it can do, and the one thing it cannot diff --git a/docs/module-layers.md b/docs/module-layers.md index 31ac64876e..06df7a3e28 100644 --- a/docs/module-layers.md +++ b/docs/module-layers.md @@ -330,13 +330,13 @@ 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, native_video, 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. | +| **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, native_video, 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 (L15b). | +| **L15b** the OS-neutral port — **open** | — | An OS-neutral video sink with the ACB bind sequence behind it and the webOS facts the gate cannot see; the simulator became its own platform in W4. See below. | | **L15c** the platform value and the three contracts — **done** | — | Wave R (the rename that gave this page `os` and `[platform webos]`) landed as #1474; W2 landed (`tv::Port` became `tv::Services`, with four groups of hooks; the shell and the frame probes moved to `app::Platform`), and so did the three contracts, W3a to W3c: who may persist credentials (#1477), what evidence admits a URI player (#1478), who ends the process (#1479). See "L15c to L15h" below. | -| **L15d** neutral types and the simulator as its own platform (L15b item 2) — **W3d landed, W4 planned** | — | W3d has landed (the opaque `Backend` tag, `sandbox` to `native_video`, identity publishes a platform name and version, `device::Info` keeps its webOS fields in `WebosDetail`, and `devcaps` reads its files through the platform), and what is planned is 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. | +| **L15d** neutral types and the simulator as its own platform (L15b item 2) — **W3d and W4 landed** | — | W3d landed (the opaque `Backend` tag, `sandbox` to `native_video`, identity publishes a platform name and version, `device::Info` keeps its webOS fields in `WebosDetail`, and `devcaps` reads its files through the platform), and so did W4: `platform_desktop` (`rust-modules/src/platform_desktop.rs`, a second fence section, `[platform desktop]`) is the simulator's and the macOS app's own platform value, which `src/bin/sim.rs` enters through; the `hostsim` terms of the television's fence are gone, so the television's code is compiled into every build and the linker drops it from a desktop executable (`simulators.yml` links the macapp feature set to guard that until W7), and the stand-ins in `webos` and `keymanager` are test seams, compiled for tests and `test-support` (`docs/platform-ports.md`, W4). The desktop platform is the second implementation. | | **L15e** events, the shell and composition — **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. | -| **L15g** the webOS facts and the remaining `hostsim` (L15b item 3) — **planned** | — | W8: the `target_arch = "arm"` and `target_os = "linux"` sites sorted into "is webOS" (a platform value or runner) and "is 32-bit ARM" or "is Linux" (stays), then the library name lists, `paths`, the packaging and the 363 `feature = "hostsim"` lines outside the fence (360 cfg lines and three doc comments). | +| **L15g** the webOS facts and the remaining `hostsim` (L15b item 3) — **planned** | — | W8: the `target_arch = "arm"` and `target_os = "linux"` sites sorted into "is webOS" (a platform value or runner) and "is 32-bit ARM" or "is Linux" (stays), then the library name lists, `paths`, the packaging and the `feature = "hostsim"` lines left in the tree (none of them in the fence now; `git grep -h 'feature = "hostsim"' -- '*.rs' | wc -l` counts them). | | **L15h** the OS-neutral Feed sink (L15b item 1) — **planned** | — | W11: `plx_acb` (an `[acb]` layer) takes the ACB plane owner and the URI media verbs out of `os`, the Feed-side ACB results become neutral, and the bind sequence moves behind a neutral sink. Needs the television. | ### L15: the webOS port @@ -356,8 +356,8 @@ tests, where nothing calls `plex_run`) `tv::Services::HOST_TEST` answers what th 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 -`player/`, `play-uri/`, `os`'s `tv/`, `tv.rs` and `webos/`, `port.rs` and -`app/adapters/backends.rs`; `play-feed/` may name the trait but never resolves `installed`), and the URI media pipe through +`player/`, `play-uri/`, `os`'s `tv/`, `tv.rs` and `webos/`, `port.rs`, `platform_desktop.rs` (each platform's table names its own +sink) and `app/adapters/backends.rs`; `play-feed/` may name the trait but never resolves `installed`), and the URI media pipe through `tv::uri::installed()`, resolved once by the composition (`app/adapters/backends.rs::install_uri_product`, every build with the `play-uri` feature) and, in a `devtriggers` build, again by the media wrapper `player::uriprobe_drive` for the developer probe. The independent `play-uri` driver receives that transport and a shared `DisplaySink` as injected ports; it @@ -381,10 +381,11 @@ published values rather than hooks: the webOS code writes them into `tv::device` | 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 `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 +that point each hook at the `webos`, `keymanager` and `system` function behind it. The C shim +enters 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 +ends the process with that status. The simulator enters through `platform_desktop::run`, which hands the desktop +platform to `run_application` and returns that status; the simulator's `main` ends the process. `lib.rs` declares the port but re-exports nothing from it, because a re-export would be a reference from the crate root into the port, which the gate refuses. The video sink landed as a verb-level cut. `tv::sink::VideoSink` has one method per verb of the @@ -412,21 +413,22 @@ 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` 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. +The simulator does not run the television's tables. `platform_desktop.rs` states its own `SERVICES` and `PLATFORM`: the +shared `NONE` groups where a host has nothing to say, its own bodies for the capability probe, the root press and the +toast, `HostSink` as the sink, and a `Shell` and a `FrameProbe` that do nothing. `port.rs` is the webOS port only. The +desktop build still compiles the television's code, and the linker drops what nothing reaches, which `simulators.yml` +guards with a link step until the platform crates split (W7). L15 is gate-complete: no entry carries its tag, `plex_run`, which the C shim calls, lives in the port, and the gate fails on a new reference into it. That is all the gate can see. L15 also set out -to put an OS-neutral sink with the bind sequence behind it and the simulator's stand-ins in their -own port. Neither landed, so L15 is not called done. They are L15b. +to put an OS-neutral sink with the bind sequence behind it and the simulator in its own port. The +sink did not land, so L15 is not called done; it is L15b. The simulator did, in W4. ### L15b: the OS-neutral port Open. L15 made every reference to the webOS code visible and one-directional. It did not make the interfaces something another OS could implement, because the verbs and several types in them are -still webOS's. Three things are left: +still webOS's. Three things were left, and item 2 is done: 1. **An OS-neutral video sink.** A sink another OS can implement takes codec configuration and timestamped access units, and it seeks, flushes, pauses and reports events. The ACB bind @@ -434,13 +436,18 @@ still webOS's. Three things are left: `sf_on_event`/`acb_on_event` and `sink_counter_kind(ty, major)` in `player/mod.rs` move behind it, into the port. This changes where the stages and the callback decode live and when they run, so it needs the television: see the reasons above. -2. **The simulator as its own port.** `ffi_host` and the simulator's arms of `system` and `port` - become a second `Port` table, a second implementation of the same interfaces, instead of the - webOS table running its host arms. That keeps both honest. The stand-ins in `webos` and - `keymanager` do not move: the nine `any(hostsim, test, test-support)` items are what the - simulator runs today (`launch_home`, `system_locale`, `sound_output`, `bind_window`, the - keymanager client, `deliver`, `call_hbc` among them), and they stay compiled for tests and - `test-support` with only their `hostsim` term gone (`docs/platform-ports.md`, W4). The +2. **The simulator as its own platform (done, W4).** `platform_desktop` is a second implementation of the + same interfaces: it states every hook of `tv::Services` (the shared `NONE` groups where a host has + nothing to say, its own capability probe, root press, toast and sink) with a no-op `Shell` and + `FrameProbe`, and `src/bin/sim.rs` enters through it, so the webOS table no longer runs host arms. The + `hostsim` terms are gone from `system`, `port`, `webos` and `keymanager`. The stand-ins in `webos` and + `keymanager` are test seams only, `cfg(any(test, feature = "test-support"))`: a simulator run executes + none of them (`docs/platform-ports.md`, W4). `hostsim` no longer selects a platform: it selects the + host build of what is not one (the media seam's host sink, the GL context request, the window flags + and the keyboard event decode), while the television's wayland and glib calls, like the rest of the + television's arms, are compiled in every build and the linker drops them from a host executable. + The comment on the feature in `rust-modules/Cargo.toml` still lists those calls under what it + switches; the certificate pins that file, so W7 rewords it when it re-seals. The webOS-shaped types in `tv` needed neutral shapes then, and have them since W3d: `tv::secure::Backend` is an opaque tag that stays a string on the wire (the two webOS spellings are constants, and a tag no installed platform knows is refused on open), `tv::sandbox` is `tv::native_video` with a verdict that is @@ -463,13 +470,13 @@ still webOS's. Three things are left: crate (`rust-modules/storage`, an LS2 service over DB8), and the Makefile's NDK cross-build and `.ipk` packaging. -L15b is done when the sink is OS-neutral, the simulator is its own port, and these facts are the -port's. The port does not wait for all three before it leaves its layers. The order, amended 2026-11-20, is item 2 -(the simulator as its own port), then the extraction, then item 3 and item 1 ("L15c to L15h" below). Extracted, the +L15b is done when the sink is OS-neutral and these facts are the +port's (the simulator became its own platform in W4). The port does not wait for both before it leaves its layers. The +order, amended 2026-11-20, is item 2 (the simulator as its own platform, done), then the extraction, then item 3 and item 1 ("L15c to L15h" below). Extracted, the port is a crate of its own on top: it names `app` to start it, and nothing names it. `plx_platform_webos` produces the staticlib the Makefile links, and `plxnative-modules` stays the application crate beneath it. Another TV OS is another platform in that position. The simulator binary, `src/bin/sim.rs`, is already a separate crate there, -and enters through `port::plex_run` until W4 gives it its own platform value. +and enters through `platform_desktop::run`. ### L15c to L15h: the platform plan diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 75bb12169e..ddbe87d1ee 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -11,8 +11,10 @@ # would need an `exclude`; here they cannot see it. # # WHAT IT FUZZES. The parsers of `plx_appkit` (`hud_format`), `plx_data` (`hudpacks`), `plx_net` (`ws`) and `plx_owp` (`json`), -# built in the host-simulator configuration: `hostsim`, the only one a host executable can link (the television build -# declares the LS2, glib and ACB symbols only the TV's own libraries define). The parsers have no `cfg` +# built in the host-simulator configuration: `hostsim`, which selects the host configuration of the layers below. The +# television's own LS2, glib and ACB declarations are compiled in every build, `hostsim` included; a host executable +# links only because nothing here references them and the linker drops them (`simulators.yml` guards that for the +# simulator). The parsers have no `cfg` # on that feature (`rust-modules/Cargo.toml`, "What it changes, and nothing else"), and nothing here # enables `test-support` or `devtriggers`. `fuzz/Cargo.lock` is not committed: `tools/fuzz-hud.py` copies # `rust-modules/Cargo.lock` over it before a build, so the shared crates (zip, serde_json, ...) are exactly @@ -45,7 +47,7 @@ plx_owp = { path = "../rust-modules/owp" } # The registry-index targets sign with TEST ONLY keys (`src/signing.rs`) to reach what follows the signature # check. The same version and features as `plx_data`, so the lock gains nothing. ed25519-compact = { version = "=2.6.1", default-features = false, features = ["opt_size"] } -# Named only to switch the layers below `plx_appkit` to their host stand-ins (`plx_media/hostsim` +# Named only to switch the layers below `plx_appkit` to their host configuration (`plx_media/hostsim` # forwards to every layer that has the feature); no code here calls it. plx_media = { path = "../rust-modules/media", features = ["hostsim"] } diff --git a/rust-modules/os/src/devcaps/dv.rs b/rust-modules/os/src/devcaps/dv.rs index 627d6f8019..e9a03d4b60 100644 --- a/rust-modules/os/src/devcaps/dv.rs +++ b/rust-modules/os/src/devcaps/dv.rs @@ -1,10 +1,12 @@ -//! The television's own Dolby Vision capability: the type, and the cache the port's boot probe -//! publishes into (`webos::caps`). +//! The television's own Dolby Vision capability: the type, the cache a platform's boot probe +//! publishes into (the webOS port's is `webos::caps`, the desktop platform's its own), and the dev +//! triggers that force the answer, which every platform's probe honours the same way. //! -//! An early render-thread read never initializes the cache: the port's worker is the only +//! An early render-thread read never initializes the cache: the platform's probe is the only //! publisher, and a failed or late answer cannot be mistaken for an affirmative capability. use std::sync::OnceLock; +use std::time::Instant; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DvCapability { @@ -110,9 +112,96 @@ pub fn publish(probe: DvProbe) { RESULT.publish(probe); } +/// The configd key the webOS probe asks for, and the one every probe line names. +pub const CONFIG_KEY: &str = "tv.config.supportDolbyHDRContents"; + +plx_base::devtrig::latched_flag!( + /// `/tmp/plxnative-dvcaps0` — force the boot's platform answer to unsupported. + fn forced_unsupported = "dvcaps0"; +); + +plx_base::devtrig::latched_flag!( + /// `/tmp/plxnative-dvcaps1` — force the boot's platform answer to supported. + fn forced_supported = "dvcaps1"; +); + +fn override_capability(zero: bool, one: bool) -> Option<(DvCapability, bool)> { + if zero { + Some((DvCapability::Unsupported, one)) + } else if one { + Some((DvCapability::Supported, false)) + } else { + None + } +} + +/// Publish a probe's answer and log it, one `webos-caps:` line, with the time the probe took. A +/// platform's probe ends in this call whatever it learned, so every answer leaves the same line. +pub fn publish_logged(probe: DvProbe, started: Instant, code: Option, detail: Option<&str>) { + publish(probe); + let elapsed = started.elapsed().as_millis(); + if probe.capability == DvCapability::Unknown { + let code = code.map(|n| format!(" code={n}")).unwrap_or_default(); + let detail = detail + .filter(|s| !s.is_empty()) + .map(|s| format!(" detail={s}")) + .unwrap_or_default(); + plx_base::eventlog::log(&format!( + "webos-caps: key={CONFIG_KEY} answer=unknown stage={}{}{} elapsed_ms={elapsed}", + probe.reason, code, detail, + )); + } else { + plx_base::eventlog::log(&format!( + "webos-caps: key={CONFIG_KEY} answer={} source={} elapsed_ms={elapsed}", + probe.capability.label(), + probe.provenance(), + )); + } +} + +/// The dev triggers' answer, if one is armed: `dvcaps0` forces unsupported and `dvcaps1` supported, +/// `dvcaps0` winning when both are (and saying so). Published and logged like any probe answer, and +/// answers whether it did, so the probe stops there instead of asking its platform. +pub fn publish_forced(started: Instant) -> bool { + let Some((capability, conflict)) = override_capability(forced_unsupported(), forced_supported()) else { + return false; + }; + if conflict { + plx_base::eventlog::log("webos-caps: dvcaps0 and dvcaps1 both armed; dvcaps0 wins"); + } + publish_logged( + DvProbe { + capability, + source: ProbeSource::Override, + reason: if conflict { "override-conflict" } else { "override" }, + }, + started, + None, + None, + ); + true +} + #[cfg(test)] mod tests { - use super::{DvCache, DvCapability, DvProbe, ProbeSource}; + use super::{override_capability, DvCache, DvCapability, DvProbe, ProbeSource}; + + #[test] + fn dv_caps_override_precedence() { + assert_eq!(override_capability(false, false), None); + assert_eq!( + override_capability(true, false), + Some((DvCapability::Unsupported, false)) + ); + assert_eq!( + override_capability(false, true), + Some((DvCapability::Supported, false)) + ); + assert_eq!( + override_capability(true, true), + Some((DvCapability::Unsupported, true)) + ); + } #[test] fn early_caps_read_does_not_initialize_cache() { diff --git a/rust-modules/os/src/keymanager.rs b/rust-modules/os/src/keymanager.rs index 0bf228480d..78b07f3a70 100644 --- a/rust-modules/os/src/keymanager.rs +++ b/rust-modules/os/src/keymanager.rs @@ -203,26 +203,24 @@ fn call_with(client: &mut platform::Client, uri: &str, payload: &Value) -> Optio .and_then(|s| serde_json::from_str(&s).ok()) } -#[cfg(any(feature = "hostsim", test, feature = "test-support"))] +#[cfg(any(test, feature = "test-support"))] mod platform { pub(super) struct Client; impl Client { pub(super) fn new() -> Result { - #[cfg(any(test, feature = "test-support"))] if super::RPC_FOR_TEST.with(|hook| hook.get().is_some()) { return Ok(Self); } Err(()) } - pub(super) fn call(&mut self, _uri: &str, _payload: &str) -> Result { - #[cfg(any(test, feature = "test-support"))] - if let Some(rpc) = super::RPC_FOR_TEST.with(|hook| hook.get()) { return rpc(_uri, _payload); } + pub(super) fn call(&mut self, uri: &str, payload: &str) -> Result { + if let Some(rpc) = super::RPC_FOR_TEST.with(|hook| hook.get()) { return rpc(uri, payload); } Err(()) } } } -#[cfg(all(not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +#[cfg(not(any(test, feature = "test-support")))] mod platform { use std::time::Duration; diff --git a/rust-modules/os/src/tv.rs b/rust-modules/os/src/tv.rs index 752c3bc93c..4d372c7798 100644 --- a/rust-modules/os/src/tv.rs +++ b/rust-modules/os/src/tv.rs @@ -111,7 +111,7 @@ impl LegacyWebosMedia { 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 + /// `cfg(any(test, feature = "test-support"))` 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, diff --git a/rust-modules/os/src/webos.rs b/rust-modules/os/src/webos.rs index d8ff5013fe..88e13eb609 100644 --- a/rust-modules/os/src/webos.rs +++ b/rust-modules/os/src/webos.rs @@ -45,7 +45,7 @@ use crate::tv::device::{Hardware, Info, NyxFile, Platform, WebosDetail}; pub mod jail_repair; pub mod caps; pub mod toast; -#[cfg(all(not(feature = "hostsim"), not(test)))] +#[cfg(not(test))] pub mod video_sink; const OS_INFO: &str = "/var/run/nyx/os_info.json"; @@ -142,7 +142,8 @@ fn plex_platform(release: &str) -> Platform { } /// The files `devcaps::probe` parses, read from the file system: webOS's own paths, named by the -/// model. The simulator's host has none of them and so answers "unreadable", as it always did. +/// model. A host that is not a television has none of them and so answers "unreadable"; the simulator does not +/// read them at all, its platform states `Files::NONE`. pub const DEVICE_FILES: crate::tv::device::Files = crate::tv::device::Files { read: |path| std::fs::read_to_string(path), exists: |path| std::path::Path::new(path).exists(), @@ -214,7 +215,7 @@ fn os_release_value<'a>(s: &'a str, key: &str) -> Option<&'a str> { /// [`OS_RELEASE_FIRST_MAJOR`]: no firmware older than that writes this file, so such a text is not /// this set's own, and a major 1 to 4 would flip the decisions that read it (the credential /// default, VP9 10-bit, the DV platform gate, the old-ABI seek). The ID check is what keeps a Linux -/// host that runs the simulator from reading its distribution's `VERSION_ID` as a firmware. +/// host that runs this probe (the unit tests, a CI runner) from reading its distribution's `VERSION_ID` as a firmware. /// /// The file carries no codename, API version or build id, so those stay empty rather than invented; /// in particular [`Info::build`] stays empty, not the release, so that this boot and a nyx boot of @@ -486,7 +487,7 @@ pub fn poll_home() { /// minimize leg instead of leaving the user on a screen whose BACK did nothing. const HOME_APP_ID: &str = "com.webos.app.home"; -#[cfg(any(feature = "hostsim", test, feature = "test-support"))] +#[cfg(any(test, feature = "test-support"))] fn launch_home() -> bool { plx_base::eventlog::log(&format!( "gohome: no LS2 bus off-device — the root press would launch {HOME_APP_ID} on a television" @@ -494,22 +495,22 @@ fn launch_home() -> bool { true } -#[cfg(any(feature = "hostsim", test, feature = "test-support"))] +#[cfg(any(test, feature = "test-support"))] fn minimize() {} -#[cfg(any(feature = "hostsim", test, feature = "test-support"))] +#[cfg(any(test, feature = "test-support"))] fn ls2_probe() { plx_base::eventlog::log("gohome: no LS2 bus off-device — nothing to probe"); } -#[cfg(all(not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +#[cfg(not(any(test, feature = "test-support")))] fn ls2_probe() { ls2::probe(); } /// Grade only the allowlisted fields in the LS2 wake reply. The raw platform JSON never enters a /// report or the local snapshot. -#[cfg(any(test, all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"))))] +#[cfg(any(test, all(target_os = "linux", target_arch = "arm")))] fn storage_activation_reply(reply: &str) -> crate::storage::wire::failure::Detail { use crate::storage::wire::failure::{Detail, Stage}; if reply.len() > 4096 { return Detail::new(Stage::ActivationInvalidReply, None); } @@ -531,7 +532,7 @@ fn storage_activation_reply(reply: &str) -> crate::storage::wire::failure::Detai /// The helper publishes readiness from its startup path, so neither a successful method reply nor /// delivery of `/wake` is required; the result is retained only as diagnostics and the authenticated /// Unix-socket `Hello` is the sole readiness proof. -#[cfg(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +#[cfg(all(target_os = "linux", target_arch = "arm", not(any(test, feature = "test-support"))))] pub fn activate_storage_helper(service: &str) -> crate::storage::wire::failure::Detail { use crate::storage::wire::failure::{Detail, Stage}; let uri = format!("luna://{service}/wake"); @@ -549,7 +550,7 @@ pub fn activate_storage_helper(service: &str) -> crate::storage::wire::failure:: /// Hosts and the simulator have no storage helper to wake: the same answer an absent port gives. #[cfg(all( target_os = "linux", - not(all(target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))) + not(all(target_arch = "arm", not(any(test, feature = "test-support")))) ))] pub fn activate_storage_helper(_service: &str) -> crate::storage::wire::failure::Detail { use crate::storage::wire::failure::{Detail, Stage}; @@ -559,7 +560,7 @@ pub fn activate_storage_helper(_service: &str) -> crate::storage::wire::failure: /// One `getSystemSettings` round trip on a fresh anonymous registration (any thread: the /// registration owns its glib context). `None` when the bus refused or timed out. `budget` bounds /// the call only: registration and unregistration are not bounded by it (`ls2`'s own doc says so). -#[cfg(all(not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +#[cfg(not(any(test, feature = "test-support")))] fn settings_reply(payload: &str, budget: std::time::Duration) -> Option { ls2::register() .map_err(ls2::Fail::from) @@ -570,7 +571,7 @@ fn settings_reply(payload: &str, budget: std::time::Duration) -> Option /// What the platform's settings service says about the locale; `i18n` owns the parse and the log /// lines. The same 600 ms bus budget as a root press, and for the same reason: the caller is the /// main thread at boot. -#[cfg(all(not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +#[cfg(not(any(test, feature = "test-support")))] pub fn system_locale() -> crate::tv::LocaleReply { match settings_reply(r#"{"keys":["localeInfo"]}"#, std::time::Duration::from_millis(600)) { Some(raw) => crate::tv::LocaleReply::Reply(raw), @@ -578,7 +579,7 @@ pub fn system_locale() -> crate::tv::LocaleReply { } } -#[cfg(any(feature = "hostsim", test, feature = "test-support"))] +#[cfg(any(test, feature = "test-support"))] pub fn system_locale() -> crate::tv::LocaleReply { crate::tv::LocaleReply::NoPlatform } @@ -597,7 +598,7 @@ pub fn system_locale() -> crate::tv::LocaleReply { /// before `Load` is ever called, for as long as the hub takes: this Load is delayed by that, and is /// failed by the pump's `NATIVE_LOAD_BUDGET` if the wait outlasts it. A hub that answers the /// registration and then stays silent costs the call's 300 ms and keeps the 400 ms default. -#[cfg(all(not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +#[cfg(not(any(test, feature = "test-support")))] pub fn sound_output() -> crate::tv::sound::Reply { use crate::tv::sound::Reply; match settings_reply(r#"{"category":"sound","keys":["soundOutput"]}"#, std::time::Duration::from_millis(300)) { @@ -606,12 +607,12 @@ pub fn sound_output() -> crate::tv::sound::Reply { } } -#[cfg(any(feature = "hostsim", test, feature = "test-support"))] +#[cfg(any(test, feature = "test-support"))] pub fn sound_output() -> crate::tv::sound::Reply { crate::tv::sound::Reply::NoPlatform } -#[cfg(all(not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +#[cfg(not(any(test, feature = "test-support")))] fn launch_home() -> bool { let payload = format!("{{\"id\":\"{HOME_APP_ID}\"}}"); let started = std::time::Instant::now(); @@ -653,7 +654,7 @@ fn launch_home() -> bool { } } -#[cfg(all(not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +#[cfg(not(any(test, feature = "test-support")))] fn minimize() { let win = WINDOW.load(std::sync::atomic::Ordering::Relaxed); if win.is_null() { @@ -666,11 +667,11 @@ fn minimize() { plx_base::eventlog::log("gohome: fallback=SDL minimize — asked, and SDL cannot say whether it took"); } -#[cfg(all(not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +#[cfg(not(any(test, feature = "test-support")))] static WINDOW: std::sync::atomic::AtomicPtr = std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()); -#[cfg(all(not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +#[cfg(not(any(test, feature = "test-support")))] extern "C" { fn SDL_MinimizeWindow(win: *mut std::os::raw::c_void); } @@ -678,21 +679,21 @@ extern "C" { /// Hand this module 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 call needs it a long way from /// there. -#[cfg(all(not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +#[cfg(not(any(test, feature = "test-support")))] pub fn bind_window(win: *mut std::os::raw::c_void) { WINDOW.store(win, std::sync::atomic::Ordering::Relaxed); } -#[cfg(any(feature = "hostsim", test, feature = "test-support"))] +#[cfg(any(test, feature = "test-support"))] pub fn bind_window(_win: *mut std::os::raw::c_void) {} /// 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. +/// worker on the television, or `NoUriMedia` in a feature-off build or a test. /// This does not select the URI playback route. -#[cfg(all(feature = "uri-transport", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +#[cfg(all(feature = "uri-transport", not(any(test, feature = "test-support"))))] pub const URI_MEDIA: &dyn crate::tv::uri::UriMedia = &ls2::uri::Transport; -#[cfg(not(all(feature = "uri-transport", not(feature = "hostsim"), not(any(test, feature = "test-support")))))] +#[cfg(not(all(feature = "uri-transport", not(any(test, feature = "test-support")))))] pub const URI_MEDIA: &dyn crate::tv::uri::UriMedia = &crate::tv::uri::NoUriMedia; /// One LS2 request/reply, on the calling thread. @@ -728,7 +729,7 @@ pub const URI_MEDIA: &dyn crate::tv::uri::UriMedia = &crate::tv::uri::NoUriMedia /// caller's log line instead of being freed. Anonymous clients do not /// collide with each other, so nothing here is serialised; a registration lives for one caller's /// use and is unregistered on drop, as both copies always did. -#[cfg(all(not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +#[cfg(not(any(test, feature = "test-support")))] pub mod ls2 { use std::ffi::{CStr, CString}; use std::os::raw::{c_char, c_int, c_void}; @@ -1409,8 +1410,8 @@ mod tests { } } - /// The probe also runs in the simulator, which installs the webOS port's table: on a Linux - /// host `/usr/lib/os-release` is the host's, and Ubuntu's `VERSION_ID` is numeric. Only a file + /// The probe also runs on a Linux host that is not a television (the unit tests, a CI runner): there + /// `/usr/lib/os-release` is the host's, and Ubuntu's `VERSION_ID` is numeric. Only a file /// that says it is webOS TV's (`ID=starfish`, on every firmware image checked from 5.5 to /// 11.2) may name a firmware. #[test] diff --git a/rust-modules/os/src/webos/caps.rs b/rust-modules/os/src/webos/caps.rs index bf6f88d53c..19ec3672d8 100644 --- a/rust-modules/os/src/webos/caps.rs +++ b/rust-modules/os/src/webos/caps.rs @@ -6,57 +6,19 @@ //! publishes into): the worker is the only publisher, and a failed or late answer cannot be //! mistaken for an affirmative capability. -use crate::devcaps::dv::{DvCapability, DvProbe, ProbeSource}; +use crate::devcaps::dv::{self, DvCapability, DvProbe, ProbeSource}; use std::sync::OnceLock; use std::time::Instant; -const KEY: &str = "tv.config.supportDolbyHDRContents"; +#[cfg(any(test, all(target_arch = "arm", target_os = "linux")))] +const KEY: &str = dv::CONFIG_KEY; static STARTED: OnceLock<()> = OnceLock::new(); -plx_base::devtrig::latched_flag!( - /// `/tmp/plxnative-dvcaps0` — force the boot's platform answer to unsupported. - pub fn forced_unsupported = "dvcaps0"; -); - -plx_base::devtrig::latched_flag!( - /// `/tmp/plxnative-dvcaps1` — force the boot's platform answer to supported. - pub fn forced_supported = "dvcaps1"; -); - -fn override_capability(zero: bool, one: bool) -> Option<(DvCapability, bool)> { - if zero { - Some((DvCapability::Unsupported, one)) - } else if one { - Some((DvCapability::Supported, false)) - } else { - None - } -} - -fn publish(probe: DvProbe, started: Instant, code: Option, detail: Option<&str>) { - crate::devcaps::dv::publish(probe); - let elapsed = started.elapsed().as_millis(); - if probe.capability == DvCapability::Unknown { - let code = code.map(|n| format!(" code={n}")).unwrap_or_default(); - let detail = detail - .filter(|s| !s.is_empty()) - .map(|s| format!(" detail={s}")) - .unwrap_or_default(); - plx_base::eventlog::log(&format!( - "webos-caps: key={KEY} answer=unknown stage={}{}{} elapsed_ms={elapsed}", - probe.reason, code, detail, - )); - } else { - plx_base::eventlog::log(&format!( - "webos-caps: key={KEY} answer={} source={} elapsed_ms={elapsed}", - probe.capability.label(), - probe.provenance(), - )); - } - // The boot worker publishes DvProbe only. Bridge captures the typed probe before present - // admission and owns the Page damage when this diagnostic fact changes. -} +// The boot worker publishes DvProbe only (`dv::publish_logged`, which every platform's probe ends +// in). Bridge captures the typed probe before present admission and owns the Page damage when this +// diagnostic fact changes. The dev triggers that force the answer (`dvcaps0`, `dvcaps1`) are +// `dv::publish_forced`'s, so a platform other than this one honours them the same way. /// Start the one boot probe. The registration and its private GLib context are both created and /// dropped on this worker; no LS2 handle crosses a thread boundary and the app never joins it. @@ -65,7 +27,7 @@ pub fn start_probe() { return; } if plx_base::task::spawn("dv-caps-probe", run_probe).is_none() { - publish( + dv::publish_logged( DvProbe { capability: DvCapability::Unknown, source: ProbeSource::Failure, @@ -80,26 +42,7 @@ pub fn start_probe() { fn run_probe() { let started = Instant::now(); - if let Some((capability, conflict)) = - override_capability(forced_unsupported(), forced_supported()) - { - if conflict { - plx_base::eventlog::log("webos-caps: dvcaps0 and dvcaps1 both armed; dvcaps0 wins"); - } - publish( - DvProbe { - capability, - source: ProbeSource::Override, - reason: if conflict { - "override-conflict" - } else { - "override" - }, - }, - started, - None, - None, - ); + if dv::publish_forced(started) { return; } run_transport(started); @@ -108,7 +51,6 @@ fn run_probe() { #[cfg(all( target_arch = "arm", target_os = "linux", - not(feature = "hostsim"), not(any(test, feature = "test-support")) ))] fn run_transport(started: Instant) { @@ -121,7 +63,7 @@ fn run_transport(started: Instant) { detail, code, }) => { - publish( + dv::publish_logged( DvProbe { capability: DvCapability::Unknown, source: ProbeSource::Failure, @@ -141,7 +83,7 @@ fn run_transport(started: Instant) { ); match reply { Ok(reply) => match parse_dv_reply(&reply) { - Ok(capability) => publish( + Ok(capability) => dv::publish_logged( platform_gate( DvProbe { capability, @@ -154,7 +96,7 @@ fn run_transport(started: Instant) { None, None, ), - Err(failure) => publish( + Err(failure) => dv::publish_logged( DvProbe { capability: DvCapability::Unknown, source: ProbeSource::Failure, @@ -165,7 +107,7 @@ fn run_transport(started: Instant) { None, ), }, - Err(super::ls2::Fail::Timeout) => publish( + Err(super::ls2::Fail::Timeout) => dv::publish_logged( DvProbe { capability: DvCapability::Unknown, source: ProbeSource::Failure, @@ -179,7 +121,7 @@ fn run_transport(started: Instant) { stage, detail, code, - }) => publish( + }) => dv::publish_logged( DvProbe { capability: DvCapability::Unknown, source: ProbeSource::Failure, @@ -195,11 +137,10 @@ fn run_transport(started: Instant) { #[cfg(not(all( target_arch = "arm", target_os = "linux", - not(feature = "hostsim"), not(any(test, feature = "test-support")) )))] fn run_transport(started: Instant) { - publish( + dv::publish_logged( DvProbe { capability: DvCapability::Unknown, source: ProbeSource::Host, @@ -214,7 +155,6 @@ fn run_transport(started: Instant) { #[cfg(all( target_arch = "arm", target_os = "linux", - not(feature = "hostsim"), not(any(test, feature = "test-support")) ))] fn reply_error_code(reply: &str) -> Option { @@ -228,7 +168,7 @@ fn reply_error_code(reply: &str) -> Option { #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg(any( test, - all(target_arch = "arm", target_os = "linux", not(feature = "hostsim")) + all(target_arch = "arm", target_os = "linux") ))] enum ProbeFailure { Json, @@ -240,13 +180,12 @@ enum ProbeFailure { #[cfg(any( test, - all(target_arch = "arm", target_os = "linux", not(feature = "hostsim")) + all(target_arch = "arm", target_os = "linux") ))] impl ProbeFailure { #[cfg(all( target_arch = "arm", target_os = "linux", - not(feature = "hostsim"), not(any(test, feature = "test-support")) ))] const fn stage(self) -> &'static str { @@ -270,7 +209,7 @@ impl ProbeFailure { /// gets. `major == 0` is an unknown version and keeps configd's answer; webOS 4+ is untouched. #[cfg(any( test, - all(target_arch = "arm", target_os = "linux", not(feature = "hostsim")) + all(target_arch = "arm", target_os = "linux") ))] fn platform_gate(probe: DvProbe, webos_major: u32) -> DvProbe { if probe.capability == DvCapability::Supported && (1..=3).contains(&webos_major) { @@ -288,7 +227,7 @@ fn platform_gate(probe: DvProbe, webos_major: u32) -> DvProbe { /// by a boolean elsewhere in the object. #[cfg(any( test, - all(target_arch = "arm", target_os = "linux", not(feature = "hostsim")) + all(target_arch = "arm", target_os = "linux") ))] fn parse_dv_reply(reply: &str) -> Result { let value: serde_json::Value = serde_json::from_str(reply).map_err(|_| ProbeFailure::Json)?; @@ -322,7 +261,7 @@ fn parse_dv_reply(reply: &str) -> Result { #[cfg(test)] mod tests { - use super::{override_capability, parse_dv_reply, platform_gate, DvCapability, ProbeFailure}; + use super::{parse_dv_reply, platform_gate, DvCapability, ProbeFailure}; use crate::devcaps::dv::{DvProbe, ProbeSource}; fn configd(capability: DvCapability) -> DvProbe { @@ -368,23 +307,6 @@ mod tests { ); } - #[test] - fn dv_caps_override_precedence() { - assert_eq!(override_capability(false, false), None); - assert_eq!( - override_capability(true, false), - Some((DvCapability::Unsupported, false)) - ); - assert_eq!( - override_capability(false, true), - Some((DvCapability::Supported, false)) - ); - assert_eq!( - override_capability(true, true), - Some((DvCapability::Unsupported, true)) - ); - } - #[test] fn dv_caps_reply_parser_real_shapes() { use DvCapability::{Supported, Unsupported}; diff --git a/rust-modules/os/src/webos/jail_repair.rs b/rust-modules/os/src/webos/jail_repair.rs index 324dc52dc4..b69f2e2cd4 100644 --- a/rust-modules/os/src/webos/jail_repair.rs +++ b/rust-modules/os/src/webos/jail_repair.rs @@ -7,12 +7,12 @@ use crate::tv::native_video::Failure; use serde_json::Value; use std::path::Path; -#[cfg(all(not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +#[cfg(not(any(test, feature = "test-support")))] use std::time::Duration; -#[cfg(all(not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +#[cfg(not(any(test, feature = "test-support")))] const EXEC_URI: &str = "luna://org.webosbrew.hbchannel.service/exec"; -#[cfg(all(not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +#[cfg(not(any(test, feature = "test-support")))] const BUDGET: Duration = Duration::from_secs(10); const OK_MARKER: &str = "PLXNATIVE_JAIL_REPAIR_OK_74"; const NOT_ROOT_MARKER: &str = "PLXNATIVE_JAIL_REPAIR_NOT_ROOT_74"; @@ -30,7 +30,7 @@ pub fn execute() -> Result<(), Failure> { const RTKMEM: &str = "/dev/rtkmem"; -#[cfg(all(not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +#[cfg(not(any(test, feature = "test-support")))] fn call_hbc(payload: &str) -> Result { let registration = super::ls2::register().map_err(|_| Failure::HbcUnavailable)?; registration @@ -41,7 +41,7 @@ fn call_hbc(payload: &str) -> Result { }) } -#[cfg(any(feature = "hostsim", test, feature = "test-support"))] +#[cfg(any(test, feature = "test-support"))] fn call_hbc(_payload: &str) -> Result { Err(Failure::HbcUnavailable) } diff --git a/rust-modules/os/src/webos/toast.rs b/rust-modules/os/src/webos/toast.rs index 53301f2918..da98a612bc 100644 --- a/rust-modules/os/src/webos/toast.rs +++ b/rust-modules/os/src/webos/toast.rs @@ -23,21 +23,19 @@ use crate::tv::toast::{Identity, Outcome, Sent}; const CREATE_TOAST: &str = "luna://com.webos.notification/createToast"; /// How long one round trip may take. Off the UI thread, so generous next to `ls2::BUDGET`. -#[cfg(all(not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +#[cfg(not(any(test, feature = "test-support")))] const BUDGET: std::time::Duration = std::time::Duration::from_secs(3); /// The `createToast` payload for `message`, attributed to `source_id`. `noaction` removes the /// launch arrow so the card is a notice, not a shortcut. Built with `serde_json` so every quote, /// backslash, newline and non-ASCII character is escaped by the same writer the rest of the crate /// trusts. -#[cfg_attr(feature = "hostsim", allow(dead_code))] // Built only for a real bus call. pub fn payload(source_id: &str, message: &str) -> String { serde_json::json!({ "sourceId": source_id, "noaction": true, "message": message }).to_string() } /// Grade the service's own reply: `returnValue: true` is acceptance; anything else is a refusal, /// carrying the `errorText` when there is one. -#[cfg_attr(feature = "hostsim", allow(dead_code))] // Graded only against a real bus reply. pub fn grade(reply: &str) -> Outcome { let value = serde_json::from_str::(reply).ok(); let field = |name: &str| value.as_ref().and_then(|v| v.get(name)); @@ -52,7 +50,7 @@ pub fn grade(reply: &str) -> Outcome { /// One attempt under the chosen [`Identity`], reply and grade both. Blocks. The port's /// `deliver_toast`: `tv::toast::send` is the door callers use. -#[cfg(any(feature = "hostsim", test, feature = "test-support"))] +#[cfg(any(test, feature = "test-support"))] pub fn deliver(_message: &str, identity: Identity) -> Sent { plx_base::eventlog::log(&format!( "toast: no LS2 bus off-device — {identity:?} call to {CREATE_TOAST} not sent" @@ -61,7 +59,7 @@ pub fn deliver(_message: &str, identity: Identity) -> Sent { } /// The on-device arm of [`deliver`] above. -#[cfg(all(not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +#[cfg(not(any(test, feature = "test-support")))] pub fn deliver(message: &str, identity: Identity) -> Sent { use super::ls2::{self, Fail}; let payload = payload(plx_base::paths::app_id(), message); diff --git a/rust-modules/os/src/webos/video_sink.rs b/rust-modules/os/src/webos/video_sink.rs index ab4776dc17..c5b9d63b9a 100644 --- a/rust-modules/os/src/webos/video_sink.rs +++ b/rust-modules/os/src/webos/video_sink.rs @@ -25,10 +25,11 @@ //! `sf_play` after `sf_destroy`). Calling any of them remains something to think about; the token //! only says *where* from. //! -//! This module is not compiled for the `hostsim` build or for this crate's own tests: the simulator's -//! own `VideoSink` is the media player's `ffi_host`. The application's test binary does carry it -//! (its dependency is compiled without `cfg(test)`), but `port.rs` installs `NoSink` there, so no -//! live code reaches an extern and the linker drops them. +//! This module is not compiled for this crate's own tests. The application's test binary does carry +//! it (its dependency is compiled without `cfg(test)`), and so does a desktop build, the simulator's +//! own `VideoSink` being the Feed backend's `ffi_host`: `port.rs` installs `NoSink` in the one, and +//! the desktop platform never names this module in the other, so no live code reaches an extern and +//! the linker drops them. use plx_base::task::MainThread; use std::ffi::CStr; use std::os::raw::{c_char, c_int, c_long}; diff --git a/rust-modules/play-feed/src/ffi_host.rs b/rust-modules/play-feed/src/ffi_host.rs index f210637efc..de971b7fd4 100644 --- a/rust-modules/play-feed/src/ffi_host.rs +++ b/rust-modules/play-feed/src/ffi_host.rs @@ -61,7 +61,7 @@ //! # How it is reached //! //! The verbs below are private; [`HostSink`] is the simulator's own `tv::sink::VideoSink`, one -//! method per verb, installed by `port.rs` for the `hostsim` build (the application builds it in +//! method per verb, held by `platform_desktop.rs`'s `SERVICES` for the `hostsim` build (the application builds it in //! `app::adapters::hostsim`, with the simulator's picture) and returned directly by the media //! tests' composition (`player::test_physical`) and the application's (`app::adapters::backends`) //! in the hostsim tests. The `*_for_test` hooks stay here, next to the statics diff --git a/rust-modules/src/app/adapters/backends.rs b/rust-modules/src/app/adapters/backends.rs index 50539a74c6..d82b91c03d 100644 --- a/rust-modules/src/app/adapters/backends.rs +++ b/rust-modules/src/app/adapters/backends.rs @@ -250,7 +250,7 @@ const START_HOOKS: StartHooks = StartHooks { play_url: plx_play_feed::playurl::playurl, }; -/// The television's (and the simulator's, whose port table holds the host sink) hooks: the +/// The television's (and the simulator's, whose platform table holds the host sink) hooks: the /// installed port's sink and the Feed's own monotonic clock. #[cfg(feature = "play-feed")] const TV_HOOKS: NativeHooks = diff --git a/rust-modules/src/app/adapters/hostsim.rs b/rust-modules/src/app/adapters/hostsim.rs index 28ca7f9d5f..7ae416a40c 100644 --- a/rust-modules/src/app/adapters/hostsim.rs +++ b/rust-modules/src/app/adapters/hostsim.rs @@ -1,4 +1,4 @@ -//! The simulator's side of the playback seam: the host sink its port table holds, and the decoded +//! The simulator's side of the playback seam: the host sink the desktop platform's `SERVICES` holds, and the decoded //! picture that sink is built with. The sink itself is the Feed backend's stand-in //! (`plx_play_feed::ffi_host`); what lives here is what only the application may name, because it //! draws: `sim_video` composites the picture under the finished UI frame with `plx_gfx`. The media @@ -10,8 +10,8 @@ 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 `Services.legacy_webos_media.sink`; a hostsim test binary of this crate reads it directly. +/// The simulator's video sink, built with the simulator's decoded picture. The desktop platform +/// (`platform_desktop.rs`) holds 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 21acced293..1645c2d47d 100644 --- a/rust-modules/src/app/boot.rs +++ b/rust-modules/src/app/boot.rs @@ -1373,8 +1373,9 @@ pub(super) fn install_pms_owned( /// Everything before the loop: SDL and the window, GL, text, the poster workers, the boot gate /// (login / token / session / picker), every dev trigger read once, and the `App` literal — /// `plex_run`'s former body up to `while app.running`, moved verbatim in phase 1b-ii. An early -/// refusal returns its `Exit` (the entry ends the process with its code, `port::plex_run`; a hosted -/// entry reports it and stays alive). +/// refusal returns its `Exit` (the entry ends the process with its code: `port::plex_run` on the +/// television, `src/bin/sim.rs` after `platform_desktop::run` on a desktop; a hosted entry reports it +/// and stays alive). /// /// `mt`, THE main-thread token, is minted once by `plex_run` itself (`plx_base::task::MainThread:: /// assume()` — that function IS the SDL main thread) and MOVES into `App.adapters.player` here, diff --git a/rust-modules/src/app/exit.rs b/rust-modules/src/app/exit.rs index 0b9ed5ec6e..a66d6f7f63 100644 --- a/rust-modules/src/app/exit.rs +++ b/rust-modules/src/app/exit.rs @@ -3,9 +3,10 @@ //! [`run_application`](super::run_application) RETURNS an [`Exit`]; it never ends the process. //! An early-boot refusal returns its code, and a played session returns after `run::shutdown` and //! the telemetry guard drop. Ending the process is the EXECUTABLE entry's: `port::plex_main` (the C -//! shim and the simulator both enter through `plex_run`, which only calls it) calls +//! shim enters through `plex_run`, which only calls it) calls //! `plx_base::process::exit_now(exit.code)` right after, in the order the app always ended in, so a -//! television behaves as before. A process that HOSTS the application never calls `exit_now` or +//! television behaves as before; the simulator's `main` calls `platform_desktop::run`, which returns the +//! code, and ends the process the same way. A process that HOSTS the application never calls `exit_now` or //! `exit`: libc's `exit` runs OpenSSL's cleanup under the detached curl workers (#1115), and a host //! would be killed under its own runtime. No exit a hosted process can reach remains in the tree: //! the graphics boot returns a [`GfxFault`](plx_gfx::gfx::GfxFault) ([`Exit::from`]) where it used diff --git a/rust-modules/src/app/mod.rs b/rust-modules/src/app/mod.rs index 78370d23e3..7210ad9e3d 100644 --- a/rust-modules/src/app/mod.rs +++ b/rust-modules/src/app/mod.rs @@ -3,7 +3,8 @@ //! the buffer-feed pump orchestration, and the dev triggers. The C boot shim //! (main.c) sets up the log and fallback crash tracer, calls the Rust image-marker and native-spool //! entries when required, then calls `plex_run` (port.rs), which hands over to `run_application` -//! and, when it returns its `Exit` (`exit.rs`), ends the process. +//! and, when it returns its `Exit` (`exit.rs`), ends the process. The desktop executable +//! (`src/bin/sim.rs`) enters through `platform_desktop::run` instead and ends the process itself. //! The only application subsystems left in C are the starfish.c C++ Feed seam and the video_plane.c //! ACB / exported-window display binding (the engine itself is Rust: plx_media::player). #![allow(non_upper_case_globals)] @@ -573,7 +574,8 @@ fn pre_boot_diagnostics() -> plx_telemetry::telemetry::native::Guard { /// reason as [`pre_boot_diagnostics`] (D4): `run_application` stays a ten-line skeleton naming only /// the THREE real phases (pre-boot diagnostics, `boot`, this), never the steps inside any one of them. /// -/// It RETURNS how the session ended; ending the process is the executable entry's (`port::plex_run`). +/// It RETURNS how the session ended; ending the process is the executable entry's (`port::plex_run` on +/// the television, `src/bin/sim.rs` after `platform_desktop::run` on a desktop). /// The `App` is leaked by the caller (`exit::entry`), so the last thing this does is the one `Drop` /// that persists something. unsafe fn run_and_shutdown(app: &mut App) -> Exit { @@ -660,7 +662,8 @@ fn enter_application(platform: &'static platform::Platform, pms_host: *const c_c 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. + // Ending the process is the entry's (`port::plex_run` on the television, `src/bin/sim.rs` after + // `platform_desktop::run` on a desktop); a hosted entry never does. 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/bin/sim.rs b/rust-modules/src/bin/sim.rs index e1b1400045..4b7066cd1d 100644 --- a/rust-modules/src/bin/sim.rs +++ b/rust-modules/src/bin/sim.rs @@ -36,9 +36,8 @@ //! PLXNATIVE_RUNTIME_DIR this instance's trigger/FIFO/log root //! PLXNATIVE_APP_DIR where appfont*.ttf and the icons live (repo `pkg/`) -use plxnative_modules::port::plex_run; +use plxnative_modules::platform_desktop; use std::ffi::CString; -use std::os::raw::c_int; /// Defaults chosen to fail loudly rather than silently talk to the wrong thing. const DEFAULT_PORT: u16 = 32400; @@ -97,7 +96,7 @@ fn main() { // No host is not an error — it is what a person who was SENT this app has. The boot host is // only ever consulted by the two paths that already hold credentials (the stored session and - // the harness's injected token); with neither, `plex_run` goes to QR sign-in and plex.tv's + // the harness's injected token); with neither, the application goes to QR sign-in and plex.tv's // `/api/v2/resources` supplies the address, exactly as on a television out of the box. // // The dev loop keeps its loud failure where it belongs: the Makefile's `SIM_PRE` refuses to @@ -145,9 +144,9 @@ fn main() { plx_base::process::exit_now(2) }); - // `as c_int` directly — an intermediate i16 would wrap every port above 32767. - // `plex_run` ends the process itself through `plx_base::process::exit_now` (no `atexit` - // handlers under live workers, #1115); the call is typed `c_int` only for the C shim. - let rc = plex_run(c_host.as_ptr(), port as c_int); + // The desktop platform's entry returns the status the application ended with; ending the + // process is this executable's, through `plx_base::process::exit_now` (no `atexit` handlers + // under live workers, #1115). + let rc = platform_desktop::run(&c_host, port); plx_base::process::exit_now(rc) } diff --git a/rust-modules/src/lib.rs b/rust-modules/src/lib.rs index 6d758077e6..f1fe806ea1 100644 --- a/rust-modules/src/lib.rs +++ b/rust-modules/src/lib.rs @@ -72,17 +72,17 @@ pub fn sim_events_log() -> std::path::PathBuf { plx_base::eventlog::events_log() } -/// The port holds `plex_run`, the C entry the simulator binary calls too. It is reached by path -/// (`plxnative_modules::port::plex_run`) so the SAME entry the C shim calls is the one called, with -/// the compiler checking the signature. It previously re-declared `plex_run` in its own `extern "C"` -/// block, which meant the one binary whose whole premise is "cannot drift from the shipped boot -/// path" was the one place a signature change would become a silent ABI mismatch instead of a -/// compile error. There is deliberately no `pub use` here: a re-export would be a reference from -/// the crate root into the port. -#[cfg(feature = "hostsim")] -pub mod port; -#[cfg(not(feature = "hostsim"))] +/// The webOS port: `plex_run`, the C entry `src/main.c` calls, and the two tables it hands the +/// application. Every build compiles it, the desktop ones included, and a desktop executable never +/// reaches it. mod port; +/// The desktop platform, the simulator's and the macOS app's own: its tables and its entry, which +/// `src/bin/sim.rs` calls by path (`plxnative_modules::platform_desktop::run`) because that binary +/// is a separate crate. It never names the webOS port, so the television's code stays unreferenced +/// in its executable. There is deliberately no `pub use` here: a re-export would be a reference from +/// the crate root into the platform. +#[cfg(feature = "hostsim")] +pub mod platform_desktop; #[cfg(feature = "hostsim")] pub use app::synthetic_home_initial; diff --git a/rust-modules/src/platform_desktop.rs b/rust-modules/src/platform_desktop.rs new file mode 100644 index 0000000000..b4cb8f580e --- /dev/null +++ b/rust-modules/src/platform_desktop.rs @@ -0,0 +1,157 @@ +//! The desktop platform: what `plxnative-sim` and the macOS app hand the application. +//! +//! A desktop has no television's services, so this is a platform in its own right and not the webOS +//! port with its answers faked: [`PLATFORM`] states every hook the application reads, from the +//! shared `NONE` groups of `plx_os::tv` wherever a host has nothing to say (the key manager, the +//! settings service, the device files, the URI media pipe) and with its own body where it has +//! something to do: +//! +//! - the capability probe publishes the host's answer, and honours the same `dvcaps0` / `dvcaps1` +//! dev triggers the television's does (`devcaps::dv`, which both probes end in); +//! - the root press is a log line, the one thing a Mac window has to say about a launcher that does +//! not exist; +//! - the system toast says it was not sent; +//! - the video sink is the Feed backend's host sink (`HOST_SINK`) when the build has one, else the +//! refusing `NoSink`. +//! +//! The shell and the frame probe are plain no-ops: SDL owns the window and its event loop, there is +//! no compositor to hint and no bus to pump. The secure store is `SecureHooks::NONE`: nothing seals, +//! so a session is the 0600 plaintext file the session layer writes itself, which the simulator's +//! harnesses plant and read. +//! +//! This module never names `port`, `system`, `webos` or `keymanager`, so a desktop executable +//! references none of the television's code. It still COMPILES it (the television arms of those +//! files have no `hostsim` gate any more), and the linker drops what nothing reaches: a build that +//! made one of them reachable would fail to link for want of libwayland, glib or luna-service2, on +//! a Mac and on Linux alike. `simulators.yml` links the shapes the simulator ships in to guard that +//! until the platform crates split (`docs/platform-ports.md`, W7). +use crate::app::platform::{FrameProbe, Platform, Shell}; +use plx_os::devcaps::dv::{self, DvCapability, DvProbe, ProbeSource}; +use plx_os::tv::toast::{Identity, Outcome, Sent}; +use plx_os::tv::{IdentityHooks, LegacyWebosMedia, SecureHooks, Services, SystemHooks}; +use std::ffi::CStr; +use std::os::raw::{c_int, c_void}; + +/// The Feed backend's host sink, built with the simulator's decoded picture. +#[cfg(feature = "play-feed")] +const SINK: &dyn plx_os::tv::sink::VideoSink = &crate::app::adapters::hostsim::HOST_SINK; +/// A build without the Feed backend has no picture to show: every verb is refused. +#[cfg(not(feature = "play-feed"))] +const SINK: &dyn plx_os::tv::sink::VideoSink = &plx_os::tv::sink::NoSink; + +/// The display binding the player's plane boot resolves: the same sink, so the plane is the host's. +const DISPLAY: &dyn plx_os::tv::sink::DisplaySink = SINK; + +/// What the lower layers read from the desktop platform. Every hook is stated, as `tv` requires: a +/// hook a host has nothing to say for is the shared `NONE` group's own, named, so a hook added to a +/// group is a compile error here until this platform states it. +static SERVICES: Services = Services { + identity: IdentityHooks { + probe_device: IdentityHooks::NONE.probe_device, + start_capability_probe, + repair_native_video: IdentityHooks::NONE.repair_native_video, + device_files: IdentityHooks::NONE.device_files, + system_locale: IdentityHooks::NONE.system_locale, + sound_output: IdentityHooks::NONE.sound_output, + }, + secure: SecureHooks::NONE, + system: SystemHooks { go_home, poll_home: SystemHooks::NONE.poll_home, deliver_toast }, + legacy_webos_media: LegacyWebosMedia { + sink: SINK, + display_sink: DISPLAY, + uri_media: LegacyWebosMedia::NONE.uri_media, + }, +}; + +/// The boot capability probe: a host has no configd to ask, so it answers `unknown`, from the host, +/// unless a dev trigger forces the answer. Synchronous, with no worker: the answer needs no bus, +/// and the app reads it only after boot. +fn start_capability_probe() { + let started = std::time::Instant::now(); + if dv::publish_forced(started) { + return; + } + dv::publish_logged( + DvProbe { capability: DvCapability::Unknown, source: ProbeSource::Host, reason: "host" }, + started, + None, + None, + ); +} + +/// The root press: there is no launcher to hand a desktop window to, so the screen does not change +/// and the press is a log line, the one the simulator's skill (`ui-sim`) tells a reader to look for. +fn go_home() { + plx_base::eventlog::log("gohome: request mode=auto"); + plx_base::eventlog::log( + "gohome: no LS2 bus off-device — the root press would launch com.webos.app.home on a television", + ); +} + +/// The system toast: a host has no notification service this app may call, so nothing is sent. +fn deliver_toast(_message: &str, identity: Identity) -> Sent { + plx_base::eventlog::log(&format!("toast: no system notifications on this host — {identity:?} toast not sent")); + Sent { reply: None, outcome: Outcome::NoBus } +} + +/// The desktop shell: SDL owns the window and its event loop, so nothing is bound, grabbed, hinted +/// or pumped, and no surface is ever held. +struct DesktopShell; + +impl Shell for DesktopShell { + 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 desktop frame probe: always unarmed, there is no compositor callback to clock. +struct DesktopProbe; + +impl FrameProbe for DesktopProbe { + fn request(&self) {} + fn prepare_begin(&self) {} + fn prepare_end(&self) {} + fn waiting(&self) {} + fn acquired(&self) {} + fn fields(&self) -> String { + String::new() + } +} + +/// The desktop platform: what [`run`] hands `app::run_application`. +static PLATFORM: Platform = Platform::new(&SERVICES, &DesktopShell, &DesktopProbe); + +/// The desktop entry: boot the application on [`PLATFORM`] and return the status it ended with. +/// Ending the process is the executable's (`src/bin/sim.rs`), which owns it, like the television's +/// entry does (`port::plex_main`): a process that hosts the application never does. +/// +/// Nothing is logged before `run_application`: a boot it refuses early must leave the log as the +/// harnesses expect (`tests/replay_fixtures.py`). +pub fn run(pms_host: &CStr, pms_port: u16) -> c_int { + crate::app::run_application(&PLATFORM, pms_host.as_ptr(), c_int::from(pms_port)).code +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 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 + /// the simulator both must be the host sink, never `NoSink`: a boot that read `NoSink` would + /// report no plane to every backend and nothing in a simulator run would say so. + #[cfg(feature = "play-feed")] + #[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::<()>(); + 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(media.sink).cast::<()>(), host, "so is the video sink"); + } +} diff --git a/rust-modules/src/port.rs b/rust-modules/src/port.rs index 6214eecef0..7f717ca525 100644 --- a/rust-modules/src/port.rs +++ b/rust-modules/src/port.rs @@ -3,25 +3,21 @@ //! `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 runs on these same tables and behaves as it always did. +//! video sink together. The simulator and the macOS app are not on these tables: they are their own +//! platform (`platform_desktop`), which never names this module, so a desktop build compiles the +//! television's code and the linker drops it. use crate::app::platform::{FrameProbe, Platform, Shell}; use std::os::raw::{c_char, c_int, c_void}; -#[cfg(all(not(feature = "hostsim"), not(test), feature = "play-feed"))] +#[cfg(all(not(test), feature = "play-feed"))] const SINK: &dyn plx_os::tv::sink::VideoSink = &plx_os::webos::video_sink::StarfishSink; -#[cfg(all(feature = "hostsim", feature = "play-feed"))] -const SINK: &dyn plx_os::tv::sink::VideoSink = &crate::app::adapters::hostsim::HOST_SINK; -#[cfg(any( - all(feature = "hostsim", not(feature = "play-feed")), - all(not(feature = "hostsim"), any(test, not(feature = "play-feed"))), -))] +#[cfg(any(test, not(feature = "play-feed")))] const SINK: &dyn plx_os::tv::sink::VideoSink = &plx_os::tv::sink::NoSink; // URI-only native builds retain the display vtable without the packet-feed vtable. -#[cfg(all(not(feature = "hostsim"), not(test)))] +#[cfg(not(test))] const DISPLAY: &dyn plx_os::tv::sink::DisplaySink = &plx_os::webos::video_sink::StarfishSink; -#[cfg(any(feature = "hostsim", test))] +#[cfg(test)] const DISPLAY: &dyn plx_os::tv::sink::DisplaySink = SINK; /// What the lower layers read: the webOS identity, key manager, Home key and toast, and the native @@ -109,8 +105,8 @@ impl FrameProbe for WebosProbe { /// for the lower layers and keeps it for the loop. 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. +/// The C shim's entry (`src/main.c`). The `-> c_int` is only the C signature: `plex_main` never +/// returns, so neither does this. #[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) @@ -152,21 +148,3 @@ pub unsafe extern "C" fn plx_launch_args(json: *const c_char) { let raw = unsafe { std::ffi::CStr::from_ptr(json) }.to_string_lossy(); plx_os::tv::launch::offer(&raw); } - -#[cfg(all(test, feature = "hostsim", feature = "play-feed"))] -mod tests { - 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 - /// the simulator both must be the host sink, never `NoSink`: a boot that read `NoSink` would - /// report no plane to every backend and nothing in a simulator run would say so. - #[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::<()>(); - 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(media.sink).cast::<()>(), host, "so is the video sink"); - } -} diff --git a/rust-modules/src/system.rs b/rust-modules/src/system.rs index 78fccd594e..21c87081bc 100644 --- a/rust-modules/src/system.rs +++ b/rust-modules/src/system.rs @@ -18,8 +18,6 @@ const GL_STENCIL_BITS: c_uint = 0x0D57; // SDL_SysWMinfo layout (32-bit): version u8[3]@0, subsystem int@4, info union@8 extern "C" { - // the wayland grab is `cfg(not(hostsim))` — desktop SDL has no webOS surface to reach for - #[cfg_attr(feature = "hostsim", allow(dead_code))] fn SDL_GetWindowWMInfo(window: *mut c_void, info: *mut c_void) -> c_int; /// Fills `SDL_version` — three `Uint8`, major/minor/patch. fn SDL_GetVersion(ver: *mut u8); @@ -28,10 +26,9 @@ extern "C" { } // The three symbols that exist only on a television: wayland's proxy marshaller and glib's main -// context. The desktop simulator links neither — SDL owns its own event loop there, and there is -// no luna bus to pump — so they are declared apart rather than in the block above, which would -// otherwise fail the host link. -#[cfg(not(feature = "hostsim"))] +// context. A host build links neither: the desktop platform (`platform_desktop`) brings its own +// shell, so nothing it runs reaches this file, and the linker drops the television code that does. +// They are declared apart rather than in the block above, which every host build links against. extern "C" { fn wl_proxy_marshal(proxy: *mut c_void, opcode: c_uint, ...); fn g_main_context_pending(ctx: *mut c_void) -> c_int; @@ -50,7 +47,6 @@ static mut G_WL_DISPLAY: *mut c_void = std::ptr::null_mut(); /// crumb does not fire. So a `surface_changed` crumb proves a replacement, but a missing crumb /// does not prove the surface was kept. Comparing `wl_proxy_get_id` would not help, because /// Wayland recycles object ids through a free list. -#[cfg(any(not(feature = "hostsim"), test))] static G_WL_SURFACE_SEEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); pub(crate) fn clear_opaque_region() { @@ -63,15 +59,12 @@ pub(crate) fn clear_opaque_region() { // commit is left to SDL_GL_SwapWindow (a bare commit here presents a // null-buffer surface and disrupts the slaved video plane). // - // Nothing to do on the simulator: there is no video plane underneath to show through, so - // a non-opaque surface would buy a desktop compositor nothing but per-frame blending. - // - // …and nothing to LINK against under `cargo test`. Since phase 9 this is reached through + // Nothing to LINK against under `cargo test`. Since phase 9 this is reached through // `Rig::clear_opaque_region` (`app/bridge.rs`), which the host suite exercises, where // before it was reachable only from `plex_run` and the dead-strip hid the missing // `libwayland-client`. The guard below is `G_WL_SURFACE`, which is null in a test, so // nothing is skipped that would have run. - #[cfg(all(not(feature = "hostsim"), not(test)))] + #[cfg(not(test))] wl_proxy_marshal(surface, 4, std::ptr::null_mut::()); } } @@ -88,10 +81,7 @@ pub(crate) fn sys_release_wayland() -> bool { let had_surface = !G_WL_SURFACE.is_null(); G_WL_SURFACE = std::ptr::null_mut(); G_WL_DISPLAY = std::ptr::null_mut(); - #[cfg(not(feature = "hostsim"))] - { - G_OPAQUE_SENT = -1; - } + G_OPAQUE_SENT = -1; if had_surface { log("wm: released borrowed Wayland handles"); } @@ -100,11 +90,7 @@ pub(crate) fn sys_release_wayland() -> bool { } /// Service the glib main context that luna-service2 replies arrive on. -/// -/// A no-op on the simulator: glib is not linked and there is no luna bus to pump, so the loop -/// simply has nothing to service. Every caller stays unchanged. pub(crate) fn ls2_pump() { - #[cfg(not(feature = "hostsim"))] unsafe { let mut guard = 8; while guard > 0 && g_main_context_pending(std::ptr::null_mut()) != 0 { @@ -151,9 +137,9 @@ pub(crate) fn sys_grab_wayland(winp: *mut c_void) { let mut sbits: c_int = -1; glGetIntegerv(GL_ALPHA_BITS, &mut abits); glGetIntegerv(GL_RED_BITS, &mut rbits); - // Deprecated in a desktop CORE profile (the simulator), where they leave the value alone - // and raise `GL_INVALID_ENUM` — harmless and once, at boot, and the SDL attributes above - // answer the same question portably. On the television's ES2 context both are legal. + // Deprecated in a desktop CORE profile, where they would leave the value alone and raise + // `GL_INVALID_ENUM`; the SDL attributes above answer the same question portably. On the + // television's ES2 context, the only one this runs on, both are legal. glGetIntegerv(GL_DEPTH_BITS, &mut dbits); glGetIntegerv(GL_STENCIL_BITS, &mut sbits); // `depth=`/`stencil=` are here to be READ: `app.rs` asks for zero of each because nothing @@ -164,14 +150,9 @@ pub(crate) fn sys_grab_wayland(winp: *mut c_void) { "FB bits: alpha={abits} red={rbits} depth={dbits} stencil={sbits} \ (config alpha={a} depth={d} stencil={s})" )); - // The Wayland query is webOS-only. Desktop SDL reports a different backend with a - // different union layout, and has no hardware video plane needing this request. // update_wayland_info reads unaligned because the oversized byte buffer has no pointer // alignment guarantee, and rejects any non-Wayland subsystem before reading the union. - #[cfg(not(feature = "hostsim"))] update_wayland_info(SDL_GetWindowWMInfo(winp, wmbuf.as_mut_ptr() as *mut c_void), &wmbuf); - #[cfg(feature = "hostsim")] - let _ = winp; let subsystem = i32::from_ne_bytes([wmbuf[4], wmbuf[5], wmbuf[6], wmbuf[7]]); let (surf, disp) = (G_WL_SURFACE, G_WL_DISPLAY); // The version bytes are still in wmbuf[0..3] — SDL_GetWindowWMInfo validates them and @@ -183,7 +164,7 @@ pub(crate) fn sys_grab_wayland(winp: *mut c_void) { // Loud, because the consequence is a black screen with working audio and nothing else in // the log would say why. SDL_SYSWM_WAYLAND is 6 in SDL2's enum; anything else here means // we did not get a surface and the video plane will stay hidden under an opaque UI. - if surf.is_null() && !cfg!(feature = "hostsim") { + if surf.is_null() { log( "wm: NO wl_surface — the UI plane cannot be made transparent, so video will \ decode invisibly beneath it. Check the SDL_SysWMinfo version handshake.", @@ -229,32 +210,22 @@ use plx_base::eventlog::log; /// `wl_registry.bind` / `wl_compositor.create_region` / `wl_region.add` — opcodes from /// `wayland-client-protocol.h` (`WL_REGISTRY_BIND 0`, `WL_COMPOSITOR_CREATE_REGION 1`, /// `WL_REGION_ADD 1`), beside `WL_SURFACE_SET_OPAQUE_REGION 4` which this file already used. -#[cfg(not(feature = "hostsim"))] const WL_REGISTRY_BIND: c_uint = 0; -#[cfg(not(feature = "hostsim"))] const WL_DISPLAY_GET_REGISTRY: c_uint = 1; -#[cfg(not(feature = "hostsim"))] const WL_COMPOSITOR_CREATE_REGION: c_uint = 1; -#[cfg(not(feature = "hostsim"))] const WL_REGION_ADD: c_uint = 1; -#[cfg(not(feature = "hostsim"))] const WL_SURFACE_SET_OPAQUE_REGION: c_uint = 4; /// The full-surface `wl_region`, created once at boot. Never per frame — a region is a server /// object and allocating one every present would be protocol traffic on the frame path. -#[cfg(not(feature = "hostsim"))] static mut G_WL_REGION: *mut c_void = std::ptr::null_mut(); /// What we last told the compositor: `1` = the full region, `0` = NULL, `-1` = nothing yet. -#[cfg(not(feature = "hostsim"))] static mut G_OPAQUE_SENT: i8 = -1; /// Set only by [`opaque_region_init`], and only when the trigger armed AND a region was built. -#[cfg(not(feature = "hostsim"))] static mut G_OPAQUE_ENABLED: bool = false; /// Scratch for the registry callback: the `wl_compositor` proxy it binds. -#[cfg(not(feature = "hostsim"))] static mut G_WL_COMPOSITOR: *mut c_void = std::ptr::null_mut(); -#[cfg(not(feature = "hostsim"))] #[repr(C)] struct RegistryListener { global: unsafe extern "C" fn(*mut c_void, *mut c_void, c_uint, *const std::ffi::c_char, c_uint), @@ -263,17 +234,14 @@ struct RegistryListener { /// A libwayland symbol from the process's own scope. `libwayland-client` is linked normally, so it /// is already mapped; this only avoids naming these particular symbols in `DT_NEEDED`. -#[cfg(not(feature = "hostsim"))] fn wl_sym(name: &str) -> Option<*mut c_void> { plx_base::dynlib::Handle::self_handle() .sym(name) .filter(|p| !p.is_null()) } -#[cfg(not(feature = "hostsim"))] unsafe extern "C" fn on_global_remove(_data: *mut c_void, _reg: *mut c_void, _name: c_uint) {} -#[cfg(not(feature = "hostsim"))] unsafe extern "C" fn on_global( _data: *mut c_void, registry: *mut c_void, @@ -324,7 +292,6 @@ unsafe extern "C" fn on_global( /// Build the full-surface opaque region, once, at boot. No-op unless `/tmp/plxnative-opaque` is /// armed; returns without touching the surface's current (NULL) region either way. -#[cfg(not(feature = "hostsim"))] pub(crate) fn opaque_region_init() { if !plx_base::devtrig::flag("opaque") { return; @@ -420,15 +387,11 @@ pub(crate) fn opaque_region_init() { )); } -#[cfg(feature = "hostsim")] -pub(crate) fn opaque_region_init() {} - /// Assert the opaque region appropriate to this route, if the experiment is armed. /// /// A no-op — one read of a `static` and a return — whenever `/tmp/plxnative-opaque` is absent, /// which is what keeps the default path byte-identical. Only sends a request when the answer /// CHANGES, because the opaque region is sticky server-side. -#[cfg(not(feature = "hostsim"))] pub(crate) fn opaque_route(player: bool) { unsafe { if !G_OPAQUE_ENABLED { @@ -464,11 +427,6 @@ pub(crate) fn opaque_route(player: bool) { } } -/// Nothing to declare opaque on a desktop: there is no video plane underneath and no LG compositor -/// to hint. The simulator keeps the same call site rather than growing a `cfg` at it. -#[cfg(feature = "hostsim")] -pub(crate) fn opaque_route(_player: bool) {} - // ---- The COMPOSITOR FRAME-CALLBACK PROBE (`/tmp/plxnative-framecb`) ----------------------------- // // A present's wait for a free back buffer is paid inside the frame's first framebuffer-0 command @@ -496,9 +454,9 @@ pub(crate) fn opaque_route(_player: bool) {} // from the process's own scope, ONCE (`frame_syms`, on the first armed present, before the swap // stretch is marked), so the probe adds no symbol to the link and its lookups are not charged to // the `s` stretch. Unarmed it is one latched bool per presented frame. The whole probe is -// compiled only with `devtriggers` (and not in the simulator); the shipping build has the empty +// compiled only with `devtriggers`; the shipping build has the empty // stubs at the end of this section. -#[cfg(all(not(feature = "hostsim"), feature = "devtriggers"))] +#[cfg(feature = "devtriggers")] plx_base::devtrig::latched_flag!( /// `/tmp/plxnative-framecb` — see the section comment above. pub(crate) fn frame_probe_armed = "framecb"; @@ -506,12 +464,12 @@ plx_base::devtrig::latched_flag!( /// `(frame seq, compositor stamp ms, our CLOCK_MONOTONIC µs at dispatch)` for every `done` that /// arrived since the last [`frame_probe_fields`]. -#[cfg(all(not(feature = "hostsim"), feature = "devtriggers"))] +#[cfg(feature = "devtriggers")] static FRAME_DONE: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); -#[cfg(all(not(feature = "hostsim"), feature = "devtriggers"))] +#[cfg(feature = "devtriggers")] static FRAME_SEQ: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); -#[cfg(all(not(feature = "hostsim"), feature = "devtriggers"))] +#[cfg(feature = "devtriggers")] fn mono_us() -> u64 { let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 }; // SAFETY: a plain clock read into a local. @@ -520,7 +478,7 @@ fn mono_us() -> u64 { } /// What the frame thread has cost so far, read at each boundary of a frame's present. -#[cfg(all(not(feature = "hostsim"), feature = "devtriggers"))] +#[cfg(feature = "devtriggers")] #[derive(Clone, Copy, Default)] struct ThreadCost { /// `CLOCK_MONOTONIC`, µs. @@ -536,7 +494,7 @@ struct ThreadCost { preempted: u64, } -#[cfg(all(not(feature = "hostsim"), feature = "devtriggers"))] +#[cfg(feature = "devtriggers")] impl ThreadCost { fn now() -> Self { let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 }; @@ -590,10 +548,10 @@ impl ThreadCost { /// This frame's boundaries: `[before the first framebuffer command, back buffer acquired, before /// the swap]`. Frame-thread only; a `Mutex` because it is a `static`. -#[cfg(all(not(feature = "hostsim"), feature = "devtriggers"))] +#[cfg(feature = "devtriggers")] static FRAME_COST: std::sync::Mutex<[Option; 3]> = std::sync::Mutex::new([None; 3]); -#[cfg(all(not(feature = "hostsim"), feature = "devtriggers"))] +#[cfg(feature = "devtriggers")] fn frame_probe_mark(slot: usize) { if !frame_probe_armed() { return; @@ -605,11 +563,11 @@ fn frame_probe_mark(slot: usize) { /// `prepare_window`'s boundaries: `[before, after]`. Independent of [`FRAME_COST`]: it is marked on /// frames that never reach the wait. Frame-thread only. -#[cfg(all(not(feature = "hostsim"), feature = "devtriggers"))] +#[cfg(feature = "devtriggers")] static PREPARE_COST: std::sync::Mutex<[Option; 2]> = std::sync::Mutex::new([None; 2]); /// `prepare_window` is next. Starts the frame's `p` stretch, dropping any earlier frame's marks. -#[cfg(all(not(feature = "hostsim"), feature = "devtriggers"))] +#[cfg(feature = "devtriggers")] pub(crate) fn frame_probe_prepare_begin() { if !frame_probe_armed() { return; @@ -620,7 +578,7 @@ pub(crate) fn frame_probe_prepare_begin() { } /// `prepare_window` has returned: closes the frame's `p` stretch. -#[cfg(all(not(feature = "hostsim"), feature = "devtriggers"))] +#[cfg(feature = "devtriggers")] pub(crate) fn frame_probe_prepare_end() { if !frame_probe_armed() { return; @@ -631,19 +589,19 @@ pub(crate) fn frame_probe_prepare_end() { } /// The frame's first framebuffer command is next: the wait for a back buffer starts here. -#[cfg(all(not(feature = "hostsim"), feature = "devtriggers"))] +#[cfg(feature = "devtriggers")] pub(crate) fn frame_probe_waiting() { frame_probe_mark(0); } /// The frame's first framebuffer command has returned: the back buffer is acquired. -#[cfg(all(not(feature = "hostsim"), feature = "devtriggers"))] +#[cfg(feature = "devtriggers")] pub(crate) fn frame_probe_acquired() { frame_probe_mark(1); } /// The libwayland entry points the probe calls, as addresses (a raw pointer is not `Sync`). -#[cfg(all(not(feature = "hostsim"), feature = "devtriggers"))] +#[cfg(feature = "devtriggers")] struct FrameSyms { ctor: usize, add_listener: usize, @@ -654,7 +612,7 @@ struct FrameSyms { /// Resolved once. `None` when any of the three request symbols is missing, which makes the probe a /// silent no-op. -#[cfg(all(not(feature = "hostsim"), feature = "devtriggers"))] +#[cfg(feature = "devtriggers")] fn frame_syms() -> Option<&'static FrameSyms> { static SYMS: std::sync::OnceLock> = std::sync::OnceLock::new(); SYMS.get_or_init(|| { @@ -668,7 +626,7 @@ fn frame_syms() -> Option<&'static FrameSyms> { .as_ref() } -#[cfg(all(not(feature = "hostsim"), feature = "devtriggers"))] +#[cfg(feature = "devtriggers")] unsafe extern "C" fn on_frame_done(data: *mut c_void, callback: *mut c_void, time: c_uint) { if let Ok(mut done) = FRAME_DONE.lock() { done.push((data as usize as u32, time, mono_us())); @@ -681,7 +639,7 @@ unsafe extern "C" fn on_frame_done(data: *mut c_void, callback: *mut c_void, tim } /// Ask for this frame's callback. Call on a PRESENTING frame, before the swap that commits it. -#[cfg(all(not(feature = "hostsim"), feature = "devtriggers"))] +#[cfg(feature = "devtriggers")] pub(crate) fn frame_probe_request() { if !frame_probe_armed() { return; @@ -722,7 +680,7 @@ pub(crate) fn frame_probe_request() { /// the section comment, then `p=`/`psw=` for the frame's `prepare_window` (independent of them: it /// prints whenever that frame took both of its marks, wait or no wait), then `cb=::` for each callback that /// arrived since the previous line. `""` unarmed. -#[cfg(all(not(feature = "hostsim"), feature = "devtriggers"))] +#[cfg(feature = "devtriggers")] pub(crate) fn frame_probe_fields() -> String { if !frame_probe_armed() { return String::new(); @@ -758,24 +716,23 @@ pub(crate) fn frame_probe_fields() -> String { out } -#[cfg(any(feature = "hostsim", not(feature = "devtriggers")))] +#[cfg(not(feature = "devtriggers"))] pub(crate) fn frame_probe_request() {} -#[cfg(any(feature = "hostsim", not(feature = "devtriggers")))] +#[cfg(not(feature = "devtriggers"))] pub(crate) fn frame_probe_prepare_begin() {} -#[cfg(any(feature = "hostsim", not(feature = "devtriggers")))] +#[cfg(not(feature = "devtriggers"))] pub(crate) fn frame_probe_prepare_end() {} -#[cfg(any(feature = "hostsim", not(feature = "devtriggers")))] +#[cfg(not(feature = "devtriggers"))] pub(crate) fn frame_probe_waiting() {} -#[cfg(any(feature = "hostsim", not(feature = "devtriggers")))] +#[cfg(not(feature = "devtriggers"))] pub(crate) fn frame_probe_acquired() {} -#[cfg(any(feature = "hostsim", not(feature = "devtriggers")))] +#[cfg(not(feature = "devtriggers"))] pub(crate) fn frame_probe_fields() -> String { String::new() } // Publish SDL's borrowed handles. Kept separate from the native query so failed queries can // be exercised without loading the television's SDL or marshalling a fake proxy. -#[cfg(any(not(feature = "hostsim"), test))] unsafe fn update_wayland_info(ok: c_int, info: &[u8; 512]) { sys_release_wayland(); let subsystem = i32::from_ne_bytes(info[4..8].try_into().unwrap()); @@ -846,11 +803,9 @@ mod wayland_tests { pointers.add(1).write_unaligned(surface_ptr); update_wayland_info(1, &info); let acquired = (G_WL_DISPLAY, G_WL_SURFACE); - #[cfg(not(feature = "hostsim"))] - { G_OPAQUE_SENT = 1; } + G_OPAQUE_SENT = 1; assert!(sys_release_wayland(), "a held surface answers true"); assert!(!sys_release_wayland(), "WILL + DID background is idempotent: nothing left to release"); - #[cfg(not(feature = "hostsim"))] { let sent = G_OPAQUE_SENT; assert_eq!(sent, -1); } let released = (G_WL_DISPLAY, G_WL_SURFACE); clear_opaque_region(); // No native marshal can run after revocation. From 6f4f12647b13333b1d937bac00d9f933df3e15f7 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 16:42:05 +0300 Subject: [PATCH 10/26] The platform states where the account's records live: tv::Services.storage (#1488) Part of step W8a of the platform plan (discussion #1460). The platform now states where the account's records live, instead of the build's CPU and OS deciding it. The session record, the install's preferences and the consent record have two homes. On a webOS television the LS2/DB8 storage helper owns them; everywhere else they are files. `plex` and `telemetry` chose between the two with `all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))`. That predicate means "32-bit ARM Linux", not "a television". A Tizen ARM build would select the helper with none behind it. ## What changes - `tv::Services` gains a fifth group, `storage: StorageHooks { authority }`, in the new `os/src/tv/authority.rs`: - `Authority::Helper` is stated by webOS (`port.rs`). The helper is the canonical store there. The app still keeps three kinds of its own files on webOS, as before: the legacy migration inputs, the marked session fallback it writes during a helper outage, and the install preferences `clear_for_erase` saves when a helper sign-out clear is not durable. The module doc names only the first two; the stacked `plex` PR completes its list. - The authority does not decide the session record alone. `secure::mode()`'s `MemoryOnly` comes first, and under it nothing is written, whatever the authority says. Tizen starts in `MemoryOnly` (W9). - `Authority::Files` is `StorageHooks::NONE`, stated by the desktop platform and `Services::HOST_TEST`. It is also what an uninstalled process reads, like every other group's host-test answer. - `tv::authority::authority()` reads the installed table. - There is no test override. The layers that will read the value take it as a parameter, so a test passes whichever authority it grades. - `storage::client::install_activator` (the helper's wake-up, installed by `port::plex_main`) belongs in this group later. It moves with the `os` part of W8a after W7b, and the module doc says so. - `docs/module-layers.md` and `docs/platform-ports.md` name the new group. Nothing reads the value yet. Two PRs stacked on this one re-key the fences to it: `plex` (21 lines) and `telemetry` (29 lines). ## Tests - `Services::HOST_TEST`'s destructuring test in `tv.rs` pins `Files`. - `port.rs` pins webOS's `Helper`, and `platform_desktop.rs`'s hostsim test `the_desktop_table_keeps_the_account_in_files` pins the desktop table's `Files`. - A source-order pin in `port.rs`'s tests checks that `run_application` installs the services before it enters the application. An uninstalled television would read `Files` and write a plaintext session file. - The lane's runs: - `plx_os` tv tests: 79 passed; - `port` tests: 2 passed; - the hostsim desktop table test: 1 passed; - `make check-nodef`: exit 0; - `ci/test_readonly_generated.py` and `ci/test_readonly_dependencies.py`: ok. No `Cargo.toml`, lock or certificate-pinned source changes. No ledger line. --- docs/module-layers.md | 2 +- docs/platform-ports.md | 6 +++ rust-modules/os/src/tv.rs | 10 +++- rust-modules/os/src/tv/authority.rs | 72 ++++++++++++++++++++++++++ rust-modules/src/platform_desktop.rs | 12 ++++- rust-modules/src/port.rs | 77 +++++++++++++++++++++++++++- 6 files changed, 174 insertions(+), 5 deletions(-) create mode 100644 rust-modules/os/src/tv/authority.rs diff --git a/docs/module-layers.md b/docs/module-layers.md index 06df7a3e28..714e309898 100644 --- a/docs/module-layers.md +++ b/docs/module-layers.md @@ -350,7 +350,7 @@ 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 by `app::run_application` (from the `Platform` its entry hands it) before anything +the port fills at boot. `tv::Services` is a table of function pointers and stated values in five groups (`identity`, `secure`, `system`, `storage` 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. diff --git a/docs/platform-ports.md b/docs/platform-ports.md index 45f9329ffc..49fe3eb595 100644 --- a/docs/platform-ports.md +++ b/docs/platform-ports.md @@ -848,6 +848,12 @@ split by who reads it (critic M4): `devcaps` parses through, `Files::NONE` for a platform with none); - `secure { seal, open, remove, mode }` (Target shape 4; until W2 `mode` is W3a's own once-set value); - `system { go_home, poll_home, deliver_toast }`; + - `storage { authority }` (W8a): `Authority::Helper` (webOS: the LS2/DB8 storage helper is the canonical store of + the session, the install's preferences and the consent record; the app's own files there are the legacy + migration inputs and the marked fallback of a helper outage) or `Authority::Files` (desktop, Tizen, a host + test: the app's own record files are the store), read through + `tv::authority::authority()`. It replaces the `target_os = "linux"` + `target_arch = "arm"` fence the persistence + layers chose their store by; the helper's wake-up (`storage::client::install_activator`) joins it after W7b; - `legacy_webos_media { sink, display_sink, uri_media }`: the Starfish, ACB and `com.webos.media` verbs (F31), named for what they are (critic M3). Every hook is required (Decision 2, C): a platform states each field, a named `NONE` being a statement and a `Default`-filled gap not allowed. The one exemption is this group: diff --git a/rust-modules/os/src/tv.rs b/rust-modules/os/src/tv.rs index 4d372c7798..4a2264b998 100644 --- a/rust-modules/os/src/tv.rs +++ b/rust-modules/os/src/tv.rs @@ -1,4 +1,5 @@ //! The television, as everything outside the port sees it (step L15, docs/module-layers.md). +pub mod authority; pub mod device; pub mod home; pub mod launch; @@ -10,13 +11,15 @@ pub mod sound; pub mod toast; pub mod uri; +pub use authority::StorageHooks; + 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) } -/// What the lower layers read from the platform, in four groups. Installed once ([`install`]) before +/// What the lower layers read from the platform, in five 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`. @@ -28,6 +31,7 @@ pub struct Services { pub identity: IdentityHooks, pub secure: SecureHooks, pub system: SystemHooks, + pub storage: StorageHooks, pub legacy_webos_media: LegacyWebosMedia, } @@ -117,6 +121,7 @@ impl Services { identity: IdentityHooks::NONE, secure: SecureHooks::NONE, system: SystemHooks::NONE, + storage: StorageHooks::NONE, legacy_webos_media: LegacyWebosMedia::NONE, }; } @@ -159,6 +164,7 @@ mod tests { identity: IdentityHooks { probe_device, start_capability_probe, repair_native_video, device_files, system_locale, sound_output }, secure: SecureHooks { seal, open, remove, mode }, system: SystemHooks { go_home, poll_home, deliver_toast }, + storage: StorageHooks { authority }, legacy_webos_media: LegacyWebosMedia { sink, display_sink, uri_media }, } = Services::HOST_TEST; @@ -193,6 +199,8 @@ mod tests { toast::Sent { reply: None, outcome: toast::Outcome::NoBus } ); + assert_eq!(authority, authority::Authority::Files, "no storage helper: the app keeps its records in files"); + 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""); diff --git a/rust-modules/os/src/tv/authority.rs b/rust-modules/os/src/tv/authority.rs new file mode 100644 index 0000000000..629a194108 --- /dev/null +++ b/rust-modules/os/src/tv/authority.rs @@ -0,0 +1,72 @@ +//! Where the account's canonical state lives: the platform's storage helper, or plain files. +//! +//! The session record, the install's preferences and the consent record each have one canonical +//! store, and the platform states which. On a webOS television it is the LS2/DB8 storage helper +//! ([`Authority::Helper`]). Everywhere else it is the app's own record files under its persistent +//! state root ([`Authority::Files`]): the desktop simulator, a host test, and a platform with no +//! helper at all (Tizen). +//! +//! Under `Helper` the app's own files are not the store. They are the legacy migration inputs an +//! older build left, and the marked fallback the session layer writes when a commit to the helper is +//! not durable (a helper outage): while the helper cannot answer, that file is served as transient +//! state, and it never replaces the helper's record. +//! +//! The platform states the value once, as the `authority` of its [`StorageHooks`](super::StorageHooks), +//! and [`authority`] reads it. A process that installed no platform (a host test) reads +//! [`StorageHooks::NONE`], which is `Files`, like every other group's host-test answer. A shipping +//! process has to install its services before anything persists, because an uninstalled television +//! would be told it has no helper; `run_application` installs them as its first statement +//! (`port::tests` pins the order). +//! +//! The value exists so that the layers that persist these records can choose their canonical store +//! from what the platform states, not from the build's CPU and OS (a 32-bit ARM Linux binary is not +//! necessarily a television). +//! +//! This group is the home of the platform's other storage statements as well. The helper's wake-up +//! (`storage::client::install_activator`, which `port::plex_main` installs for webOS today) belongs +//! here as a later member and moves with the os lane after W7b; it is not moved yet. + +/// Where the account's canonical state lives. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Authority { + /// The platform's storage helper (webOS: the LS2/DB8 service) is the canonical store. The app's + /// own files are only the legacy migration inputs and the session layer's marked fallback, which + /// is written during a helper outage and is never the record. + Helper, + /// The app's own record files under its persistent state root are the canonical store. + #[default] + Files, +} + +/// The storage group of [`Services`](super::Services): what a platform states about where the app's +/// own records live. +pub struct StorageHooks { + pub authority: Authority, +} + +impl StorageHooks { + /// A platform with no storage helper: the app keeps its records in files. + pub const NONE: Self = Self { authority: Authority::Files }; +} + +/// The installed platform's [`Authority`], or `Files` when nothing is installed. +pub fn authority() -> Authority { + super::services().storage.authority +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_default_authority_is_files() { + assert_eq!(Authority::default(), Authority::Files); + assert_eq!(StorageHooks::NONE.authority, Authority::Files, "a platform with no helper keeps files"); + } + + /// Nothing is installed in a test process, so the reader answers the host-test group's `Files`. + #[test] + fn an_uninstalled_process_reads_files() { + assert_eq!(authority(), Authority::Files); + } +} diff --git a/rust-modules/src/platform_desktop.rs b/rust-modules/src/platform_desktop.rs index b4cb8f580e..3a412fb051 100644 --- a/rust-modules/src/platform_desktop.rs +++ b/rust-modules/src/platform_desktop.rs @@ -18,6 +18,8 @@ //! no compositor to hint and no bus to pump. The secure store is `SecureHooks::NONE`: nothing seals, //! so a session is the 0600 plaintext file the session layer writes itself, which the simulator's //! harnesses plant and read. +//! The storage group is `StorageHooks::NONE`: there is no storage helper, so the account's records +//! live in files under the persistent state root. //! //! This module never names `port`, `system`, `webos` or `keymanager`, so a desktop executable //! references none of the television's code. It still COMPILES it (the television arms of those @@ -28,7 +30,7 @@ use crate::app::platform::{FrameProbe, Platform, Shell}; use plx_os::devcaps::dv::{self, DvCapability, DvProbe, ProbeSource}; use plx_os::tv::toast::{Identity, Outcome, Sent}; -use plx_os::tv::{IdentityHooks, LegacyWebosMedia, SecureHooks, Services, SystemHooks}; +use plx_os::tv::{IdentityHooks, LegacyWebosMedia, SecureHooks, Services, StorageHooks, SystemHooks}; use std::ffi::CStr; use std::os::raw::{c_int, c_void}; @@ -56,6 +58,7 @@ static SERVICES: Services = Services { }, secure: SecureHooks::NONE, system: SystemHooks { go_home, poll_home: SystemHooks::NONE.poll_home, deliver_toast }, + storage: StorageHooks::NONE, legacy_webos_media: LegacyWebosMedia { sink: SINK, display_sink: DISPLAY, @@ -141,6 +144,13 @@ pub fn run(pms_host: &CStr, pms_port: u16) -> c_int { mod tests { use super::*; + /// A desktop has no storage helper: the session, the install's preferences and the consent record + /// are files. The same value a host test reads from `Services::HOST_TEST`. + #[test] + fn the_desktop_table_keeps_the_account_in_files() { + assert_eq!(SERVICES.storage.authority, plx_os::tv::authority::Authority::Files); + } + /// 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 /// the simulator both must be the host sink, never `NoSink`: a boot that read `NoSink` would diff --git a/rust-modules/src/port.rs b/rust-modules/src/port.rs index 7f717ca525..ec914547a8 100644 --- a/rust-modules/src/port.rs +++ b/rust-modules/src/port.rs @@ -20,8 +20,8 @@ const DISPLAY: &dyn plx_os::tv::sink::DisplaySink = &plx_os::webos::video_sink:: #[cfg(test)] const DISPLAY: &dyn plx_os::tv::sink::DisplaySink = SINK; -/// 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`]. +/// What the lower layers read: the webOS identity, key manager, Home key and toast, the storage helper +/// 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, @@ -42,6 +42,7 @@ static SERVICES: plx_os::tv::Services = plx_os::tv::Services { poll_home: plx_os::webos::poll_home, deliver_toast: plx_os::webos::toast::deliver, }, + storage: plx_os::tv::StorageHooks { authority: plx_os::tv::authority::Authority::Helper }, legacy_webos_media: plx_os::tv::LegacyWebosMedia { sink: SINK, display_sink: DISPLAY, @@ -148,3 +149,75 @@ pub unsafe extern "C" fn plx_launch_args(json: *const c_char) { let raw = unsafe { std::ffi::CStr::from_ptr(json) }.to_string_lossy(); plx_os::tv::launch::offer(&raw); } + +#[cfg(test)] +mod tests { + use super::SERVICES; + use plx_os::tv::authority::Authority; + + /// The webOS table states the storage helper as the canonical home of the session, the install's + /// preferences and the consent record: on a television that is DB8, and a table that stated + /// `Files` would say the app's own files are. + #[test] + fn the_webos_table_states_the_storage_helper_as_the_authority() { + assert_eq!(SERVICES.storage.authority, Authority::Helper); + assert_eq!(SERVICES.secure.mode, plx_os::tv::secure::StoreMode::Durable); + } + + /// Every `.rs` file under the application crate's `src`, as text. + fn crate_sources() -> Vec { + fn walk(dir: &std::path::Path, out: &mut Vec) { + for entry in std::fs::read_dir(dir).expect("read a source directory") { + let path = entry.expect("a directory entry").path(); + if path.is_dir() { + walk(&path, out); + } else if path.extension().is_some_and(|ext| ext == "rs") { + out.push(std::fs::read_to_string(&path).expect("read a source file")); + } + } + } + let mut out = Vec::new(); + walk(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut out); + out + } + + /// `run_application` installs the services as its first statement, before anything can read + /// them: a process that has installed none reads the host-test answers, which for the storage + /// group is `Files`, so a television that persisted ahead of its install would be told it has no + /// helper. One production install, and the only caller of `tv::install` is the `Platform` method + /// it goes through. Reads the source, like `app::boot`'s `seam_order_tests`, because no host test + /// can run the entry. + #[test] + fn the_services_are_installed_first_and_only_there() { + let body = include_str!("app/mod.rs") + .split_once("fn run_application(") + .expect("run_application") + .1 + .split_once('{') + .expect("run_application's body") + .1; + let first = body + .lines() + .map(str::trim) + .find(|line| !line.is_empty() && !line.starts_with("//")) + .expect("a first statement"); + let first = first.split_once("//").map_or(first, |(code, _)| code).trim(); + assert_eq!( + first, + concat!("platform.install_", "services();"), + "the install must be run_application's first statement" + ); + let sources = crate_sources(); + let count = |needle: &str| sources.iter().map(|text| text.matches(needle).count()).sum::(); + assert_eq!( + count(concat!(".install_", "services()")), + 1, + "one production install; a second would be refused by tv and could hide a missing first" + ); + assert_eq!( + count(concat!("tv::", "install(")), + 1, + "`tv::install` is called by `Platform::install_services` and nowhere else" + ); + } +} From 3923286725b93c4b7bcf165c17abc1321f839d73 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 17:14:14 +0300 Subject: [PATCH 11/26] Telemetry's consent store follows the platform's storage authority, not the build's CPU (#1490) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Part of step W8a of the platform plan (discussion #1460). Telemetry's consent store now follows the storage authority the platform states (#1488), instead of `all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(test))`. That predicate means "32-bit ARM Linux", not "a webOS television". webOS behaves as before. Every other platform keeps the files arm it already took. ## What changes - **The 29 fenced lines** (`persistence.rs` 23, `consent.rs` 5, `mod.rs` 1) become a run-time `match` on `plx_os::tv::authority::authority()`. - `load`, `record_at` and `forget_at` read the authority once per operation, then hand it to `load_with(authority, transport, …)`, `record_with(…)` and `forget_with(authority, legacy, root)`. `Helper` runs the helper arm; `Files` runs the files arm. - Only the selection changes. Every `*_helper` item (`load_helper`, `record_helper`, the legacy import, the legacy sweep) and every files-arm body is byte-for-byte as before, apart from its deleted cfg line. No fallback, migration read or sweep is dropped. - The helper-arm items and the consent codec (`split_canonical`/`join_canonical`) now compile on every build. - **`cleanup_after_account_clear` is unconditional.** It calls a private `account_clear_sweep(authority, legacy)`. - `Helper` sweeps the legacy candidates through `cleanup_after_combined_clear`. - `Files` answers `true` without reading a path. - **`app/boot.rs` `install_plex_seams`** installs `install_account_clear_cleanup` on every platform. Its cfg line is removed and its doc bullet follows; the hunk is 5 lines. - `plex/session.rs` loses the matching cfg on `ACCOUNT_CLEAR_CLEANUP` and `install_account_clear_cleanup`. - The two lines go from `ci/allow/forks/plex.txt`, whose count falls from 33 to 31. - The call site in `clear_for_erase` keeps its fence, so until the stacked `plex` PR re-keys it, a non-webOS build installs the hook and never calls it. - **Consent on Tizen** takes `Files`, with no third `Authority` value. How `StoreMode::MemoryOnly` applies to consent is decided in W9. ## Counts in `rust-modules/telemetry` | | before | after | |---|---|---| | `target_arch = "arm"` | 38 | 9 | | `target_os = "linux"` | 41 | 12 | - **The 9/9 left in `native.rs`** (the Sentry Native crash capture: `mod sdk`, 17 externs, `src/sentry_context.c`) are the recorded follow-up for Tizen ARM retail builds. They do not affect the x86_64 emulator, where both predicates already pick the non-webOS arm. - **The 3 `target_os = "linux"` lines in `crashreport.rs`** are true Linux facts and stay. ## Tests New tests pass the authority as a parameter. There is no process-global override: - `upgrade_tests::the_platform_authority_picks_the_store_for_{load,record,forget}`; - `tests::the_account_clear_sweep_retires_legacy_files_only_where_the_helper_defers_it`. Results on the committed, restacked tree (`git status --short` was empty before and after): - `make test-crate C=plx_telemetry`: `test result: ok. 381 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out` - `make check-nodef`: exit 0 - `make test-hostsim T=lifecycle_regression_tests::parking`: `test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 1750 filtered out` - This shows the app crate builds under `hostsim` with the `boot.rs` change. - The whole `lifecycle_regression_tests` module was not graded. One test in it, `player_owner_events_record_and_replay_through_the_actual_app_host`, kills the test binary (SIGSEGV) on the lane's Mac at 8f5575182 and 641ba143a too. - `ci/check-deps.sh`, `ci/check-module-layers.py`, `ci/check-ledger-ratchet.py` and `ci/check-statics.sh` are green. - `ci/test_readonly_generated.py` (22 tests) and `ci/test_readonly_dependencies.py` (64 tests) are OK. - No `Cargo.toml`, lock, `.cargo` or certificate-pinned source changes. ## Not covered - No television run. The helper-arm bodies are unchanged; what changed on webOS is the dispatch, which now reads `authority()`. #1488's pin keeps `install_services()` ahead of every reader. - The `plex` W8a PR edits the same lines in `plex/session.rs` and `ci/allow/forks/plex.txt`, with identical hunks. Whichever lands second merges `main`, and may need to resolve the `# count:` line. --- ci/allow/forks/plex.txt | 4 +- rust-modules/plex/src/plex/session.rs | 15 +- rust-modules/src/app/boot.rs | 5 +- .../telemetry/src/telemetry/consent.rs | 5 - rust-modules/telemetry/src/telemetry/mod.rs | 56 ++++- .../telemetry/src/telemetry/persistence.rs | 201 ++++++++++++------ 6 files changed, 192 insertions(+), 94 deletions(-) diff --git a/ci/allow/forks/plex.txt b/ci/allow/forks/plex.txt index ef9ce4bba2..00a5ca7ee3 100644 --- a/ci/allow/forks/plex.txt +++ b/ci/allow/forks/plex.txt @@ -1,4 +1,4 @@ -# count: 33 +# count: 31 # Test/production forks (docs/sans-io.md), area `plex`: one line per production-visible `#[cfg(..)]` / `cfg!(..)` whose predicate reads `test` or `feature = "test-support"` # (`not(test)`, `not(any(test, feature = "test-support"))`, ...) in every machine crate (data/, plex/, media/, session/, screens/, ui/, appkit/ and machine/), keyed `::` (an attribute on an item), `::` (a statement or an inline `cfg!`) or `::` (a field). # Logic is one thing in production and tests deliver it events: there is no cfg(test) fork. Spec: ci/check-deps.sh `forks`. @@ -8,12 +8,10 @@ rust-modules/plex/src/plex/identity.rs::version rust-modules/plex/src/plex/origin.rs::latched_flag! rust-modules/plex/src/plex/origin.rs::store_policy_forced rust-modules/plex/src/plex/servers.rs::register_captured_origin_with_connection -rust-modules/plex/src/plex/session.rs::ACCOUNT_CLEAR_CLEANUP rust-modules/plex/src/plex/session.rs::auth_paths rust-modules/plex/src/plex/session.rs::clear_for_erase rust-modules/plex/src/plex/session.rs::clear_for_erase rust-modules/plex/src/plex/session.rs::clear_for_erase -rust-modules/plex/src/plex/session.rs::install_account_clear_cleanup rust-modules/plex/src/plex/session.rs::publish rust-modules/plex/src/plex/session.rs::read_into_cache_locked rust-modules/plex/src/plex/session.rs::read_into_cache_locked diff --git a/rust-modules/plex/src/plex/session.rs b/rust-modules/plex/src/plex/session.rs index 698d864e28..320bfdbc22 100644 --- a/rust-modules/plex/src/plex/session.rs +++ b/rust-modules/plex/src/plex/session.rs @@ -4282,17 +4282,16 @@ fn auto_quality_ready() -> bool { } /// **The telemetry/consent legacy-file sweep that follows a durable canonical clear** -/// ([`clear_for_erase`]'s ARM arm): `telemetry` owns the files and sits above `plex`, so the app -/// installs its `cleanup_after_account_clear` as a hook ([`install_account_clear_cleanup`]; -/// `app::boot::install_plex_seams`). It answers whether every candidate was retired. Unset there is -/// nothing registered to retire, which reads as retired, so the "could not be retired" branch is -/// never taken without a sweep that failed. Compiled where the sweep is: ARM, not the simulator, -/// not a test build. -#[cfg(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +/// ([`clear_for_erase`] where the storage helper is canonical): `telemetry` owns the files and sits +/// above `plex`, so the app installs its `cleanup_after_account_clear` as a hook +/// ([`install_account_clear_cleanup`]; `app::boot::install_plex_seams`). It answers whether every +/// candidate was retired. Unset there is nothing registered to retire, which reads as retired, so +/// the "could not be retired" branch is never taken without a sweep that failed. The sweep runs +/// only where the platform states [`Authority::Helper`]; elsewhere the files it retires are not +/// deferred to a sign-out, so an installed hook is never asked. static ACCOUNT_CLEAR_CLEANUP: std::sync::OnceLock bool> = std::sync::OnceLock::new(); /// Install the sweep [`ACCOUNT_CLEAR_CLEANUP`] runs. Once; later calls are ignored. -#[cfg(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] pub fn install_account_clear_cleanup(sweep: fn() -> bool) { let _ = ACCOUNT_CLEAR_CLEANUP.set(sweep); } diff --git a/rust-modules/src/app/boot.rs b/rust-modules/src/app/boot.rs index 1645c2d47d..a24fa1d82a 100644 --- a/rust-modules/src/app/boot.rs +++ b/rust-modules/src/app/boot.rs @@ -434,11 +434,10 @@ mod panic_log_tests { /// * `plex::session::install_auto_quality_ready` — `route::auto_quality_ready`, the gate a fresh /// session record's default quality is seeded from (unset, `plex` reads `true`, the gate's value); /// * `plex::session::install_account_clear_cleanup` — `telemetry::cleanup_after_account_clear`, the -/// telemetry/consent legacy-file sweep a durable sign-out runs. It exists only where the sweep does -/// (ARM, not the simulator, not a test build); unset, `plex` reads it as already retired. +/// telemetry/consent legacy-file sweep a durable sign-out runs. It is installed on every platform: +/// the sweep retires files only where the storage helper owns them; unset, `plex` reads it as retired. pub(crate) fn install_plex_seams() { plx_plex::plex::session::install_auto_quality_ready(plx_media::route::auto_quality_ready); - #[cfg(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(test)))] plx_plex::plex::session::install_account_clear_cleanup(plx_telemetry::telemetry::cleanup_after_account_clear); } diff --git a/rust-modules/telemetry/src/telemetry/consent.rs b/rust-modules/telemetry/src/telemetry/consent.rs index 15765389ac..1e35364b02 100644 --- a/rust-modules/telemetry/src/telemetry/consent.rs +++ b/rust-modules/telemetry/src/telemetry/consent.rs @@ -200,7 +200,6 @@ pub fn migrate_loaded(mut c: Consent) -> Consent { c } -#[cfg(any(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))), test, feature = "test-support"))] #[derive(serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] struct CanonicalDecision { @@ -212,7 +211,6 @@ struct CanonicalDecision { extensions: std::collections::BTreeMap, } -#[cfg(any(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))), test, feature = "test-support"))] #[derive(serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] struct CanonicalScopes { @@ -220,7 +218,6 @@ struct CanonicalScopes { usage: u32, } -#[cfg(any(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))), test, feature = "test-support"))] #[derive(serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] struct CanonicalIds { @@ -228,7 +225,6 @@ struct CanonicalIds { errors: Option, } -#[cfg(any(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))), test, feature = "test-support"))] /// Split consent into the three DB8-public slots the canonical state clears atomically on logout. pub fn split_canonical(consent: &Consent) -> Result { Ok(plx_os::storage::state::ConsentPayload { @@ -254,7 +250,6 @@ pub fn split_canonical(consent: &Consent) -> Result Result { let decision: CanonicalDecision = serde_json::from_value(payload.consent.clone()).map_err(|_| ())?; let scopes: CanonicalScopes = serde_json::from_value(payload.scopes.clone()).map_err(|_| ())?; diff --git a/rust-modules/telemetry/src/telemetry/mod.rs b/rust-modules/telemetry/src/telemetry/mod.rs index d8ab2adf2c..b0f134268e 100644 --- a/rust-modules/telemetry/src/telemetry/mod.rs +++ b/rust-modules/telemetry/src/telemetry/mod.rs @@ -234,15 +234,31 @@ pub fn forget() { } /// Called after the shared account tombstone (`plex::session::clear`'s canonical commit) is -/// confirmed durable. On ARM, `persistence::forget_at` deliberately leaves telemetry/consent's own -/// legacy files in place when a decision is cleared, relying on this sweep to run once the ONE -/// atomic DB8 revocation for both domains — session and telemetry/consent — is confirmed rather -/// than merely queued. Ported from `release/v0.6`'s `telemetry::cleanup_after_account_clear` / -/// `persistence::cleanup_after_combined_clear`, which the 0.7 forward-port dropped along with -/// their only caller (Copilot review on PR #105, finding 7). -#[cfg(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] +/// confirmed durable. Where the platform's storage authority is the helper +/// ([`plx_os::tv::authority::Authority::Helper`], a webOS television), `persistence::forget_at` +/// deliberately leaves telemetry/consent's own legacy files in place when a decision is cleared, +/// relying on this sweep to run once the ONE atomic DB8 revocation for both domains — session and +/// telemetry/consent — is confirmed rather than merely queued. With files +/// ([`plx_os::tv::authority::Authority::Files`]) `forget_at` already removed them inline, so there is +/// nothing left to retire and this answers `true`. Ported from `release/v0.6`'s +/// `telemetry::cleanup_after_account_clear` / `persistence::cleanup_after_combined_clear`, which the +/// 0.7 forward-port dropped along with their only caller (Copilot review on PR #105, finding 7). pub fn cleanup_after_account_clear() -> bool { - persistence::cleanup_after_combined_clear(&candidates()) != persistence::CleanupResult::Failed + account_clear_sweep(plx_os::tv::authority::authority(), candidates) +} + +/// [`cleanup_after_account_clear`] with the platform's authority handed in. `legacy` is called only +/// by the helper arm, so the files arm reads no path. +fn account_clear_sweep( + authority: plx_os::tv::authority::Authority, + legacy: impl FnOnce() -> Vec, +) -> bool { + match authority { + plx_os::tv::authority::Authority::Helper => { + persistence::cleanup_after_combined_clear(&legacy()) != persistence::CleanupResult::Failed + } + plx_os::tv::authority::Authority::Files => true, + } } // ---- the spool, and the one worker that drains it --------------------------------------------- @@ -794,4 +810,28 @@ mod tests { .expect("a file with more fields still parses"); assert!(newer.usage); } + + /// The sweep after a durable account clear belongs to the helper authority alone: it retires + /// every legacy candidate there, and with files it answers `true` without reading a path, because + /// `forget_at` already removed them inline. The webOS answer and the one Tizen gets, side by side. + #[test] + fn the_account_clear_sweep_retires_legacy_files_only_where_the_helper_defers_it() { + use plx_os::tv::authority::Authority; + let dir = std::env::temp_dir().join(format!("plxnative-account-clear-sweep-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let candidate = dir.join("telemetry.json"); + std::fs::write(&candidate, b"{}").unwrap(); + + assert!( + account_clear_sweep(Authority::Files, || panic!("the files authority reads no candidate")), + "files: nothing deferred, nothing to retire" + ); + assert!(candidate.exists(), "files: the sweep touched nothing"); + + assert!(account_clear_sweep(Authority::Helper, || vec![candidate.clone()])); + assert!(!candidate.exists(), "helper: the deferred legacy candidate is retired"); + + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/rust-modules/telemetry/src/telemetry/persistence.rs b/rust-modules/telemetry/src/telemetry/persistence.rs index ede6ec41b3..e503c128ab 100644 --- a/rust-modules/telemetry/src/telemetry/persistence.rs +++ b/rust-modules/telemetry/src/telemetry/persistence.rs @@ -3,17 +3,19 @@ //! The record backend owns framing and filesystem durability. This adapter owns the consent JSON //! payload, revision choice, and the rule that a present canonical record is terminal: legacy //! files are consulted only when `consent.json` is genuinely absent. +//! +//! Where the canonical record lives is the platform's statement +//! ([`plx_os::tv::authority::authority`]): the storage helper ([`Authority::Helper`], a webOS +//! television) or files under the persistent state root ([`Authority::Files`]). [`load`], +//! [`record_at`] and [`forget_at`] read it once per operation and hand it, with the helper's +//! transport, to their `*_with` form, which is what a test calls to grade either store. use super::consent::Consent; use plx_os::storage::{Record, RecordKey, RecordState, RecordStore}; -#[cfg(not(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))))] use plx_os::storage::StoreError; +use plx_os::tv::authority::Authority; use std::path::{Path, PathBuf}; -#[cfg(any( - all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))), - test -))] use plx_os::storage::{ client::{self, Load as HelperLoad}, state::{self, Generation, MigrationProgress}, @@ -21,7 +23,6 @@ use plx_os::storage::{ }; #[derive(Clone, Copy, Debug, PartialEq, Eq)] -#[allow(dead_code)] // `Delegated` is produced only by the shipping webOS adapter. pub enum PersistResult { NotAttempted, /// Durability belongs to the immediately-following atomic Session `ClearTenure` operation. @@ -108,17 +109,14 @@ pub fn forget() -> PersistOutcome { forget_at(&super::resource_candidates(), root()) } -#[cfg(not(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))))] fn store() -> Result { plx_os::storage::open(root()) } -#[cfg(not(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))))] fn store_at(root: PathBuf) -> Result { plx_os::storage::open(root) } -#[cfg(not(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))))] fn cleanup_canonical(store: &impl RecordStore) -> CleanupResult { if store.cleanup(RecordKey::Consent).is_ok() { CleanupResult::Complete @@ -140,11 +138,10 @@ fn log_cleanup_failure(stage: &str, path: &Path, error: &std::io::Error) { } /// Sweep telemetry/consent's own legacy candidates once the shared account ClearTenure DB8 -/// mutation has been confirmed durable. [`forget_at`]'s ARM branch defers exactly this cleanup -/// here rather than doing it inline, because the immediately-following session ClearTenure is the -/// one atomic DB8 revocation for both domains and legacy sources must survive until THAT commit is -/// confirmed, not merely queued. -#[cfg(any(test, feature = "test-support", all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"))))] +/// mutation has been confirmed durable. [`forget_at`]'s helper branch ([`Authority::Helper`]) defers +/// exactly this cleanup here rather than doing it inline, because the immediately-following session +/// ClearTenure is the one atomic DB8 revocation for both domains and legacy sources must survive +/// until THAT commit is confirmed, not merely queued. pub fn cleanup_after_combined_clear(legacy: &[PathBuf]) -> CleanupResult { remove_legacy_sources(legacy.iter().cloned()) } @@ -181,11 +178,14 @@ fn remove_legacy_sources(paths: impl IntoIterator) -> CleanupRes /// Load canonical consent, falling back to trusted legacy candidates only when canonical is /// absent. A malformed, inaccessible, future, or otherwise present canonical record is terminal. pub fn load(legacy: &[PathBuf]) -> Consent { - #[cfg(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] - { - return load_helper(&mut client::NativeTransport, legacy); + load_with(plx_os::tv::authority::authority(), &mut client::NativeTransport, legacy) +} + +/// [`load`] with the platform's authority and the helper's transport handed in. +fn load_with(authority: Authority, transport: &mut dyn client::Transport, legacy: &[PathBuf]) -> Consent { + if authority == Authority::Helper { + return load_helper(transport, legacy); } - #[cfg(not(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))))] { #[cfg(not(any(test, feature = "test-support")))] if plx_base::paths::ensure_persistent_state_root().is_err() { @@ -268,18 +268,10 @@ pub fn load(legacy: &[PathBuf]) -> Consent { } } -#[cfg(any( - all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))), - test -))] fn helper_expected(snapshot: &client::Snapshot) -> Option<(&str, state::Expected)> { Some((&snapshot.db_rev, snapshot.state.expected())) } -#[cfg(any( - all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))), - test -))] #[derive(Clone, Copy)] struct HelperCommit { result: PersistResult, @@ -288,10 +280,6 @@ struct HelperCommit { conflict: bool, } -#[cfg(any( - all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))), - test -))] fn helper_commit( transport: &mut dyn client::Transport, loaded: &HelperLoad, @@ -359,10 +347,6 @@ fn helper_commit( } } -#[cfg(any( - all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))), - test -))] fn legacy_consent(legacy: &[PathBuf]) -> Result)>, ()> { let mut found: Option<(Consent, Vec)> = None; for path in legacy { @@ -387,10 +371,6 @@ fn legacy_consent(legacy: &[PathBuf]) -> Result)>, Ok(found) } -#[cfg(any( - all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))), - test -))] enum PreviousCanonical { Missing, Data(Consent), @@ -400,18 +380,10 @@ enum PreviousCanonical { /// Decode the complete `plxnative-record` wrapper used by the JSON canonical store that preceded /// DB8. A corrupt/future record is terminal and is never treated like an absent legacy source. -#[cfg(any( - all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))), - test -))] fn previous_canonical_consent() -> PreviousCanonical { previous_canonical_consent_at(root()) } -#[cfg(any( - all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))), - test -))] fn previous_canonical_consent_at(root: PathBuf) -> PreviousCanonical { match std::fs::symlink_metadata(&root) { Err(error) if error.kind() == std::io::ErrorKind::NotFound => PreviousCanonical::Missing, @@ -440,10 +412,6 @@ fn previous_canonical_consent_at(root: PathBuf) -> PreviousCanonical { } } -#[cfg(any( - all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))), - test -))] fn load_helper(transport: &mut dyn client::Transport, legacy: &[PathBuf]) -> Consent { let loaded = match client::load_with(transport) { Ok(loaded) => loaded, @@ -615,7 +583,6 @@ fn read_legacy(path: &Path) -> LegacyRead { } } -#[cfg(not(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))))] fn load_legacy_and_migrate(store: &impl RecordStore, legacy: &[PathBuf]) -> Consent { let mut found: Option<(Consent, Vec<(PathBuf, Vec)>)> = None; for path in legacy { @@ -727,12 +694,21 @@ pub(super) fn record_at( legacy: &[PathBuf], canonical_root: PathBuf, ) -> PersistOutcome { - #[cfg(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] - { + record_with(plx_os::tv::authority::authority(), &mut client::NativeTransport, consent, legacy, canonical_root) +} + +/// [`record_at`] with the platform's authority and the helper's transport handed in. +fn record_with( + authority: Authority, + transport: &mut dyn client::Transport, + consent: &Consent, + legacy: &[PathBuf], + canonical_root: PathBuf, +) -> PersistOutcome { + if authority == Authority::Helper { let _ = canonical_root; - return record_helper(&mut client::NativeTransport, consent, legacy); + return record_helper(transport, consent, legacy); } - #[cfg(not(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))))] { let store = match store_at(canonical_root) { Ok(store) => store, @@ -827,10 +803,6 @@ pub(super) fn record_at( } } -#[cfg(any( - all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))), - test -))] fn record_helper( transport: &mut dyn client::Transport, consent: &Consent, @@ -906,8 +878,13 @@ fn record_helper( /// Write a canonical cleared tombstone, then remove stale legacy copies best-effort. pub(super) fn forget_at(legacy: &[PathBuf], canonical_root: PathBuf) -> PersistOutcome { - #[cfg(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] - { + forget_with(plx_os::tv::authority::authority(), legacy, canonical_root) +} + +/// [`forget_at`] with the platform's authority handed in. The helper arm touches nothing itself, so +/// it takes no transport. +fn forget_with(authority: Authority, legacy: &[PathBuf], canonical_root: PathBuf) -> PersistOutcome { + if authority == Authority::Helper { let _ = canonical_root; // Session's immediately-following ClearTenure is the one atomic DB8 revocation for both // domains. Consent has already been unpublished before this worker job runs. Legacy @@ -920,7 +897,6 @@ pub(super) fn forget_at(legacy: &[PathBuf], canonical_root: PathBuf) -> PersistO publish(outcome); return outcome; } - #[cfg(not(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))))] { let store = match store_at(canonical_root) { Ok(store) => store, @@ -1038,12 +1014,13 @@ mod tests { /// Copilot review on PR #105, finding 7. `release/v0.6` swept telemetry/consent's own legacy /// files (`telemetry::cleanup_after_account_clear` / `persistence::cleanup_after_combined_clear`) /// once the shared account ClearTenure DB8 mutation was confirmed durable on ARM sign-out; the - /// 0.7 forward-port dropped both the function and its only caller entirely (`forget_at`'s ARM + /// 0.7 forward-port dropped both the function and its only caller entirely (`forget_at`'s helper /// branch still says it relies on this sweep, but nothing performed it — confirmed absent by - /// grep against this tree before this fix). ARM's `forget_at` is compiled out on host - /// (`not(all(target_os = "linux", target_arch = "arm", ...))`), so the real defect cannot be - /// observed red on this platform; this test pins the restored sweep function directly rather - /// than through the ARM-only call site. `cleanup_after_combined_clear` did not exist before + /// grep against this tree before this fix). That branch ran only where the build was a 32-bit ARM + /// Linux binary, so the real defect could not be observed red on a host; this test pins the + /// restored sweep function directly rather than through that call site (the dispatch itself is + /// graded by `upgrade_tests::the_platform_authority_picks_the_store_for_forget`). + /// `cleanup_after_combined_clear` did not exist before /// this fix, so the red here is simulated (a compile failure against the old tree), not an /// observed runtime failure. #[test] @@ -1587,4 +1564,94 @@ mod upgrade_tests { assert!(!after.any() && !after.answered() && after.errors_id.is_none()); assert!(!source.exists(), "a stale source is retired, never imported, after sign-out"); } + + /// A transport that counts its calls and answers none: the files arm must never reach it. + fn silent(asked: &std::cell::Cell) -> impl FnMut(Request) -> Result + '_ { + move |_| { + asked.set(asked.get() + 1); + Err(plx_os::storage::client::ClientError::Unavailable) + } + } + + /// The platform's [`Authority`], not the build's CPU and OS, picks where consent is read from: + /// `Files` migrates a legacy source into the state root's own file and never asks the helper; + /// `Helper` imports it into the helper and never creates the state root's consent file. + #[test] + fn the_platform_authority_picks_the_store_for_load() { + let _g = plx_base::testlock::serial(); + { + let dir = Dir::new("authority-load-files"); + let source = dir.legacy(GENERATED_DECLINE_065); + let asked = std::cell::Cell::new(0); + let mut transport = silent(&asked); + let loaded = load_with(Authority::Files, &mut transport, std::slice::from_ref(&source)); + assert_eq!(asked.get(), 0, "the files arm never reaches the storage helper"); + assert_preserved("files authority", &loaded, GENERATED_DECLINE_065); + assert!(dir.0.join("state/consent.json").exists(), "the files arm keeps its own record"); + assert!(!source.exists(), "the legacy source is retired once the file is durable"); + } + { + let dir = Dir::new("authority-load-helper"); + let source = dir.legacy(GENERATED_DECLINE_065); + let mut b = backend(None); + let mut transport = |request: Request| Ok(b.dispatch(request)); + let loaded = load_with(Authority::Helper, &mut transport, std::slice::from_ref(&source)); + assert_preserved("helper authority", &loaded, GENERATED_DECLINE_065); + assert!(b.rpc.puts >= 1, "the helper arm commits the import to the helper"); + assert!(!dir.0.join("state/consent.json").exists(), "the helper arm never creates the state root's consent file"); + assert!(!source.exists(), "the legacy source is retired once the helper holds it"); + } + } + + /// The same split for a write: `Files` writes the state root's file and never asks the helper; + /// `Helper` commits to the helper, whatever root it was handed, and creates no consent file there. + #[test] + fn the_platform_authority_picks_the_store_for_record() { + let _g = plx_base::testlock::serial(); + let consent = super::super::consent::apply(&Consent::default(), true, true, || Some("f".repeat(32))); + { + let dir = Dir::new("authority-record-files"); + let asked = std::cell::Cell::new(0); + let mut transport = silent(&asked); + let outcome = record_with(Authority::Files, &mut transport, &consent, &[], dir.0.join("state")); + assert_eq!(outcome.write, PersistResult::Durable); + assert_eq!(asked.get(), 0, "the files arm never reaches the storage helper"); + assert!(dir.0.join("state/consent.json").exists(), "the files arm keeps its own record"); + } + { + let dir = Dir::new("authority-record-helper"); + let elsewhere = dir.0.join("elsewhere"); + let mut b = backend(Some(db8_066())); + let mut transport = |request: Request| Ok(b.dispatch(request)); + let outcome = record_with(Authority::Helper, &mut transport, &consent, &[], elsewhere.clone()); + assert_eq!(outcome.write, PersistResult::Durable); + assert!(b.rpc.puts >= 1, "the helper arm commits to the helper"); + assert!(!dir.0.join("state/consent.json").exists() && !elsewhere.exists(), "no consent file under the state root"); + assert_eq!(helper_load(&mut b, &[]), consent, "the helper holds the decision"); + } + } + + /// And for a sign-out: `Files` writes the cleared tombstone and retires the legacy source itself; + /// `Helper` delegates both to the session's ClearTenure and touches neither. + #[test] + fn the_platform_authority_picks_the_store_for_forget() { + let _g = plx_base::testlock::serial(); + { + let dir = Dir::new("authority-forget-files"); + let source = dir.legacy(GENERATED_DECLINE_065); + let outcome = forget_with(Authority::Files, std::slice::from_ref(&source), dir.0.join("state")); + assert_eq!(outcome.write, PersistResult::Durable); + assert!(!source.exists(), "the files arm retires the legacy source itself"); + assert!(dir.0.join("state/consent.json").exists(), "the files arm writes its own tombstone"); + } + { + let dir = Dir::new("authority-forget-helper"); + let source = dir.legacy(GENERATED_DECLINE_065); + let outcome = forget_with(Authority::Helper, std::slice::from_ref(&source), dir.0.join("state")); + assert_eq!(outcome.write, PersistResult::Delegated); + assert_eq!(outcome.cleanup, CleanupResult::NotAttempted); + assert!(source.exists(), "the legacy source waits for the confirmed ClearTenure"); + assert!(!dir.0.join("state/consent.json").exists(), "the helper arm never creates the state root's consent file"); + } + } } From f7038a8fd8708d26c3a8771fe29d10717f110112 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 17:30:56 +0300 Subject: [PATCH 12/26] The platform supplies the media composition, and the app publishes it once (#1489) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Step W6b of the platform plan (discussion #1460): the platform supplies the playback composition, in two boot phases. The app publishes what it gets once, on every boot. Before, `app/boot.rs` called `acb_init` and `compose_backends` directly, and `playback.rs` and `run.rs` chose code paths with `feature = "play-uri"` gates. Now `Platform` carries a `MediaBoot`: webOS fills it with today's bodies, the desktop with the Feed host sink alone, and `Platform::HOST_TEST` with nothing. webOS boots the same way at the same points, with one new log line. ## What changes - **`app/platform.rs`** - `Platform` gains `media: MediaBoot { early_init: fn(&MainThread), compose: fn(&mut PlayerAdapter, controlled: bool) -> Composition }`. `Platform::new` takes it as a fourth argument. - `Composition { resolver: Option }` derives `Default`, which means no resolver. - `publish_composition(session, adapter, Composition)` publishes the resolver first, then `install_backends(adapter.composed_backends())`. - It runs on every boot, for every platform, so a platform with no drivers publishes `BackendSet::NONE` and no resolver. The session's set and its resolver can no longer disagree. - It logs one new line, `compose: backends= resolver=`. Every existing log line is unchanged. - `HOST_TEST` composes nothing, and the pin test covers the new field. - **`app/boot.rs`**: two hunks. - The `acb_init` call becomes `(platform.media.early_init)(&mt)`. It stays on the same line, inside the same `if !controlled`, before `ffi::boot()`. - The `compose_backends` block becomes `(platform.media.compose)(…)`, then `publish_composition(…)`, at the same site. - **Who fills what** - `src/port.rs` (webOS): `MediaBoot { early_init: backends::acb_init, compose: backends::compose_native }`. - `src/platform_desktop.rs`: a no-op `early_init`. Its `compose` calls `compose_feed` and returns `Composition::default()`. - **`app/adapters/backends.rs`** - `compose_backends` is split into `compose_feed` (shared), `compose_native`, and `compose_with(adapter, controlled, install_uri)`, which the tests use. - `install_uri_product` and `install_uri_product_with_ports` no longer take the session. They return `Option`, built only after the physical URI install succeeds. - The `uri: product driver installation refused` line moved into `install_uri_product`, with its text unchanged. - **`media/src/route/decision.rs`** - `install_uri_preflight_port` takes `impl Into>`, so an absent resolver clears the slot, and the existing callers that pass a resolver compile unchanged. - A reader, `uri_preflight_port()`, is added for the tests. - **`playback.rs` and `run.rs`**: the ten `feature = "play-uri"` lines that chose a path at build time are deleted, six in `playback.rs` and four in `run.rs`. Those paths now read the published set at run time. Nothing else in either file changes. - **Docs**: Target shape 6a in `docs/platform-ports.md` gains an "As landed" note, and `docs/module-layers.md` follows. ## Deviations from the plan - **Composition is a seam, not a move.** `port.rs` points at functions in `app/adapters/backends.rs` instead of owning their bodies, because those bodies name ACB, and the app crate's own ACB names leave it only in W11a. The 6a text and the W6b paragraph say so. - **`compose` takes no `&PlaybackSession`.** The only use of the session was the old resolver publication, which now happens in `publish_composition`. 6a records that W10 adds a read-only session parameter if a Tizen driver needs one. - **46 `play-uri` lines remain**: 40 in `backends.rs`, 1 in a `run.rs` test fixture, 3 in `dev.rs`, 1 in `lib.rs` and 1 in the rig. None remain in `boot.rs`, production `run.rs`, `playback.rs` or `platform.rs`. This commit adds five gated lines to `backends.rs`, so the docs give the grep instead of a count. - `Composition::NONE` became `Default`: the constant was read only by the desktop platform, and `make check-nodef` failed on it as dead code. ## What the simulator does differently - No URI driver is composed. `play-uri` is a default feature, so before this change the simulator composed the product URI driver over null ports. Its session set is now Feed alone, with no resolver. - Its log no longer has the `vplane: exported window …` or `vplane: this device has NEITHER libAcbAPI …` line, nor the `uri: product binding=…` and `uri: display path=…` lines. - `PlaneOwner::boot(ABSENT)` is no longer called. The default plane facts are the same absent facts. - `dev::uriprobe::install` no longer runs in a simulator `devtriggers` build. ## Tests In each case, the published set and resolver must agree: - `a_composed_uri_driver_is_published_with_its_resolver` and `a_controlled_boot_composes_no_uri_driver_and_no_resolver` call webOS's own `compose_native`, the function `port.rs` installs as `Platform.media.compose`; - `a_refused_uri_install_publishes_neither_the_driver_nor_a_resolver` drives `compose_with` with an injected install failure; - `the_desktop_platform_composes_the_feed_and_no_resolver` (in `platform_desktop.rs`) calls the desktop's `PLATFORM.media.compose`; - a zero-driver publish; - reading back the published resolver. The URI boot rig's 18 calls, and `install_exported_uri`, now publish through `publish_composition`. A rig adapter is Feed plus URI, so its session set is now `BOTH` (it was `FEED`). That is the set a production boot publishes with both drivers. Results on the committed tree at 036034fe7: - The app crate's lib tests without `hostsim` (`make test-crate C=app`), each by name: `a_composed_uri_driver_is_published_with_its_resolver`, `a_refused_uri_install_publishes_neither_the_driver_nor_a_resolver` and `a_controlled_boot_composes_no_uri_driver_and_no_resolver`, each `test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 1503 filtered out` - `make test-hostsim T=uri_boot`: `test result: ok. 29 passed; 0 failed; 0 ignored; 0 measured; 1725 filtered out` - `make test-hostsim T=the_desktop_platform_composes_the_feed_and_no_resolver`: `test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 1753 filtered out` - `make check-nodef PLAYBACK_BACKENDS=feed`: exit 0 - The four static gates are green. Results on b951d2ae4, the head before the test-only fix commit: - `make test-crate C=plx_media`: `test result: ok. 2159 passed; 0 failed; 104 ignored; 0 measured; 0 filtered out` - Full `make test-hostsim`, without two tests that kill the test binary (SIGSEGV) on the lane's Mac at base 8f5575182 as well: 1750 passed, 2 failed. The two failures were in `deeplink_route_tests`, which passed on rerun: `test result: ok. 9 passed; 0 failed`. - `make check-nodef PLAYBACK_BACKENDS=both|uri|feed|none`: all four compile. - `make check-replay`: `6 fixtures, 12 replays, SAME=4 REFUSED_EXPECTED=8 unexpected=0` - `ci/test_readonly_generated.py` (22 tests) and `ci/test_readonly_dependencies.py` (64 tests) pass. - No Cargo, `.cargo` or certificate-pinned file changes. Both spellings of every touched path were checked against `ci/proofs/*.json`. ## Reviews - `fw-compat-reviewer` on b951d2ae4 found nothing. CI's firmware load matrix passes on all 9 gated releases, from 4.4.2 to 11.2.0. The binary still has 15 DT_NEEDED entries and 371 undefined symbols, as at base. `acb_init` still runs before `ffi::boot()` inside the same `if !controlled`, and no FFI, link directive or `dynlib!` changes. - `doc-claim-auditor` found three stale claims, all fixed. ## On the television On the dev TV (webOS 4.x, ACB), `--guest --mock`, base 8f5575182 against b951d2ae4. Both binaries were md5-verified on the set. No key was sent and no setting changed. - **Boot.** These lines are identical and in the same main-thread order on both: `vplane: ACB (webOS 4.x)`, `ptype=10`, the `acb initialize`/`create`/`handle=feed` lines, `ff: bound …`, `uri: product binding=Acb mode=1 …` and `uri: display path=acb ready`. Head adds `compose: backends=uri+feed resolver=yes` once, right after the display-path line. Neither build logs an installation-refused line. - **Feed.** `pipe_h264_aac_mp4` passes on both: `feed: presented`, 24.1 fps, `dropped=0`. - **URI.** `pipe_uri_product_hls_720p24_20m_bound` passes all 10 checks on both, including `uri_plane_bound`, `uri_presented` and `uri_service_playing`. - **`…_bound_collapse` fails identically on base and head.** The check is `uri_drain_warning: buffered lead fell 3 -> 2 …`. This change does not cause it. - **One line moves.** The identity line, `pms: server 0 version=…`, comes before `vplane:` on base and after `ptype=10` on head, 4 of 4 boots each way, including an interleaved repeat. That line comes from the `serverinfo` worker thread, not the main thread, so its position is a race; nothing at that point reads the version. The main thread's own order does not change. - The TV ran on b951d2ae4. The commit after it, 036034fe7, changes tests and one test-only cfg. ## Not covered - `check-nodef` only compiles. The single-backend shapes (`uri`, `feed`, `none`) are not built as tests or run anywhere in CI. --- docs/module-layers.md | 4 +- docs/platform-ports.md | 38 +++- rust-modules/media/src/route/decision.rs | 16 +- .../media/src/route/decision_version_tests.rs | 19 ++ rust-modules/src/app/adapters/backends.rs | 169 +++++++++++++----- rust-modules/src/app/boot.rs | 9 +- rust-modules/src/app/platform.rs | 105 ++++++++++- rust-modules/src/app/playback.rs | 6 - rust-modules/src/app/run.rs | 4 - rust-modules/src/app/run_uri_boot_tests.rs | 52 +++--- rust-modules/src/dev/uriprobe.rs | 2 +- rust-modules/src/dev/uriprobe_tests.rs | 2 +- rust-modules/src/platform_desktop.rs | 49 ++++- rust-modules/src/port.rs | 15 +- 14 files changed, 378 insertions(+), 112 deletions(-) diff --git a/docs/module-layers.md b/docs/module-layers.md index 714e309898..a969fdebf9 100644 --- a/docs/module-layers.md +++ b/docs/module-layers.md @@ -358,8 +358,8 @@ 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 `player/`, `play-uri/`, `os`'s `tv/`, `tv.rs` and `webos/`, `port.rs`, `platform_desktop.rs` (each platform's table names its own sink) and `app/adapters/backends.rs`; `play-feed/` may name the trait but never resolves `installed`), and the URI media pipe through -`tv::uri::installed()`, resolved once by the composition (`app/adapters/backends.rs::install_uri_product`, every build with the -`play-uri` feature) and, in a `devtriggers` build, again by the media wrapper `player::uriprobe_drive` for the developer probe. The independent +`tv::uri::installed()`, resolved once by the webOS platform's composition (`app/adapters/backends.rs::compose_native`, which calls +`install_uri_product`, in a build with the `play-uri` feature; the desktop platform composes the Feed only and never resolves it) and, in a `devtriggers` build, again by the media wrapper `player::uriprobe_drive` for the developer probe. The independent `play-uri` driver receives that transport and a shared `DisplaySink` as injected ports; it does not read the webOS port registry or the feed-only `VideoSink` itself. Lazily computed facts (device identity, the sandbox verdict, the Dolby Vision capability) are diff --git a/docs/platform-ports.md b/docs/platform-ports.md index 49fe3eb595..5071fff48a 100644 --- a/docs/platform-ports.md +++ b/docs/platform-ports.md @@ -998,26 +998,39 @@ Ecore names to `remote_token_key` pairs". ### 6. Media, as four things - a. Composition and the two boot phases (review M5, C3; critic F7). `Platform.media` is `MediaBoot { early_init: - fn(&MainThread), compose: fn(&mut PlayerAdapter, &PlaybackSession, controlled: bool) -> Composition }`, with - `Composition { resolver: Option }`: + fn(&MainThread), compose: fn(&mut PlayerAdapter, controlled: bool) -> Composition }`, with + `Composition { resolver: Option }` (W6b landed this shape; the `&PlaybackSession` parameter this + paragraph first named is dropped, see the deviation below): - `early_init` runs at today's `acb_init` site (`app/boot.rs:2043`, inside `if !controlled`, before `ffi::boot()`, F32). webOS fills it with `acb_init`, the others with a no-op. - `compose` runs where `compose_backends` runs (`:2323`). webOS fills it with today's function (`backends.rs:64,141-164`) minus both publications; the desktop installs HostSink Feed; Tizen installs nothing (W9), then its URI driver (W10). It returns the resolver of a URI product only when the physical install succeeded (today's `install_uri_product_with_ports`, `:418-421`); `None` on a refused install, a - controlled boot or no URI driver. It reads the session (`&PlaybackSession`: a driver may need a snapshot) and - publishes nothing. + controlled boot or no URI driver. It publishes nothing. Deviation, W6b: it takes no `&PlaybackSession`. The + session was read by nothing in the composition (the only session use was the resolver publication that moved + out), so the parameter would have been dead; W10 adds a read-only session parameter if a Tizen driver needs + one. - After `compose` returns, the APP publishes both facts in one function, once, always: the resolver (`install_uri_preflight_port`) if present, then `install_backends(adapter.composed_backends())`, - `BackendSet::NONE` included (`backends.rs:163` and `:421` moved app-side, F43). The session starts at `FEED` + `BackendSet::NONE` included (`backends.rs:163` and `:421` moved app-side, F43; landed in W6b as + `app::platform::publish_composition`, which also logs the one `compose: backends= resolver=` + line). The session starts at `FEED` (F31), so a zero-driver platform that forgot the call would offer Feed, and a set that advertised URI without its resolver would reach the planner as `NoPort`. No platform keeps adapter and session in step. - The Cargo feature `play-uri` (`rust-modules/Cargo.toml:81`) keeps meaning "the webOS ACB URI driver" and is - webOS-only. `PLAYBACK_BACKENDS` maps per platform (Tizen: its own `uri` feature; `play-uri` never). The 37 - `feature = "play-uri"` sites in `rust-modules/src` are sorted in W6b: composition and `acb_init` go to the - webOS platform; `playback.rs`, `run.rs` and `dev.rs` read `adapter.composed_backends()` at run time, or stay - webOS-platform code if they name ACB. + webOS-only. `PLAYBACK_BACKENDS` maps per platform (Tizen: its own `uri` feature; `play-uri` never). The + `feature = "play-uri"` sites in `rust-modules/src` (37 when this was written, 51 at W6b: #1478 added 14 to + `backends.rs`) are sorted in W6b: the 10 in `playback.rs` and `run.rs` read the installed drivers at run + time (the attempt's backend, the adapter's queues, the resolver's offer) and lost their gate; every site that + remains names ACB or the URI product and keeps it (`git grep -n 'feature = "play-uri"' -- rust-modules/src` + lists them: `backends.rs`, `dev.rs`, `lib.rs`'s ARM guard and two test files). + Composition is a SEAM until W11a, not a move: `port.rs` fills `Platform.media` with + `backends::acb_init` and `backends::compose_native`, and the bodies stay in `app/adapters/backends.rs`. They + cannot go to `port` yet, because `dev/uri_product.rs`, `dev/uri_exported.rs`, `run_uri_boot_tests.rs` and + `backends.rs`'s own tests name `UriProduct`, `UriDriverSettings` and `install_uri_product_with_ports`, and the + layer fence forbids anything outside the webOS platform naming `port`. W11a moves the file whole, with its + callers. - b. Evidence is the driver's, in three separate decisions (review B3, C5; critic M1, F12). - Display readiness: `UriDriver::display() -> DisplayEvidence { readiness: Ready | NotReady(DisplayUnavailable), preview_rectangle, tag }`, beside the capabilities and certification its offers carry. `Binding` leaves the @@ -1588,6 +1601,13 @@ W3d. Neutral types (L15b item 2 prerequisites; part of item 3). shows `acb_init` at the same point. - Risk: `acb_init`'s order relative to `ffi::boot()` and the first frame; moving it into `compose` would change its timing (review M5). +- As landed: the seam, not the move (Target shape 6a, "Composition is a SEAM until W11a"). `port.rs` fills + `Platform.media` with `backends::acb_init` and `backends::compose_native`; the bodies stay in + `app/adapters/backends.rs` until W11a, because dev and the tests name `UriProduct` and its siblings and the fence + forbids them naming `port`. `early_init` is called at the old `acb_init` line and `compose` at the old + `compose_backends` line, so neither phase moved. `dev.rs`, `lib.rs` and the `sink` + rule are unchanged (`backends.rs` stays an allowed path). The desktop composes the Feed over the host sink and no + URI driver; its `early_init` is a no-op. ### W6c (N). A URI-only and a two-driver composition play an ordinary title (host tests, before W10) - Goal (review B3, M8, C5; critic M1): through the real planner, with `FakeUriDriver` (`test_support.rs:143`) carrying diff --git a/rust-modules/media/src/route/decision.rs b/rust-modules/media/src/route/decision.rs index d150d6b920..4713c9c561 100644 --- a/rust-modules/media/src/route/decision.rs +++ b/rust-modules/media/src/route/decision.rs @@ -1342,8 +1342,20 @@ impl PlaybackSession { self.source_selection = Some(selection); } - pub fn install_uri_preflight_port(&mut self, port: super::uri_preflight::ResolvePort) { - self.uri_preflight_port = Some(port); + /// Publish the composition's resolver, or its absence: a boot whose URI install was refused (or + /// that composed no URI driver) passes `None`, and the planner then answers `UriDecline::NoPort`. + /// Takes `Some(port)` or a bare port, so the set of installed drivers and this resolver are + /// published by the one call the boot makes (`app::platform::publish_composition`). + pub fn install_uri_preflight_port( + &mut self, + port: impl Into>, + ) { + self.uri_preflight_port = port.into(); + } + + /// The resolver the composition published, `None` when it published none. + pub fn uri_preflight_port(&self) -> Option<&super::uri_preflight::ResolvePort> { + self.uri_preflight_port.as_ref() } /// The playback backends the composition supplies. Boot installs the set its drivers form diff --git a/rust-modules/media/src/route/decision_version_tests.rs b/rust-modules/media/src/route/decision_version_tests.rs index 6413617158..0f0c396210 100644 --- a/rust-modules/media/src/route/decision_version_tests.rs +++ b/rust-modules/media/src/route/decision_version_tests.rs @@ -1271,3 +1271,22 @@ fn the_picked_version_rides_the_request_and_the_landing() { test_support::apply_plan(&mut ps, Plan { media_index: 1, ..Default::default() }, "rk-v"); assert_eq!(cur_media_index(&ps), 1); } + +/// The composition's resolver is published as a value, absence included: a bare port installs it, +/// `None` clears it, and the reader says which. The boot's one publisher relies on all three +/// (`app::platform::publish_composition` passes the compose's `Option` straight through). +#[test] +fn the_published_resolver_is_readable_and_an_absence_clears_it() { + use crate::route::uri_preflight::{CarrierQualifier, ProductEvidence, ResolvePort}; + let port = || ResolvePort::new( + ProductEvidence::unqualified_on(plx_playback_contract::uri::DisplayEvidence::ready("test")), + std::sync::Arc::new(CarrierQualifier)); + let mut ps = crate::route::PlaybackSession::IDLE; + assert!(ps.uri_preflight_port().is_none(), "a session nobody published to holds none"); + ps.install_uri_preflight_port(port()); + assert!(ps.uri_preflight_port().is_some(), "a bare port installs"); + ps.install_uri_preflight_port(Some(port())); + assert!(ps.uri_preflight_port().is_some(), "so does a `Some`"); + ps.install_uri_preflight_port(Option::::None); + assert!(ps.uri_preflight_port().is_none(), "an absence clears it"); +} diff --git a/rust-modules/src/app/adapters/backends.rs b/rust-modules/src/app/adapters/backends.rs index d82b91c03d..6c22f7cb30 100644 --- a/rust-modules/src/app/adapters/backends.rs +++ b/rust-modules/src/app/adapters/backends.rs @@ -10,9 +10,13 @@ //! to it (`PlaneOwner::ensure_handle`, run by `UriDriver::ready_to_start`), so a viewer who //! never plays through it never has a second ACB core (#1394), while a normal boot still //! composes the URI driver `Acb` with no `ptype` trigger. -//! - [`compose_backends`] installs the product URI driver and then tells the route session which -//! backends the installed drivers form, so policy offers what is physically there instead of -//! what Cargo features happened to be on. +//! - [`compose_feed`] and [`compose_native`] install what a platform's drivers are: the Feed (or, with +//! none, the platform's display sink) for every platform, and on webOS the product URI driver +//! too. They publish nothing: they return what they composed, and the application's one +//! publisher (`app::platform::publish_composition`) tells the route session the set the +//! installed drivers form, so policy offers what is physically there instead of what Cargo +//! features happened to be on. `port.rs` and `platform_desktop.rs` name these two through +//! `Platform::media`; the bodies stay here until the webOS platform owns this file. //! - [`install_uri_product`] builds the product URI driver (`plx_play_uri::backend::UriBackend`) //! from the installed display and URI bus and hands it to the player adapter, which holds it //! only as a `UriDriver`. The player crate names neither the driver nor its settings. @@ -21,8 +25,9 @@ use plx_base::task::MainThread; use plx_media::player::adapter::PlayerAdapter; #[cfg(feature = "play-feed")] use plx_media::player::adapter::StartHooks; -use plx_media::route::PlaybackSession; +use plx_media::route::uri_preflight::ResolvePort; use plx_os::tv::plane::{self, PlaneFacts, PlaneOwner}; +use crate::app::platform::Composition; #[cfg(feature = "play-feed")] use plx_os::tv::plane::DEFAULT_PLAYER_TYPE; #[cfg(feature = "play-feed")] @@ -41,7 +46,7 @@ use plx_play_feed::{control::FeedBackend, feed_resources::{FeedResources, LoadRe use plx_os::tv::sink::{RefusingSink, UnloadTicket, VideoSink}; #[cfg(feature = "play-uri")] use plx_media::route::uri_preflight::{KnownSource, OriginalQualifier, OriginalRequest, - ProductEvidence, ResolvePort, UriDecline, Verdict, SOURCE_VERDICT_TTL}; + ProductEvidence, UriDecline, Verdict, SOURCE_VERDICT_TTL}; #[cfg(feature = "play-uri")] use plx_play_uri::backend::{Binding as UriBinding, Config as UriConfig, MonotonicClock, UriBackend}; #[cfg(feature = "play-uri")] @@ -139,12 +144,10 @@ fn acb_init_acb(mt: &MainThread, display: &dyn DisplaySink, owner: &PlaneOwner) owner.boot(PlaneFacts::ABSENT); } -/// Compose the backends this boot supplies. A normal boot installs the product URI driver first -/// (a refused install leaves URI out of the set); a controlled run (replay, scripted Home) touches -/// no native port and so installs none. Then the session is told the set the installed drivers -/// form. -pub(crate) fn compose_backends(adapter: &mut PlayerAdapter, session: &mut PlaybackSession, - controlled: bool) { +/// Compose the Feed into the adapter, or, in a build with no Feed, hand the adapter the platform's +/// own display sink: the part of a composition every platform shares (the television's and the +/// desktop's alike). Installs no URI driver and tells no session anything. +pub(crate) fn compose_feed(adapter: &mut PlayerAdapter) { #[cfg(feature = "play-feed")] if !adapter.composed_backends().feed && !install_feed(adapter, &TV_HOOKS) { log("feed: physical set installation refused"); @@ -155,17 +158,34 @@ pub(crate) fn compose_backends(adapter: &mut PlayerAdapter, session: &mut Playba if !adapter.install_display_sink(sink::installed) { log("player: display sink installation refused"); } +} + +/// The webOS composition, [`Platform::media`](crate::app::platform::Platform)'s `compose` for the +/// television: [`compose_with`] over the product URI driver this build has (none in a build without +/// `play-uri`). +pub(crate) fn compose_native(adapter: &mut PlayerAdapter, controlled: bool) -> Composition { #[cfg(feature = "play-uri")] - if !controlled && !install_uri_product(adapter, session) { - log("uri: product driver installation refused"); - } + let install_uri = install_uri_product; #[cfg(not(feature = "play-uri"))] - let _ = controlled; + let install_uri = |_: &mut PlayerAdapter| None; + compose_with(adapter, controlled, install_uri) +} + +/// Compose the backends a television boot supplies, with the URI driver installed by `install_uri`. +/// The Feed first; then, on a normal boot only, the URI driver (a refused install leaves URI out of +/// the set and yields no resolver); a controlled run (replay, scripted Home) touches no native port +/// and so installs none. What the adapter holds afterwards is the set the session is told, and the +/// resolver returned is `Some` only when `install_uri` installed the driver the resolver describes. +/// The boot passes the product installer; a host rig passes one over its own ports. +pub(crate) fn compose_with(adapter: &mut PlayerAdapter, controlled: bool, + install_uri: impl FnOnce(&mut PlayerAdapter) -> Option) -> Composition { + compose_feed(adapter); + let resolver = if controlled { None } else { install_uri(adapter) }; // The URI-mode probe (issue #1064) rides every boot, controlled or not: it reads its trigger // file only when a play starts. #[cfg(all(feature = "devtriggers", feature = "play-uri"))] crate::dev::uriprobe::install(adapter); - session.install_backends(adapter.composed_backends()); + Composition { resolver } } /// The hooks table the Feed's native executor runs over, built over the raw sink, the slice @@ -447,7 +467,7 @@ impl UriProduct { /// `dev::uri_product`. A debug build's exported-window override, `dev::uri_exported`, is read here /// too but certifies nothing: it only composes the display path.) #[cfg(feature = "play-uri")] -pub(crate) fn install_uri_product(adapter: &mut PlayerAdapter, session: &mut PlaybackSession) -> bool { +pub(crate) fn install_uri_product(adapter: &mut PlayerAdapter) -> Option { let display = sink::display_installed(); let binding = uri_product_binding(display, plx_os::tv::device::info().major, plx_play_uri::backend::EXPORTED_STRATA); @@ -463,19 +483,23 @@ pub(crate) fn install_uri_product(adapter: &mut PlayerAdapter, session: &mut Pla // product is returned as built. #[cfg(feature = "devtriggers")] let product = crate::dev::uri_product::compose(product, crate::dev::uri_product::trigger()); - install_uri_product_with_ports(adapter, session, product, plx_os::tv::uri::installed(), display) + let resolver = install_uri_product_with_ports(adapter, product, plx_os::tv::uri::installed(), display); + if resolver.is_none() { + log("uri: product driver installation refused"); + } + resolver } /// One boot composition for both real and injected ports. The driver is configured with the binding /// and the capabilities an opted-in viewer certifies ([`UriProduct::driver_capabilities`]); the -/// resolver receives the product's evidence joined to the display the installed driver reports, only -/// after physical installation succeeds. The boot log names that display, so a television's log -/// shows what the driver reported without a trigger. +/// resolver, returned for the caller to publish, receives the product's evidence joined to the +/// display the installed driver reports, only after physical installation succeeds: `None` is a +/// refused install, and the adapter then holds no URI driver. The boot log names that display, so a +/// television's log shows what the driver reported without a trigger. #[cfg(feature = "play-uri")] -pub(crate) fn install_uri_product_with_ports(adapter: &mut PlayerAdapter, - session: &mut PlaybackSession, product: UriProduct, +pub(crate) fn install_uri_product_with_ports(adapter: &mut PlayerAdapter, product: UriProduct, transport: &'static dyn plx_os::tv::uri::UriMedia, - display: &'static dyn DisplaySink) -> bool { + display: &'static dyn DisplaySink) -> Option { let settings = UriDriverSettings { clock: Box::new(ProductUriClock(plx_media::player::adapter::MonotonicMs::start())), app_id: plx_base::paths::app_id().to_owned(), @@ -485,9 +509,7 @@ pub(crate) fn install_uri_product_with_ports(adapter: &mut PlayerAdapter, release_allowance_ms: 10_000, source_ttl_ms: 30_000, }; - let Some(path) = install_uri_backend_with_ports(adapter, settings, transport, display) else { - return false; - }; + let path = install_uri_backend_with_ports(adapter, settings, transport, display)?; let state = match path.readiness { DisplayReadiness::Ready => "ready".to_owned(), DisplayReadiness::NotReady(why) => format!("unavailable ({})", why.log_name()), @@ -495,8 +517,23 @@ pub(crate) fn install_uri_product_with_ports(adapter: &mut PlayerAdapter, log(&format!("uri: display path={} {state}", path.tag)); let evidence = ProductEvidence { display: path, callable: product.callable, certified: product.certified }; - session.install_uri_preflight_port(ResolvePort::new(evidence, product.qualifier)); - true + Some(ResolvePort::new(evidence, product.qualifier)) +} + +/// A host rig's composition of the product URI driver over its own ports, published as the boot +/// publishes: the install, then [`publish_composition`](crate::app::platform::publish_composition) +/// with the resolver it returned (the session learns the adapter's whole set, Feed included). +/// Whether the driver installed. Gated as its only caller is: the lifecycle rig's +/// `uri_boot_tests`, which `run.rs` builds under `hostsim` and `play-feed`. +#[cfg(all(test, feature = "hostsim", feature = "play-feed", feature = "play-uri"))] +pub(crate) fn install_and_publish_uri_product(adapter: &mut PlayerAdapter, + session: &mut plx_media::route::PlaybackSession, product: UriProduct, + transport: &'static dyn plx_os::tv::uri::UriMedia, + display: &'static dyn DisplaySink) -> bool { + let resolver = install_uri_product_with_ports(adapter, product, transport, display); + let installed = resolver.is_some(); + crate::app::platform::publish_composition(session, adapter, Composition { resolver }); + installed } /// Build the URI driver from `settings` over the captured platform ports and install it into @@ -787,18 +824,67 @@ mod tests { assert!(acb.contains(" major=4 evidence=none\n"), "{acb}"); } - #[test] + /// The television's own composition ([`compose_native`], which is what `Platform::media` names + /// for webOS, with the product installer behind it) over a fresh adapter and session, published + /// as the boot publishes it. #[cfg(feature = "play-uri")] - fn the_session_set_gains_uri_only_when_the_product_driver_is_installed() { + fn composed_natively(controlled: bool) -> (PlayerAdapter, plx_media::route::PlaybackSession) { let mut adapter = PlayerAdapter::new(unsafe { MainThread::assume() }); - let mut session = PlaybackSession::IDLE; - // A controlled run installs no driver: the set is what the drivers form, not what - // Cargo features were on. - compose_backends(&mut adapter, &mut session, true); - assert!(!session.backends().contains(plx_playback_contract::BackendKind::Uri)); - compose_backends(&mut adapter, &mut session, false); - assert!(session.backends().contains(plx_playback_contract::BackendKind::Uri), - "an installed product driver is offered"); + let mut session = plx_media::route::PlaybackSession::IDLE; + let composed = compose_native(&mut adapter, controlled); + crate::app::platform::publish_composition(&mut session, &adapter, composed); + (adapter, session) + } + + /// The composition over an injected URI installer, for the one outcome the product installer + /// cannot be made to produce here: a refused install. + #[cfg(feature = "play-uri")] + fn composed_and_published(controlled: bool, + install_uri: impl FnOnce(&mut PlayerAdapter) -> Option) + -> (PlayerAdapter, plx_media::route::PlaybackSession) { + let mut adapter = PlayerAdapter::new(unsafe { MainThread::assume() }); + let mut session = plx_media::route::PlaybackSession::IDLE; + let composed = compose_with(&mut adapter, controlled, install_uri); + crate::app::platform::publish_composition(&mut session, &adapter, composed); + (adapter, session) + } + + #[test] + #[cfg(feature = "play-uri")] + fn a_composed_uri_driver_is_published_with_its_resolver() { + let (adapter, session) = composed_natively(false); + assert!(adapter.composed_backends().uri, "the product driver installed"); + assert_eq!(session.backends(), adapter.composed_backends(), "the session is told the adapter's set"); + assert!(session.uri_preflight_port().is_some(), "and the resolver that driver comes with"); + } + + #[test] + #[cfg(feature = "play-uri")] + fn a_refused_uri_install_publishes_neither_the_driver_nor_a_resolver() { + // The physical install refuses a driver that claims the packet feed; the composition yields + // no resolver for it, and the adapter holds no URI driver. + let ports = (&plx_os::tv::uri::NoUriMedia, &sink::NoSink); + let (adapter, session) = composed_and_published(false, |adapter| { + install_uri_backend_with_ports(adapter, settings(true), ports.0, ports.1) + .map(|_| unreachable!("a packet-feed driver is refused")) + }); + assert!(!adapter.composed_backends().uri); + assert!(!session.backends().uri, "the session offers no URI backend"); + assert!(session.uri_preflight_port().is_none(), "and holds no resolver for one"); + assert_eq!(session.backends(), adapter.composed_backends()); + } + + #[test] + #[cfg(feature = "play-uri")] + fn a_controlled_boot_composes_no_uri_driver_and_no_resolver() { + // The same composition as the normal boot's test above, with the one flag a replay or a + // scripted Home sets: it touches no native port, so the product driver is not installed. + let (adapter, session) = composed_natively(true); + assert!(!adapter.composed_backends().uri); + assert!(!session.backends().uri); + assert!(session.uri_preflight_port().is_none()); + assert_eq!(session.backends(), adapter.composed_backends(), + "the Feed is composed as in a normal boot (or the build has none)"); } #[cfg(feature = "play-uri")] @@ -971,9 +1057,8 @@ mod tests { fn the_boot_log_names_the_display_the_installed_driver_reports() { let line = |binding| plx_base::eventlog::with_private_log(|| { let mut adapter = PlayerAdapter::new(unsafe { MainThread::assume() }); - let mut session = PlaybackSession::IDLE; - assert!(install_uri_product_with_ports(&mut adapter, &mut session, - UriProduct::production(binding), &plx_os::tv::uri::NoUriMedia, &sink::NoSink)); + assert!(install_uri_product_with_ports(&mut adapter, + UriProduct::production(binding), &plx_os::tv::uri::NoUriMedia, &sink::NoSink).is_some()); std::fs::read_to_string(plx_base::eventlog::events_log()).unwrap_or_default() }); let acb = line(UriBinding::Acb); diff --git a/rust-modules/src/app/boot.rs b/rust-modules/src/app/boot.rs index a24fa1d82a..553163d685 100644 --- a/rust-modules/src/app/boot.rs +++ b/rust-modules/src/app/boot.rs @@ -1973,7 +1973,7 @@ pub(crate) unsafe fn construct( activate_session(&mut bridge, &mut pages, &mut super::recorder::Recplay::Off) }; if !controlled { - super::adapters::backends::acb_init(&mt); // every backend set: the plane owner's boot facts + (platform.media.early_init)(&mt); // every backend set: the platform's boot facts (webOS: the plane owner's) plx_media_codecs::ffi::boot(); // Codec resource boot; controlled Home cannot invoke ABI probes. } // dev: /tmp/plxnative-logintest validates the plex.tv account path end-to-end on the device — a @@ -2248,12 +2248,13 @@ pub(crate) unsafe fn construct( let adapters = super::Adapters { player: plx_media::player::adapter::PlayerAdapter::new(mt), }; - // The session's backend set is the one the installed drivers form (after the product URI driver - // is installed, and for every build, not only a URI one). + // The platform installs its drivers, and the session is told what they form: the set and the + // resolver, together, for every platform (`platform::publish_composition`). let (player, adapters) = { let mut player = player; let mut adapters = adapters; - super::adapters::backends::compose_backends(&mut adapters.player, &mut player.session, controlled); + let composed = (platform.media.compose)(&mut adapters.player, controlled); + super::platform::publish_composition(&mut player.session, &adapters.player, composed); (player, adapters) }; let repause_at = 0i64; diff --git a/rust-modules/src/app/platform.rs b/rust-modules/src/app/platform.rs index d9ffd985a5..87765c0e75 100644 --- a/rust-modules/src/app/platform.rs +++ b/rust-modules/src/app/platform.rs @@ -1,7 +1,7 @@ //! The platform the application runs on, as only the loop reads it. //! //! [`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: +//! it does not compile. It carries four 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). @@ -12,11 +12,20 @@ //! 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`). +//! - `media`: [`MediaBoot`], the platform's two boot-time playback steps. `early_init` runs once before +//! the first adapter exists; `compose` installs the platform's drivers on the adapter and hands +//! back what it composed as a [`Composition`]. The boot then tells the route session what the +//! platform composed through [`publish_composition`], the one function that does, so the set of +//! installed drivers and the resolver the planner reads cannot disagree. //! //! `Shell`, `FrameProbe` and `Platform` are app-private on purpose: no type a platform's shell has //! 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_base::task::MainThread; +use plx_media::player::adapter::PlayerAdapter; +use plx_media::route::uri_preflight::ResolvePort; +use plx_media::route::PlaybackSession; use plx_os::tv::Services; use std::os::raw::c_void; @@ -60,6 +69,53 @@ pub(crate) trait FrameProbe: Sync { fn fields(&self) -> String; } +/// What a platform's composition installed that the route session also has to know: the resolver the +/// planner asks before it offers a URI source. `Some` only when the physical URI install succeeded, +/// so it is present exactly when the composed set holds a URI driver. +/// +/// `Composition::default()` is a platform that composed no URI driver (the Feed or nothing): no resolver. +#[derive(Default)] +pub(crate) struct Composition { + pub(crate) resolver: Option, +} + +/// A platform's two playback steps at boot. Both are plain functions: the platform's entry states +/// them once, in its `static`, and the boot calls them through [`Platform::media`]. +pub(crate) struct MediaBoot { + /// Before the first adapter exists, once per process. The caller runs it only on a boot that + /// touches the television (not a controlled one), so a platform's body never asks. + pub(crate) early_init: fn(&MainThread), + /// Install this platform's drivers on the adapter, and return what the session must also be told. + /// `controlled` is a replay or scripted Home, which touches no native port and so installs no + /// native driver. It takes no session and publishes nothing: [`publish_composition`] does that. + pub(crate) compose: fn(&mut PlayerAdapter, controlled: bool) -> Composition, +} + +/// Tell the route session what the platform composed: the resolver first, then the backend set the +/// adapter's installed drivers form, and log what it published in the one `compose:` line (the +/// television's boot log shows it). One call, every boot, for every platform: a platform that +/// composed nothing still publishes `BackendSet::NONE` (and no resolver), instead of leaving the +/// session on the Feed-only default, which would offer a backend nothing installed. +pub(crate) fn publish_composition( + session: &mut PlaybackSession, + adapter: &PlayerAdapter, + composed: Composition, +) { + let set = adapter.composed_backends(); + let named = match (set.uri, set.feed) { + (true, true) => "uri+feed", + (true, false) => "uri", + (false, true) => "feed", + (false, false) => "none", + }; + plx_base::eventlog::log(&format!( + "compose: backends={named} resolver={}", + if composed.resolver.is_some() { "yes" } else { "no" } + )); + session.install_uri_preflight_port(composed.resolver); + session.install_backends(set); +} + /// Everything the application needs from its platform. Built by the platform's entry (`port.rs` for /// webOS) with [`Platform::new`] and passed to `run_application`, which keeps it as `App::platform`. /// @@ -71,16 +127,18 @@ pub(crate) struct Platform { services: &'static Services, pub(crate) shell: &'static dyn Shell, pub(crate) diag: &'static dyn FrameProbe, + pub(crate) media: MediaBoot, } impl Platform { - /// A platform's entry states its three parts once, in a `static`. + /// A platform's entry states its four parts once, in a `static`. pub(crate) const fn new( services: &'static Services, shell: &'static dyn Shell, diag: &'static dyn FrameProbe, + media: MediaBoot, ) -> Self { - Platform { services, shell, diag } + Platform { services, shell, diag, media } } /// Hand the lower layers the platform's `tv` services, once: `run_application` does it before @@ -124,12 +182,27 @@ impl FrameProbe for HostProbe { } } +#[cfg(test)] +impl MediaBoot { + /// The media boot of a process with no platform: nothing to initialize and no driver to install. + pub(crate) const HOST_TEST: MediaBoot = MediaBoot { early_init: host_test_early_init, compose: host_test_compose }; +} + +#[cfg(test)] +fn host_test_early_init(_mt: &MainThread) {} + +#[cfg(test)] +fn host_test_compose(_adapter: &mut PlayerAdapter, _controlled: bool) -> Composition { + Composition::default() +} + #[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`. 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); + pub(crate) const HOST_TEST: Platform = + Platform::new(&Services::HOST_TEST, &HostShell, &HostProbe, MediaBoot::HOST_TEST); } #[cfg(test)] @@ -142,7 +215,7 @@ mod tests { /// 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; + let Platform { services, shell: s, diag: p, media } = Platform::HOST_TEST; assert!( matches!((services.identity.system_locale)(), plx_os::tv::LocaleReply::NoPlatform), @@ -165,5 +238,27 @@ mod tests { p.waiting(); p.acquired(); assert_eq!(p.fields(), "", "an unarmed probe has nothing to log"); + + // SAFETY: a host test owns the one thread it runs the media boot on. + let mt = unsafe { MainThread::assume() }; + (media.early_init)(&mt); + let mut adapter = PlayerAdapter::new(mt); + let composed = (media.compose)(&mut adapter, false); + assert!(composed.resolver.is_none(), "the host platform composes no URI driver"); + assert_eq!(adapter.composed_backends(), plx_playback_contract::BackendSet::NONE, + "and installs no driver of any kind"); + } + + /// **The one publisher.** A platform that composed nothing still publishes: the session leaves + /// its Feed-only default for `NONE`, and the resolver is the absence the compose returned. + #[test] + fn publishing_a_composition_that_installed_nothing_replaces_the_feed_default_with_none() { + let mut session = PlaybackSession::IDLE; + assert_eq!(session.backends(), plx_playback_contract::BackendSet::FEED, + "the session starts on the Feed-only default"); + let adapter = PlayerAdapter::new(unsafe { MainThread::assume() }); + publish_composition(&mut session, &adapter, Composition::default()); + assert_eq!(session.backends(), plx_playback_contract::BackendSet::NONE); + assert!(session.uri_preflight_port().is_none()); } } diff --git a/rust-modules/src/app/playback.rs b/rust-modules/src/app/playback.rs index c8196e575a..9ebc5ce0da 100644 --- a/rust-modules/src/app/playback.rs +++ b/rust-modules/src/app/playback.rs @@ -532,7 +532,6 @@ pub(crate) fn close_player_overlays(pages: &mut plx_ui::dispatch::Dispatcher { - #[cfg(feature = "play-uri")] if ps.attempt_view().backend() == Some(plx_media::player::attempt_view::Backend::Uri) { if pa.uri_maps_track(ps, plx_playback_contract::TrackKind::Audio, carried.sid) == Some(false) @@ -664,7 +660,6 @@ pub(crate) fn commit_track( // The route commits the pick and performs the sidecar half of it too // (`route::commit_subtitle_and_sidecar`): the sidecar policy lives beside the track memory's. TrackCommit::Subtitle { render_ordinal, stream_id, sidecar_key, sidecar_codec, memo } => { - #[cfg(feature = "play-uri")] if ps.attempt_view().backend() == Some(plx_media::player::attempt_view::Backend::Uri) { if render_ordinal < 0 || sidecar_key.is_some() || pa.uri_maps_track(ps, plx_playback_contract::TrackKind::Subtitle, @@ -683,7 +678,6 @@ pub(crate) fn commit_track( // the route holds the mode and remembers `ForcedOnly { lang }` when it changed, and drops // any sidecar (`route::commit_forced_only_and_sidecar`). TrackCommit::SubtitleForcedOnly { render_ordinal, stream_id, lang, changed } => { - #[cfg(feature = "play-uri")] if ps.attempt_view().backend() == Some(plx_media::player::attempt_view::Backend::Uri) { let memo = changed.then(|| plx_plex::plex::session::prefs::SubtitleMemo::ForcedOnly { diff --git a/rust-modules/src/app/run.rs b/rust-modules/src/app/run.rs index c0d8025e34..dd5ba848b2 100644 --- a/rust-modules/src/app/run.rs +++ b/rust-modules/src/app/run.rs @@ -2288,7 +2288,6 @@ pub(crate) unsafe fn playback_tick(app: &mut App, fr: &mut Frame) { let _ = app.adapters.player.backend_set_foreground_at(&mut app.player.session, foreground, backend_at); // A playback the server ended is retired whichever backend plays it; the Feed's `pump` opens // with the same door. - #[cfg(feature = "play-uri")] if foreground { plx_media::player::retire_if_server_stopped(&mut app.player.session, &mut app.adapters.player); } @@ -2316,10 +2315,8 @@ pub(crate) unsafe fn playback_tick(app: &mut App, fr: &mut Frame) { // Engine and is polled here on every frame as well. let backend_at = app.adapters.player.backend_tick(); let _ = app.adapters.player.backend_poll_session_at(&mut app.player.session, backend_at); - #[cfg(feature = "play-uri")] super::playback::drain_uri_track_fallbacks(&mut app.player.session, &mut app.adapters.player, app.runtime.metadata_mut()); - #[cfg(feature = "play-uri")] if let Some(recovery) = app.adapters.player.take_released_uri_recovery() { // The driver has proved this exact URI owner Released and the adapter has retired // its reporter. Re-resolve the same source episode before generic report::tick can @@ -2957,7 +2954,6 @@ pub(crate) unsafe fn update(app: &mut App, fr: &mut Frame) { app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); // The resolved URI locator is an owned IO result. Install it against the // route ticket before the common start door chooses a physical backend. - #[cfg(feature = "play-uri")] if let Some(offer) = r.uri_offer { let offer_id = offer.offer_id(); if app.adapters.player.offer_qualified_uri(&mut app.player.session, offer).is_err() { diff --git a/rust-modules/src/app/run_uri_boot_tests.rs b/rust-modules/src/app/run_uri_boot_tests.rs index 94cd0151f1..06c12a8227 100644 --- a/rust-modules/src/app/run_uri_boot_tests.rs +++ b/rust-modules/src/app/run_uri_boot_tests.rs @@ -212,7 +212,7 @@ mod uri_boot_tests { subtitle_track: true, audio_off: false, subtitle_off: false }; let product = UriProduct { binding: Binding::Exported { canvas: (1920, 1080) }, callable: caps, certified: caps, qualifier: Arc::new(QualifiedOriginal) }; - assert!(crate::app::adapters::backends::install_uri_product_with_ports( + assert!(crate::app::adapters::backends::install_and_publish_uri_product( &mut rig.app.adapters.player, &mut rig.app.player.session, product, bus, display)); rig.request(); let metric_request = rig.app.player.session.metric_request().expect("accepted URI request"); @@ -278,7 +278,7 @@ mod uri_boot_tests { .set_link(plx_plex::plex::probe::Location::Local); let bus: &'static Bus = Box::leak(Box::new(Bus::new())); let display: &'static Display = Box::leak(Box::new(Display)); - assert!(crate::app::adapters::backends::install_uri_product_with_ports( + assert!(crate::app::adapters::backends::install_and_publish_uri_product( &mut rig.app.adapters.player, &mut rig.app.player.session, composed_product(true, display), bus, display)); rig.request(); @@ -315,7 +315,7 @@ mod uri_boot_tests { .set_link(plx_plex::plex::probe::Location::Local); let bus: &'static Bus = Box::leak(Box::new(Bus::new())); let display: &'static Display = Box::leak(Box::new(Display)); - assert!(crate::app::adapters::backends::install_uri_product_with_ports( + assert!(crate::app::adapters::backends::install_and_publish_uri_product( &mut rig.app.adapters.player, &mut rig.app.player.session, composed_product(false, display), bus, display)); rig.request(); @@ -343,7 +343,7 @@ mod uri_boot_tests { let display: &'static Display = Box::leak(Box::new(Display)); let product = UriProduct { binding: Binding::Unbound, callable: ProductEvidence::CALLABLE, certified: ProductEvidence::UNCERTIFIED, qualifier: Arc::new(QualifiedOriginal) }; - assert!(crate::app::adapters::backends::install_uri_product_with_ports( + assert!(crate::app::adapters::backends::install_and_publish_uri_product( &mut rig.app.adapters.player, &mut rig.app.player.session, product, bus, display)); rig.request(); rig.release.send(()).unwrap(); @@ -380,7 +380,7 @@ mod uri_boot_tests { subtitle_track: false, audio_off: false, subtitle_off: false }; let product = UriProduct { binding: Binding::Exported { canvas: (1920, 1080) }, callable: caps, certified: caps, qualifier: Arc::new(QualifiedOriginal) }; - assert!(crate::app::adapters::backends::install_uri_product_with_ports( + assert!(crate::app::adapters::backends::install_and_publish_uri_product( &mut rig.app.adapters.player, &mut rig.app.player.session, product, bus, display)); rig.request(); rig.release.send(()).unwrap(); @@ -435,7 +435,7 @@ mod uri_boot_tests { subtitle_track: false, audio_off: false, subtitle_off: false }; let product = UriProduct { binding: Binding::Exported { canvas: (1920, 1080) }, callable: caps, certified: caps, qualifier: Arc::new(QualifiedOriginal) }; - assert!(crate::app::adapters::backends::install_uri_product_with_ports( + assert!(crate::app::adapters::backends::install_and_publish_uri_product( &mut rig.app.adapters.player, &mut rig.app.player.session, product, bus, display)); rig.request(); assert!(plx_media::route::arm_play_resume(&mut rig.app.player.session, 12_000_000_000), @@ -499,7 +499,7 @@ mod uri_boot_tests { .set_link(plx_plex::plex::probe::Location::Local); let bus: &'static Bus = Box::leak(Box::new(Bus::new())); let display: &'static Display = Box::leak(Box::new(Display)); - assert!(crate::app::adapters::backends::install_uri_product_with_ports( + assert!(crate::app::adapters::backends::install_and_publish_uri_product( &mut rig.app.adapters.player, &mut rig.app.player.session, acb_product(trigger), bus, display)); rig.request(); @@ -637,7 +637,7 @@ mod uri_boot_tests { subtitle_track: true, audio_off: false, subtitle_off: false }; let product = UriProduct { binding: Binding::Exported { canvas: (1920, 1080) }, callable: caps, certified: caps, qualifier: Arc::new(QualifiedOriginal) }; - assert!(crate::app::adapters::backends::install_uri_product_with_ports( + assert!(crate::app::adapters::backends::install_and_publish_uri_product( &mut rig.app.adapters.player, &mut rig.app.player.session, product, bus, display)); rig.request(); let request = rig.app.player.session.metric_request().expect("logical request"); @@ -718,7 +718,7 @@ mod uri_boot_tests { subtitle_track: true, audio_off: false, subtitle_off: false }; let product = UriProduct { binding: Binding::Exported { canvas: (1920, 1080) }, callable: caps, certified: caps, qualifier: Arc::new(QualifiedOriginal) }; - assert!(crate::app::adapters::backends::install_uri_product_with_ports( + assert!(crate::app::adapters::backends::install_and_publish_uri_product( &mut rig.app.adapters.player, &mut rig.app.player.session, product, bus, display)); rig.request(); let request = rig.app.player.session.metric_request().expect("logical request"); @@ -783,7 +783,7 @@ mod uri_boot_tests { subtitle_track: true, audio_off: false, subtitle_off: false }; let product = UriProduct { binding: Binding::Exported { canvas: (1920, 1080) }, callable: caps, certified: caps, qualifier: Arc::new(QualifiedOriginal) }; - assert!(crate::app::adapters::backends::install_uri_product_with_ports( + assert!(crate::app::adapters::backends::install_and_publish_uri_product( &mut rig.app.adapters.player, &mut rig.app.player.session, product, bus, display)); rig.request(); let request = rig.app.player.session.metric_request().expect("logical request"); @@ -892,7 +892,7 @@ mod uri_boot_tests { subtitle_track: true, audio_off: false, subtitle_off: false }; let product = UriProduct { binding: Binding::Exported { canvas: (1920, 1080) }, callable: caps, certified: caps, qualifier: Arc::new(QualifiedOriginal) }; - assert!(crate::app::adapters::backends::install_uri_product_with_ports( + assert!(crate::app::adapters::backends::install_and_publish_uri_product( &mut rig.app.adapters.player, &mut rig.app.player.session, product, bus, display)); rig.request(); rig.release.send(()).unwrap(); @@ -1017,7 +1017,7 @@ mod uri_boot_tests { subtitle_track: true, audio_off: false, subtitle_off: false }; let product = UriProduct { binding: Binding::Exported { canvas: (1920, 1080) }, callable: caps, certified: caps, qualifier: Arc::new(QualifiedTwoAudio) }; - assert!(crate::app::adapters::backends::install_uri_product_with_ports( + assert!(crate::app::adapters::backends::install_and_publish_uri_product( &mut rig.app.adapters.player, &mut rig.app.player.session, product, bus, display)); rig.request(); rig.release.send(()).unwrap(); @@ -1098,7 +1098,7 @@ mod uri_boot_tests { subtitle_track: true, audio_off: false, subtitle_off: false }; let product = UriProduct { binding: Binding::Exported { canvas: (1920, 1080) }, callable: caps, certified: caps, qualifier: Arc::new(QualifiedOriginal) }; - assert!(crate::app::adapters::backends::install_uri_product_with_ports( + assert!(crate::app::adapters::backends::install_and_publish_uri_product( &mut rig.app.adapters.player, &mut rig.app.player.session, product, bus, display)); rig.request(); rig.release.send(()).unwrap(); @@ -1154,7 +1154,7 @@ mod uri_boot_tests { subtitle_track: true, audio_off: false, subtitle_off: false }; let product = UriProduct { binding: Binding::Exported { canvas: (1920, 1080) }, callable: caps, certified: caps, qualifier: Arc::new(QualifiedTwoAudio) }; - assert!(crate::app::adapters::backends::install_uri_product_with_ports( + assert!(crate::app::adapters::backends::install_and_publish_uri_product( &mut rig.app.adapters.player, &mut rig.app.player.session, product, bus, display)); rig.request(); rig.release.send(()).unwrap(); @@ -1213,7 +1213,7 @@ mod uri_boot_tests { subtitle_track: true, audio_off: false, subtitle_off: false }; let product = UriProduct { binding: Binding::Exported { canvas: (1920, 1080) }, callable: caps, certified: caps, qualifier: Arc::new(QualifiedOriginal) }; - assert!(crate::app::adapters::backends::install_uri_product_with_ports( + assert!(crate::app::adapters::backends::install_and_publish_uri_product( &mut rig.app.adapters.player, &mut rig.app.player.session, product, bus, display)); rig.request(); rig.release.send(()).unwrap(); @@ -1286,7 +1286,7 @@ mod uri_boot_tests { subtitle_track: true, audio_off: false, subtitle_off: false }; let product = UriProduct { binding: Binding::Exported { canvas: (1920, 1080) }, callable: caps, certified: caps, qualifier: Arc::new(QualifiedOriginal) }; - assert!(crate::app::adapters::backends::install_uri_product_with_ports( + assert!(crate::app::adapters::backends::install_and_publish_uri_product( &mut rig.app.adapters.player, &mut rig.app.player.session, product, bus, display)); rig.request(); rig.release.send(()).unwrap(); @@ -1349,7 +1349,7 @@ mod uri_boot_tests { subtitle_track: true, audio_off: false, subtitle_off: false }; let product = UriProduct { binding: Binding::Exported { canvas: (1920, 1080) }, callable: caps, certified: caps, qualifier: Arc::new(QualifiedOriginal) }; - assert!(crate::app::adapters::backends::install_uri_product_with_ports( + assert!(crate::app::adapters::backends::install_and_publish_uri_product( &mut rig.app.adapters.player, &mut rig.app.player.session, product, bus, display)); rig.request(); rig.release.send(()).unwrap(); @@ -1468,9 +1468,10 @@ mod uri_boot_tests { const WINDOW_STARTUP_MS: u64 = 1_000; const WINDOW_RELEASE_MS: u64 = 500; - /// Compose the URI driver as the boot does (`install_uri_product_with_ports`: the opted-in - /// viewer's capabilities over an exported canvas), but on `clock` with short allowances, over - /// `display`, so a startup timeout and an unreleased close are reachable by moving the clock. + /// Compose the URI driver as the boot does (the opted-in viewer's capabilities over an exported + /// canvas, published through `platform::publish_composition`), but on `clock` with short + /// allowances, over `display`, so a startup timeout and an unreleased close are reachable by + /// moving the clock. fn install_exported_uri(rig: &mut Rig, bus: &'static Bus, display: &'static CountingDisplay, clock: Arc) { let caps = Capabilities { progressive_uri: true, hls_uri: false, @@ -1490,10 +1491,11 @@ mod uri_boot_tests { let path = crate::app::adapters::backends::install_uri_backend_with_ports( &mut rig.app.adapters.player, settings, bus, display) .expect("the URI driver installs"); - rig.app.player.session.install_uri_preflight_port( - plx_media::route::uri_preflight::ResolvePort::new( - ProductEvidence { display: path, callable: product.callable, - certified: product.certified }, product.qualifier)); + let resolver = plx_media::route::uri_preflight::ResolvePort::new( + ProductEvidence { display: path, callable: product.callable, + certified: product.certified }, product.qualifier); + crate::app::platform::publish_composition(&mut rig.app.player.session, + &rig.app.adapters.player, crate::app::platform::Composition { resolver: Some(resolver) }); } /// One frame of the app loop's playback half, as the other URI fixtures run it. @@ -1635,7 +1637,7 @@ mod uri_boot_tests { packet_feed: false, pause: true, seek: true, audio_track: true, subtitle_track: true, audio_off: false, subtitle_off: false }; let product = UriProduct { binding: Binding::Acb, callable: caps, certified: caps, qualifier }; - assert!(crate::app::adapters::backends::install_uri_product_with_ports( + assert!(crate::app::adapters::backends::install_and_publish_uri_product( &mut rig.app.adapters.player, &mut rig.app.player.session, product, bus, display)); assert!(display.created_player_types().is_empty(), "composing the driver creates no handle"); (bus, display) diff --git a/rust-modules/src/dev/uriprobe.rs b/rust-modules/src/dev/uriprobe.rs index 4889830fd5..9cf142e84d 100644 --- a/rust-modules/src/dev/uriprobe.rs +++ b/rust-modules/src/dev/uriprobe.rs @@ -19,7 +19,7 @@ use plx_media::route::RouteStartAttempt; use plx_play_uri::uriprobe::{AbrBps, Firmware, Kind, Settle, Trigger, Variant}; use plx_play_uri::uriprobe_drive::{DriverConfig, UriSession as CoreSession}; -/// Install the probe on the player adapter, once, at boot (`compose_backends`). +/// Install the probe on the player adapter, once, at boot (`backends::compose_with`). pub(crate) fn install(adapter: &mut PlayerAdapter) { adapter.install_uri_probe(Box::new(Probe)); } diff --git a/rust-modules/src/dev/uriprobe_tests.rs b/rust-modules/src/dev/uriprobe_tests.rs index 95bf499d7d..5ddd8183e3 100644 --- a/rust-modules/src/dev/uriprobe_tests.rs +++ b/rust-modules/src/dev/uriprobe_tests.rs @@ -924,7 +924,7 @@ mod hostsim { plx_media::route::CandidatePurpose::NewCandidate), "the prepared fixture source must qualify its stable Feed recipe"); let mut pa = crate::app::adapters::backends::test_adapter(); - // The composition installs the probe at boot (`compose_backends`); the fork is a boot. + // The composition installs the probe at boot (`backends::compose_with`); the fork is a boot. super::super::install(&mut pa); Fork { ps, pa, pms, _host: host } } diff --git a/rust-modules/src/platform_desktop.rs b/rust-modules/src/platform_desktop.rs index 3a412fb051..4eae281b66 100644 --- a/rust-modules/src/platform_desktop.rs +++ b/rust-modules/src/platform_desktop.rs @@ -27,7 +27,7 @@ //! made one of them reachable would fail to link for want of libwayland, glib or luna-service2, on //! a Mac and on Linux alike. `simulators.yml` links the shapes the simulator ships in to guard that //! until the platform crates split (`docs/platform-ports.md`, W7). -use crate::app::platform::{FrameProbe, Platform, Shell}; +use crate::app::platform::{Composition, FrameProbe, MediaBoot, Platform, Shell}; use plx_os::devcaps::dv::{self, DvCapability, DvProbe, ProbeSource}; use plx_os::tv::toast::{Identity, Outcome, Sent}; use plx_os::tv::{IdentityHooks, LegacyWebosMedia, SecureHooks, Services, StorageHooks, SystemHooks}; @@ -41,7 +41,8 @@ const SINK: &dyn plx_os::tv::sink::VideoSink = &crate::app::adapters::hostsim::H #[cfg(not(feature = "play-feed"))] const SINK: &dyn plx_os::tv::sink::VideoSink = &plx_os::tv::sink::NoSink; -/// The display binding the player's plane boot resolves: the same sink, so the plane is the host's. +/// The display binding the table must state. The desktop runs no plane boot, so nothing reads it in +/// production; it is the host sink only so that the hook is never `NoSink`. const DISPLAY: &dyn plx_os::tv::sink::DisplaySink = SINK; /// What the lower layers read from the desktop platform. Every hook is stated, as `tv` requires: a @@ -127,8 +128,24 @@ impl FrameProbe for DesktopProbe { } } +/// The desktop's media boot: nothing to initialize before the first adapter (the plane owner's +/// default facts are the absent ones the host sink's `VP_EXPORTED`/`VP_NONE` boot would state), and +/// the Feed over the host sink as its only driver. It composes no URI driver (that is the +/// television's ACB driver), so it returns no resolver and the session is published the Feed alone. +fn media_early_init(_mt: &plx_base::task::MainThread) {} + +fn media_compose(adapter: &mut plx_media::player::adapter::PlayerAdapter, _controlled: bool) -> Composition { + crate::app::adapters::backends::compose_feed(adapter); + Composition::default() +} + /// The desktop platform: what [`run`] hands `app::run_application`. -static PLATFORM: Platform = Platform::new(&SERVICES, &DesktopShell, &DesktopProbe); +static PLATFORM: Platform = Platform::new( + &SERVICES, + &DesktopShell, + &DesktopProbe, + MediaBoot { early_init: media_early_init, compose: media_compose }, +); /// The desktop entry: boot the application on [`PLATFORM`] and return the status it ended with. /// Ending the process is the executable's (`src/bin/sim.rs`), which owns it, like the television's @@ -151,17 +168,33 @@ mod tests { assert_eq!(SERVICES.storage.authority, plx_os::tv::authority::Authority::Files); } - /// 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 - /// the simulator both must be the host sink, never `NoSink`: a boot that read `NoSink` would - /// report no plane to every backend and nothing in a simulator run would say so. + /// The video sink the Feed runs over and the display binding the table states are the one host + /// sink in the simulator, never `NoSink`: a Feed that ran over `NoSink` would show no picture + /// and nothing in a simulator run would say so. #[cfg(feature = "play-feed")] #[test] - fn the_simulator_port_display_is_the_host_sink_the_acb_init_reads() { + fn the_simulator_port_display_is_the_host_sink() { let host = std::ptr::from_ref(&crate::app::adapters::hostsim::HOST_SINK).cast::<()>(); 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(media.sink).cast::<()>(), host, "so is the video sink"); } + + /// The desktop's own `media.compose`, the one `run_application` calls, composes the Feed and no + /// URI driver: published, the session offers the adapter's set (no `Uri` in it) and holds no + /// resolver. A resolver here would describe a driver this platform never installed. + #[test] + fn the_desktop_platform_composes_the_feed_and_no_resolver() { + use plx_media::player::adapter::PlayerAdapter; + let mut adapter = PlayerAdapter::new(unsafe { plx_base::task::MainThread::assume() }); + let mut session = plx_media::route::PlaybackSession::IDLE; + let composed = (PLATFORM.media.compose)(&mut adapter, false); + crate::app::platform::publish_composition(&mut session, &adapter, composed); + assert_eq!(session.backends(), adapter.composed_backends()); + assert!(!session.backends().uri); + assert!(session.uri_preflight_port().is_none()); + #[cfg(feature = "play-feed")] + assert!(session.backends().feed, "the Feed is the desktop's driver"); + } } diff --git a/rust-modules/src/port.rs b/rust-modules/src/port.rs index ec914547a8..53ac2cb740 100644 --- a/rust-modules/src/port.rs +++ b/rust-modules/src/port.rs @@ -6,7 +6,8 @@ //! video sink together. The simulator and the macOS app are not on these tables: they are their own //! platform (`platform_desktop`), which never names this module, so a desktop build compiles the //! television's code and the linker drops it. -use crate::app::platform::{FrameProbe, Platform, Shell}; +use crate::app::adapters::backends; +use crate::app::platform::{FrameProbe, MediaBoot, Platform, Shell}; use std::os::raw::{c_char, c_int, c_void}; #[cfg(all(not(test), feature = "play-feed"))] @@ -103,8 +104,16 @@ 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::new(&SERVICES, &WebosShell, &WebosProbe); +/// for the lower layers and keeps it for the loop. Its media boot is the television's: the plane +/// owner's boot, and the Feed plus the product URI driver. The bodies are the application's +/// `adapters::backends` until the webOS platform owns that file: the dev surface and the tests name the +/// URI product there, and nothing outside this module may name `port`. +static PLATFORM: Platform = Platform::new( + &SERVICES, + &WebosShell, + &WebosProbe, + MediaBoot { early_init: backends::acb_init, compose: backends::compose_native }, +); /// The C shim's entry (`src/main.c`). The `-> c_int` is only the C signature: `plex_main` never /// returns, so neither does this. From f78ce7dc12698423f71072d5ce0ff71493dd4fd8 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 17:45:25 +0300 Subject: [PATCH 13/26] plex's session persistence reads the platform's storage authority instead of the build's CPU (#1491) Part of step W8a of the platform plan (discussion #1460). `plex`'s session persistence now follows the storage authority the platform states (#1488). Before, it was fenced by `all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))`, which means "32-bit ARM Linux", not "a webOS television". webOS behaves as before. Every other platform keeps the files arm it already took. On x86_64, the Tizen emulator build's CPU, that fence was already false. ## What changes - **The fenced lines** (21 at #1488's base; 19 left after #1490 ungated the account-clear hook's two) in `plex/session.rs`, `session/persistence.rs` and `session/install_preferences.rs` become a run-time choice on `plx_os::tv::authority::authority()`. - The `persistence.rs` dispatchers take `(authority, &mut dyn Transport)`. The public functions pass `authority()` and the native transport. - `Helper` runs the storage-helper arm and `Files` runs the files arm. - Only the selection changes. The session layer's marked fallback during a helper outage and the legacy migration reads are untouched. - Both arms now compile on every build. - **The account-clear hook.** `clear_for_erase` calls the telemetry account-clear hook only when the authority is `Helper`. An unset hook still reads as retired, so this PR and #1490 (telemetry, which installs the hook on every platform) were safe in either order. #1490 has landed. - **`ci/allow/forks/plex.txt`** falls from 31 lines to 12, by deletion only. It was 33 before #1490, which deleted two of the same lines first. - **#1488's last review minor is folded in.** `os/src/tv/authority.rs` and `docs/platform-ports.md` now: - name the third file the app keeps on webOS beside the helper, the install preferences `clear_for_erase` saves when a helper sign-out clear is not durable; - say that `secure::mode()`'s `MemoryOnly` decides the session record before the authority does. - **Docs.** `plex/src/plex/CLAUDE.md` says what reads the authority, and two prose claims that named the ARM fence as plex's store fence follow. So does a doc comment in `base/src/paths.rs` that called the helper-owned DB8 record "the canonical ARM adapter". The guide and the `persistence.rs` module doc name the two helpers that still name `NativeTransport` without a `_via` seam: `reset_cleared_language`, which `clear_for_erase` calls on a television only, and `helper_commit`, which has no caller. - **Left for W8c.** `plex/Cargo.toml` still declares the `hostsim` feature, though nothing in `plex` reads it now. `Cargo.toml` is certificate-pinned. ## Counts in `rust-modules/plex` | | before #1490 | main, before this PR | after | |---|---|---|---| | `target_arch = "arm"` | 21 | 19 | 0 | | `target_os = "linux"` | 21 | 19 | 0 | | `feature = "hostsim"` | 21 | 19 | 0 | | `ci/allow/forks/plex.txt` lines | 33 | 31 | 12 | ## Tests - Fake-transport tests in `migration_tests.rs` drive the `Helper` arm on every host, with the authority passed as a parameter. There is no process-global override. - Positive `Helper` tests cover load and clear. - Write, migrate, commit and bootstrap are covered through an unavailable transport. The helper fake cannot accept a positive commit outside a device. - `plx_plex` lib tests went from 823 to 828. Results on the committed tree at a63719442, after merging main at 392328672: - `make test-crate C=plx_plex`: `test result: ok. 828 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out` - `make test-crate C=plx_os T=tv`: `test result: ok. 79 passed; 0 failed; 0 ignored; 0 measured; 383 filtered out` - `make test-crate C=plxnative-modules T=port::tests`: `test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1501 filtered out` - `make test-crate C=plxnative-modules T=app::adapters::session`: `test result: ok. 35 passed; 0 failed; 0 ignored; 0 measured; 1468 filtered out` - `make test-crate C=plx_session T=auth`: `test result: ok. 353 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out` - `make test-hostsim T=app::adapters::session`: `test result: ok. 35 passed; 0 failed; 0 ignored; 0 measured; 1718 filtered out` - `make test-hostsim T=the_desktop_table_keeps_the_account_in_files`: `test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 1752 filtered out` - `make check-nodef`: exit 0 - ARM `cargo check --target armv7-unknown-linux-gnueabi` for `plx_plex` and for the app crate with `play-uri,play-feed`: both exit 0 - `ci/check-deps.sh`, `ci/check-module-layers.py`, `ci/check-ledger-ratchet.py` and `ci/check-statics.sh` are green. - `ci/test_readonly_generated.py` (22 tests) and `ci/test_readonly_dependencies.py` (64 tests) are OK. - No `Cargo.toml`, lock, `.cargo` or certificate-pinned source changes. ## Prose left for one follow-up The review found two stale sentences in prose this PR edits. Both are left for one docs PR, after a doc-claim audit of the whole W8a series (#1488, #1490, this PR): - `docs/platform-ports.md` says telemetry's sites "follow in its own PR". They landed in #1490. - `plex/CLAUDE.md` and the `persistence.rs` module doc list `cleanup_temporaries` among the `*_via(authority, helper, ..)` dispatchers. It calls `cleanup_temporaries_for(authority)`, which takes no transport. ## Not covered - **The television.** The ARM evidence is a `cargo check`, so there is no link and no size figure. Both arms now compile into the ARM binary, so a small size change is possible and unmeasured. - The device check: on a `--guest --mock` boot, `session: authority read reason=miss` still appears, the identity line is unchanged, and no `session.json` appears under the state root. - **Device-only paths.** `clear_for_erase`'s `Helper` branch has no transport seam, so it, and the telemetry sweep after a durable clear, run only on a device. - **Read order.** A read before `run_application` installs the services would see `Files`. #1488's pin holds `install_services()` first in `run_application`. Nothing earlier that we found reads `plex::session`: `port::plex_main`'s storage activator and clear probe, or `main.c`'s crash and launch-argument entries. That was checked by reading the code, not by a test. --- ci/allow/forks/plex.txt | 21 +- docs/platform-ports.md | 21 +- rust-modules/base/src/paths.rs | 7 +- rust-modules/os/src/tv/authority.rs | 26 +- rust-modules/plex/src/plex/CLAUDE.md | 21 +- rust-modules/plex/src/plex/session.rs | 24 +- .../src/plex/session/install_preferences.rs | 38 +- .../plex/src/plex/session/migration_tests.rs | 105 ++++ .../plex/src/plex/session/persistence.rs | 472 +++++++++--------- .../src/plex/session_persistence_tests.rs | 2 +- 10 files changed, 451 insertions(+), 286 deletions(-) diff --git a/ci/allow/forks/plex.txt b/ci/allow/forks/plex.txt index 00a5ca7ee3..232dcca530 100644 --- a/ci/allow/forks/plex.txt +++ b/ci/allow/forks/plex.txt @@ -1,4 +1,4 @@ -# count: 31 +# count: 12 # Test/production forks (docs/sans-io.md), area `plex`: one line per production-visible `#[cfg(..)]` / `cfg!(..)` whose predicate reads `test` or `feature = "test-support"` # (`not(test)`, `not(any(test, feature = "test-support"))`, ...) in every machine crate (data/, plex/, media/, session/, screens/, ui/, appkit/ and machine/), keyed `::` (an attribute on an item), `::` (a statement or an inline `cfg!`) or `::` (a field). # Logic is one thing in production and tests deliver it events: there is no cfg(test) fork. Spec: ci/check-deps.sh `forks`. @@ -10,27 +10,8 @@ rust-modules/plex/src/plex/origin.rs::store_policy_forced rust-modules/plex/src/plex/servers.rs::register_captured_origin_with_connection rust-modules/plex/src/plex/session.rs::auth_paths rust-modules/plex/src/plex/session.rs::clear_for_erase -rust-modules/plex/src/plex/session.rs::clear_for_erase -rust-modules/plex/src/plex/session.rs::clear_for_erase rust-modules/plex/src/plex/session.rs::publish rust-modules/plex/src/plex/session.rs::read_into_cache_locked -rust-modules/plex/src/plex/session.rs::read_into_cache_locked -rust-modules/plex/src/plex/session/install_preferences.rs::candidates rust-modules/plex/src/plex/session/install_preferences.rs::candidates rust-modules/plex/src/plex/session/persistence.rs::bootstrap -rust-modules/plex/src/plex/session/persistence.rs::bootstrap -rust-modules/plex/src/plex/session/persistence.rs::bootstrap -rust-modules/plex/src/plex/session/persistence.rs::cleanup_after_confirmed_clear rust-modules/plex/src/plex/session/persistence.rs::cleanup_after_confirmed_clear -rust-modules/plex/src/plex/session/persistence.rs::cleanup_temporaries -rust-modules/plex/src/plex/session/persistence.rs::cleanup_temporaries -rust-modules/plex/src/plex/session/persistence.rs::commit_cleared -rust-modules/plex/src/plex/session/persistence.rs::commit_cleared -rust-modules/plex/src/plex/session/persistence.rs::commit_data -rust-modules/plex/src/plex/session/persistence.rs::commit_data -rust-modules/plex/src/plex/session/persistence.rs::load -rust-modules/plex/src/plex/session/persistence.rs::load -rust-modules/plex/src/plex/session/persistence.rs::migrate_session -rust-modules/plex/src/plex/session/persistence.rs::migrate_session -rust-modules/plex/src/plex/session/persistence.rs::write_session -rust-modules/plex/src/plex/session/persistence.rs::write_session diff --git a/docs/platform-ports.md b/docs/platform-ports.md index 5071fff48a..889afccedb 100644 --- a/docs/platform-ports.md +++ b/docs/platform-ports.md @@ -458,9 +458,11 @@ Citations in this section quote the tree at e9924f0f9 with its old names (see "N `load_login_client_id`, `:4336-4349`), reusing one process-local id when storage is unavailable. `install_preferences::Saved` is `deny_unknown_fields`, version 1 (`:28-38`): it cannot carry the id without a new version. - - The authority is chosen by `target_arch = "arm"`, not by a platform value (`session/persistence.rs:1400-1425`, + - The authority was chosen by `target_arch = "arm"`, not by a platform value (`session/persistence.rs:1400-1425`, `commit_data` `:288-308`); a Tizen ARM build would select the DB8 arm with no helper behind it (F12). The - `MemoryOnly` gate sits above that selection, and W8a re-keys it. + `MemoryOnly` gate sits above that selection. W8a re-keyed plex's 21 sites to `tv::authority::authority()`: + `persistence.rs`'s dispatchers take the authority and the helper's transport, so a host test drives the helper + arm with a fake one; telemetry's sites follow in its own PR. ### Evidence from the second reviews: F40-F46 (each citation checked in the tree) @@ -502,9 +504,11 @@ Citations in this section quote the tree at e9924f0f9 with its old names (see "N - `CompletionOutcome` (`plex/src/plex/session/async_persistence.rs:112`) and `LiveWrite` are matched in `session.rs`, `session/{persistence,async_persistence,prefs/profile_prefs}.rs`, `session/src/auth/owner.rs`, `telemetry/src/telemetry/incident.rs:592-600`, `src/app/adapters/session.rs` and three test files. - - `install_preferences::candidates` (`:40`) and `clear_for_erase` (`session.rs:5341`) key on the ARM cfg, so - Tizen ARM reads `native = true`; `load` accepts `version == 1` only (`:59`) and `Saved` is - `deny_unknown_fields`. The ARM canonical write is cfg'd out of host tests (`session/persistence.rs:1400-1425`). + - `install_preferences::candidates` (`:40`) and `clear_for_erase` (`session.rs:5341`) keyed on the ARM cfg, so + Tizen ARM read `native = true` (W8a re-keyed them to `tv::authority::authority()`); `load` accepts + `version == 1` only (`:59`) and `Saved` is `deny_unknown_fields`. The ARM canonical write was cfg'd out of + host tests (`session/persistence.rs:1400-1425`); it is now the `Helper` arm of `persistence::*_via`, which every + host runs over a fake transport. - `ci/check-deps.sh`: `plex/` is in `FORK_SCOPE`, `session.rs` in `MACHINES` (`:1406-1408`): a new `cfg(test)` branch there is a `forks` line, a new static a `statics` line. `platform/` is not in `FORK_SCOPE`, and only `platform/src/tv/plane.rs` is in `MACHINES` (`:1406-1408`; the scan `find` at `:1439` lists it too). The @@ -850,9 +854,12 @@ split by who reads it (critic M4): - `system { go_home, poll_home, deliver_toast }`; - `storage { authority }` (W8a): `Authority::Helper` (webOS: the LS2/DB8 storage helper is the canonical store of the session, the install's preferences and the consent record; the app's own files there are the legacy - migration inputs and the marked fallback of a helper outage) or `Authority::Files` (desktop, Tizen, a host + migration inputs, the marked fallback of a helper outage and the install-preferences file a sign-out writes + when the helper's clear is not durable) or `Authority::Files` (desktop, Tizen, a host test: the app's own record files are the store), read through - `tv::authority::authority()`. It replaces the `target_os = "linux"` + `target_arch = "arm"` fence the persistence + `tv::authority::authority()`. `secure::mode()` decides the session record ahead of it: under `MemoryOnly` + (where Tizen starts, W9) the session lives in memory and no credential store is read or written, whatever the + authority says; only the install's own preference file persists. It replaces the `target_os = "linux"` + `target_arch = "arm"` fence the persistence layers chose their store by; the helper's wake-up (`storage::client::install_activator`) joins it after W7b; - `legacy_webos_media { sink, display_sink, uri_media }`: the Starfish, ACB and `com.webos.media` verbs (F31), named for what they are (critic M3). Every hook is required (Decision 2, C): a platform states each field, diff --git a/rust-modules/base/src/paths.rs b/rust-modules/base/src/paths.rs index b38fd88eb7..8c93833aba 100644 --- a/rust-modules/base/src/paths.rs +++ b/rust-modules/base/src/paths.rs @@ -1336,8 +1336,11 @@ mod tests { } } -/// Legacy JSON/host-simulator persistence root. The canonical ARM adapter uses helper-owned DB8; -/// this path exists for old-record migration and for host tests that must never touch the checkout. +/// Legacy JSON/host-simulator persistence root. Where the platform states the storage helper as the +/// canonical store (a webOS television, `plx_os::tv::authority`) the canonical record is +/// helper-owned DB8; where it states plain files (the desktop simulator) the canonical record files +/// are kept here. This path also exists for old-record migration and for host tests that must never +/// touch the checkout. /// /// **Test builds never resolve this to the machine-wide runtime dir by accident.** A test that /// calls [`redirect_persistent_state_root_for_test`] gets the directory it asked for; a test that diff --git a/rust-modules/os/src/tv/authority.rs b/rust-modules/os/src/tv/authority.rs index 629a194108..7d865f24d7 100644 --- a/rust-modules/os/src/tv/authority.rs +++ b/rust-modules/os/src/tv/authority.rs @@ -6,10 +6,20 @@ //! state root ([`Authority::Files`]): the desktop simulator, a host test, and a platform with no //! helper at all (Tizen). //! -//! Under `Helper` the app's own files are not the store. They are the legacy migration inputs an -//! older build left, and the marked fallback the session layer writes when a commit to the helper is -//! not durable (a helper outage): while the helper cannot answer, that file is served as transient -//! state, and it never replaces the helper's record. +//! The authority is not the whole answer for the session record: the platform's persistence mode +//! ([`secure::mode()`](super::secure::mode)) decides it first. Under `StoreMode::MemoryOnly`, where +//! Tizen starts (W9), the session lives in memory and no credential store is read or written, +//! whatever the authority says; only the install's own preference file (client id, language and +//! Interface resolution) persists. +//! +//! Under `Helper` the app's own files are not the store. Three kinds remain: +//! - the legacy migration inputs an older build left; +//! - the marked fallback the session layer writes when a commit to the helper is not durable (a +//! helper outage): while the helper cannot answer, that file is served as transient state, and it +//! never replaces the helper's record; +//! - the install-preferences file a sign-out writes when the helper's clear is not durable +//! (`install_preferences::save`): an unmarked `….language.json` file beside a session candidate, which +//! `install_preferences::load` reads back into the `Locked` and `Cleared` states. //! //! The platform states the value once, as the `authority` of its [`StorageHooks`](super::StorageHooks), //! and [`authority`] reads it. A process that installed no platform (a host test) reads @@ -30,10 +40,12 @@ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Authority { /// The platform's storage helper (webOS: the LS2/DB8 service) is the canonical store. The app's - /// own files are only the legacy migration inputs and the session layer's marked fallback, which - /// is written during a helper outage and is never the record. + /// own files are only the legacy migration inputs, the session layer's marked fallback (written + /// during a helper outage, never the record) and the install-preferences file a sign-out writes + /// when the helper's clear is not durable. Helper, - /// The app's own record files under its persistent state root are the canonical store. + /// The app's own record files under its persistent state root are the canonical store. A process + /// in `StoreMode::MemoryOnly` still keeps the session record in memory (see the module doc). #[default] Files, } diff --git a/rust-modules/plex/src/plex/CLAUDE.md b/rust-modules/plex/src/plex/CLAUDE.md index 58e41e3861..a5f97c54df 100644 --- a/rust-modules/plex/src/plex/CLAUDE.md +++ b/rust-modules/plex/src/plex/CLAUDE.md @@ -627,6 +627,25 @@ a dead source is **absent** from Home and states itself in its own library secti struct, and a new field follows the omit rule. 6. **The Settings row** (labels, i18n, picker) is a screens edit, and `Choice` gains a variant (T-settings). +- **Which store holds the session is the platform's statement, `plx_os::tv::authority::authority()`** + (`Helper`: the LS2/DB8 storage helper, webOS; `Files`: the 0600 record files, the desktop, a host test and + any platform with no helper), never the build's CPU or OS. `session/persistence.rs` reads it once per + public call (`load`, `commit_data`, `commit_cleared`, `write_session`, `migrate_session`, `bootstrap`, + `cleanup_after_confirmed_clear`, `cleanup_temporaries`) and hands it to the `*_via(authority, helper, ..)` + form, so a test passes the authority it grades and, for `Helper`, a transport of its own (an in-memory + `Backend` or a closure); the real `NativeTransport` is named by those public forms and by two helpers + with no `_via` seam (`reset_cleared_language()`, which `clear_for_erase` calls under `Helper` and which is + device-only, and `helper_commit`, which has no caller here), because on a Linux host it waits out a 12 s + start deadline with no helper behind it. There is no process-global override. + Under `Helper` the dispatchers never answer for a helper that cannot answer (a blocked read stays blocked, + and a legacy file is neither imported nor retired on its word); the files a television does keep beside DB8 + are `session.rs`'s own: the marked fallback `save_legacy_fallback_locked` writes when a commit is not + durable, which `read_legacy_filtered_locked` serves as transient state, the legacy migration inputs, and the + install-preferences file (`install_preferences::save`, an unmarked `….language.json` beside a session + candidate) that `clear_for_erase` writes when a sign-out's helper clear is not durable. `secure::mode()`'s + `MemoryOnly` is read before the authority: it holds the session in memory and touches no credential store. + `clear_for_erase`, `read_into_cache_locked` and `install_preferences::keeps_language_file` read the same + value; the telemetry sweep after a durable clear runs only under `Helper`. - **The DB8 document may not pass `MAX_LOGICAL_BYTES` (256 KiB), and per-profile memory is what grows it.** Past the cap EVERY write fails (`LogicalTooLarge`, reported as `InvalidSchema`), so `persistence::commit_session_with` measures the projected document (the os layer's own @@ -688,7 +707,7 @@ a dead source is **absent** from Home and states itself in its own library secti 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 fallback or revocation marker. The gate sits in `read_live_locked`, `save_locked_with_authority` - and `clear_for_erase`, above every `TEST_FILE` and `target_arch` branch, so nothing behind them + and `clear_for_erase`, above every `TEST_FILE` and storage-authority branch, so nothing behind them is reachable. A write answers `PersistOutcome::Memory`, which classifies as `CompletionOutcome::Ephemeral`: signed in for this run, so the auth owner goes on to Home, but never a saved-login claim and never a warning. `drop_cache_locked` must not run in this mode diff --git a/rust-modules/plex/src/plex/session.rs b/rust-modules/plex/src/plex/session.rs index 320bfdbc22..109c42182d 100644 --- a/rust-modules/plex/src/plex/session.rs +++ b/rust-modules/plex/src/plex/session.rs @@ -65,6 +65,7 @@ pub use prefs::{IntroSkipPref, CreditsSkipPref, DolbyVisionModePref, InstantDpad ProfilePrefsRecord, ProfileSetting, ProfileWrite, QualityPref, Row, Setting, SkipIntervalPref, SubtitlePositionPref, SubtitleSizePref, SubtitleTonePref, TrailerAutoplayPref, HudEndTimePref, UiResolutionPref, UnderPostersPref}; use prefs::ProfileMemory; +use plx_os::tv::authority::{authority as storage_authority, Authority}; use serde::de::DeserializeOwned; use serde::{Deserialize, Deserializer, Serialize}; use std::sync::Mutex; @@ -3225,8 +3226,9 @@ fn read_into_cache_locked(expected: Option) -> (std::sync::Arc, let state = std::sync::Arc::new(CACHE_READ_FOR_TEST.with(|read| { read.get().unwrap_or(read_live_locked)() })); - #[cfg(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] - plx_base::eventlog::log("session: authority read reason=miss"); + if storage_authority() == Authority::Helper { + plx_base::eventlog::log("session: authority read reason=miss"); + } if !replace_cache(cached_arm(state.clone()), expected, false) { return (state, false); } if let ReadState::Ready { session, .. } = &*state { publish_identities(session); } (state, true) @@ -5331,7 +5333,7 @@ fn clear_cleanup_outcome(outcome: persistence::ClearCleanupOutcome) -> ClearOutc /// load. The old-path copy goes too, or the migration fallback would resurrect the stale session. /// **And commits an explicit Cleared record to the canonical authority** — the legacy-file sweep /// below only ever touches pre-DB8 candidates; on a build where `persistence::load`/`write_session` -/// actually read/write the canonical store (DB8 or its host/ARM equivalent), that store is a +/// actually read/write the canonical store (DB8 or its host equivalent), that store is a /// SEPARATE copy of the account token and roster, and clearing only the legacy files would leave a /// clean-looking sign-out that the canonical authority still hands back on the next boot. /// @@ -5367,7 +5369,7 @@ pub fn clear_for_erase(all_local: bool, retry: Option) -> Erasure { return memory_only::clear_locked(all_local, retry); } let kept = retry.unwrap_or_else(|| Retained::of(&session_from_read(&read_live_locked()))); - let native = cfg!(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))); + let native = storage_authority() == Authority::Helper; // File backends need a credential-free resource before the credential file disappears. let mut preference_failures = Vec::new(); if !all_local && !native && !install_preferences::save(kept) { @@ -5419,22 +5421,20 @@ pub fn clear_for_erase(all_local: bool, retry: Option) -> Erasure { // `auth_paths()` above only ever covered `paths::session_candidates()` — the legacy // sign-in file and its pre-relocation predecessor. The recognized migration source set // is bigger (`paths::session_migration_candidates()`, plus the pre-DB8 canonical JSON - // wrapper on ARM), and a candidate this sweep never visits is a live account token left + // wrapper where the helper is canonical), and a candidate this sweep never visits is a live account token left // on a rooted, world-readable install prefix after a sign-out that otherwise looked // clean. `cleanup_after_confirmed_clear` re-reads the authority to confirm it really is // Cleared before retiring anything, so this can only ever remove residue, never data a // concurrent re-login just wrote. - #[allow(unused_mut)] // only mutated on the ARM cfg arm below let mut outcome = clear_cleanup_outcome(persistence::cleanup_after_confirmed_clear()); // Telemetry/consent's own legacy files are a SEPARATE candidate set from the session // auth-token sweep above (`persistence::cleanup_after_confirmed_clear` never touches // them — see `paths::telemetry_candidates` vs `paths::session_migration_candidates`). - // On ARM, `telemetry::persistence::forget_at` defers their removal to exactly this - // moment, once this canonical commit is confirmed durable (Copilot review on PR #105, - // finding 7; ported from `release/v0.6`'s `telemetry::cleanup_after_account_clear`, - // called here in that release). - #[cfg(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] - if !ACCOUNT_CLEAR_CLEANUP.get().is_none_or(|sweep| sweep()) { + // Where the storage helper is canonical, `telemetry::persistence::forget_at` defers their + // removal to exactly this moment, once this canonical commit is confirmed durable + // (Copilot review on PR #105, finding 7; ported from `release/v0.6`'s + // `telemetry::cleanup_after_account_clear`, called here in that release). + if native && !ACCOUNT_CLEAR_CLEANUP.get().is_none_or(|sweep| sweep()) { plx_base::eventlog::log( "session: canonical clear is durable but a telemetry/consent legacy \ candidate could not be retired — it remains on disk and will be swept \ diff --git a/rust-modules/plex/src/plex/session/install_preferences.rs b/rust-modules/plex/src/plex/session/install_preferences.rs index 6cc21def12..4d62f22c6f 100644 --- a/rust-modules/plex/src/plex/session/install_preferences.rs +++ b/rust-modules/plex/src/plex/session/install_preferences.rs @@ -1,11 +1,13 @@ //! Credential-free install-wide choices (the UI language and the Interface resolution) retained by -//! host stores and explicitly supported file fallbacks. -//! Native DB8 remains authoritative whenever it answers; these files cannot authorize login. +//! file stores and explicitly supported file fallbacks. +//! The storage helper (DB8) remains authoritative whenever the platform states one +//! ([`Authority::Helper`]) and it answers; these files cannot authorize login. //! //! On a [`StoreMode::MemoryOnly`] platform this file is also where the install's own client id //! lives (version 2): the one thing a launch must know before anyone signs in and that no credential //! store is there to keep. The id is an install label, not a secret, and cannot authorize a login. use super::*; +use plx_os::tv::authority::{authority, Authority}; use plx_os::tv::secure::{mode, StoreMode}; use std::path::PathBuf; @@ -59,6 +61,13 @@ impl Saved { } } +/// Whether the install's own state root holds a `language.json`. webOS keeps these choices in DB8 +/// and never in this root; a memory-only platform has no DB8, so its root is where they live. A +/// redirected test fixture names its own files instead. +fn keeps_language_file(authority: Authority, mode: StoreMode, redirected: bool) -> bool { + (authority == Authority::Files || mode == StoreMode::MemoryOnly) && !redirected +} + fn candidates() -> Vec { #[cfg(any(test, feature = "test-support"))] let redirected = TEST_FILE.lock().unwrap_or_else(|e| e.into_inner()).is_some() @@ -66,9 +75,7 @@ fn candidates() -> Vec { #[cfg(not(any(test, feature = "test-support")))] let redirected = false; let mut paths = Vec::new(); - // webOS keeps these choices in DB8 and never in this root; a memory-only platform has no DB8. - if (!cfg!(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))) - || mode() == StoreMode::MemoryOnly) && !redirected { + if keeps_language_file(authority(), mode(), redirected) { paths.push(plx_base::paths::persistent_state_root().join("language.json")); } paths.extend(auth_paths().into_iter().map(|path| path.with_extension("language.json"))); @@ -131,3 +138,24 @@ pub(super) fn erase() -> Vec { .err().map(|error| format!("{}: {error}", path.display())) }).collect() } + +#[cfg(test)] +mod authority_tests { + use super::*; + + /// The install's own `language.json` is where a file platform keeps its choices and where a + /// memory-only platform keeps the only thing that outlives the process. A television whose + /// storage helper holds them has none, and a redirected fixture names its own files. + #[test] + fn the_language_file_is_kept_unless_the_helper_holds_the_choices() { + use Authority::{Files, Helper}; + use StoreMode::{Durable, MemoryOnly}; + assert!(keeps_language_file(Files, Durable, false), "the desktop and Tizen keep the file"); + assert!(keeps_language_file(Files, MemoryOnly, false)); + assert!(!keeps_language_file(Helper, Durable, false), "webOS keeps these choices in DB8, never in this root"); + assert!(keeps_language_file(Helper, MemoryOnly, false), "a memory-only platform has no DB8 to hold them"); + for (authority, mode) in [(Files, Durable), (Files, MemoryOnly), (Helper, MemoryOnly)] { + assert!(!keeps_language_file(authority, mode, true), "a redirected fixture never reaches the real root"); + } + } +} diff --git a/rust-modules/plex/src/plex/session/migration_tests.rs b/rust-modules/plex/src/plex/session/migration_tests.rs index 14e856f63c..1c61a7f7a0 100644 --- a/rust-modules/plex/src/plex/session/migration_tests.rs +++ b/rust-modules/plex/src/plex/session/migration_tests.rs @@ -1,6 +1,7 @@ //! Canonical schema and the shipping client/coordinator path, using synthetic helper transport. use super::*; use plx_os::storage::{client, state, wire::*}; +use plx_os::tv::authority::Authority; use persistence::CanonicalRead; fn fixture() -> Session { @@ -1389,3 +1390,107 @@ fn pending_revocation_prevents_missing_canonical_from_importing_a_marked_snapsho assert_eq!(store.commits, 0); assert!(source.path.exists()); } + +// Which store is canonical is the platform's statement (`plx_os::tv::authority`). The dispatchers +// take the authority and the helper's transport, so every host runs the helper arm over a +// transport of its own, and the files arm over one that fails the test if it is reached. + +/// The transport the files arm must never reach. +fn no_helper(_: Request) -> Result { + panic!("a files authority never talks to the storage helper") +} + +/// The helper arm over the production backend, which holds the record the way DB8 does: the app's +/// own state root stays empty. +#[test] +fn a_helper_authority_reads_and_clears_through_the_helper_and_keeps_no_file() { + let _serial = plx_base::testlock::serial(); + let state = TempCanonicalState::new("authority-helper"); + let mut backend = plx_os::storage::backend::Backend::new( + Db8::default(), state::Flavor::Stable, "com.beb.plxnative.storage".into()); + let mut transport = |request: Request| Ok(backend.dispatch(request)); + assert!(matches!(persistence::load_via(Authority::Helper, &mut transport), CanonicalRead::Missing)); + commit_fresh(&fixture(), &mut transport); + let CanonicalRead::Opened { session, .. } = persistence::load_via(Authority::Helper, &mut transport) else { + panic!("the helper holds the session") + }; + assert_eq!(session.account_token, "synthetic-account"); + assert!(matches!(persistence::commit_cleared_via(Authority::Helper, &mut transport), + persistence::CanonicalCommit::Durable { .. })); + assert!(matches!(persistence::load_via(Authority::Helper, &mut transport), CanonicalRead::Cleared { .. })); + assert_eq!( + with_io_for_test(|| persistence::cleanup_after_confirmed_clear_via(Authority::Helper, &mut transport, Vec::new())), + persistence::ClearCleanupOutcome::Confirmed); + assert_eq!(std::fs::read_dir(&state.dir).unwrap().count(), 0, "the helper arm leaves no record file under the state root"); +} + +/// The files arm for a platform with no helper (the desktop, a host test, Tizen): the record is the +/// 0600 file under the state root, and the helper is never asked. +#[test] +fn a_files_authority_keeps_the_record_in_files_and_never_asks_the_helper() { + let _serial = plx_base::testlock::serial(); + let state = TempCanonicalState::new("authority-files"); + let session = fixture(); + let payload = serde_json::to_string(&session).unwrap(); + assert!(matches!(persistence::load_via(Authority::Files, &mut no_helper), CanonicalRead::Missing)); + assert!(matches!(persistence::commit_data_via(Authority::Files, &mut no_helper, payload), + persistence::CanonicalCommit::Durable { revision: 1, .. })); + assert!(matches!( + persistence::write_session_via(Authority::Files, &mut no_helper, &session, SaveAuthority::Routine), + persistence::CanonicalCommit::Durable { revision: 2, .. })); + assert!(matches!(persistence::migrate_session_via(Authority::Files, &mut no_helper, &session), + persistence::CanonicalCommit::Durable { revision: 3, .. })); + let CanonicalRead::Data { revision: 3, payload: stored } = persistence::load_via(Authority::Files, &mut no_helper) else { + panic!("the files hold the session") + }; + assert_eq!(serde_json::from_str::(&stored).unwrap().account_token, "synthetic-account"); + assert!(state.dir.join("session.json").exists()); + assert!(matches!(persistence::commit_cleared_via(Authority::Files, &mut no_helper), + persistence::CanonicalCommit::Durable { revision: 4, .. })); + assert!(matches!(persistence::load_via(Authority::Files, &mut no_helper), CanonicalRead::Cleared { revision: 4, .. })); + assert_eq!( + with_io_for_test(|| persistence::cleanup_after_confirmed_clear_via(Authority::Files, &mut no_helper, Vec::new())), + persistence::ClearCleanupOutcome::Confirmed); + let boot = persistence::bootstrap_via(Authority::Files, &mut no_helper, &mut opener(), Vec::new()); + assert!(matches!(boot.state, CanonicalRead::Cleared { revision: 4, .. }), "the record the files hold is read as it is"); +} + +/// At this layer a helper that cannot answer is a blocked canonical store: no read, write or +/// migration is answered from the record files, and a legacy file is neither imported nor retired. +/// (The session layer above writes its own marked fallback after a non-durable commit; that file is +/// not the record and is not exercised here.) +#[test] +fn a_helper_authority_never_answers_from_the_record_files_when_the_helper_cannot_answer() { + use plx_os::storage::StoreError; + let _serial = plx_base::testlock::serial(); + let state = TempCanonicalState::new("authority-helper-down"); + let legacy = LegacyFile::new("authority-helper-down", &serde_json::to_value(fixture()).unwrap()); + let session = fixture(); + let requests = std::cell::Cell::new(0usize); + let mut down = |_: Request| { + requests.set(requests.get() + 1); + Err(client::ClientError::Unavailable) + }; + let unavailable = persistence::CanonicalCommit::Failed(StoreError::HelperUnavailable); + assert!(matches!(persistence::load_via(Authority::Helper, &mut down), + CanonicalRead::Blocked(StoreError::HelperUnavailable))); + assert_eq!(persistence::commit_data_via(Authority::Helper, &mut down, serde_json::to_string(&session).unwrap()), + unavailable); + assert_eq!(requests.get(), 2); + assert_eq!(persistence::commit_data_via(Authority::Helper, &mut down, "not a session".into()), + persistence::CanonicalCommit::Failed(StoreError::InvalidSchema), + "a payload the helper cannot take is refused before it is sent"); + assert_eq!(requests.get(), 2); + assert_eq!(persistence::write_session_via(Authority::Helper, &mut down, &session, SaveAuthority::Routine), unavailable); + assert_eq!(persistence::migrate_session_via(Authority::Helper, &mut down, &session), unavailable); + assert_eq!(persistence::commit_cleared_via(Authority::Helper, &mut down), unavailable); + assert_eq!(requests.get(), 5, "each of those asked the helper, and only the helper"); + let boot = persistence::bootstrap_via(Authority::Helper, &mut down, &mut opener(), vec![legacy.path.clone()]); + assert!(matches!(boot.state, CanonicalRead::Blocked(StoreError::HelperUnavailable))); + assert!(boot.migration.is_none(), "a helper that is down authorizes no import"); + assert_eq!( + persistence::cleanup_after_confirmed_clear_via(Authority::Helper, &mut down, vec![legacy.path.clone()]), + persistence::ClearCleanupOutcome::AuthorityNotConfirmed); + assert!(legacy.path.exists(), "an unconfirmed clear retires nothing"); + assert_eq!(std::fs::read_dir(&state.dir).unwrap().count(), 0, "no record file was created under the state root"); +} diff --git a/rust-modules/plex/src/plex/session/persistence.rs b/rust-modules/plex/src/plex/session/persistence.rs index 4cfb5d9681..249a105b51 100644 --- a/rust-modules/plex/src/plex/session/persistence.rs +++ b/rust-modules/plex/src/plex/session/persistence.rs @@ -3,6 +3,16 @@ //! This module owns the distinction between the versioned canonical record and the legacy //! filename candidates. Canonical helper loads, typed migration, and exact readback share this //! adapter; no unavailable helper response authorizes a file-backend fallback. +//! +//! **Which store is canonical is the platform's statement**, [`plx_os::tv::authority::authority`]: +//! the storage helper ([`Authority::Helper`], webOS) or the 0600 record files ([`Authority::Files`], +//! the desktop, a host test and a platform with no helper). Every dispatcher here reads it once per +//! call, in its public form, and hands it to a `*_via(authority, helper, ..)` form that takes the +//! authority and the helper's transport as parameters, so a host test grades the helper arm with a +//! fake transport and the files arm with a transport that fails the test if it is touched. The +//! helper's real transport (`NativeTransport`) is named by the dispatchers' public forms and by +//! two helpers that have no `_via` seam: `reset_cleared_language()`, which `clear_for_erase` calls +//! under `Helper` (device-only), and `helper_commit`, which has no caller in this crate. use plx_os::storage::{ CommitReceipt, CommitStage, Record, RecordKey, RecordState, RecordStore, StoreError, @@ -15,6 +25,7 @@ use plx_os::storage::{ state::{self, Generation, MigrationProgress, Status}, wire::{AuthLoad, CommitStatus, MigrationMutation, Response, WireMutation}, }; +use plx_os::tv::authority::{authority as storage_authority, Authority}; pub enum CanonicalRead { Missing, @@ -84,26 +95,16 @@ pub fn path() -> PathBuf { } pub fn cleanup_temporaries() -> Result<(), StoreError> { - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - { + cleanup_temporaries_for(storage_authority()) +} + +fn cleanup_temporaries_for(authority: Authority) -> Result<(), StoreError> { + match authority { // DB8 has no app-owned rename temporaries. Legacy paths are retired explicitly after the // helper has verified the committed destination; absence of the old app/state directory // is normal on a fresh install and must not turn sign-out into a cleanup failure. - Ok(()) - } - #[cfg(not(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - )))] - { - store()?.cleanup(RecordKey::Session) + Authority::Helper => Ok(()), + Authority::Files => store()?.cleanup(RecordKey::Session), } } @@ -158,45 +159,44 @@ std::thread_local! { const { std::cell::Cell::new(None) }; } +/// The canonical record from the platform's store. pub fn load() -> CanonicalRead { + load_via(storage_authority(), &mut client::NativeTransport) +} + +/// [`load`] with the authority and the helper's transport as parameters. The transport is touched +/// only by [`Authority::Helper`]. +pub(super) fn load_via(authority: Authority, helper: &mut dyn client::Transport) -> CanonicalRead { + match authority { + Authority::Helper => load_helper_with(helper), + Authority::Files => load_file(), + } +} + +/// The record files' read. A test may substitute it (`READ_FOR_TEST`), which only ever stands in +/// for this store: the helper arm is read through its transport. +fn load_file() -> CanonicalRead { #[cfg(any(test, feature = "test-support"))] if let Some(read) = READ_FOR_TEST.with(|hook| hook.get()) { return read(); } - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - { - return load_helper(); - } - #[cfg(not(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - )))] - { - let store = match store() { - Ok(store) => store, - Err(error) => return CanonicalRead::Blocked(error), - }; - match store.load(RecordKey::Session) { - Ok(None) => CanonicalRead::Missing, - Ok(Some(record)) => match record.state { - RecordState::Data { payload } => CanonicalRead::Data { - revision: record.revision, - payload, - }, - RecordState::Cleared => CanonicalRead::Cleared { - revision: record.revision, - kept: super::install_preferences::load().unwrap_or_default(), - }, + let store = match store() { + Ok(store) => store, + Err(error) => return CanonicalRead::Blocked(error), + }; + match store.load(RecordKey::Session) { + Ok(None) => CanonicalRead::Missing, + Ok(Some(record)) => match record.state { + RecordState::Data { payload } => CanonicalRead::Data { + revision: record.revision, + payload, }, - Err(error) => CanonicalRead::Blocked(error), - } + RecordState::Cleared => CanonicalRead::Cleared { + revision: record.revision, + kept: super::install_preferences::load().unwrap_or_default(), + }, + }, + Err(error) => CanonicalRead::Blocked(error), } } @@ -221,10 +221,6 @@ fn helper_rejection(code: plx_os::storage::wire::ErrorCode) -> StoreError { } } -fn load_helper() -> CanonicalRead { - load_helper_with(&mut client::NativeTransport) -} - pub fn load_helper_with(transport: &mut dyn client::Transport) -> CanonicalRead { match client::load_with(transport) { Ok(HelperLoad::Missing) => CanonicalRead::Missing, @@ -286,75 +282,81 @@ fn commit(record: Record) -> CanonicalCommit { } pub fn commit_data(payload: String) -> CanonicalCommit { - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - { - let session = match serde_json::from_str::(&payload) { - Ok(session) => session, - Err(_) => return CanonicalCommit::Failed(StoreError::InvalidSchema), - }; - return commit_session(&session, false, super::SaveAuthority::Routine); - } - #[cfg(not(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - )))] - { - let revision = match load() { - CanonicalRead::Data { revision, .. } - | CanonicalRead::Opened { revision, .. } - | CanonicalRead::Cleared { revision, .. } - | CanonicalRead::Locked { revision, .. } - | CanonicalRead::Pending { revision, .. } => match revision.checked_add(1) { - Some(revision) => revision, - None => return CanonicalCommit::Failed(StoreError::InvalidSchema), - }, - CanonicalRead::Missing => 1, - CanonicalRead::Blocked(error) => return CanonicalCommit::Failed(error), - }; - commit(Record::data(revision, payload)) + commit_data_via(storage_authority(), &mut client::NativeTransport, payload) +} + +/// [`commit_data`] with the authority and the helper's transport as parameters. The helper takes +/// the decoded session as a routine write; the files take the payload as it is. +pub(super) fn commit_data_via( + authority: Authority, + helper: &mut dyn client::Transport, + payload: String, +) -> CanonicalCommit { + match authority { + Authority::Helper => { + let session = match serde_json::from_str::(&payload) { + Ok(session) => session, + Err(_) => return CanonicalCommit::Failed(StoreError::InvalidSchema), + }; + commit_session_with( + &session, + false, + super::SaveAuthority::Routine, + plx_os::tv::device::info().major, + helper, + ) + } + Authority::Files => commit_data_file(payload), } } +fn commit_data_file(payload: String) -> CanonicalCommit { + let revision = match load_file() { + CanonicalRead::Data { revision, .. } + | CanonicalRead::Opened { revision, .. } + | CanonicalRead::Cleared { revision, .. } + | CanonicalRead::Locked { revision, .. } + | CanonicalRead::Pending { revision, .. } => match revision.checked_add(1) { + Some(revision) => revision, + None => return CanonicalCommit::Failed(StoreError::InvalidSchema), + }, + CanonicalRead::Missing => 1, + CanonicalRead::Blocked(error) => return CanonicalCommit::Failed(error), + }; + commit(Record::data(revision, payload)) +} + pub fn commit_cleared() -> CanonicalCommit { - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - { - return commit_clear(); - } - #[cfg(not(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - )))] - { - let revision = match load() { - CanonicalRead::Data { revision, .. } - | CanonicalRead::Opened { revision, .. } - | CanonicalRead::Cleared { revision, .. } - | CanonicalRead::Locked { revision, .. } - | CanonicalRead::Pending { revision, .. } => match revision.checked_add(1) { - Some(revision) => revision, - None => return CanonicalCommit::Failed(StoreError::InvalidSchema), - }, - CanonicalRead::Missing => 1, - CanonicalRead::Blocked(_) => 1, - }; - commit(Record::cleared(revision)) + commit_cleared_via(storage_authority(), &mut client::NativeTransport) +} + +/// [`commit_cleared`] with the authority and the helper's transport as parameters. +pub(super) fn commit_cleared_via( + authority: Authority, + helper: &mut dyn client::Transport, +) -> CanonicalCommit { + match authority { + Authority::Helper => commit_clear_with(helper), + Authority::Files => commit_cleared_file(), } } +fn commit_cleared_file() -> CanonicalCommit { + let revision = match load_file() { + CanonicalRead::Data { revision, .. } + | CanonicalRead::Opened { revision, .. } + | CanonicalRead::Cleared { revision, .. } + | CanonicalRead::Locked { revision, .. } + | CanonicalRead::Pending { revision, .. } => match revision.checked_add(1) { + Some(revision) => revision, + None => return CanonicalCommit::Failed(StoreError::InvalidSchema), + }, + CanonicalRead::Missing => 1, + CanonicalRead::Blocked(_) => 1, + }; + commit(Record::cleared(revision)) +} + /// Exact-payload migration. The caller owns keymanager semantics and legacy cleanup; this helper /// only commits the bytes and reports whether cleanup may proceed. pub fn migrate_exact(source: &Path, payload: &[u8]) -> (CanonicalCommit, PathBuf) { @@ -372,13 +374,25 @@ pub fn migrate_exact(source: &Path, payload: &[u8]) -> (CanonicalCommit, PathBuf /// Import an already decoded migration input through the same backend used by bootstrap. pub fn migrate_session(session: &super::Session) -> CanonicalCommit { - #[cfg(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support"))))] - { - commit_session(session, true, super::SaveAuthority::Routine) - } - #[cfg(not(all(target_os = "linux", target_arch = "arm", not(feature = "hostsim"), not(any(test, feature = "test-support")))))] - { - write_session(session, super::SaveAuthority::Routine) + migrate_session_via(storage_authority(), &mut client::NativeTransport, session) +} + +/// [`migrate_session`] with the authority and the helper's transport as parameters. Only the helper +/// distinguishes a migration from a routine write (it advances the migration ledger). +pub(super) fn migrate_session_via( + authority: Authority, + helper: &mut dyn client::Transport, + session: &super::Session, +) -> CanonicalCommit { + match authority { + Authority::Helper => commit_session_with( + session, + true, + super::SaveAuthority::Routine, + plx_os::tv::device::info().major, + helper, + ), + Authority::Files => write_session_file(session), } } @@ -754,20 +768,6 @@ fn expected(snapshot: &client::Snapshot) -> Option<(&str, state::Expected)> { Some((&snapshot.db_rev, snapshot.state.expected())) } -fn commit_session( - session: &super::Session, - migration: bool, - authority: super::SaveAuthority, -) -> CanonicalCommit { - commit_session_with( - session, - migration, - authority, - plx_os::tv::device::info().major, - &mut client::NativeTransport, - ) -} - pub fn commit_session_with( session: &super::Session, migration: bool, @@ -901,17 +901,6 @@ pub fn commit_session_with( helper_commit_for_app_with(transport, expectation, operation, mutation) } -pub fn commit_session_with_authority( - session: &super::Session, - authority: super::SaveAuthority, -) -> CanonicalCommit { - commit_session(session, false, authority) -} - -fn commit_clear() -> CanonicalCommit { - commit_clear_with(&mut client::NativeTransport) -} - pub(super) fn commit_clear_with(transport: &mut dyn client::Transport) -> CanonicalCommit { let loaded = match client::load_with(transport) { Ok(loaded) => loaded, @@ -1184,22 +1173,38 @@ mod db8_policy_tests { let _ = std::fs::remove_dir_all(root); } + /// A television's helper keeps no app-owned rename temporaries, so there is nothing to sweep and + /// the root is left as it is; a files platform sweeps the abandoned ones its own commits left. + #[test] + fn the_helper_keeps_no_app_temporaries_and_the_files_sweep_theirs() { + let _serial = plx_base::testlock::serial(); + let root = TempPersistenceRoot::new("cleanup-temporaries"); + plx_base::paths::ensure_persistent_state_root().expect("a writable state root"); + let abandoned = root.dir.join(".session.json.new-0123456789abcdef0123456789abcdef"); + std::fs::write(&abandoned, b"temporary").unwrap(); + std::fs::set_permissions(&abandoned, std::fs::Permissions::from_mode(0o600)).unwrap(); + assert_eq!(cleanup_temporaries_for(Authority::Helper), Ok(())); + assert!(abandoned.exists(), "the helper arm sweeps nothing in the app's root"); + assert_eq!(cleanup_temporaries_for(Authority::Files), Ok(())); + assert!(!abandoned.exists(), "the files arm removes the abandoned temporary"); + } + /// `bootstrap()` and `cleanup_after_confirmed_clear()` must search and sweep the pre-DB8 - /// canonical JSON wrapper identically on ARM, so both funnel through this one helper rather - /// than each carrying its own `insert(0, path())`. This is callable unconditionally (it is - /// pure path arithmetic), so a host test can prove the shared assembly directly instead of - /// only trusting that the two ARM-gated call sites still agree. + /// canonical JSON wrapper identically where the helper is canonical, so both funnel through + /// this one helper rather than each carrying its own `insert(0, path())`. It is pure path + /// arithmetic, so a host test proves the shared assembly directly for either authority. Under + /// `Files` the wrapper is the store itself, so it is no migration source. #[test] - fn arm_candidate_assembly_puts_the_canonical_wrapper_first() { + fn the_candidates_a_platform_searches_follow_its_authority() { // `path()` reads the process-global persistent state root, which every redirecting test in // this binary moves under the lock. Two unlocked reads can straddle one of those moves, so // this takes the same lock: both reads then see one root. let _serial = plx_base::testlock::serial(); - let mut candidates = vec![PathBuf::from("/some/legacy/auth.json")]; - insert_arm_canonical_wrapper(&mut candidates); - assert_eq!(candidates[0], path()); - assert_eq!(candidates.len(), 2); - assert_eq!(candidates[1], PathBuf::from("/some/legacy/auth.json")); + let legacy = vec![PathBuf::from("/some/legacy/auth.json")]; + let helper = migration_candidates(Authority::Helper, legacy.clone()); + assert_eq!(helper, vec![path(), PathBuf::from("/some/legacy/auth.json")]); + let files = migration_candidates(Authority::Files, legacy.clone()); + assert_eq!(files, legacy, "the files platform's own store is never one of its migration sources"); } /// Point the canonical persistence root at a directory of this test's own; restore the @@ -1397,32 +1402,39 @@ pub fn write_session_timed( commit } -/// The authority-selected write used by the shared worker. ARM has exactly one authority: DB8. +/// The authority-selected write used by the shared worker. The platform has exactly one canonical +/// store at a time: the storage helper where it states one, the record files everywhere else. pub fn write_session( session: &super::Session, authority: super::SaveAuthority, ) -> CanonicalCommit { - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - { - commit_session_with_authority(session, authority) - } - #[cfg(not(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - )))] - { - let _ = authority; - match serde_json::to_string(session) { - Ok(payload) => commit_data(payload), - Err(_) => CanonicalCommit::Failed(StoreError::InvalidSchema), - } + write_session_via(storage_authority(), &mut client::NativeTransport, session, authority) +} + +/// [`write_session`] with the storage authority and the helper's transport as parameters. `save` is +/// how the caller may write ([`super::SaveAuthority`]); only the helper's protection rules read it. +pub(super) fn write_session_via( + authority: Authority, + helper: &mut dyn client::Transport, + session: &super::Session, + save: super::SaveAuthority, +) -> CanonicalCommit { + match authority { + Authority::Helper => commit_session_with( + session, + false, + save, + plx_os::tv::device::info().major, + helper, + ), + Authority::Files => write_session_file(session), + } +} + +fn write_session_file(session: &super::Session) -> CanonicalCommit { + match serde_json::to_string(session) { + Ok(payload) => commit_data_file(payload), + Err(_) => CanonicalCommit::Failed(StoreError::InvalidSchema), } } @@ -1580,16 +1592,13 @@ impl MigrationStore for HelperMigration<'_> { struct FileMigration; impl MigrationStore for FileMigration { fn load(&mut self) -> CanonicalRead { - load() + load_file() } fn import(&mut self, session: &super::Session) -> CanonicalCommit { - match serde_json::to_string(session) { - Ok(payload) => commit_data(payload), - Err(_) => CanonicalCommit::Failed(StoreError::InvalidSchema), - } + write_session_file(session) } fn clear(&mut self) -> CanonicalCommit { - commit_cleared() + commit_cleared_file() } } @@ -1722,13 +1731,17 @@ fn retire_exact_candidate(path: &Path, expected: &[u8]) -> bool { .is_some_and(|directory| directory.sync_all().is_ok()) } -/// The previous canonical JSON wrapper (`path()`, the pre-DB8 `session.json`) outranks older -/// bare candidates on ARM: it is a recognized migration source in its own right and must be -/// searched (on boot) and swept (on sign-out) ahead of the plain legacy files. Both call sites -/// that assemble an ARM candidate list must go through this one function so the two lists -/// cannot drift apart again. -fn insert_arm_canonical_wrapper(candidates: &mut Vec) { - candidates.insert(0, path()); +/// The migration sources a platform searches (on boot) and sweeps (on sign-out), given the legacy +/// files `base` names. Where the storage helper is canonical, the previous canonical JSON wrapper +/// (`path()`, the pre-DB8 `session.json`) outranks the older bare candidates: it is a recognized +/// migration source in its own right. Where the files are canonical it IS the store, never a +/// source. Both call sites that assemble a candidate list go through this one function so the two +/// lists cannot drift apart again. +fn migration_candidates(authority: Authority, mut base: Vec) -> Vec { + if authority == Authority::Helper { + base.insert(0, path()); + } + base } pub fn bootstrap(opener: &mut dyn LegacyOpener) -> Bootstrap { @@ -1736,32 +1749,25 @@ pub fn bootstrap(opener: &mut dyn LegacyOpener) -> Bootstrap { let candidates = plx_base::paths::session_migration_candidates(); #[cfg(any(test, feature = "test-support"))] let candidates = super::auth_paths(); - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - { - let mut candidates = candidates; - insert_arm_canonical_wrapper(&mut candidates); - bootstrap_with( - &mut HelperMigration { - transport: &mut client::NativeTransport, - major: plx_os::tv::device::info().major, - }, + bootstrap_via(storage_authority(), &mut client::NativeTransport, opener, candidates) +} + +/// [`bootstrap`] with the authority, the helper's transport and the legacy files `base` as +/// parameters. The canonical store is chosen here, before the loop, and never by a failed read. +pub(super) fn bootstrap_via( + authority: Authority, + helper: &mut dyn client::Transport, + opener: &mut dyn LegacyOpener, + base: Vec, +) -> Bootstrap { + let candidates = migration_candidates(authority, base); + match authority { + Authority::Helper => bootstrap_with( + &mut HelperMigration { transport: helper, major: plx_os::tv::device::info().major }, opener, &candidates, - ) - } - #[cfg(not(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - )))] - { - bootstrap_with(&mut FileMigration, opener, &candidates) + ), + Authority::Files => bootstrap_with(&mut FileMigration, opener, &candidates), } } @@ -1793,24 +1799,28 @@ pub enum ClearCleanupOutcome { /// residues. Failed retirement remains visible: canonical Cleared shadows a residue only while /// the authority can answer, so a marked fallback must also be removed or neutralized. pub fn cleanup_after_confirmed_clear() -> ClearCleanupOutcome { - if !matches!(load(), CanonicalRead::Cleared { .. }) { - return ClearCleanupOutcome::AuthorityNotConfirmed; - } #[cfg(not(any(test, feature = "test-support")))] let candidates = plx_base::paths::session_migration_candidates(); #[cfg(any(test, feature = "test-support"))] let candidates = super::auth_paths(); - #[cfg(all( - target_os = "linux", - target_arch = "arm", - not(feature = "hostsim"), - not(any(test, feature = "test-support")) - ))] - let candidates = { - let mut candidates = candidates; - insert_arm_canonical_wrapper(&mut candidates); - candidates - }; + cleanup_after_confirmed_clear_via( + storage_authority(), + &mut client::NativeTransport, + candidates, + ) +} + +/// [`cleanup_after_confirmed_clear`] with the authority, the helper's transport and the legacy +/// files `base` as parameters. +pub(super) fn cleanup_after_confirmed_clear_via( + authority: Authority, + helper: &mut dyn client::Transport, + base: Vec, +) -> ClearCleanupOutcome { + if !matches!(load_via(authority, helper), CanonicalRead::Cleared { .. }) { + return ClearCleanupOutcome::AuthorityNotConfirmed; + } + let candidates = migration_candidates(authority, base); let mut complete = super::retry_pending_retirements_locked(); for candidate in candidates { match plx_os::storage::read_owned_bytes(&candidate) { diff --git a/rust-modules/plex/src/plex/session_persistence_tests.rs b/rust-modules/plex/src/plex/session_persistence_tests.rs index 779cfbcc69..d6925e12b8 100644 --- a/rust-modules/plex/src/plex/session_persistence_tests.rs +++ b/rust-modules/plex/src/plex/session_persistence_tests.rs @@ -584,7 +584,7 @@ fn clear_under_a_redirected_legacy_fixture_never_touches_the_canonical_authority /// `signout-leaves-token-in-unswept-candidates`: `clear()` must actually reach /// `persistence::cleanup_after_confirmed_clear()` after a durable canonical commit — the step /// that retires the full recognized migration-candidate set -/// (`paths::session_migration_candidates()`, plus the pre-DB8 canonical JSON wrapper on ARM), +/// (`paths::session_migration_candidates()`, plus the pre-DB8 canonical JSON wrapper where the helper is canonical), /// which is a strict superset of the legacy `auth_paths()` list `clear()`'s own loop sweeps. /// /// **On the honesty of this test**: `persistence::bootstrap`/`cleanup_after_confirmed_clear` From fb35a0e978e10fc471a0c89ddaa2974a9ff695c7 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 17:52:31 +0300 Subject: [PATCH 14/26] Pointer and wheel reach the loop as a HostEvent, and the cursor hide is the platform's (#1492) Step W5c of the platform plan (discussion #1460). Pointer and wheel input now reach the loop as `HostEvent`s, as keys and text did in W5b (#1487). The Magic Remote's cursor hide moves behind the platform's `Shell`. webOS hides and shows the pointer exactly as before. The desktop and the host-test platform hide nothing, which is what the simulator already did. ## What changes - **`HostEvent::Pointer { x: f32, y: f32, edge: PointerEdge }`**, where `PointerEdge` is `Move`, `Down` or `Up`, and **`HostEvent::Wheel { dy: i32 }`**. - `decode_host_event` (`app/events.rs`) maps `SDL_MOUSEMOTION`, `SDL_MOUSEBUTTONDOWN` and `SDL_MOUSEBUTTONUP` to `Pointer`, and `SDL_MOUSEWHEEL` to `Wheel`. - x and y are logical coordinates, from `plx_base::surface::to_logical`. At 1920x1080 that is the identity. Because they are floats, `HostEvent` keeps `PartialEq` but loses `Eq`. - `decode_wheel_dy` keeps the existing wheel-offset handling and its comment. Under hostsim it reads the float at +32 and rounds it; otherwise it reads the `Sint32` at +20. - **The plan proposed `Pointer { x, y, buttons, shown }`. This lands without `buttons` and `shown`:** - The loop never read which button was pressed: the edge is the SDL event type alone, whatever the button. `the_edge_is_the_event_type_whatever_the_button_bytes_say` pins that. - Whether the pointer is shown is the pointer machine's own `cur_hidden`, not event data. - **`ingest_host_event`** (`app/run.rs`) handles both events through `ingest_pointer_{motion,down,up}` and `ingest_wheel`. Effect order, the recorder rows (`enc_pointer`, and `("wheel", 0, dy)` after the 250 ms debounce) and the drop of real input under a controlled replay do not change. - **The cursor hide.** `app/boot.rs` gives up `hide_cursor`, `cursor_is_transparent`, `show_cursor_after_motion`, `hide_through`, `show_through`, `SHOWN_CURSOR`, `CursorDoor` and `cursor_door` to `rust-modules/src/system.rs`. `system` already sits in `[platform webos]`, so no module is added. - `Shell` gains `hide_pointer`, `show_pointer_after_motion` and `hide_is_cursor_swap`. - `WebosShell` forwards each one to `system`. `DesktopShell` and `HostShell` are no-ops and answer `hide_is_cursor_swap` false. A test-only `SwapShell` counts its calls and says true. - Callers in `input.rs`, `playback.rs` (through a new `Bridge::shell()`) and `run.rs` reach the hide through the shell. - Apart from the cfg lines, the television's code paths are unchanged. The hostsim gates and arms are gone, the three wrappers are safe `fn`s, and `wl_sym` is renamed `self_sym`. - `SHOWN_CURSOR` moves with no new ledger line. - `boot.rs` keeps the pre-`SDL_Init` cursor sleep hint (`webos3_cursor_sleep_hint`, `cursor_sleep_hint`, its own `self_sym`) and its source-order pins. - **`feature = "hostsim"` occurrences.** The ones on the moved cursor functions go from 13 to 0. Across the touched files the count goes from 99 to 89: | file | before | after | |---|---|---| | `boot.rs` | 52 | 39 | | `run.rs` | 27 | 26 | | `events.rs` | 8 | 12 | `events.rs` rises by one production `cfg!` in `decode_wheel_dy` and three test-only gates. - **Carried from #1487's review:** - The `press()` helper's vacuous `armed` assertions now observe the real press with `is_live`, with a direction-key control. - The "minted by `plex_run`" prose is fixed. The main-thread token is minted in `enter_application`. The fix covers `base/src/task.rs`, `media/src/player/{adapter,mod}.rs`, `dev.rs`, `docs/async-model-decision.md`, `docs/agent-reference.md` and `docs/remote-keys.md`. - The `docs/agent-reference.md` fuzz wording is fixed. ## Tests - **Decode:** - `pointer_event_tests`: the edge and position; the edge ignoring the button bytes; the synthesized bytes round-tripping; the wheel offset at +20; the FIFO token's television-shaped wheel decoding to 0 under hostsim; and, under hostsim, a fractional trackpad tick rounding to whole ticks. - `host_event_tests`. - **The loop** (`lifecycle_regression_tests`, hostsim): - pointer and wheel take the paths their SDL events took; - the D-pad motion gate; - OK-as-click under a cursor swap, and its button-up; - the D-pad hiding the pointer through the shell, and a motion showing it again; - the recorder rows; - the wheel FIFO token; - the controlled-replay drop. - **The hide door:** - `system::cursor_door_tests`, five tests, not gated; - `input::pointer_hide_tests`; - the shells' own tests in `platform.rs` and `platform_desktop.rs`. - **Mutations.** 21 mutants were applied one at a time, and each was killed by the test aimed at it. - No mutant exists for the three one-line `WebosShell` forwards or for the `sync_back_cursor` call in `playback.rs`, because the host cannot observe them. - Three more call sites are moved verbatim but no test guards them: - the idle-over-video hide in `run.rs`'s `playback_tick` (`shell.hide_pointer()` after 3000 ms without motion); - `host_background`'s `sync_back_cursor`; - `controlled_key_input`'s `note_cursor_motion`. `SwapShell` could now observe them, but no test drives those paths on it. Deleting any one of them fails no test. Results on the committed tree at 17d0574e8, after merging main at f7038a8fd (W6b #1489, which contains #1488 and #1490): - Full hostsim suite, without the two tests that kill the test binary on the lane's Mac at base too: `test result: ok. 1781 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out` - Default-feature suite, the same way: `test result: ok. 1514 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out` - `make test-hostsim T=uri_boot`: `test result: ok. 29 passed; 0 failed; 0 ignored; 0 measured; 1754 filtered out` - `make test-crate C=plxnative-modules`: - `T=port::tests`: `test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1513 filtered out` - `T=pointer`: `test result: ok. 18 passed; 0 failed; 0 ignored; 0 measured; 1497 filtered out` - `T=cursor_door`: `test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 1510 filtered out` - `make check-nodef`: exit 0. `make lint` was exit 0 on b7ec914af; the only edit since the merge is a test-only line. - `make check-replay`: `6 fixtures, 12 replays, SAME=4 REFUSED_EXPECTED=8 unexpected=0` - The merge needed one fix: `SwapShell::platform()` passes `MediaBoot::HOST_TEST` to W6b's four-argument `Platform::new`. `the_host_test_platform_answers_nothing_and_says_so` destructures all four `Platform` fields. Results on b0ad245fc, before the merge: - Full hostsim suite, without the two tests that kill the test binary on the lane's Mac at base too: `test result: ok. 1774 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out` - The skipped tests are `player_owner_events_record_and_replay_through_the_actual_app_host` and `an_unregistered_product_screen_uses_generic_navigation_and_actual_store_effects`. - Default-feature suite, the same way: `test result: ok. 1509 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out` - `make check-replay`: `6 fixtures, 12 replays, SAME=4 REFUSED_EXPECTED=8 unexpected=0` - `tests/keytable.json` is unchanged. - `ci/check-deps.sh`, `ci/check-module-layers.py`, `ci/check-ledger-ratchet.py` and `ci/check-statics.sh` are green. - `ci/test_readonly_generated.py` and `ci/test_readonly_dependencies.py` pass. - No change under `ci/`, to any Cargo file or `.cargo`, or to `rust-modules/src/lib.rs`. - `fw-compat-reviewer`: no findings. It graded the source only. The same `SDL_*` symbols are looked up in the same order, with the same hide method per firmware release. The 3.x releases sit below the graded floor. - `doc-claim-auditor`: five findings, all fixed. ## Not covered - **No television run.** Not checked on a set: the pointer hide and show on a 3.x set against a 4.5+ set, the `WebosShell` forwards, and the Back sync in `playback.rs`. - **The `wheel:` FIFO token.** It builds the television's +20 layout, so under hostsim it decodes to 0. This was already true before this PR, and a test now pins it. --- .agents/agents/fw-compat-reviewer.md | 2 +- docs/agent-reference.md | 2 +- docs/async-model-decision.md | 3 +- docs/implicit-machines-audit-2026-11-16.md | 2 +- docs/module-layers.md | 2 +- docs/remote-keys.md | 16 +- rust-modules/base/src/task.rs | 4 +- rust-modules/media/src/player/adapter.rs | 6 +- rust-modules/media/src/player/mod.rs | 6 +- rust-modules/src/app/boot.rs | 264 +----- rust-modules/src/app/bridge.rs | 16 +- rust-modules/src/app/events.rs | 273 +++++- rust-modules/src/app/input.rs | 177 ++-- rust-modules/src/app/platform.rs | 102 ++- rust-modules/src/app/playback.rs | 4 +- rust-modules/src/app/run.rs | 987 ++++++++++++++++----- rust-modules/src/dev.rs | 4 +- rust-modules/src/platform_desktop.rs | 25 +- rust-modules/src/port.rs | 14 +- rust-modules/src/system.rs | 284 +++++- 20 files changed, 1570 insertions(+), 623 deletions(-) diff --git a/.agents/agents/fw-compat-reviewer.md b/.agents/agents/fw-compat-reviewer.md index 9fe7412380..e703609633 100644 --- a/.agents/agents/fw-compat-reviewer.md +++ b/.agents/agents/fw-compat-reviewer.md @@ -260,7 +260,7 @@ Reading the output: C++11 `std::string` ABI and are untested on a set apart from one 3.4.3 (webOS 1.x/2.x were never tried). They used to fail on two missing symbols, `SDL_webOSCursorVisibility` and `StarfishMediaAPIs::Feed`'s C++11 name, but since #578 both are `dlsym`'d at runtime - (`src/starfish.c`, `rust-modules/src/app/boot.rs`), so the binary no longer imports them. Re-run + (`src/starfish.c`, `rust-modules/src/app/boot.rs`, and `rust-modules/src/system.rs`'s `cursor_door`), so the binary no longer imports them. Re-run `tools/fwcompat.py` for what the old rows print now; they are still printed below the floor and do not set the exit status. * **Baseline as of 2026-08-23** (verified by running it): `15 DT_NEEDED, 319 undefined dynamic diff --git a/docs/agent-reference.md b/docs/agent-reference.md index c1b2787593..70bedc6cb6 100644 --- a/docs/agent-reference.md +++ b/docs/agent-reference.md @@ -345,7 +345,7 @@ the pinned Sentry Native cross-build), and `sshpass` (Homebrew; deploy/run use y asserts only what its code promises (no panic, the documented bounds, round trips) and a crash fails the run, with the input in `fuzz/artifacts//`. The package is a top-level `fuzz/` with its own `[workspace]`, so no shipped `Cargo.toml` names it and no shipped build changes; it depends on the layer - crates by path, with `plx_media/hostsim` (the host configuration: the Feed backend's host sink and the layers' host stand-ins), and `fuzz/build.rs` + crates by path, with `plx_media/hostsim` (the host configuration of the layers below it: the stand-ins they compile in place of the television's calls, so the package links and runs on a desktop), and `fuzz/build.rs` reuses `rust-modules/build_support/host_link.rs`. `tools/fuzz-hud.py` is the whole workflow (`list | seed | lock | build | run`): it copies `rust-modules/Cargo.lock` to the gitignored `fuzz/Cargo.lock` (the shared crates are exactly the shipped versions), builds with the nightly named by `FUZZ_TOOLCHAIN` diff --git a/docs/async-model-decision.md b/docs/async-model-decision.md index 1fdf02fcb2..d6e1e150fd 100644 --- a/docs/async-model-decision.md +++ b/docs/async-model-decision.md @@ -360,7 +360,8 @@ flagged as unused, precisely because it reached the static directly instead of t **Superseded for the slot, 2026-09-10 (UI restructure phase 9).** `ENGINE` is no longer a `static mut` and the four accessors are gone: the slot is a FIELD, `App.adapters.player`, and -`player::adapter::PlayerAdapter::new` **consumes** the one token `plex_run` mints. So the token is +`player::adapter::PlayerAdapter::new` **consumes** the one token `enter_application` mints (`app/mod.rs`, +`MainThread::assume()`, reached by `plex_run` and `platform_desktop::run` alike through `run_application`). So the token is no longer an argument that ASSERTS main-thread confinement for the session — holding `&mut PlayerAdapter` IS the confinement, and the borrow checker keeps it. The seam half of this finding is unchanged: `ffi.rs`'s wrappers still take `&MainThread`, reached as `pa.mt()`. What the diff --git a/docs/implicit-machines-audit-2026-11-16.md b/docs/implicit-machines-audit-2026-11-16.md index 64655e7eb4..9288e5bf70 100644 --- a/docs/implicit-machines-audit-2026-11-16.md +++ b/docs/implicit-machines-audit-2026-11-16.md @@ -283,7 +283,7 @@ Paths are relative to `rust-modules/src/` unless they start with `media/` or `ui | # | lifecycle | where | kind | states | writer sites | user-visible | defect traced | size | |---|---|---|---|---|---|---|---|---| | 1 | Parked-playback restore claim (`App.decoder_parked` + `App.foreground_retry` + `App.repause_at` + `WindowActivity.active`, layered on the registered `ForegroundLifecycle`) | app/mod.rs:302-309, app/run.rs:1243-1283, 1876-2008 | a, e | 6 | 9 field writes + 5 claim call sites | yes (film restore after app switch / screensaver) | YES: retry claim not gated on foreground | M | -| 2 | Pointer mode / cursor visibility / button (`Pointer`, `SHOWN_CURSOR`, `App.down_sym`) | app/input.rs:31, app/boot.rs:1057 | a, c | 2x4x3 | about 19 | yes (cursor, OK-as-click, edge glide) | YES: two sibling-flag omissions (the PLAY entry's is not shown reachable; see Traced defects) | M | +| 2 | Pointer mode / cursor visibility / button (`Pointer`, `SHOWN_CURSOR`, `App.down_sym`) | app/input.rs:31, app/boot.rs:1057 (`SHOWN_CURSOR` has since moved to `system.rs`, behind `Shell`) | a, c | 2x4x3 | about 19 | yes (cursor, OK-as-click, edge glide) | YES: two sibling-flag omissions (the PLAY entry's is not shown reachable; see Traced defects) | M | | 3 | Poster slot lifecycle (`Pslot.state` as a `c_int` const + 9 sibling fields, in `static STORE`) | app/adapters/poster.rs:115-130, 156 | b, c, d | 8 | 11 state writes in 7 fns, 2 threads | yes (every poster) | none proven | L | | 4 | Player-exit to hubs refetch to Home reveal hold (`App.refresh_hubs` + `ReturnHold` + `PageDip` floor) | app/mod.rs:333-335, app/playback.rs:1028, app/run.rs:2258-2288 | a, d, e | 5 | 8 | yes (Continue Watching after playback) | none proven | S-M | | 5 | Preview to feature-play hand-off (`thread_local HELD_FEATURE`, `PREVIEW_HOST`, plus media `preview::occupies/abandoning`) | app/content.rs:120-173, 203-333 | c, e | 4 | 5 | yes (Play over an auto-playing trailer) | none proven (no cancel path, see detail) | S | diff --git a/docs/module-layers.md b/docs/module-layers.md index a969fdebf9..6d78438251 100644 --- a/docs/module-layers.md +++ b/docs/module-layers.md @@ -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`, 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` | +| 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 and lends, through `Bridge::shell`, to playback's pointer hide); `Shell` also carries the Magic Remote's pointer hide (`hide_pointer`, `show_pointer_after_motion`, `hide_is_cursor_swap`), which `port::WebosShell` forwards to `system` | `app::boot`, `app::run`, `app::bridge`, `app::input`, `app::playback` | | 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` | diff --git a/docs/remote-keys.md b/docs/remote-keys.md index 8f13c51fc6..cbffb39ca6 100644 --- a/docs/remote-keys.md +++ b/docs/remote-keys.md @@ -276,9 +276,10 @@ predicate: `classify` names a `Key`, **or** `page_dir` answers, **or** the sym i build's configured upload trigger (`crate::labcfg::is_trigger_key`, `false` at compile time in every build anyone can install; `docs/lab-diagnostics.md`). The guarded half lives in `app/input.rs::note_global_press`, split -out so `make check` can grade it — `begin_fresh_press` itself calls `hide_cursor`, which acts on -whatever pointer calls the process's SDL exports, so a host test that reached it would be grading the -host's SDL rather than the press. The bare player samples the HUD for bound keys in ordered screen +out so `make check` can grade it — `begin_fresh_press` itself hides the pointer through the platform's +`Shell` (`hide_pointer`), which on a television acts on whatever pointer calls the process's SDL +exports, so a test that reached the television's shell would be grading the host's SDL rather than the +press. The bare player samples the HUD for bound keys in ordered screen delivery. A second Back in the same SDL batch sees the first one's dismissal, and an intervening bound press spends any exit arming. The LG pointer-hidden notification only stops edge scrolling. @@ -323,10 +324,13 @@ un-dismisses the HUD. Narrowing that means making the predicate route-aware, i.e the ladder's own order — the duplication `page_dir` exists to have ended. A number key is also, unlike a colour button, a key this app really does bind, so calling it bound is honest. -Graded twice, because neither half implies the other: `app/input.rs`'s `unsupported_key_tests` covers the -two global effects (invisible to any focus fingerprint), and `tools/keytable.py` covers "moves +Graded in three places, because no one of them implies the others: `app/input.rs`'s +`unsupported_key_tests` covers the HUD wake (invisible to any focus fingerprint); the press half is +observed on the dispatcher's real press in `run.rs`'s `lifecycle_regression_tests` (an unbound key +leaves a click armed and live, a direction key abandons it); and `tools/keytable.py` covers "moves nothing on any screen" — its `k:0,269` (HOME) and `k:53,34` (the digit 5) rows are inert on Home, -Library and Search in `tests/keytable.json`. +Library and Search in `tests/keytable.json`. The trap to avoid is an `armed` assertion beside +`note_global_press`: that function holds no press, so such an assertion cannot fail. **What neither covers**: the player route. The simulator has no video path, so no fingerprint in that table was taken with a HUD on screen. The HUD half of this invariant has been graded as a unit diff --git a/rust-modules/base/src/task.rs b/rust-modules/base/src/task.rs index 3ae90986c7..fdd2678393 100644 --- a/rust-modules/base/src/task.rs +++ b/rust-modules/base/src/task.rs @@ -129,7 +129,9 @@ impl OffFrame { pub struct MainThread(PhantomData<*const ()>); impl MainThread { - /// Mint the token. `plex_run` calls this once, at the top, and nothing else should. + /// Mint the token. In production `enter_application` (`app/mod.rs`) calls this once, for every entry + /// (`plex_run` on the television and `platform_desktop::run` on a desktop reach it through + /// `run_application`), and nothing else should; a test rig assumes its own. /// /// # Safety /// The caller asserts this is the SDL main thread. It is not a memory-safety obligation in diff --git a/rust-modules/media/src/player/adapter.rs b/rust-modules/media/src/player/adapter.rs index 0dcfcf7f17..4a7ad3e8e7 100644 --- a/rust-modules/media/src/player/adapter.rs +++ b/rust-modules/media/src/player/adapter.rs @@ -16,8 +16,8 @@ //! — see `docs/async-model-decision.md`). //! //! The reasoning is unchanged and the enforcement is stronger. **The token is now CONSUMED at -//! construction** ([`PlayerAdapter::new`] takes it by value, and `plex_run` is the only place that -//! can mint one), so holding a `&mut PlayerAdapter` IS the proof the old argument stood in for — +//! construction** ([`PlayerAdapter::new`] takes it by value, and `enter_application` is the only +//! production place that mints one), so holding a `&mut PlayerAdapter` IS the proof the old argument stood in for — //! and it is a proof the borrow checker keeps rather than one a caller could satisfy twice. Two //! live `&mut` to the engine no longer requires a convention: it does not compile. The native //! feed owns that borrow; common callers receive addressed facts or coarse physical actions. @@ -558,7 +558,7 @@ pub enum QueuedLanding { } impl PlayerAdapter { - /// Take the token. `app::boot` calls this once, with the token `plex_run` minted. + /// Take the token. `app::boot` calls this once, with the token `enter_application` minted. pub fn new(mt: MainThread) -> Self { Self { mt, diff --git a/rust-modules/media/src/player/mod.rs b/rust-modules/media/src/player/mod.rs index a4335fd364..5944a8bdb2 100644 --- a/rust-modules/media/src/player/mod.rs +++ b/rust-modules/media/src/player/mod.rs @@ -10,9 +10,9 @@ //! docs/engine-port-design.md. //! //! "Runs on the SDL main thread" is a **compile error to violate** for the two things where it -//! matters — the ACB/Starfish seam and the native session slot. `plex_run` mints ONE -//! [`MainThread`] token; `boot` moves it into [`adapter::PlayerAdapter`], which owns the session -//! that was `engine::ENGINE`. The seam still takes `&MainThread` (reached through the adapter), +//! matters — the ACB/Starfish seam and the native session slot. `enter_application` mints ONE +//! [`MainThread`] token (every entry reaches it through `run_application`); `boot` moves it into +//! [`adapter::PlayerAdapter`], which owns the session that was `engine::ENGINE`. The seam still takes `&MainThread` (reached through the adapter), //! the slot takes `&mut PlayerAdapter`, and the token is `!Send`, so a closure that captured //! either cannot be handed to `task::spawn`. The exceptions are the honest ones: the two callbacks //! above are `extern "C"` entry points *from* the library thread and touch only `FEED_SHARED`, diff --git a/rust-modules/src/app/boot.rs b/rust-modules/src/app/boot.rs index 553163d685..d8436dd07b 100644 --- a/rust-modules/src/app/boot.rs +++ b/rust-modules/src/app/boot.rs @@ -724,92 +724,6 @@ mod seam_order_tests { } } -/// Hide the Magic Remote's on-screen pointer. A webOS-only concept: there is no such cursor to -/// hide on a desktop, and `SDL_webOSCursorVisibility` exists in no SDL but LG's fork. -/// -/// One door rather than a branch at each caller, so the platform question is asked once -/// and the callers read the same on LG's extension and on the transparent-cursor path. -/// -/// Resolved at runtime rather than linked: webOS 3.4 ships SDL 2.0.3, which has none of LG's -/// `SDL_webOS*` extensions, and a strong reference there is a lazily-bound PLT slot that kills -/// the process on the first D-pad press (`tools/fwcompat.py --release 3.4.0`). -/// -/// **Without LG's extension the pointer is SDL's own cursor, and it is swapped for a transparent -/// one rather than switched off.** webOS 3.9.3 ships SDL 2.0.4 with no `SDL_webOS*` export at all, -/// and that SDL draws the pointer itself (its `.rodata` carries `/usr/share/im/cursorType*.png` -/// and `wl_starfish_pointer`). With nothing to call, every hide was a no-op and the pointer stayed -/// up until LG's ~5-minute idle timeout, issue #642. `SDL_ShowCursor(SDL_DISABLE)` does hide it -/// there, but measured on that set it also stops pointer motion reaching the app until the pointer -/// re-enters the window (opening and closing the Settings overlay), so no motion could bring it -/// back. With a transparent cursor the motion keeps arriving, and [`show_cursor_after_motion`] puts -/// the previous cursor back on the next one. Every SDL call is dlsym'd, so the binary gains no -/// import. -#[inline] -pub(crate) unsafe fn hide_cursor() { - #[cfg(not(feature = "hostsim"))] - { - hide_through(cursor_door(), &SHOWN_CURSOR); - } -} - -/// True where the pointer is hidden by swapping in a transparent cursor rather than by LG's call, -/// so the system's pointer stays up and the remote's OK arrives as a click (`input::click_is_ok`). -/// False on the host simulator, where a click is always a real one. -pub(crate) unsafe fn cursor_is_transparent() -> bool { - #[cfg(not(feature = "hostsim"))] - { - matches!(cursor_door(), CursorDoor::Sdl { .. }) - } - #[cfg(feature = "hostsim")] - { - false - } -} - -/// Bring the pointer back after [`hide_cursor`] swapped in the transparent cursor. Call on pointer -/// motion while the cursor is hidden. A no-op wherever LG's extension exists: there the -/// compositor shows its own pointer on motion, as it always has. -#[inline] -pub(crate) unsafe fn show_cursor_after_motion() { - #[cfg(not(feature = "hostsim"))] - { - show_through(cursor_door(), &SHOWN_CURSOR); - } -} - -/// [`hide_cursor`] on a given door, the cursor it replaced kept in `shown`. Split out so the -/// bookkeeping is gradeable on the host with a door of fake functions. -#[cfg(not(feature = "hostsim"))] -unsafe fn hide_through(door: CursorDoor, shown: &std::sync::atomic::AtomicUsize) { - match door { - CursorDoor::Lg(f) => { - f(0); - } - CursorDoor::Sdl { set, get, def, blank } => { - let cur = get() as usize; - if cur != blank { - let keep = if cur != 0 { cur } else { def() as usize }; - if keep == 0 { - return; // nothing to put back, so the pointer would never return: leave it - } - shown.store(keep, std::sync::atomic::Ordering::Relaxed); - } - set(blank as *mut std::ffi::c_void); - } - CursorDoor::None => {} - } -} - -/// [`show_cursor_after_motion`] on a given door. -#[cfg(not(feature = "hostsim"))] -unsafe fn show_through(door: CursorDoor, shown: &std::sync::atomic::AtomicUsize) { - if let CursorDoor::Sdl { set, .. } = door { - let shown = shown.load(std::sync::atomic::Ordering::Relaxed); - if shown != 0 { - set(shown as *mut std::ffi::c_void); - } - } -} /// The window to ask for when it is not the 1920x1080 canvas, `None` for the canvas (1:1): whatever /// `/tmp/plxnative-drawable=x` says when that trigger is armed (debug builds only; it /// outranks the setting and is bounded to 640x360..=1920x1080 so a typo cannot ask for nonsense), @@ -985,177 +899,9 @@ unsafe extern "C" fn wrapped_message(msg: *mut std::ffi::c_void) -> *const std:: p } -/// The cursor [`hide_cursor`] replaced with the transparent one, for the motion that restores it. -#[cfg(not(feature = "hostsim"))] -static SHOWN_CURSOR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - -#[cfg(not(feature = "hostsim"))] -type CursorVisibilityFn = unsafe extern "C" fn(c_int) -> c_int; -#[cfg(not(feature = "hostsim"))] -type SetCursorFn = unsafe extern "C" fn(*mut std::ffi::c_void); -#[cfg(not(feature = "hostsim"))] -type GetCursorFn = unsafe extern "C" fn() -> *mut std::ffi::c_void; -#[cfg(not(feature = "hostsim"))] -type CreateCursorFn = - unsafe extern "C" fn(*const u8, *const u8, c_int, c_int, c_int, c_int) -> *mut std::ffi::c_void; - -/// Which call hides the pointer on this firmware, resolved once: LG's extension when the system -/// SDL has it (webOS 4+), else a transparent SDL cursor (webOS 3.x). -#[cfg(not(feature = "hostsim"))] -#[derive(Clone, Copy)] -enum CursorDoor { - Lg(CursorVisibilityFn), - /// `SDL_SetCursor` / `SDL_GetCursor` / `SDL_GetDefaultCursor`, and the transparent cursor. - Sdl { set: SetCursorFn, get: GetCursorFn, def: GetCursorFn, blank: usize }, - None, -} - -/// Resolved on the first hide, after `SDL_Init`, because `SDL_CreateCursor` needs the video -/// subsystem. -#[cfg(not(feature = "hostsim"))] -fn cursor_door() -> CursorDoor { - static DOOR: std::sync::OnceLock = std::sync::OnceLock::new(); - *DOOR.get_or_init(|| { - use std::ffi::c_void; - use std::mem::transmute; - // SAFETY: each symbol is transmuted to the signature SDL2's public API (or, for - // `SDL_webOSCursorVisibility`, LG's fork) gives it, and is called on the main thread. - let door = unsafe { - if let Some(f) = self_sym("SDL_webOSCursorVisibility") { - CursorDoor::Lg(transmute::<*mut c_void, CursorVisibilityFn>(f)) - } else if let (Some(set), Some(get), Some(def), Some(create)) = ( - self_sym("SDL_SetCursor"), - self_sym("SDL_GetCursor"), - self_sym("SDL_GetDefaultCursor"), - self_sym("SDL_CreateCursor"), - ) { - // 8x1 with every data and mask bit clear: SDL's transparent pixel throughout. - let bits = [0u8; 1]; - let create = transmute::<*mut c_void, CreateCursorFn>(create); - let blank = create(bits.as_ptr(), bits.as_ptr(), 8, 1, 0, 0); - if blank.is_null() { - CursorDoor::None - } else { - CursorDoor::Sdl { - set: transmute::<*mut c_void, SetCursorFn>(set), - get: transmute::<*mut c_void, GetCursorFn>(get), - def: transmute::<*mut c_void, GetCursorFn>(def), - blank: blank as usize, - } - } - } else { - CursorDoor::None - } - }; - log(match door { - CursorDoor::Lg(_) => "cursor: SDL_webOSCursorVisibility", - CursorDoor::Sdl { .. } => "cursor: transparent SDL cursor (no SDL_webOS* in this SDL)", - CursorDoor::None => "cursor: no way to hide the pointer", - }); - door - }) -} #[cfg(all(test, not(feature = "hostsim")))] -mod cursor_door_tests { +mod cursor_sleep_hint_tests { use super::*; - use std::cell::{Cell, RefCell}; - use std::ffi::c_void; - use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; - - const BLANK: usize = 0x99; - - thread_local! { - static CURRENT: Cell = const { Cell::new(0) }; - static DEFAULT: Cell = const { Cell::new(0) }; - static SET: RefCell> = const { RefCell::new(Vec::new()) }; - static LG: RefCell> = const { RefCell::new(Vec::new()) }; - } - - unsafe extern "C" fn set(c: *mut c_void) { - SET.with(|s| s.borrow_mut().push(c as usize)); - CURRENT.with(|cur| cur.set(c as usize)); - } - unsafe extern "C" fn get() -> *mut c_void { - CURRENT.with(Cell::get) as *mut c_void - } - unsafe extern "C" fn def() -> *mut c_void { - DEFAULT.with(Cell::get) as *mut c_void - } - unsafe extern "C" fn lg(visible: c_int) -> c_int { - LG.with(|l| l.borrow_mut().push(visible)); - 0 - } - - /// A fresh door with SDL's current cursor and default cursor as given (0 = NULL). - fn sdl(current: usize, default: usize) -> CursorDoor { - CURRENT.with(|c| c.set(current)); - DEFAULT.with(|d| d.set(default)); - SET.with(|s| s.borrow_mut().clear()); - CursorDoor::Sdl { set, get, def, blank: BLANK } - } - fn installed() -> Vec { - SET.with(|s| s.borrow().clone()) - } - - #[test] - fn hiding_swaps_in_the_blank_cursor_and_motion_puts_the_previous_one_back() { - let shown = AtomicUsize::new(0); - let door = sdl(0x10, 0x20); - unsafe { - hide_through(door, &shown); - assert_eq!(installed(), [BLANK]); - show_through(door, &shown); - } - assert_eq!(installed(), [BLANK, 0x10]); - } - - #[test] - fn with_no_current_cursor_the_default_one_is_what_comes_back() { - let shown = AtomicUsize::new(0); - let door = sdl(0, 0x20); - unsafe { - hide_through(door, &shown); - show_through(door, &shown); - } - assert_eq!(installed(), [BLANK, 0x20]); - } - - #[test] - fn hiding_again_while_hidden_keeps_the_cursor_to_restore() { - let shown = AtomicUsize::new(0); - let door = sdl(0x10, 0x20); - unsafe { - hide_through(door, &shown); - hide_through(door, &shown); // `get` now answers the blank cursor - show_through(door, &shown); - } - assert_eq!(installed(), [BLANK, BLANK, 0x10]); - } - - /// With no current and no default cursor there is nothing to put back, so the pointer must not - /// be hidden: it would never come back. - #[test] - fn with_nothing_to_restore_the_cursor_is_left_alone() { - let shown = AtomicUsize::new(0); - let door = sdl(0, 0); - unsafe { - hide_through(door, &shown); - show_through(door, &shown); - } - assert_eq!(installed(), Vec::::new()); - assert_eq!(shown.load(Relaxed), 0); - } - - #[test] - fn lgs_extension_is_asked_to_hide_and_motion_leaves_it_to_the_compositor() { - let shown = AtomicUsize::new(0); - LG.with(|l| l.borrow_mut().clear()); - unsafe { - hide_through(CursorDoor::Lg(lg), &shown); - show_through(CursorDoor::Lg(lg), &shown); - } - assert_eq!(LG.with(|l| l.borrow().clone()), [0]); - } #[test] fn the_idle_hide_hint_is_asked_for_only_where_lgs_extension_is_absent() { @@ -1299,7 +1045,7 @@ pub(crate) fn direct_trigger_server() -> Result { + /// The platform's shell, which the pointer's callers (`playback`'s PLAY key and Back-cursor + /// commands) hide and show the Magic Remote's pointer through: the one `App::platform` holds. + pub(super) fn shell(&self) -> &'static dyn Shell { + self.retained.shell + } + #[cfg(test)] pub(crate) fn measurement_queries(&self)->Vec { self.retained.measure.queries() } /// The measurer every screen of this bridge lays out with (a host test's has no fonts): the HUD @@ -858,8 +864,16 @@ impl BridgeRetained { /// dies inside `text.rs` on a `debug_assert!`, several frames away from anything it asserted. #[cfg(test)] pub(crate) fn for_test(now_us: fn() -> u64) -> (super::runtime_owners::RuntimeOwners, Self) { + Self::for_test_on(now_us, super::platform::Platform::HOST_TEST.shell) + } + + /// [`Self::for_test`] on a given platform's shell, for a test that counts what the bridge's + /// callers ask of the shell (the PLAY key's and Back's pointer hide). + #[cfg(test)] + pub(crate) fn for_test_on(now_us: fn() -> u64, shell: &'static dyn Shell) + -> (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, super::platform::Platform::HOST_TEST.shell, + let (mut runtime, mut retained) = Self::with_measure(&FIXTURE, now_us, shell, plx_session::auth::SessionInit::captured(plx_plex::plex::session::Session::default()), super::adapters::session::SessionAdapter::fixture(), Default::default(), super::adapters::consent::ConsentAdapter::fixture(), diff --git a/rust-modules/src/app/events.rs b/rust-modules/src/app/events.rs index 3aaa5ce67e..949ceec4cc 100644 --- a/rust-modules/src/app/events.rs +++ b/rust-modules/src/app/events.rs @@ -3,8 +3,9 @@ //! Moved out of `app.rs` verbatim in phase 1a (a pure move; `pub(crate)` widening only). //! //! The one decode that yields a platform-neutral value is [`decode_host_event`]: SDL's quit, -//! application-lifecycle, key and text events become a [`HostEvent`], which the loop consumes in one -//! function. A key carries its canonical [`Action`] (`ui::consts`) beside the raw pair. +//! application-lifecycle, key, text, pointer and wheel events become a [`HostEvent`], which the loop +//! consumes in one function. A key carries its canonical [`Action`] (`ui::consts`) beside the raw +//! pair; a pointer event carries authored coordinates, and a wheel tick its already-decoded count. use super::*; use plx_machine::machine::Edge; @@ -139,8 +140,8 @@ const SDL_APP_DIDENTERBACKGROUND: u32 = 0x104; const SDL_APP_WILLENTERFOREGROUND: u32 = 0x105; const SDL_APP_DIDENTERFOREGROUND: u32 = 0x106; -/// What the platform tells the loop: a key press, a text commit, the window leaving or returning to -/// the screen, and the host asking the application to end. App-private, like +/// What the platform tells the loop: a key press, a text commit, the pointer, the wheel, the window +/// leaving or returning to the screen, and the host asking the application to end. App-private, like /// [`Shell`](super::platform::Shell): no platform reaches it by a type of its own until the /// platform contract is settled (`docs/platform-ports.md`, Target shape 2). /// @@ -148,13 +149,14 @@ const SDL_APP_DIDENTERFOREGROUND: u32 = 0x106; /// ONE function (`run::ingest_host_event`), so a host that stops the application without SDL /// (the hosted entry's `plx_host_stop`) arrives as the same [`HostEvent::Quit`] an `SDL_QUIT` /// does and takes the same path, and a host with no SDL key pair sends a [`HostEvent::Key`] that -/// carries an [`Action`]. Pointer and wheel are not here yet: they keep their raw path in -/// `run::ingest_sdl_event_with_window` until their own step (W5c) moves them. +/// carries an [`Action`]. The pointer and the wheel are decoded here too (W5c), so what the loop reads +/// of a mouse or a Magic Remote is a [`HostEvent::Pointer`] in authored coordinates and a +/// [`HostEvent::Wheel`] count, never SDL's bytes or either layout's wheel offset. /// /// There is no `Edit` event: nothing produces one. `SDL_TEXTEDITING` (the IME pre-edit) is read by /// nothing and stays a log-only raw event, and the system keyboard's edit keys (caret, backspace, /// clear-all) are ordinary [`HostEvent::Key`] actions. `Edit` arrives with its first producer (W9). -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq)] pub(crate) enum HostEvent { /// The window left or came back to the screen. Lifecycle(Lifecycle), @@ -167,6 +169,40 @@ pub(crate) enum HostEvent { /// loop ignores an empty one as it always has). The platform's own text layout is decoded /// before it gets here (`textinput::decode`, the one place that knows the offsets). Text(String), + /// One pointer event, at authored 1920x1080 coordinates ([`ptr_xy`]: the window's pixels + /// converted exactly once, the identity while the drawable is the canvas). `edge` is what it did: + /// moved, went down or came up. It is the event TYPE alone, for any button, as the loop has always + /// read it. The plan's `buttons` and `shown` members are not carried, because today's SDL events + /// give them no source the loop reads: whether a button is held is the loop's own state, set by + /// the down and up edges (`Pointer::button_down`), and whether the pointer is shown is not in any + /// SDL pointer event (LG's own hide arrives as a key, [`Action::PointerHidden`]; a show is a motion). + Pointer { x: f32, y: f32, edge: PointerEdge }, + /// One tick of the wheel: its vertical count in the signed whole ticks the loop reads (a + /// fractional trackpad tick that rounds to nothing is `0`, which the loop records and then + /// ignores, as it always has). Decoded from whichever offset this host carries it at + /// ([`decode_wheel_dy`]). + Wheel { dy: i32 }, +} + +/// What a [`HostEvent::Pointer`] did. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PointerEdge { + /// `SDL_MOUSEMOTION`. + Move, + /// `SDL_MOUSEBUTTONDOWN`, any button. + Down, + /// `SDL_MOUSEBUTTONUP`, any button. + Up, +} + +impl HostEvent { + /// Is this the viewer's INPUT (a key, text, pointer or wheel event), as opposed to the window's + /// (a lifecycle edge, quit)? The loop's activity bookkeeping asks it: input keeps a release-health + /// session open and repaints as input damage, where the window's events are page damage. The same + /// split [`is_input_event`] makes of an SDL event type, which `host_event_tests` pins them to. + pub(crate) fn is_input(&self) -> bool { + matches!(self, HostEvent::Key(_) | HostEvent::Text(_) | HostEvent::Pointer { .. } | HostEvent::Wheel { .. }) + } } /// The raw `(sym, wcode)` pair a key arrived as. Kept beside the [`Action`] because three things @@ -298,9 +334,10 @@ impl Lifecycle { } /// An SDL event decoded into a [`HostEvent`]: `SDL_QUIT`, the four application lifecycle types, a -/// key edge (`SDL_KEYDOWN`/`SDL_KEYUP`, through [`decode_key`], so both layouts) and a text commit -/// (`SDL_TEXTINPUT`, through `textinput::decode`). `None` for everything else, which the loop reads -/// raw (pointer, wheel, the IME's pre-edit, and the SDL events nothing acts on). Beside +/// key edge (`SDL_KEYDOWN`/`SDL_KEYUP`, through [`decode_key`], so both layouts), a text commit +/// (`SDL_TEXTINPUT`, through `textinput::decode`), a pointer event (motion, button down and button up, +/// through [`ptr_xy`]) and a wheel tick (through [`decode_wheel_dy`]). `None` for everything else, +/// which the loop reads raw (the IME's pre-edit, and the SDL events nothing acts on). Beside /// [`decode_key`], the other place that knows SDL's event bytes. #[inline] pub(crate) fn decode_host_event(ev: &[u8]) -> Option { @@ -308,6 +345,10 @@ pub(crate) fn decode_host_event(ev: &[u8]) -> Option { SDL_QUIT => HostEvent::Quit, SDL_KEYDOWN | SDL_KEYUP => HostEvent::Key(KeyPress::from_sdl(ev)?), SDL_TEXTINPUT => HostEvent::Text(crate::textinput::decode(ev)), + SDL_MOUSEMOTION => pointer_event(ev, PointerEdge::Move), + SDL_MOUSEBUTTONDOWN => pointer_event(ev, PointerEdge::Down), + SDL_MOUSEBUTTONUP => pointer_event(ev, PointerEdge::Up), + SDL_MOUSEWHEEL => HostEvent::Wheel { dy: decode_wheel_dy(ev) }, SDL_APP_WILLENTERBACKGROUND => HostEvent::Lifecycle(Lifecycle::WillBackground), SDL_APP_DIDENTERBACKGROUND => HostEvent::Lifecycle(Lifecycle::DidBackground), SDL_APP_WILLENTERFOREGROUND => HostEvent::Lifecycle(Lifecycle::WillForeground), @@ -316,6 +357,39 @@ pub(crate) fn decode_host_event(ev: &[u8]) -> Option { }) } +/// A pointer event's position and edge. The coordinates are read at +20 and +24 in both layouts (the +/// pointer offsets agree, [`ptr_xy`]), and the button at +16 and its state at +17 are not read: the +/// edge is the event type, for any button, as the loop has always taken it. +#[inline] +fn pointer_event(ev: &[u8], edge: PointerEdge) -> HostEvent { + let (x, y) = ptr_xy(ev); + HostEvent::Pointer { x, y, edge } +} + +/// A wheel event's vertical tick count, in the signed whole ticks the loop reads. +/// +/// **The host reads a DIFFERENT offset, and this one is not the LG-fork +/// shift `decode_key` documents — it is macOS `libSDL2` again being +/// sdl2-compat forwarding into SDL3.** `SDL_MouseWheelEvent` on real SDL2 +/// (what the television runs) carries a plain `Sint32 y` at +20, which is +/// what production code always read. Measured 2026-09-02 by dumping the +/// polled bytes of an injected -40 tick on this host: `+20` came back 0, and +/// -40.0 arrived instead as the FLOAT `preciseY` field at `+32` — SDL2's own +/// struct gained that field in 2.0.18 for fractional trackpad scroll, and +/// sdl2-compat's round trip apparently only forwards it, leaving the legacy +/// integer field zeroed for both a genuine trackpad tick and anything +/// `SDL_PushEvent`d in this shape (item 13's `wheel:` FIFO token hit +/// this the first time anything synthesized a wheel event at all — nothing +/// needed one before). `cfg!`, not `#[cfg]`, so both arms keep compiling. +#[inline] +fn decode_wheel_dy(ev: &[u8]) -> i32 { + if cfg!(feature = "hostsim") { + rd_f32(ev, 32).round() as i32 + } else { + rd_i32(ev, 20) + } +} + /// The bytes a synthetic key event needs, in whichever layout [`decode_key`] reads. /// /// **The inverse of `decode_key`, and the pair is only correct together.** They already shipped @@ -629,7 +703,7 @@ pub(crate) fn remote_synth_key_repeat(sym: c_uint, wcode: c_uint) { /// Synthesize one Magic-Remote scroll-wheel tick — item 13's `wheel:` FIFO token, so a script /// can drive the wheel with no mouse in the room. Encoded in the plain, real-SDL2 shape /// (`Sint32 y` at `+20`) unconditionally: it is the READING side that has to branch by platform -/// now, not this one — see the wheel arm's own comment on why `+20` decodes to 0 on this host and +/// now, not this one — see [`decode_wheel_dy`] on why `+20` decodes to 0 on this host and /// where the value actually lands after `SDL_PushEvent` round-trips it. pub(crate) fn remote_synth_wheel(dy: i32) { let mut ev = [0u8; 128]; @@ -1011,18 +1085,185 @@ mod host_event_tests { } } - /// Everything the loop still reads raw stays raw: no pointer or wheel event decodes (0x400 to - /// 0x403, until W5c), nor the IME's pre-edit (0x302, which nothing reads), nor the SDL events - /// nothing acts on (terminating and low memory, which sit between quit and the background pair, - /// and the window events). Keys (0x300, 0x301) and text (0x303) are decoded: `key_event_tests`. + /// Everything the loop still reads raw stays raw: the IME's pre-edit (0x302, which nothing reads), + /// the SDL events nothing acts on (terminating and low memory, which sit between quit and the + /// background pair, and the window events), and the types either side of the pointer and wheel + /// block (0x3ff and 0x404). Keys (0x300, 0x301), text (0x303), the pointer (0x400 to 0x402) and + /// the wheel (0x403) are decoded: `key_event_tests` and `pointer_event_tests`. #[test] fn every_other_event_stays_on_the_raw_path() { for code in [ - 0, 0x101, 0x102, 0x107, 0x200, 0x302, 0x400, 0x401, 0x402, 0x403, u32::MAX, + 0, 0x101, 0x102, 0x107, 0x200, 0x302, 0x3ff, 0x404, u32::MAX, ] { assert_eq!(decode_host_event(&event_of(code)), None, "{code:#x}"); } } + + /// **`HostEvent::is_input` and `is_input_event` are one classification.** The loop asks the first + /// of a decoded event and the second of the raw type, and `Dispatcher::input_scope` rests on the + /// second, so a pointer or wheel event the first called window damage (or a lifecycle edge it called + /// input) would repaint under the wrong owner. Every type that decodes is held to both: the window's + /// are not input, the viewer's are. The IME's pre-edit (0x302) is input to the type table and decodes + /// to nothing, so it has no `HostEvent` to compare. + #[test] + fn a_host_event_is_input_exactly_when_its_sdl_type_is() { + let _serial = plx_base::testlock::serial(); + for (code, input) in [ + (0x100, false), (0x103, false), (0x104, false), (0x105, false), (0x106, false), + (0x300, true), (0x301, true), (0x303, true), + (0x400, true), (0x401, true), (0x402, true), (0x403, true), + ] { + let mut ev = event_of(code); + if code == 0x300 || code == 0x301 { + ev = super::encode_key(plx_ui::consts::SDLK_UP, 0, code == 0x300); + } + let event = decode_host_event(&ev).unwrap_or_else(|| panic!("{code:#x} decodes")); + assert_eq!(event.is_input(), input, "{code:#x} as a HostEvent"); + assert_eq!(is_input_event(code), input, "{code:#x} as a type"); + } + } +} + +/// A pointer event and a wheel tick as a [`HostEvent`] (W5c): what the SDL decoder makes of the +/// bytes, in both layouts. The offsets are literals, written out here and not read back from the +/// decoder: they are the contract with SDL (and, for the pointer, with `docs/testing-player-pointer.md`'s +/// `offsetof` assertions). +#[cfg(test)] +mod pointer_event_tests { + use super::{decode_host_event, encode_pointer, HostEvent, PointerEdge}; + + const MOTION: u32 = 0x400; + const DOWN: u32 = 0x401; + const UP: u32 = 0x402; + const WHEEL: u32 = 0x403; + + /// A pointer event as SDL lays it out, written by hand: `type` at +0, the window id at +8, the + /// button at +16 and its state at +17, then `Sint32 x` at +20 and `Sint32 y` at +24. LG's fork and + /// stock SDL2 agree on all of it (the keyboard event is the one that shifts), which is why the + /// decoder has one reading for both. + fn bytes(code: u32, button: u8, state: u8, x: i32, y: i32) -> [u8; 128] { + let mut ev = [0u8; 128]; + ev[0..4].copy_from_slice(&code.to_ne_bytes()); + ev[8..12].copy_from_slice(&7u32.to_ne_bytes()); + ev[16] = button; + ev[17] = state; + ev[20..24].copy_from_slice(&x.to_ne_bytes()); + ev[24..28].copy_from_slice(&y.to_ne_bytes()); + ev + } + + fn pointer(x: f32, y: f32, edge: PointerEdge) -> Option { + Some(HostEvent::Pointer { x, y, edge }) + } + + /// **The decode table.** Each of the three SDL types, at the corners and the middle of the canvas + /// and just outside it (a drag past the edge reports negative and over-large positions), decodes + /// to its edge and its position. The surface is the identity here (1920x1080, the default), so the + /// position is what the bytes say; `ptr_xy`'s conversion off the identity is `plx_base::surface`'s. + #[test] + fn an_sdl_pointer_event_decodes_to_its_edge_and_its_position() { + let _serial = plx_base::testlock::serial(); + for (code, edge) in [(MOTION, PointerEdge::Move), (DOWN, PointerEdge::Down), (UP, PointerEdge::Up)] { + for (x, y) in [(0, 0), (960, 540), (1919, 1079), (1400, 870), (-3, 1085), (2000, -1)] { + assert_eq!(decode_host_event(&bytes(code, 1, 1, x, y)), pointer(x as f32, y as f32, edge), + "{code:#x} at ({x}, {y})"); + } + } + } + + /// **The edge is the event type alone**, for any button and whatever its state byte says, as the + /// loop has always taken it: a button-up carrying state 1, a button-down carrying state 0 and a + /// motion with a button byte set are still an up, a down and a move. Bytes the decoder must not read + /// (the window id, the bytes after `y`, the float where the wheel keeps its fraction) are noise here. + #[test] + fn the_edge_is_the_event_type_whatever_the_button_bytes_say() { + let _serial = plx_base::testlock::serial(); + for button in [0u8, 1, 2, 3, 255] { + for state in [0u8, 1] { + for (code, edge) in [(MOTION, PointerEdge::Move), (DOWN, PointerEdge::Down), (UP, PointerEdge::Up)] { + let mut ev = bytes(code, button, state, 640, 360); + ev[28..64].fill(0xa5); + assert_eq!(decode_host_event(&ev), pointer(640.0, 360.0, edge), "{code:#x} button {button} state {state}"); + } + } + } + } + + /// The bytes the loop's own synthesis writes (`encode_pointer`, which the FIFO's `ck:` `pm:` `pd:` + /// `pu:` tokens and the replay driver push) decode to the position and edge they were built from. + /// The encoder and the decoder shipped apart once for keys; this is what couples them for the pointer. + #[test] + fn the_synthesized_pointer_bytes_round_trip() { + let _serial = plx_base::testlock::serial(); + for (code, edge) in [(MOTION, PointerEdge::Move), (DOWN, PointerEdge::Down), (UP, PointerEdge::Up)] { + for (x, y) in [(0, 0), (1400, 870), (1919, 1079)] { + assert_eq!(decode_host_event(&encode_pointer(code, x, y)), pointer(x as f32, y as f32, edge), "{code:#x}"); + } + } + } + + /// A wheel event as the television's SDL2 lays it out: `Sint32 y` at +20. + fn wheel_lg(dy: i32) -> [u8; 128] { + let mut ev = [0u8; 128]; + ev[0..4].copy_from_slice(&WHEEL.to_ne_bytes()); + ev[20..24].copy_from_slice(&dy.to_ne_bytes()); + ev + } + + /// A wheel event as the simulator's stock SDL2 (sdl2-compat over SDL3) delivers it: the count in + /// the float `preciseY` at +32, with the legacy integer at +20 left at zero. + fn wheel_stock(precise_y: f32) -> [u8; 128] { + let mut ev = [0u8; 128]; + ev[0..4].copy_from_slice(&WHEEL.to_ne_bytes()); + ev[32..36].copy_from_slice(&precise_y.to_ne_bytes()); + ev + } + + fn wheel(dy: i32) -> Option { + Some(HostEvent::Wheel { dy }) + } + + /// **Each layout's wheel, and the one this build does not read.** The television's integer at +20 + /// is the count in the default build and is ignored in the simulator's; the simulator's float at +32 + /// is the count there (rounded to whole ticks) and is ignored on the television. A decoder that + /// read both, or the wrong one, fails one of the two assertions in each build. + #[test] + fn a_wheel_tick_is_read_from_the_offset_this_hosts_sdl_carries_it_at() { + for dy in [-40, -3, -1, 1, 2, 120] { + if cfg!(feature = "hostsim") { + assert_eq!(decode_host_event(&wheel_stock(dy as f32)), wheel(dy), "stock layout, {dy}"); + assert_eq!(decode_host_event(&wheel_lg(dy)), wheel(0), "the television's field is not this host's: {dy}"); + } else { + assert_eq!(decode_host_event(&wheel_lg(dy)), wheel(dy), "LG layout, {dy}"); + assert_eq!(decode_host_event(&wheel_stock(dy as f32)), wheel(0), "the simulator's field is not read here: {dy}"); + } + } + } + + /// **The `+20` case.** `remote_synth_wheel`, the `wheel:` token's pusher, writes the television's + /// shape (`Sint32 y` at +20) unconditionally, so the bytes it builds decode to the count on the + /// television and to ZERO in the simulator (where `SDL_PushEvent` hands the value back at +32; the + /// decoder's doc has the measurement). The zero is not a bug: it is why the decoder reads the other + /// offset there. It is pinned so a "fix" that reads `+20` everywhere shows up here, in the simulator + /// run, as a count that is no longer zero. + #[test] + fn the_television_shaped_wheel_the_fifo_token_builds_decodes_to_zero_in_the_simulator() { + let mut token_shape = [0u8; 128]; + token_shape[0..4].copy_from_slice(&WHEEL.to_ne_bytes()); + token_shape[20..24].copy_from_slice(&(-2i32).to_ne_bytes()); + let expected = if cfg!(feature = "hostsim") { 0 } else { -2 }; + assert_eq!(decode_host_event(&token_shape), wheel(expected)); + } + + /// A fractional trackpad tick keeps the sign of what it rounds to, and a half tick or less is no + /// tick (the loop records a zero and ignores it). Only the simulator's layout carries a fraction. + #[cfg(feature = "hostsim")] + #[test] + fn a_fractional_trackpad_tick_rounds_to_whole_ticks() { + for (precise, dy) in [(-0.4, 0), (0.4, 0), (-0.6, -1), (0.6, 1), (-1.4, -1), (2.5, 3), (-40.0, -40)] { + assert_eq!(decode_host_event(&wheel_stock(precise)), wheel(dy), "{precise}"); + } + } } /// A key edge and a text commit as a [`HostEvent`] (W5b): what the SDL decoder makes of the bytes, diff --git a/rust-modules/src/app/input.rs b/rust-modules/src/app/input.rs index 1dd299ca33..8992b6e99a 100644 --- a/rust-modules/src/app/input.rs +++ b/rust-modules/src/app/input.rs @@ -18,7 +18,7 @@ //! consumes only the Session owner's committed Ready handoff. use super::*; - +use super::platform::Shell; /// The Magic Remote POINTER, as one value: which input mode the remote is in, what the /// cursor is doing, and the two gestures that outlive a single event (a scrub drag and the @@ -64,8 +64,8 @@ struct BackCursorOwner { impl Pointer { /// **Enter D-pad mode** — the one place its state is written, for the arrow keys and PLAY - /// alike. Each caller keeps its own decision to call `hide_cursor()`; this is the state - /// half: the cursor reads hidden, Back no longer owns it, motion is counted afresh against + /// alike. Each caller keeps its own decision to hide the pointer (`Shell::hide_pointer`); this + /// is the state half: the cursor reads hidden, Back no longer owns it, motion is counted afresh against /// `DPAD_MOTION_GATE` and the edge glide stops. pub(crate) fn enter_dpad(&mut self) { self.dpad_mode = true; @@ -94,9 +94,9 @@ impl Pointer { self.back_cursor.is_some() } - pub(crate) fn note_cursor_motion(&mut self) { + pub(crate) fn note_cursor_motion(&mut self, shell: &dyn Shell) { if self.cur_hidden && !self.back_cursor_active() { - unsafe { super::boot::show_cursor_after_motion(); } + shell.show_pointer_after_motion(); self.cur_hidden = false; } } @@ -108,12 +108,13 @@ impl Pointer { pub(crate) fn sync_back_cursor( &mut self, + shell: &dyn Shell, current: Option, request: Option<(BackCursorTarget, plx_screens::registry::BackCursorChange)>, ) { use plx_screens::registry::BackCursorChange; if self.back_cursor.as_ref().is_some_and(|owner| Some(owner.target) != current) { - self.release_back_cursor(false); + self.release_back_cursor(shell, false); } let Some((target, change)) = request.filter(|(target, _)| Some(*target) == current) else { return; @@ -121,20 +122,20 @@ impl Pointer { match change { BackCursorChange::Hide => { let installed = !self.cur_hidden || self.back_cursor.as_ref().is_some_and(|owner| owner.installed); - unsafe { hide_cursor(); } + shell.hide_pointer(); self.cur_hidden = true; self.back_cursor = Some(BackCursorOwner { target, installed }); } - BackCursorChange::Wake => self.release_back_cursor(true), - BackCursorChange::Release => self.release_back_cursor(false), + BackCursorChange::Wake => self.release_back_cursor(shell, true), + BackCursorChange::Release => self.release_back_cursor(shell, false), } } - fn release_back_cursor(&mut self, motion: bool) { + fn release_back_cursor(&mut self, shell: &dyn Shell, motion: bool) { if self.back_cursor.take().is_some_and(|owner| motion || owner.installed) { // On LG's backend this is a no-op. Only a blank cursor installed by // this app can be restored here. - unsafe { super::boot::show_cursor_after_motion(); } + shell.show_pointer_after_motion(); self.cur_hidden = false; } } @@ -317,7 +318,7 @@ impl EdgeScroll { /// **Is this pointer click really the remote's OK button?** /// /// On a set without LG's `SDL_webOSCursorVisibility` (webOS 3.9.3's SDL 2.0.4, issue #642) the -/// app hides the pointer by swapping in a transparent cursor (`boot::hide_cursor`). The system +/// app hides the pointer by swapping in a transparent cursor (`Shell::hide_is_cursor_swap`). The system /// still believes its pointer is up, so the Magic Remote's OK arrives as a CLICK at wherever that /// invisible pointer sits, never as an OK key: the viewer arrows to the `…` disc, presses OK, and /// the click lands on the picture and toggles pause. (Measured on an OLED55B7V-Z, 3.9.3, @@ -1251,7 +1252,7 @@ pub(crate) unsafe fn begin_fresh_press( down_sym: &mut u32, hud: Option<&mut HudState>, ptr: &mut Pointer, - + shell: &dyn Shell, ) { *down_sym = sym; note_global_press(ps, sym, wcode, now, viewer_paused, hud); @@ -1260,7 +1261,7 @@ pub(crate) unsafe fn begin_fresh_press( Key::Up | Key::Down | Key::Left { alt: false } | Key::Right { alt: false } ) { if !ptr.dpad_mode || !ptr.cur_hidden { - hide_cursor(); + shell.hide_pointer(); } ptr.enter_dpad(); } @@ -1269,10 +1270,11 @@ pub(crate) unsafe fn begin_fresh_press( /// **The global HUD wake of a fresh press, and the guard that decides whether it happens** — /// the half of [`begin_fresh_press`] that LG checklist item 40 is about, and its only caller. /// -/// Split out for one blunt reason: `begin_fresh_press` calls `hide_cursor`, which acts on whatever -/// pointer calls the process's SDL exports (resolved at run time, `app/boot.rs`), so a host test -/// that reached it would be grading the host's SDL rather than the press. This half touches no SDL -/// at all, so the invariant is gradeable by `make check` instead of only by a television. +/// Split out for one blunt reason: `begin_fresh_press` hides the pointer through the platform's +/// shell, which on a television calls whatever pointer functions the process's SDL exports (resolved +/// at run time, `system.rs`), so a test that reached the television's shell would be grading the +/// host's SDL rather than the press. This half touches no shell at all, so the invariant is +/// gradeable by `make check` instead of only by a television. pub(crate) fn note_global_press( ps: &plx_media::route::PlaybackSession, sym: c_uint, @@ -1294,46 +1296,44 @@ pub(crate) fn note_global_press( // Release and cancellation are owned by the dispatcher's InputMachine. } -/// **The unsupported-key invariant, graded.** `tools/keytable.py` grades the other half — that an -/// unbound press moves no focus on any screen — and cannot see either of these two, because neither -/// appears in a focus fingerprint. +/// **The unsupported-key invariant, graded.** `tools/keytable.py` grades one half — that an unbound +/// press moves no focus on any screen — and cannot see the HUD wake this module grades, because it +/// appears in no focus fingerprint. The press half is graded on the real press, in the loop's tests. #[cfg(test)] mod unsupported_key_tests { use super::*; - /// Drive one fresh press through [`note_global_press`] and report what it left behind: - /// `(a click is still armed, the HUD is still dismissed)`. `press::*`, `hud_until()` and - /// The caller supplies the viewer's pause goal at the input boundary; the press is this - /// test's own `Press`. - fn press(ps: &plx_media::route::PlaybackSession, sym: c_uint, wcode: c_uint) -> (bool, bool) { + /// Drive one fresh press through [`note_global_press`] and report whether the HUD is still + /// dismissed afterwards. The caller supplies the viewer's pause goal at the input boundary. + /// + /// This used to report a second thing, "a click is still armed", by arming a `Press` of its own + /// beside the call. `note_global_press` no longer touches any press (the dispatcher's input + /// machine owns it, "Release and cancellation are owned by the dispatcher's InputMachine"), so + /// that local `Press` was never reachable from the code under test and the `armed` assertions + /// could not fail. They are gone, and what they meant to guard is observed on the real press, armed + /// by a click and left alone by an unbound key through the loop's key ingress: + /// `run::lifecycle_regression_tests::an_unbound_key_leaves_the_press_a_click_armed_live_and_a_direction_key_abandons_it`. + fn press(ps: &plx_media::route::PlaybackSession, sym: c_uint, wcode: c_uint) -> bool { let mut hud = HudState::IDLE; - hud.dismissed = true; // …and the transport was hidden by hand (UP from the control row) - let mut p = plx_ui::dispatch::press::Press::new(); - p.begin(1_000); - note_global_press(ps, sym, wcode, 1_000, false, - Some(&mut hud)); - let out = (p.is_active(), hud.dismissed); - p.cancel(); - out + note_global_press(ps, sym, wcode, 1_000, false, Some(&mut hud)); + hud.dismissed } - /// Bound keys wake the HUD; physical bookkeeping leaves all gesture cancellation to input. + /// Bound keys wake the HUD. #[test] - fn a_bound_key_still_wakes_the_hud_without_owning_the_press() { + fn a_bound_key_still_wakes_the_hud() { let ps = plx_media::route::PlaybackSession::IDLE; let _g = plx_base::testlock::serial(); - let (armed, dismissed) = press(&ps, plx_ui::consts::SDLK_ESCAPE, 0); - assert!(armed, "physical bookkeeping must leave press ownership to the dispatcher"); - assert!(!dismissed, "…and any key un-dismisses the transport"); + assert!(!press(&ps, plx_ui::consts::SDLK_ESCAPE, 0), "any bound key un-dismisses the transport"); } - /// **The regression.** An unsupported key must do NEITHER — it is not input the app acted on, - /// so it may not raise the transport over playback and it may not abandon a press in flight. - /// 269 is HOME (`SDL_SCANCODE_AC_HOME`, evdev 172 `KEY_HOMEPAGE`); every other unbound - /// scancode takes the same branch. + /// **The regression.** An unsupported key must not raise the transport over playback, it is not + /// input the app acted on (nor may it abandon a press in flight: that half is observed on the + /// real press, see [`press`]). 269 is HOME (`SDL_SCANCODE_AC_HOME`, evdev 172 `KEY_HOMEPAGE`); + /// every other unbound scancode takes the same branch. #[test] - fn an_unsupported_key_wakes_nothing_and_abandons_nothing() { + fn an_unsupported_key_wakes_nothing() { let ps = plx_media::route::PlaybackSession::IDLE; let _g = plx_base::testlock::serial(); for (sym, wcode, what) in [ @@ -1341,9 +1341,7 @@ mod unsupported_key_tests { (0, 270, "AC_BACK"), (b'a' as c_uint, 4, "a letter"), ] { - let (armed, dismissed) = press(&ps, sym, wcode); - assert!(armed, "{what} must not cancel the armed click"); - assert!(dismissed, "{what} must not un-dismiss the HUD"); + assert!(press(&ps, sym, wcode), "{what} must not un-dismiss the HUD"); } } @@ -1354,23 +1352,20 @@ mod unsupported_key_tests { fn a_number_key_counts_as_bound_because_the_pin_keypad_types_from_it() { let ps = plx_media::route::PlaybackSession::IDLE; let _g = plx_base::testlock::serial(); - let (armed, dismissed) = press(&ps, b'5' as c_uint, 34); - assert!(armed, "physical bookkeeping leaves cancellation to the input owner"); - assert!(!dismissed); + assert!(!press(&ps, b'5' as c_uint, 34)); } /// The native pair as the loop reads it: decoded from the SDL bytes a television sends, then /// handed to [`press`]. Returns the decoded action too. fn native(ps: &plx_media::route::PlaybackSession, sym: c_uint, wcode: c_uint) - -> (Option, (bool, bool)) { + -> (Option, bool) { let (key, _) = crate::app::events::native_key_input(sym, wcode, true, plx_machine::machine::Tick::default()); let pair = key.pair(); assert_eq!((pair.sym, pair.wcode), (sym, wcode), "the decoder keeps the raw pair"); (key.action(), press(ps, pair.sym, pair.wcode)) } - /// **A native key that no action names wakes nothing and abandons nothing, and a bound one still - /// wakes the HUD.** Both halves through the decoder, each pair a literal, in one test so the bound + /// **A native key that no action names wakes nothing, and a bound one still wakes the HUD.** Both halves through the decoder, each pair a literal, in one test so the bound /// keys are the positive control for the unbound ones: the colour button (504), HOME (269), /// and the wcode-only press in 48..=57. That last one is the keypad's: `pin_digit` reads the /// wcode, `is_remote_bound` reads the sym only (`action_of`'s number-key arm), so a scancode that @@ -1383,9 +1378,8 @@ mod unsupported_key_tests { let mut unbound: Vec<(c_uint, c_uint)> = vec![(0, 504), (0, 269), (0, 270), (b'a' as c_uint, 4), (0, 0)]; unbound.extend((48..=57).map(|wcode| (0, wcode))); for (sym, wcode) in unbound { - let (action, (armed, dismissed)) = native(&ps, sym, wcode); + let (action, dismissed) = native(&ps, sym, wcode); assert_eq!(action, None, "({sym}, {wcode}) names no action"); - assert!(armed, "({sym}, {wcode}) must not cancel the armed click"); assert!(dismissed, "({sym}, {wcode}) must not un-dismiss the HUD"); } for (sym, wcode, action) in [ @@ -1394,7 +1388,7 @@ mod unsupported_key_tests { (0x4000_004e, 0, Action::PageDown), (0, 300, Action::PageUp), (8, 42, Action::Backspace), (53, 34, Action::Digit(5)), ] { - let (decoded, (_, dismissed)) = native(&ps, sym, wcode); + let (decoded, dismissed) = native(&ps, sym, wcode); assert_eq!(decoded, Some(action), "({sym}, {wcode}) decodes to its action"); assert!(!dismissed, "{action:?} is bound, so it un-dismisses the HUD"); } @@ -2055,6 +2049,77 @@ mod click_is_ok_tests { } } +/// **The pointer's hide and show reach the shell, and only when they should.** The machine owns the +/// decision (`cur_hidden`, the D-pad mode, Back's ownership); the shell owns the act. Counted on a +/// shell that says what it was asked, with no loop and no feature gate, so the default build grades +/// the same calls the hostsim loop tests do. +#[cfg(test)] +mod pointer_hide_tests { + use super::*; + use std::sync::atomic::Ordering::Relaxed; + + fn press_down(ptr: &mut Pointer, shell: &dyn Shell) { + let ps = plx_media::route::PlaybackSession::IDLE; + let mut down_sym = 0; + unsafe { + begin_fresh_press(&ps, Key::Down, plx_ui::consts::SDLK_DOWN, 0, 0, false, &mut down_sym, None, ptr, shell) + }; + } + + /// The first direction key hides (and enters the D-pad's mode), a second while the pointer is + /// still hidden asks for nothing, a motion shows it once and a second motion nothing more, and the + /// next direction key hides it again. A key that is no direction hides nothing. + #[test] + fn a_direction_key_hides_once_and_a_motion_shows_once() { + let _g = plx_base::testlock::serial(); + let (platform, counted) = crate::app::platform::SwapShell::platform(); + let shell = platform.shell; + let counts = || (counted.hides.load(Relaxed), counted.shows.load(Relaxed)); + let mut ptr = Pointer::IDLE; + ptr.note_cursor_motion(shell); + assert_eq!(counts(), (0, 0), "a pointer that was never hidden is not shown"); + let ps = plx_media::route::PlaybackSession::IDLE; + let mut down_sym = 0; + unsafe { begin_fresh_press(&ps, Key::Ok, 13, 0, 0, false, &mut down_sym, None, &mut ptr, shell) }; + assert_eq!(counts(), (0, 0), "OK is no direction: nothing hides"); + press_down(&mut ptr, shell); + assert_eq!(counts(), (1, 0), "the first direction key hides"); + assert!(ptr.dpad_mode && ptr.cur_hidden); + press_down(&mut ptr, shell); + assert_eq!(counts(), (1, 0), "a second one, with the pointer already hidden, asks for nothing"); + ptr.note_cursor_motion(shell); + assert_eq!(counts(), (1, 1), "a motion shows it"); + assert!(!ptr.cur_hidden); + ptr.note_cursor_motion(shell); + assert_eq!(counts(), (1, 1), "...once"); + press_down(&mut ptr, shell); + assert_eq!(counts(), (2, 1), "and the next direction key hides it again"); + } + + /// Back's cursor owns what it hid: a motion does not show it while Back holds it (`Wake` does), + /// and handing it back restores the pointer only if Back's own `Hide` was what hid it. + #[test] + fn backs_cursor_is_hidden_through_the_shell_and_restored_only_if_back_hid_it() { + use plx_machine::machine::{InstanceId, MachineId}; + use plx_screens::registry::BackCursorChange; + let target = (MachineId::Instance(InstanceId(1)), 7); + let _g = plx_base::testlock::serial(); + for already_hidden in [false, true] { + let (platform, counted) = crate::app::platform::SwapShell::platform(); + let shell = platform.shell; + let mut ptr = Pointer::IDLE; + ptr.cur_hidden = already_hidden; + ptr.sync_back_cursor(shell, Some(target), Some((target, BackCursorChange::Hide))); + assert_eq!(counted.hides.load(Relaxed), 1, "Back's Hide hides through the shell"); + ptr.note_cursor_motion(shell); + assert_eq!(counted.shows.load(Relaxed), 0, "a motion does not undo Back's hide while Back holds it"); + ptr.sync_back_cursor(shell, Some(target), Some((target, BackCursorChange::Release))); + assert_eq!(counted.shows.load(Relaxed), usize::from(!already_hidden), + "release shows the pointer only if Back's own Hide had hidden it (already hidden: {already_hidden})"); + } + } +} + #[cfg(test)] mod edge_scroll_tests { use super::{EdgeScroll, EDGE_BAND, EDGE_DWELL_MS, EDGE_RAMP_MS, EDGE_SIDE_BAND}; diff --git a/rust-modules/src/app/platform.rs b/rust-modules/src/app/platform.rs index 87765c0e75..cb89b04963 100644 --- a/rust-modules/src/app/platform.rs +++ b/rust-modules/src/app/platform.rs @@ -6,10 +6,11 @@ //! - `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). //! `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. +//! - `shell`: the window, the bus and the pointer's visibility, [`Shell`]. Its consumers are boot +//! (`app::boot` brings the window up with the platform it was handed), the loop (`app::run` drives +//! it every frame, through `App::platform`) and the bridge, which holds the shell for the +//! dispatcher's two opaque-region hooks and lends it to the pointer's own callers (`input`, +//! `playback`), which hide and show the Magic Remote's pointer through it. //! - `diag`: the six frame probes, [`FrameProbe`], read by the loop. The renderer's clear hook takes //! plain functions, so the platform's entry installs it (`gfx::install_clear_probe`). //! - `media`: [`MediaBoot`], the platform's two boot-time playback steps. `early_init` runs once before @@ -29,9 +30,10 @@ use plx_media::route::PlaybackSession; use plx_os::tv::Services; 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 a no-op, as the test-only host platform does. +/// The platform's window, bus and pointer, as the application drives them: the SDL window and its +/// surface, the opaque-region hint, the platform bus pump, and the visibility of the Magic Remote's +/// pointer. Every call runs on the loop thread, and every hook is required: a platform with nothing +/// to do states a no-op, as the desktop and the test-only host platform do. 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). @@ -50,6 +52,18 @@ pub(crate) trait Shell: Sync { fn clear_opaque_region(&self); /// Service the platform bus once; the frame loop calls this every frame. fn pump_bus(&self); + /// Hide the remote's on-screen pointer: the D-pad took over, or the pointer idled over video. + /// A platform whose pointer is not the application's to hide, a desktop's mouse, does nothing. + fn hide_pointer(&self); + /// Bring the pointer back after [`hide_pointer`](Shell::hide_pointer), on the next pointer motion. + /// Where the hide was the platform's own call, the platform shows its pointer by itself and this + /// does nothing. + fn show_pointer_after_motion(&self); + /// Whether [`hide_pointer`](Shell::hide_pointer) hides the pointer by swapping in a transparent + /// cursor rather than by the platform's own call. Then the system's pointer is still up, and the + /// remote's OK arrives as a click at wherever the invisible pointer sits, which the loop reads as + /// the OK key (`input::click_is_ok`). `false` where a click is always a real one. + fn hide_is_cursor_swap(&self) -> bool; } /// The dev frame probe (`/tmp/plxnative-framecb`): the platform's presentation-callback clock, read @@ -164,6 +178,11 @@ impl Shell for HostShell { fn opaque_route(&self, _player: bool) {} fn clear_opaque_region(&self) {} fn pump_bus(&self) {} + fn hide_pointer(&self) {} + fn show_pointer_after_motion(&self) {} + fn hide_is_cursor_swap(&self) -> bool { + false + } } /// The frame probe of a process with no platform: always unarmed. Test builds only. @@ -182,6 +201,52 @@ impl FrameProbe for HostProbe { } } +/// A shell whose hide is a cursor swap, counting what the application asks of it. Test builds only. +/// The swap is the webOS 3.x case, where the remote's OK arrives as a click (`input::click_is_ok`), and a +/// test of it needs a platform that says so, which [`Platform::HOST_TEST`] does not: it hides nothing. +#[cfg(test)] +pub(crate) struct SwapShell { + pub(crate) hides: std::sync::atomic::AtomicUsize, + pub(crate) shows: std::sync::atomic::AtomicUsize, +} + +#[cfg(test)] +impl Shell for SwapShell { + 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) {} + fn hide_pointer(&self) { + self.hides.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + fn show_pointer_after_motion(&self) { + self.shows.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + fn hide_is_cursor_swap(&self) -> bool { + true + } +} + +#[cfg(test)] +impl SwapShell { + /// A platform whose shell is a fresh `SwapShell`, and that shell, for a test to read the counts + /// from. Leaked, because a `Platform` holds its parts for `'static`; every call makes its own + /// counters, so the shell is no process global and no test shares a count with another. + pub(crate) fn platform() -> (&'static Platform, &'static SwapShell) { + let shell: &'static SwapShell = Box::leak(Box::new(SwapShell { + hides: std::sync::atomic::AtomicUsize::new(0), + shows: std::sync::atomic::AtomicUsize::new(0), + })); + let platform = Platform::new(&Services::HOST_TEST, shell, &HostProbe, MediaBoot::HOST_TEST); + (Box::leak(Box::new(platform)), shell) + } +} + #[cfg(test)] impl MediaBoot { /// The media boot of a process with no platform: nothing to initialize and no driver to install. @@ -231,6 +296,9 @@ mod tests { s.opaque_route(false); s.clear_opaque_region(); s.pump_bus(); + s.hide_pointer(); + s.show_pointer_after_motion(); + assert!(!s.hide_is_cursor_swap(), "no hide, so a click is always a real one"); p.request(); p.prepare_begin(); @@ -261,4 +329,24 @@ mod tests { assert_eq!(session.backends(), plx_playback_contract::BackendSet::NONE); assert!(session.uri_preflight_port().is_none()); } + + /// **The counting shell says what it is and counts what it is asked, per platform.** It is a + /// cursor swap (the webOS 3.x answer), every `platform()` call has counters of its own, and the + /// pointer calls are the only ones it counts. The loop's tests read these counts, so the shell they + /// read is pinned here, where no feature gate hides it. + #[test] + fn the_swap_shell_is_a_cursor_swap_that_counts_its_own_pointer_calls() { + use std::sync::atomic::Ordering::Relaxed; + let (platform, counted) = SwapShell::platform(); + let (other, other_counted) = SwapShell::platform(); + assert!(platform.shell.hide_is_cursor_swap(), "a swap says so"); + platform.shell.hide_pointer(); + platform.shell.hide_pointer(); + platform.shell.show_pointer_after_motion(); + assert!(!platform.shell.release_surface(), "a shell call that is no pointer call is not counted"); + assert_eq!((counted.hides.load(Relaxed), counted.shows.load(Relaxed)), (2, 1)); + assert_eq!((other_counted.hides.load(Relaxed), other_counted.shows.load(Relaxed)), (0, 0), + "another platform's counts are its own"); + assert!(!other.shell.release_surface(), "the rest of the shell answers as the host-test one does"); + } } diff --git a/rust-modules/src/app/playback.rs b/rust-modules/src/app/playback.rs index 9ebc5ce0da..7fafea1672 100644 --- a/rust-modules/src/app/playback.rs +++ b/rust-modules/src/app/playback.rs @@ -732,7 +732,7 @@ pub(crate) fn execute_player_command(request: plx_screens::registry::PlayerReq, resources.repause_at, vec![request], now, resources.refresh_hubs, pages, bridge); if outcome.back_cursor.is_some() || resources.ptr.back_cursor_active() { let target = if outcome.exiting { None } else { back_cursor_target(pages) }; - resources.ptr.sync_back_cursor(target, outcome.back_cursor); + resources.ptr.sync_back_cursor(bridge.shell(), target, outcome.back_cursor); } if outcome.slot_refresh { let slot = plx_appkit::player_hud::slot_with_preferences(&resources.player.session, @@ -1571,7 +1571,7 @@ pub(crate) unsafe fn key_play( } } if was_off_player && !ptr.dpad_mode { - hide_cursor(); + bridge.shell().hide_pointer(); ptr.enter_dpad(); } super::bridge::send_player_message(pages, diff --git a/rust-modules/src/app/run.rs b/rust-modules/src/app/run.rs index dd5ba848b2..dbd88d74d4 100644 --- a/rust-modules/src/app/run.rs +++ b/rust-modules/src/app/run.rs @@ -103,7 +103,8 @@ impl Frame { } } -/// The loop. `plex_run` calls this once, after `boot`, and `shutdown` after it returns. +/// The loop. `run_and_shutdown` (`app/mod.rs`) calls this once, after `boot`, and `shutdown` after it +/// returns. /// /// **No `mt: &MainThread` parameter since phase 9.** The token is a FIELD now /// (`app.adapters.player`, see `player::adapter`), so the proof travels with `&mut App` — every @@ -1179,15 +1180,16 @@ fn window_step(stage: plx_telemetry::telemetry::window::Stage, playing: Option {} - // The tape owns logical ingress; a real key or text commit must not be counted a second time. - HostEvent::Key(_) | HostEvent::Text(_) => {} + // The tape owns logical ingress; a real key, text commit, pointer or wheel event must not + // be counted a second time. + HostEvent::Key(_) | HostEvent::Text(_) | HostEvent::Pointer { .. } | HostEvent::Wheel { .. } => {} } return; } // Attribute only the input repaint to its owner; lifecycle changes remain page damage. - if matches!(event, HostEvent::Key(_) | HostEvent::Text(_)) { app.note_input_damage(); } + if event.is_input() { app.note_input_damage(); } else { app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); } match event { HostEvent::Key(press) => ingest_key(app, press), HostEvent::Text(text) => ingest_text_commit(app, text), + HostEvent::Pointer { x, y, edge } => ingest_pointer(app, x, y, edge), + HostEvent::Wheel { dy } => ingest_wheel(app, dy), // Nothing is torn down here: the loop ends, then `shutdown` releases what is held. HostEvent::Quit => app.running = false, HostEvent::Lifecycle(edge) => { @@ -1288,7 +1293,7 @@ unsafe fn host_background(app: &mut App, fr: &mut Frame, edge: Lifecycle, playin // Outside the player guard below on purpose: this is the OS taking the screen from // whatever is on it, not a fact about playback. super::bridge::background(&mut app.pages); - app.ptr.sync_back_cursor(None, None); + app.ptr.sync_back_cursor(app.platform.shell, None, None); // The notification feed is a live socket the OS will not keep: cancel it at the first edge // that says the screen is going (idempotent on the second), reopened by DID foreground. app.runtime.bridge(&mut app.bridge).notify_suspend(); @@ -1519,7 +1524,7 @@ unsafe fn ingest_key(app: &mut App, press: KeyPress) { &mut app.down_sym, None, // The mounted player samples fresh presses in its own input delivery. &mut app.ptr, - + app.platform.shell, ); if !ordered_player_key { super::bridge::send_player_message(&mut app.pages, @@ -1779,10 +1784,10 @@ unsafe fn ingest_sdl_event(app: &mut App, fr: &mut Frame) { /// The window reacquisition is a platform operation, supplied separately so the /// recorded/live ingress boundary can be exercised without an SDL/GL context. /// -/// Quit, the four lifecycle edges, a key edge and a text commit are decoded into a [`HostEvent`] -/// and consumed by [`ingest_host_event`]. What follows is the raw path: pointer and wheel events, -/// and the IME's pre-edit, read from the event's bytes here until their own step (W5c) moves the -/// pointer and wheel behind the decoder. +/// Quit, the four lifecycle edges, a key edge, a text commit, a pointer event and a wheel tick are +/// decoded into a [`HostEvent`] and consumed by [`ingest_host_event`]. What follows is the raw path +/// of what has no `HostEvent`: the IME's pre-edit, which nothing reads and which is only logged, and +/// the SDL events nothing acts on (the window events and the rest), which are page damage. unsafe fn ingest_sdl_event_with_window(app: &mut App, fr: &mut Frame, restore_window: impl FnOnce(*mut c_void)) { if let Some(event) = decode_host_event(&app.ev) { @@ -1795,7 +1800,7 @@ unsafe fn ingest_sdl_event_with_window(app: &mut App, fr: &mut Frame, return; } let et = rd_u32(&app.ev, 0); - // A key or pointer event is the activity that keeps a release-health session open + // The IME's pre-edit is input like a key: the activity that keeps a release-health session open // (`telemetry::session`; consent-gated inside, a no-op while crash reports are off). if is_input_event(et) { plx_telemetry::telemetry::session::input(); } if controlled_replay(app) { @@ -1807,228 +1812,222 @@ unsafe fn ingest_sdl_event_with_window(app: &mut App, fr: &mut Frame, else { app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); } // The raw bytes of what is left on this path: the IME's pre-edit, which nothing else reads. log_raw_input_event(&app.ev); - if et == SDL_MOUSEMOTION { - app.last_input = clock::now(); - app.ptr.last_motion = app.last_input; - app.ptr.note_cursor_motion(); - let (mx, my) = ptr_xy(&app.ev); - if app.boot_initial.is_none() { - app.rec.input(super::recorder::enc_pointer("pointer", mx as i32, my as i32)); - } - if app.ptr.prev_mx >= 0.0 { - app.ptr.mot_accum += (mx - app.ptr.prev_mx).abs() + (my - app.ptr.prev_my).abs(); - } - app.ptr.prev_mx = mx; - app.ptr.prev_my = my; - // **The BARE transport's pointer, handed to the page that owns it** (phase 12, - // PX-PLAYER). This arm used to raise the HUD and move the scrub preview HERE, on the - // screen's own fields, and then `return` — so the player page never saw a pointer event - // at all, and the drag preview kept reading a flag whose producer had become unreachable. - // Both halves are `PlayerScreen`'s now; what is left is the choice of EVENT. - // - // It stays AHEAD of the D-pad accumulation gate below, deliberately and as it always was: - // over full-screen video a mouse nudge is how the transport is found, and 120 px of - // accumulated travel is not what that costs. (`ui::hit`'s own dpad gate still suppresses - // hover-driven focus underneath, which is the half that rule is actually about.) - // - // A button held down makes this a DRAG rather than a move — §7.5, the one pointer kind - // that drives a control with no hover and no click. - if matches!(app.route(), AppArg::Player) - && !app.pages.surface_up() - && super::bridge::owns_input(&app.pages) - { - let at = plx_machine::machine::Tick { ms: app.last_input, dt_us: 0 }; - app.inputs.push(if app.ptr.button_down { - super::bridge::drag_input(mx, my, at) - } else { - super::bridge::pointer_input(mx, my, at) - }); - return; - } - if app.ptr.dpad_mode { - if app.ptr.mot_accum < super::input::DPAD_MOTION_GATE { - return; - } - app.ptr.dpad_mode = false; - } - // Hover is the tree's on every screen it owns — `ui::route_screen`'s rule 11 - // ("hover parks focus on every screen in the family") is the HIT MAP's job now. - // Three hand-written arms stood here, keyed by the same open-state flags the key - // ladder used, and they existed because a hover ladder keyed by `route` reached - // none of the family: a pointer move across Settings, Privacy & data or Legal - // drove HOME's focus underneath instead. The press-cancel each of them paid for - // by hand — a pointer sliding off the control it armed must abandon that press — - // is `dispatch`'s ingest, which cancels an arm whose hit no longer resolves to it. - // a running edge glide holds the pointer: its moves in the band are not hover (a move onto - // a button of the top bar stops it and is the bar's) - if app.ptr.edge.moved(mx, my, pointer_on_bar(app, mx, my)) { - return; - } - if super::bridge::owns_input(&app.pages) { - // `app.last_input`, stamped from the clock at the top of this arm: `fr.now` - // is not written until after ingest (`tree_tick` above says why). - app.inputs.push(super::bridge::pointer_input( - mx, - my, - plx_machine::machine::Tick { ms: app.last_input, dt_us: 0 }, - )); - return; - } - // `Route::Profiles | Route::Search | Route::ItemMenu` are deliberately absent (phases - // 6/7/10): all three are owned screens or surfaces now, so their hover was already taken - // by `owns_input()` above. - } else if et == SDL_MOUSEBUTTONDOWN { - // OK on a set whose pointer the app can only make transparent: see `click_is_ok`. Pushed - // as an OK key-down, so it reaches the focused control by the key path. - let on_control = { - let (cx, cy) = ptr_xy(&app.ev); - app.pages.input.hit.top_at(cx, cy).is_some() - }; - let as_ok = app.ptr.click_is_ok(on_control, super::boot::cursor_is_transparent()); - if as_ok { - app.ptr.ok_from_click = true; - super::events::remote_synth_key_edge(SDLK_RETURN, 0, true); +} + +/// One pointer event, at authored coordinates: the Magic Remote's (or a mouse's) motion, button down +/// and button up. `HostEvent::Pointer` is what the SDL drain decodes them to, and the loop's whole +/// reaction to them is here. +unsafe fn ingest_pointer(app: &mut App, x: f32, y: f32, edge: PointerEdge) { + match edge { + PointerEdge::Move => ingest_pointer_motion(app, x, y), + PointerEdge::Down => ingest_pointer_down(app, x, y), + PointerEdge::Up => ingest_pointer_up(app, x, y), + } +} + +/// The pointer moved to `(mx, my)`. +unsafe fn ingest_pointer_motion(app: &mut App, mx: f32, my: f32) { + app.last_input = clock::now(); + app.ptr.last_motion = app.last_input; + app.ptr.note_cursor_motion(app.platform.shell); + if app.boot_initial.is_none() { + app.rec.input(super::recorder::enc_pointer("pointer", mx as i32, my as i32)); + } + if app.ptr.prev_mx >= 0.0 { + app.ptr.mot_accum += (mx - app.ptr.prev_mx).abs() + (my - app.ptr.prev_my).abs(); + } + app.ptr.prev_mx = mx; + app.ptr.prev_my = my; + // **The BARE transport's pointer, handed to the page that owns it** (phase 12, + // PX-PLAYER). This arm used to raise the HUD and move the scrub preview HERE, on the + // screen's own fields, and then `return` — so the player page never saw a pointer event + // at all, and the drag preview kept reading a flag whose producer had become unreachable. + // Both halves are `PlayerScreen`'s now; what is left is the choice of EVENT. + // + // It stays AHEAD of the D-pad accumulation gate below, deliberately and as it always was: + // over full-screen video a mouse nudge is how the transport is found, and 120 px of + // accumulated travel is not what that costs. (`ui::hit`'s own dpad gate still suppresses + // hover-driven focus underneath, which is the half that rule is actually about.) + // + // A button held down makes this a DRAG rather than a move — §7.5, the one pointer kind + // that drives a control with no hover and no click. + if matches!(app.route(), AppArg::Player) + && !app.pages.surface_up() + && super::bridge::owns_input(&app.pages) + { + let at = plx_machine::machine::Tick { ms: app.last_input, dt_us: 0 }; + app.inputs.push(if app.ptr.button_down { + super::bridge::drag_input(mx, my, at) + } else { + super::bridge::pointer_input(mx, my, at) + }); + return; + } + if app.ptr.dpad_mode { + if app.ptr.mot_accum < super::input::DPAD_MOTION_GATE { return; } - app.last_input = clock::now(); - { - let (cx, cy) = ptr_xy(&app.ev); - if app.boot_initial.is_none() { - app.rec.input(super::recorder::enc_pointer("click", cx as i32, cy as i32)); - } - } - // The button is DOWN from here until its up, which is the whole of what the pointer - // machine now records about it: motion in that window is a DRAG (§7.5) rather than a - // move, and the idle-cursor hide below leaves a held pointer alone. - app.ptr.button_down = true; - // The dispatcher owns supersession/cancellation of any previous pointer press. - - // A click on NO control is the player's play/pause toggle, so it wakes a paused park - // Playing (`wake_input`); a click on a control (the scrub bar, a disc, a tab) is that - // control's, which a paused park keeps drawn, so it is only a wake. The OK key a set - // delivers as a click never gets here: `click_is_ok` above re-sent it as OK, which is - // only a wake too. - let press = if on_control { WakePress::Wake } else { WakePress::Toggle }; - if claim_press_after_decoder_release(app, press) { + app.ptr.dpad_mode = false; + } + // Hover is the tree's on every screen it owns — `ui::route_screen`'s rule 11 + // ("hover parks focus on every screen in the family") is the HIT MAP's job now. + // Three hand-written arms stood here, keyed by the same open-state flags the key + // ladder used, and they existed because a hover ladder keyed by `route` reached + // none of the family: a pointer move across Settings, Privacy & data or Legal + // drove HOME's focus underneath instead. The press-cancel each of them paid for + // by hand — a pointer sliding off the control it armed must abandon that press — + // is `dispatch`'s ingest, which cancels an arm whose hit no longer resolves to it. + // a running edge glide holds the pointer: its moves in the band are not hover (a move onto + // a button of the top bar stops it and is the bar's) + if app.ptr.edge.moved(mx, my, pointer_on_bar(app, mx, my)) { + return; + } + if super::bridge::owns_input(&app.pages) { + // `app.last_input`, stamped from the clock at the top of this arm: `fr.now` + // is not written until after ingest (`tree_tick` above says why). + app.inputs.push(super::bridge::pointer_input( + mx, + my, + plx_machine::machine::Tick { ms: app.last_input, dt_us: 0 }, + )); + return; + } + // `Route::Profiles | Route::Search | Route::ItemMenu` are deliberately absent (phases + // 6/7/10): all three are owned screens or surfaces now, so their hover was already taken + // by `owns_input()` above. +} + +/// A pointer button went down at `(cx, cy)`. +unsafe fn ingest_pointer_down(app: &mut App, cx: f32, cy: f32) { + // OK on a set whose pointer the app can only make transparent: see `click_is_ok`. Pushed + // as an OK key-down, so it reaches the focused control by the key path. + let on_control = app.pages.input.hit.top_at(cx, cy).is_some(); + let as_ok = app.ptr.click_is_ok(on_control, app.platform.shell.hide_is_cursor_swap()); + if as_ok { + app.ptr.ok_from_click = true; + super::events::remote_synth_key_edge(SDLK_RETURN, 0, true); + return; + } + app.last_input = clock::now(); + if app.boot_initial.is_none() { + app.rec.input(super::recorder::enc_pointer("click", cx as i32, cy as i32)); + } + // The button is DOWN from here until its up, which is the whole of what the pointer + // machine now records about it: motion in that window is a DRAG (§7.5) rather than a + // move, and the idle-cursor hide below leaves a held pointer alone. + app.ptr.button_down = true; + // The dispatcher owns supersession/cancellation of any previous pointer press. + + // A click on NO control is the player's play/pause toggle, so it wakes a paused park + // Playing (`wake_input`); a click on a control (the scrub bar, a disc, a tab) is that + // control's, which a paused park keeps drawn, so it is only a wake. The OK key a set + // delivers as a click never gets here: `click_is_ok` above re-sent it as OK, which is + // only a wake too. + let press = if on_control { WakePress::Wake } else { WakePress::Toggle }; + if claim_press_after_decoder_release(app, press) { + return; + } + // Rule 11's click half, and the same one arm the hover path takes. The three it + // replaces each spelled out the two activation shapes by hand — a control FACE + // dips and commits on the spring-back, a table row commits on the button-down — + // which is exactly what `ElemKind` says once, per element, for every owned screen. + if super::bridge::owns_input(&app.pages) { + app.inputs.push(super::bridge::click_input( + cx, + cy, + plx_machine::machine::Tick { ms: app.last_input, dt_us: 0 }, + )); + return; + } + // (The player's two click blocks stood here — the failure read-out's `failure_quality_hit` + // band, and the transport's own `icon_hit`/`scrub_hit` ladder with the control row's + // deferred press, the scrub-band seek and the fall-through play/pause toggle. Every one of + // those regions is a registered `Stop` now (`PlayerScreen::draw`), resolved by the shared + // hit map and answered by `PlayerScreen::handle_click`, which is what closed + // `ci/check-deps.sh`'s `hittest` gate: the three raw hit-tester calls this block made were + // the only ones in `app/`. They had also been unreachable since the page began answering + // `HitSource::Engine` — the `owns_input()` early return above claims the click first — + // which is exactly the shape phase 12 exists to end: a live path and a dead one on one + // piece of state. Phase 12, PX-PLAYER. This chain's head was that block's + // `matches!(app.route, Route::Player)`, so what follows is now the head itself.) + // **A click that gets past `owns_input()` lands on nothing.** The shared bar's profile chip and + // pills are stops in the hit map like any other control (`Dispatcher::draw` registers them at the + // place the bar is DRAWN, tucked or not), so the arm above claims their clicks for every mounted + // page; the old `chip_clicked` ladder here tested the chip's RESTING rect against the route + // alone, so it opened the account menu over a bar that was lifted away or not drawn. A page + // whose body has not mounted yet draws no bar, so there is nothing here for a click to press. + // + // (`Route::Profiles`, `Route::Login`, `Route::Search` and `Route::ItemMenu` once had arms in + // this chain; each is an owned screen or a surface now, so `owns_input()`'s arm above takes + // its clicks. The menu's panel in particular is why the container answers a click off a + // surface by construction: a click cannot fall through onto the shelf under it.) +} + +/// A pointer button came up at `(cx, cy)`. +unsafe fn ingest_pointer_up(app: &mut App, cx: f32, cy: f32) { + if std::mem::take(&mut app.ptr.ok_from_click) { + super::events::remote_synth_key_edge(SDLK_RETURN, 0, false); + return; + } + app.last_input = clock::now(); + if app.boot_initial.is_none() { + app.rec.input(super::recorder::enc_pointer("release", cx as i32, cy as i32)); + } + // Forward button-up as the dispatcher's OK-up release. Unconditional on ownership: + // querying owns_input here could drop an up while a surface begins closing. + // With nothing armed, InputMachine::release is inert. + app.inputs.push(super::bridge::release_input(plx_machine::machine::Tick { + ms: app.last_input, + dt_us: 0, + })); + // …and the button is up, which is all this arm still says. Committing the player's drag + // from here was the other half of the split ownership phase 12 retires: the release above + // reaches `PlayerScreen::handle_release` as the `Ok`/`Edge::Up` the tree already gets, and + // the page commits its own preview with `PlayerReq::CommitSeek`. + app.ptr.button_down = false; +} + +/// One tick of the wheel, `dy` of it (`HostEvent::Wheel`, decoded from whichever offset the host +/// carries it at). +unsafe fn ingest_wheel(app: &mut App, dy: i32) { + app.last_input = clock::now(); + if app.last_input.wrapping_sub(app.ptr.last_wheel) > 250 { + app.ptr.last_wheel = app.last_input; + app.rec.input(super::recorder::enc_pointer("wheel", 0, dy)); + // the wheel scrolls VERTICALLY only, and only on routes with a vertical + // flow (it used to drive home's focus behind every other screen) + // + // Item 13: an owned surface takes the wheel BEFORE the route dispatch below + // ever sees it — otherwise a wheel tick over Settings/Privacy/Legal fell + // through to whatever route sat behind it (Home's own hero/grid dive, a + // Detail scroll, …), which is the same ownership question the key ladder + // answers for a fresh press, asked here for the wheel instead. It is the + // same `owns_input` the other three arms ask, so the four cannot drift. + if dy == 0 { + // a fractional trackpad tick that rounded to nothing (hostsim), or a + // `wheel:0` token — not a step in either direction return; } - // Rule 11's click half, and the same one arm the hover path takes. The three it - // replaces each spelled out the two activation shapes by hand — a control FACE - // dips and commits on the spring-back, a table row commits on the button-down — - // which is exactly what `ElemKind` says once, per element, for every owned screen. - if super::bridge::owns_input(&app.pages) { - let (cx, cy) = ptr_xy(&app.ev); - app.inputs.push(super::bridge::click_input( - cx, - cy, + if super::bridge::search_owns_input(&app.pages) { + app.inputs.push(plx_machine::machine::InputEvent { + at: plx_machine::machine::Tick { ms: app.last_input, dt_us: 0 }, + source: plx_machine::machine::Source::Sdl, + kind: plx_machine::machine::InputKind::Wheel { dy: dy as f32 }, + }); + } else if super::bridge::owns_input(&app.pages) { + // A tick becomes the DIRECTION KEY it stands for (`bridge::wheel_input`), + // rather than a `Wheel` the family's tables would each have to interpret: + // one tick is one row, which is what `on_updown(±1)` meant. `RepeatGate` + // is deliberately NOT applied — a wheel gesture's ticks are the user's own + // cadence and the gate is armed against the remote's 50 ms hardware + // repeat, so sharing it would let a held key mute a scroll and vice versa. + app.inputs.extend(super::bridge::wheel_input( + dy, plx_machine::machine::Tick { ms: app.last_input, dt_us: 0 }, )); - return; - } - // (The player's two click blocks stood here — the failure read-out's `failure_quality_hit` - // band, and the transport's own `icon_hit`/`scrub_hit` ladder with the control row's - // deferred press, the scrub-band seek and the fall-through play/pause toggle. Every one of - // those regions is a registered `Stop` now (`PlayerScreen::draw`), resolved by the shared - // hit map and answered by `PlayerScreen::handle_click`, which is what closed - // `ci/check-deps.sh`'s `hittest` gate: the three raw hit-tester calls this block made were - // the only ones in `app/`. They had also been unreachable since the page began answering - // `HitSource::Engine` — the `owns_input()` early return above claims the click first — - // which is exactly the shape phase 12 exists to end: a live path and a dead one on one - // piece of state. Phase 12, PX-PLAYER. This chain's head was that block's - // `matches!(app.route, Route::Player)`, so what follows is now the head itself.) - // **A click that gets past `owns_input()` lands on nothing.** The shared bar's profile chip and - // pills are stops in the hit map like any other control (`Dispatcher::draw` registers them at the - // place the bar is DRAWN, tucked or not), so the arm above claims their clicks for every mounted - // page; the old `chip_clicked` ladder here tested the chip's RESTING rect against the route - // alone, so it opened the account menu over a bar that was lifted away or not drawn. A page - // whose body has not mounted yet draws no bar, so there is nothing here for a click to press. - // - // (`Route::Profiles`, `Route::Login`, `Route::Search` and `Route::ItemMenu` once had arms in - // this chain; each is an owned screen or a surface now, so `owns_input()`'s arm above takes - // its clicks. The menu's panel in particular is why the container answers a click off a - // surface by construction: a click cannot fall through onto the shelf under it.) - } else if et == SDL_MOUSEBUTTONUP { - if std::mem::take(&mut app.ptr.ok_from_click) { - super::events::remote_synth_key_edge(SDLK_RETURN, 0, false); - return; - } - app.last_input = clock::now(); - { - let (cx, cy) = ptr_xy(&app.ev); - if app.boot_initial.is_none() { - app.rec.input(super::recorder::enc_pointer("release", cx as i32, cy as i32)); - } - } - // Forward button-up as the dispatcher's OK-up release. Unconditional on ownership: - // querying owns_input here could drop an up while a surface begins closing. - // With nothing armed, InputMachine::release is inert. - app.inputs.push(super::bridge::release_input(plx_machine::machine::Tick { - ms: app.last_input, - dt_us: 0, - })); - // …and the button is up, which is all this arm still says. Committing the player's drag - // from here was the other half of the split ownership phase 12 retires: the release above - // reaches `PlayerScreen::handle_release` as the `Ok`/`Edge::Up` the tree already gets, and - // the page commits its own preview with `PlayerReq::CommitSeek`. - app.ptr.button_down = false; - } else if et == SDL_MOUSEWHEEL { - app.last_input = clock::now(); - if app.last_input.wrapping_sub(app.ptr.last_wheel) > 250 { - app.ptr.last_wheel = app.last_input; - // **The host reads a DIFFERENT offset, and this one is not the LG-fork - // shift `decode_key` documents — it is macOS `libSDL2` again being - // sdl2-compat forwarding into SDL3.** `SDL_MouseWheelEvent` on real SDL2 - // (what the television runs) carries a plain `Sint32 y` at +20, which is - // what production code always read. Measured 2026-09-02 by dumping the - // polled bytes of an injected -40 tick on this host: `+20` came back 0, and - // -40.0 arrived instead as the FLOAT `preciseY` field at `+32` — SDL2's own - // struct gained that field in 2.0.18 for fractional trackpad scroll, and - // sdl2-compat's round trip apparently only forwards it, leaving the legacy - // integer field zeroed for both a genuine trackpad tick and anything - // `SDL_PushEvent`d in this shape (item 13's `wheel:` FIFO token hit - // this the first time anything synthesized a wheel event at all — nothing - // needed one before). `cfg!`, not `#[cfg]`, so both arms keep compiling. - let dy = if cfg!(feature = "hostsim") { - rd_f32(&app.ev, 32).round() as i32 - } else { - rd_i32(&app.ev, 20) - }; - app.rec.input(super::recorder::enc_pointer("wheel", 0, dy)); - // the wheel scrolls VERTICALLY only, and only on routes with a vertical - // flow (it used to drive home's focus behind every other screen) - // - // Item 13: an owned surface takes the wheel BEFORE the route dispatch below - // ever sees it — otherwise a wheel tick over Settings/Privacy/Legal fell - // through to whatever route sat behind it (Home's own hero/grid dive, a - // Detail scroll, …), which is the same ownership question the key ladder - // answers for a fresh press, asked here for the wheel instead. It is the - // same `owns_input` the other three arms ask, so the four cannot drift. - if dy == 0 { - // a fractional trackpad tick that rounded to nothing (hostsim), or a - // `wheel:0` token — not a step in either direction - return; - } - if super::bridge::search_owns_input(&app.pages) { - app.inputs.push(plx_machine::machine::InputEvent { - at: plx_machine::machine::Tick { ms: app.last_input, dt_us: 0 }, - source: plx_machine::machine::Source::Sdl, - kind: plx_machine::machine::InputKind::Wheel { dy: dy as f32 }, - }); - } else if super::bridge::owns_input(&app.pages) { - // A tick becomes the DIRECTION KEY it stands for (`bridge::wheel_input`), - // rather than a `Wheel` the family's tables would each have to interpret: - // one tick is one row, which is what `on_updown(±1)` meant. `RepeatGate` - // is deliberately NOT applied — a wheel gesture's ticks are the user's own - // cadence and the gate is armed against the remote's 50 ms hardware - // repeat, so sharing it would let a held key mute a scroll and vice versa. - app.inputs.extend(super::bridge::wheel_input( - dy, - plx_machine::machine::Tick { ms: app.last_input, dt_us: 0 }, - )); - } - // `Route::Search` is deliberately absent here: `search_owns_input()` above - // already took every wheel tick on this route and returned. } + // `Route::Search` is deliberately absent here: `search_owns_input()` above + // already took every wheel tick on this route and returned. } } @@ -2566,7 +2565,7 @@ pub(crate) unsafe fn playback_tick(app: &mut App, fr: &mut Frame) { && app.ptr.last_motion != 0 && fr.now.wrapping_sub(app.ptr.last_motion) > 3000 { - hide_cursor(); + app.platform.shell.hide_pointer(); app.ptr.cur_hidden = true; } // re-pause the foreground restore's paused load the INSTANT its resume frame is on screen @@ -3962,7 +3961,7 @@ unsafe fn controlled_key_input(app: &mut App, event: plx_machine::machine::Input if matches!(event.kind, InputKind::Pointer{..}|InputKind::Click{..}|InputKind::Drag{..}) { app.last_input=event.at.ms; app.ptr.last_motion=event.at.ms; - app.ptr.note_cursor_motion(); + app.ptr.note_cursor_motion(app.platform.shell); if matches!(event.kind,InputKind::Click{..}) { app.ptr.button_down=true; } app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); app.inputs.push(event); @@ -3999,7 +3998,7 @@ unsafe fn controlled_key_input(app: &mut App, event: plx_machine::machine::Input let viewer_paused = viewer_paused_for(&app.player.session, &app.adapters.player); begin_fresh_press(&mut app.player.session, classify(sym, wcode), sym, wcode, event.at.ms, viewer_paused, &mut app.down_sym, - None, &mut app.ptr); + None, &mut app.ptr, app.platform.shell); } } app.inputs.push(event); @@ -4069,10 +4068,15 @@ pub(in crate::app) mod lifecycle_regression_tests { // No boot, renderer or device: the real App/event/frame phases with Bridge's host rig. pub(in crate::app) fn app() -> App { + app_on(&crate::app::platform::Platform::HOST_TEST) + } + + /// [`app`] on `platform`: the application's shell and its bridge's are that platform's. + pub(in crate::app) fn app_on(platform: &'static crate::app::platform::Platform) -> App { 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 (runtime, bridge) = super::super::bridge::BridgeRetained::for_test_on(|| 0, platform.shell); let mut app = App { - platform: &crate::app::platform::Platform::HOST_TEST, + platform, last_input: Default::default(), loop_t: Default::default(), iters_ct: Default::default(), @@ -4611,8 +4615,8 @@ pub(in crate::app) mod lifecycle_regression_tests { HostEvent::Lifecycle(Lifecycle::DidBackground) => 0x104, HostEvent::Lifecycle(Lifecycle::WillForeground) => 0x105, HostEvent::Lifecycle(Lifecycle::DidForeground) => 0x106, - HostEvent::Key(_) | HostEvent::Text(_) => { - panic!("a key or a text commit arrives as its own bytes (`encode_key`, `encode_event`), not as a type code") + HostEvent::Key(_) | HostEvent::Text(_) | HostEvent::Pointer { .. } | HostEvent::Wheel { .. } => { + panic!("a key, a text commit, a pointer event and a wheel tick arrive as their own bytes, not as a type code") } } } @@ -4990,6 +4994,496 @@ pub(in crate::app) mod lifecycle_regression_tests { assert_eq!(tapes[0], tapes[1], "the tape is byte-equal whichever way a key arrives"); } + // ---- W5c: a pointer event and a wheel tick as a `HostEvent` --------------------------------- + // + // As above, each is delivered two ways: as the SDL bytes the drain decodes and as the + // `HostEvent` a platform with no SDL sends. A pointer's position is authored coordinates either + // way (the surface is the identity in these tests), so the hosted event carries the integers the + // bytes do. The loop's pointer state (`app.ptr`) and what it queued for the tree are compared. + + /// One pointer edge at `(x, y)`, either way. + fn deliver_pointer(app: &mut App, fr: &mut Frame, hosted: bool, edge: PointerEdge, x: i32, y: i32) { + if hosted { + unsafe { ingest_host_event(app, fr, HostEvent::Pointer { x: x as f32, y: y as f32, edge }, |_| {}) }; + } else { + app.ev = [0; 128]; + app.ev[20..24].copy_from_slice(&x.to_ne_bytes()); + app.ev[24..28].copy_from_slice(&y.to_ne_bytes()); + event(app, fr, match edge { + PointerEdge::Move => 0x400, + PointerEdge::Down => 0x401, + PointerEdge::Up => 0x402, + }); + } + } + + /// One wheel tick of `dy`, either way. The SDL door writes the simulator's layout (the float at + /// +32, which is where this build reads it) and the television's integer at +20 as well, so the + /// bytes are a wheel event whichever offset a build reads. + fn deliver_wheel(app: &mut App, fr: &mut Frame, hosted: bool, dy: i32) { + if hosted { + unsafe { ingest_host_event(app, fr, HostEvent::Wheel { dy }, |_| {}) }; + } else { + app.ev = [0; 128]; + app.ev[20..24].copy_from_slice(&dy.to_ne_bytes()); + app.ev[32..36].copy_from_slice(&(dy as f32).to_ne_bytes()); + event(app, fr, 0x403); + } + } + + /// Everything a pointer event can leave behind in the loop: what it queued for the tree (as the + /// tape would carry it) and the pointer machine's own state. + #[derive(Debug, PartialEq)] + struct PointerAftermath { + inputs: Vec, + button_down: bool, + prev_mx: u32, + mot_accum: u32, + dpad_mode: bool, + cur_hidden: bool, + ok_from_click: bool, + } + + fn pointer_aftermath(app: &mut App) -> PointerAftermath { + let inputs = app.inputs.drain(..) + .map(|e| super::super::bootstrap::effects::input(&e).unwrap()) + .collect(); + PointerAftermath { + inputs, + button_down: app.ptr.button_down, + prev_mx: app.ptr.prev_mx.to_bits(), + mot_accum: app.ptr.mot_accum.to_bits(), + dpad_mode: app.ptr.dpad_mode, + cur_hidden: app.ptr.cur_hidden, + ok_from_click: app.ptr.ok_from_click, + } + } + + /// The pointer positions, click count and key edges the loop has queued for the tree. + fn queued(app: &App) -> (Vec<(f32, f32)>, usize, Vec<(plx_machine::machine::Key, plx_machine::machine::Edge)>) { + use plx_machine::machine::InputKind; + let mut pointers = Vec::new(); + let mut clicks = 0; + let mut keys = Vec::new(); + for e in &app.inputs { + match e.kind { + InputKind::Pointer { x, y, .. } => pointers.push((x, y)), + InputKind::Click { .. } => clicks += 1, + InputKind::Key { key, edge, .. } => keys.push((key, edge)), + _ => {} + } + } + (pointers, clicks, keys) + } + + /// The Settings root, mounted, on `platform` (a cursor-swap one for the tests of an OK that + /// arrives as a click), with the loop's clock pinned as the other pointer tests pin it. + fn settings_app_on(platform: &'static crate::app::platform::Platform) -> (App, Frame) { + clock::set_replay(100); + let mut app = app_on(platform); + super::super::bridge::show_page(&mut app.pages, AppArg::Settings(plx_screens::family::SettingsPage::Root)); + frame(&mut app, 0); + let fr = Frame::begin(&app.player.session, app.runtime.metadata_view()); + (app, fr) + } + + fn settings_app() -> (App, Frame) { + settings_app_on(&crate::app::platform::Platform::HOST_TEST) + } + + /// **A hosted pointer is the pointer an SDL event is.** A press, a drag, a release, a direction + /// key that hands the page to the D-pad, three small motions the gate swallows and one big one it + /// does not: every step leaves the same queue and the same pointer state whichever way it arrives. + #[test] + fn a_host_pointer_takes_the_path_an_sdl_pointer_event_takes() { + use plx_machine::machine::Edge; + use plx_ui::consts::Action; + let _serial = plx_base::testlock::serial(); + let mut seen = Vec::new(); + for hosted in [false, true] { + let (mut app, mut fr) = settings_app(); + let mut steps = Vec::new(); + for (edge, x, y) in [(PointerEdge::Down, 200, 300), (PointerEdge::Move, 400, 300), (PointerEdge::Up, 400, 300)] { + deliver_pointer(&mut app, &mut fr, hosted, edge, x, y); + steps.push(pointer_aftermath(&mut app)); + } + deliver_key(&mut app, &mut fr, hosted, Action::Down, Edge::Down); + steps.push(pointer_aftermath(&mut app)); + for x in [405, 410, 415, 640] { + deliver_pointer(&mut app, &mut fr, hosted, PointerEdge::Move, x, 300); + steps.push(pointer_aftermath(&mut app)); + } + seen.push(steps); + } + let steps = &seen[0]; + let kind = |step: &PointerAftermath| step.inputs.first().map(|i| i["body"]["kind"].clone()); + assert_eq!(kind(&steps[0]), Some(serde_json::json!("click")), "premise: a press is a click for the tree"); + assert!(steps[0].button_down && steps[1].button_down && !steps[2].button_down, "the button is down from the press to the release"); + assert_eq!(kind(&steps[1]), Some(serde_json::json!("pointer"))); + assert_eq!(steps[2].inputs.len(), 1, "the release is the one OK key-up the press machine takes"); + assert!(steps[3].dpad_mode && steps[3].cur_hidden, "premise: the direction key is the D-pad's"); + assert!(steps[4..7].iter().all(|s| s.dpad_mode && s.inputs.is_empty()), "the small motions are swallowed"); + assert!(!steps[7].dpad_mode && steps[7].inputs.len() == 1, "the big one hands the page back to the pointer"); + assert_eq!(seen[0], seen[1], "a host's pointer and an SDL pointer event leave the same loop"); + } + + /// **The D-pad motion gate, edge for edge.** After a direction key the page is the D-pad's and the + /// motion of the hand holding the remote is swallowed until it adds up to `DPAD_MOTION_GATE` (120 + /// px): 119 px is still swallowed and exactly 120 hands the page back (the gate is `<`, not `<=`). + /// The bare player's pointer is the page's own and rides ahead of the gate. + #[test] + fn small_pointer_motion_after_a_dpad_press_is_swallowed_until_it_adds_up_to_the_gate() { + use plx_machine::machine::Edge; + use plx_ui::consts::Action; + let _serial = plx_base::testlock::serial(); + for hosted in [false, true] { + let (mut app, mut fr) = settings_app(); + deliver_pointer(&mut app, &mut fr, hosted, PointerEdge::Move, 500, 300); + assert_eq!(queued(&app).0, [(500.0, 300.0)], "premise: in pointer mode a move is the tree's hover"); + app.inputs.clear(); + deliver_key(&mut app, &mut fr, hosted, Action::Down, Edge::Down); + assert!(app.ptr.dpad_mode && app.ptr.mot_accum == 0.0, "the direction key starts a fresh accumulation"); + app.inputs.clear(); + deliver_pointer(&mut app, &mut fr, hosted, PointerEdge::Move, 560, 300); + assert!(app.ptr.dpad_mode && app.ptr.mot_accum == 60.0 && queued(&app).0.is_empty(), "60 px is swallowed"); + deliver_pointer(&mut app, &mut fr, hosted, PointerEdge::Move, 619, 300); + assert!(app.ptr.dpad_mode && app.ptr.mot_accum == 119.0 && queued(&app).0.is_empty(), "119 px is swallowed"); + deliver_pointer(&mut app, &mut fr, hosted, PointerEdge::Move, 620, 300); + assert!(!app.ptr.dpad_mode && app.ptr.mot_accum == 120.0, "exactly the gate hands the page back (hosted {hosted})"); + assert_eq!(queued(&app).0, [(620.0, 300.0)], "and that move is the tree's hover"); + + let (mut app, mut fr) = mounted_player(); + deliver_pointer(&mut app, &mut fr, hosted, PointerEdge::Move, 500, 300); + app.inputs.clear(); + deliver_key(&mut app, &mut fr, hosted, Action::Down, Edge::Down); + assert!(app.ptr.dpad_mode, "premise: the direction key is the D-pad's on the player too"); + app.inputs.clear(); + deliver_pointer(&mut app, &mut fr, hosted, PointerEdge::Move, 510, 300); + assert!(app.ptr.dpad_mode && app.ptr.mot_accum == 10.0, "the player's pointer leaves the D-pad's gate alone"); + assert_eq!(queued(&app).0, [(510.0, 300.0)], "a nudge reaches the player page at once, ahead of the gate"); + } + } + + /// What a click on the bare player left after a direction key, with `travel` px of pointer + /// motion since it: `(the click was re-sent as the OK key, the button is held, clicks queued)`. + /// `on_control` fills the hit map so the click lands on a control, and empties it otherwise. + fn click_after_dpad(hosted: bool, swap: bool, travel: i32, on_control: bool) -> (bool, bool, usize) { + use plx_machine::machine::Edge; + use plx_ui::{screen::{Activate, Hover, Stop}, Rect}; + let (mut app, mut fr) = mounted_player(); + if swap { + app.platform = crate::app::platform::SwapShell::platform().0; + } + deliver_key(&mut app, &mut fr, hosted, plx_ui::consts::Action::Down, Edge::Down); + assert!(app.ptr.dpad_mode, "premise: the direction key is the D-pad's"); + if travel > 0 { + deliver_pointer(&mut app, &mut fr, hosted, PointerEdge::Move, 400, 300); + deliver_pointer(&mut app, &mut fr, hosted, PointerEdge::Move, 400 + travel, 300); + assert_eq!(app.ptr.mot_accum, travel as f32, "premise: the pointer travelled {travel} px since the key"); + assert!(app.ptr.dpad_mode, "premise: the player keeps the D-pad's mode through the motion"); + } + let stops = if on_control { + let key = app.pages.focus().expect("the player has a seat"); + vec![Stop { key, rect: Rect::FULL, rest_rect: Rect::FULL, clip: Rect::FULL, + hover: Hover::Ignore, activate: Activate::Direct }] + } else { + Vec::new() + }; + app.pages.input.hit.fill(stops); + app.pages.input.hit.swap(); + app.inputs.clear(); + deliver_pointer(&mut app, &mut fr, hosted, PointerEdge::Down, 500, 400); + (app.ptr.ok_from_click, app.ptr.button_down, queued(&app).1) + } + + /// **OK arrives as a click on a set that can only make its pointer transparent, and a click is a + /// click anywhere else** (issue #642; `input::click_is_ok`). The shell says which set this is + /// (`Shell::hide_is_cursor_swap`): on a cursor swap, a click in D-pad mode with the pointer still + /// (or off every control) is the OK key, re-sent through SDL and queued as no click; once the + /// pointer has travelled onto a control it is that control's click; and on a set whose own hide + /// makes OK a real key (the host-test shell, like the simulator's) a click is always a click. + #[test] + fn under_a_cursor_swap_a_click_in_dpad_mode_is_the_ok_key_and_otherwise_a_click_is_a_click() { + let _serial = plx_base::testlock::serial(); + let _events = SdlEvents::init(); + for hosted in [false, true] { + let ok = (true, false, 0); + let click = (false, true, 1); + assert_eq!(click_after_dpad(hosted, true, 0, true), ok, "still pointer on a control: the OK key (hosted {hosted})"); + assert_eq!(click_after_dpad(hosted, true, 0, false), ok, "still pointer on bare video: the OK key"); + assert_eq!(click_after_dpad(hosted, true, 200, false), ok, "drift onto bare video is still the OK key"); + assert_eq!(click_after_dpad(hosted, true, 200, true), click, "travel onto a control is that control's click"); + assert_eq!(click_after_dpad(hosted, false, 0, false), click, "no cursor swap: a click is a click"); + assert_eq!(click_after_dpad(hosted, false, 200, true), click, "...and so is one on a control"); + } + } + + /// **An OK-as-click is released as an OK, and a real click as the press machine's release.** The + /// button-up of a click the loop re-sent as OK sends the OK's key-up and queues nothing of its own, + /// where the button-up of a real click queues the one release the dispatcher takes. + #[test] + fn the_button_up_of_an_ok_as_click_is_the_ok_key_up_and_a_real_one_is_the_release() { + use plx_machine::machine::{Edge, Key}; + use plx_ui::consts::Action; + let _serial = plx_base::testlock::serial(); + let _events = SdlEvents::init(); + for hosted in [false, true] { + for swap in [true, false] { + let platform: &'static crate::app::platform::Platform = if swap { + crate::app::platform::SwapShell::platform().0 + } else { + &crate::app::platform::Platform::HOST_TEST + }; + let (mut app, mut fr) = settings_app_on(platform); + deliver_key(&mut app, &mut fr, hosted, Action::Down, Edge::Down); + app.inputs.clear(); + deliver_pointer(&mut app, &mut fr, hosted, PointerEdge::Down, 500, 300); + assert_eq!(app.ptr.ok_from_click, swap, "swap {swap}: the press was re-sent as OK exactly on a cursor swap"); + assert_eq!(app.ptr.button_down, !swap); + if swap { + // the OK the press became is in SDL's queue, and comes back as the key it stands for + app.inputs.clear(); + unsafe { drain_sdl(&mut app, &mut fr) }; + assert_eq!(queued(&app).2, [(Key::Ok, Edge::Down)], "the click became the OK key-down"); + } + app.inputs.clear(); + deliver_pointer(&mut app, &mut fr, hosted, PointerEdge::Up, 500, 300); + assert!(!app.ptr.ok_from_click && !app.ptr.button_down); + if swap { + assert!(app.inputs.is_empty(), "the up of an OK-as-click queues nothing of its own"); + unsafe { drain_sdl(&mut app, &mut fr) }; + assert_eq!(queued(&app).2, [(Key::Ok, Edge::Up)], "...it is the OK key-up, through SDL"); + } else { + assert_eq!(queued(&app).2, [(Key::Ok, Edge::Up)], "a real up is the press machine's release, at once"); + } + } + } + } + + /// **The D-pad hides the pointer through the platform's shell, and a motion shows it.** The first + /// direction key hides (once: a second press while already hidden asks again for nothing), the + /// next pointer motion shows, a second motion shows nothing more, and the next direction key hides + /// again. Counted on the shell the application holds, which is the only way the loop reaches it. + #[test] + fn the_dpad_hides_the_pointer_through_the_platforms_shell_and_a_motion_shows_it_again() { + use plx_machine::machine::Edge; + use plx_ui::consts::Action; + use std::sync::atomic::Ordering::Relaxed; + let _serial = plx_base::testlock::serial(); + for hosted in [false, true] { + let (platform, shell) = crate::app::platform::SwapShell::platform(); + let (mut app, mut fr) = settings_app_on(platform); + let counts = || (shell.hides.load(Relaxed), shell.shows.load(Relaxed)); + deliver_pointer(&mut app, &mut fr, hosted, PointerEdge::Move, 500, 300); + assert_eq!(counts(), (0, 0), "a pointer that was never hidden is not shown"); + deliver_key(&mut app, &mut fr, hosted, Action::Down, Edge::Down); + assert_eq!(counts(), (1, 0), "the first direction key hides (hosted {hosted})"); + assert!(app.ptr.cur_hidden); + deliver_key(&mut app, &mut fr, hosted, Action::Down, Edge::Up); + deliver_key(&mut app, &mut fr, hosted, Action::Down, Edge::Down); + assert_eq!(counts(), (1, 0), "a second one, with the pointer already hidden, asks for nothing"); + deliver_pointer(&mut app, &mut fr, hosted, PointerEdge::Move, 520, 300); + assert_eq!(counts(), (1, 1), "a pointer motion shows it again"); + assert!(!app.ptr.cur_hidden); + deliver_pointer(&mut app, &mut fr, hosted, PointerEdge::Move, 540, 300); + assert_eq!(counts(), (1, 1), "...once"); + deliver_key(&mut app, &mut fr, hosted, Action::Down, Edge::Up); + deliver_key(&mut app, &mut fr, hosted, Action::Down, Edge::Down); + assert_eq!(counts(), (2, 1), "and the next direction key hides it again"); + } + } + + /// **The tape is the same whichever way a pointer event or a wheel tick arrives**, and it is + /// today's: one `pointer`, `click` or `release` row per event at its authored position, and the + /// wheel's `wheel` row (its count in `y`) at the debounce's pace, before the zero-tick return. + #[test] + fn a_host_pointer_and_wheel_are_recorded_as_the_rows_their_sdl_events_are() { + use super::super::{bootstrap::Initial, recorder::{Recplay, state_fp}}; + use plx_ui::rec::{Header, MemSink, Recording}; + let _serial = plx_base::testlock::serial(); + let initial = Initial::synthetic_home(1, 32517, None).unwrap(); + let mut tapes = Vec::new(); + for hosted in [false, true] { + let (mut app, mut fr) = settings_app(); + let sink = MemSink::default(); + let segments = sink.segments.clone(); + let manifest = Header::new(state_fp(), &initial).to_json().to_string(); + app.rec = Recplay::recording_with_sink(&initial, Box::new(sink)).unwrap(); + app.rec.tick(initial.clock_start, 0.0); + clock::set_replay(1_000); + for (edge, x, y) in [(PointerEdge::Move, 400, 300), (PointerEdge::Down, 410, 310), (PointerEdge::Up, 420, 320)] { + deliver_pointer(&mut app, &mut fr, hosted, edge, x, y); + } + for (ms, dy) in [(1_000, -2), (1_100, -2), (1_300, 0), (1_400, 3), (1_700, 1)] { + clock::set_replay(ms); + deliver_wheel(&mut app, &mut fr, hosted, dy); + } + app.rec.end_frame(&|| 7); + std::mem::replace(&mut app.rec, Recplay::Off).finish(plx_machine::landgate::fixture_gate()); + let recording = Recording::parse(&manifest, + &segments.borrow().iter().map(Vec::as_slice).collect::>(), state_fp()).unwrap(); + tapes.push(recording.frames.iter().flat_map(|frame| frame.inputs.clone()).collect::>()); + } + let rows: Vec<(String, i64, i64)> = tapes[0].iter() + .map(|r| (r["kind"].as_str().unwrap().to_owned(), r["x"].as_i64().unwrap(), r["y"].as_i64().unwrap())) + .collect(); + let row = |kind: &str, x, y| (kind.to_owned(), x, y); + assert_eq!(rows, [ + row("pointer", 400, 300), row("click", 410, 310), row("release", 420, 320), + // 1000: first tick; 1100: inside the 250 ms debounce, not recorded; 1300: a zero is + // recorded and then ignored; 1400: inside the debounce the zero started; 1700: recorded. + row("wheel", 0, -2), row("wheel", 0, 0), row("wheel", 0, 1), + ], "one row per event, in `enc_pointer`'s shape; the wheel keeps its debounce"); + assert_eq!(tapes[0], tapes[1], "the tape is byte-equal whichever way an event arrives"); + } + + /// **A wheel tick is the direction key it stands for, at the debounce's pace.** Negative is DOWN + /// and positive is UP, each as both of its edges; a second tick inside 250 ms is dropped whole, and + /// a zero tick queues nothing but takes the debounce slot, as it always has. Either way of delivery. + #[test] + fn a_host_wheel_tick_takes_the_path_an_sdl_wheel_event_takes() { + use plx_machine::machine::{Edge, Key}; + let _serial = plx_base::testlock::serial(); + let mut seen = Vec::new(); + for hosted in [false, true] { + let (mut app, mut fr) = settings_app(); + let mut steps = Vec::new(); + for (ms, dy) in [(1_000, -2), (1_100, -2), (1_300, 1), (1_600, 0), (1_700, -1), (2_000, -1)] { + clock::set_replay(ms); + deliver_wheel(&mut app, &mut fr, hosted, dy); + steps.push((ms, dy, queued(&app).2, app.ptr.last_wheel)); + app.inputs.clear(); + } + seen.push(steps); + } + let steps = &seen[0]; + let keys = |ms: u32| steps.iter().find(|s| s.0 == ms).unwrap().2.clone(); + assert_eq!(keys(1_000), [(Key::Down, Edge::Down), (Key::Down, Edge::Up)], "a negative tick is DOWN"); + assert!(keys(1_100).is_empty(), "a second tick inside 250 ms is dropped"); + assert_eq!(keys(1_300), [(Key::Up, Edge::Down), (Key::Up, Edge::Up)], "a positive tick is UP"); + assert!(keys(1_600).is_empty(), "a zero tick is not a step"); + assert!(keys(1_700).is_empty(), "and it took the debounce slot"); + assert_eq!(keys(2_000), [(Key::Down, Edge::Down), (Key::Down, Edge::Up)]); + assert_eq!(seen[0], seen[1], "a host's wheel tick and an SDL wheel event leave the same loop"); + } + + /// **The `wheel:` token still drives the wheel.** `remote_synth_wheel` writes the television's + /// shape (`Sint32 y` at +20) and `SDL_PushEvent` hands it back as whatever this host's SDL makes of + /// it: sdl2-compat (the Mac simulator) returns the count as the float at +32, which the decoder + /// reads here, while genuine SDL2 (the Linux CI job) returns the bytes as pushed, whose +32 is + /// zero, so the same token decodes to a zero tick there. The test follows the carrier: it polls + /// the event, requires the count to have survived in one of the two fields, and expects the direction + /// key exactly when it survived at the offset this build reads, through SDL's own queue and the real + /// decoder either way. + #[test] + fn the_wheel_fifo_token_reaches_the_loop_through_sdl_as_far_as_the_carrier_keeps_it() { + use plx_machine::machine::{Edge, Key}; + let _serial = plx_base::testlock::serial(); + let _events = SdlEvents::init(); + let (mut app, mut fr) = settings_app(); + clock::set_replay(1_000); + remote_synth_wheel(-2); + let polled = unsafe { SDL_PollEvent(app.ev.as_mut_ptr() as *mut c_void) }; + assert_eq!(polled, 1, "SDL handed the pushed wheel event back"); + let precise = rd_f32(&app.ev, 32); + assert!(rd_i32(&app.ev, 20) == -2 || precise == -2.0, "premise: the tick survived SDL's round trip in one field"); + unsafe { ingest_sdl_event(&mut app, &mut fr) }; + let expected: &[(Key, Edge)] = if precise == -2.0 { &[(Key::Down, Edge::Down), (Key::Down, Edge::Up)] } else { &[] }; + assert_eq!(queued(&app).2, expected, "a `wheel:-2` token is one tick DOWN where the count is at +32 (carried at +32: {})", + precise == -2.0); + } + + /// A Settings page with a control face's press armed by a click, either way: the press on the + /// dispatcher's input machine (`app.pages.input.press`), the one the loop's key ingress can abandon. + fn armed_press_app(hosted: bool) -> (App, Frame) { + use plx_ui::{screen::{Activate, Hover, Stop}, Rect}; + let (mut app, mut fr) = settings_app(); + let key = app.pages.focus().unwrap(); + app.pages.input.hit.fill(vec![Stop { key, rect: Rect::FULL, rest_rect: Rect::FULL, clip: Rect::FULL, + hover: Hover::Focus, activate: Activate::Press }]); + app.pages.input.hit.swap(); + deliver_pointer(&mut app, &mut fr, hosted, PointerEdge::Down, 400, 300); + deliver_inputs(&mut app, 120); + assert!(app.pages.input.press.is_live(), "premise: the click armed the control face's press (hosted {hosted})"); + (app, fr) + } + + /// **An unsupported key leaves a press in flight alone, observed on the real press.** The press a + /// control face arms lives on the dispatcher's input machine, not in `note_global_press` (which + /// only wakes the HUD), so the guard arms THAT one with a click on a control face and sends the key + /// through the loop's own key ingress. It reads `is_live`, not `is_active`: an abandoned press stays + /// active for the ~200 ms its spring-back plays, so `is_active` cannot tell a kept press from a + /// cancelled one. A colour button (504) is bound to nothing and must leave the press live; the + /// control, a direction key through the same door, must abandon it, which is what shows the + /// observation can fail. Either way of delivery. + #[test] + fn an_unbound_key_leaves_the_press_a_click_armed_live_and_a_direction_key_abandons_it() { + use plx_machine::machine::Edge; + let _serial = plx_base::testlock::serial(); + for hosted in [false, true] { + let (mut app, mut fr) = armed_press_app(hosted); + if hosted { + let press = KeyPress::new(None, Edge::Down, Some(RawKey { sym: 0, wcode: 504 })).unwrap(); + unsafe { ingest_host_event(&mut app, &mut fr, HostEvent::Key(press), |_| {}) }; + } else { + app.ev = encode_key(0, 504, true); + event(&mut app, &mut fr, SDL_KEYDOWN); + } + deliver_inputs(&mut app, 136); + assert!(app.pages.input.press.is_live(), "an unsupported key must not abandon the press (hosted {hosted})"); + + let (mut app, mut fr) = armed_press_app(hosted); + deliver_key(&mut app, &mut fr, hosted, plx_ui::consts::Action::Down, Edge::Down); + deliver_inputs(&mut app, 136); + assert!(app.pages.input.press.is_active() && !app.pages.input.press.is_live(), + "control: a direction key abandons it, and the spring-back plays (hosted {hosted})"); + } + } + + /// **A real pointer or wheel event is dropped under a controlled replay, as a real key is.** The tape + /// owns logical ingress, so an ambient pointer motion, button or wheel tick (a hand on the remote + /// while a scenario replays) must reach no input and no pointer state. The same events on a live loop + /// are the control: they do queue, so the empty queue is the replay's doing. + #[test] + fn a_real_pointer_or_wheel_event_is_dropped_under_a_controlled_replay() { + use super::super::{bootstrap::{Initial, Preflight}, recorder::{Recplay, ReplayMode, state_fp}}; + use plx_machine::machine::Tick; + use plx_ui::{dispatch::Tap, rec::{Header, Recording}}; + let _serial = plx_base::testlock::serial(); + for hosted in [false, true] { + for replaying in [false, true] { + let (mut app, mut fr) = settings_app(); + if replaying { + let initial = Initial::synthetic_home(1, 32517, None).unwrap(); + let recording = Recording { + header: Header::new(state_fp(), &initial), + frames: vec![plx_ui::rec::Frame { f: 0, tick: Some(Tick { ms: 0, dt_us: 0 }), + st: Some(7), focus: Some(None), ..Default::default() }], + metrics: Default::default(), stopped_at: None, + }; + app.boot_initial = Some(initial.clone()); + app.rec = Recplay::controlled( + Preflight::Replay { initial: initial.clone(), recording, mode: ReplayMode::Targets }, + &initial).unwrap(); + Tap::focus(&mut app.rec, 0, None); + } + for (edge, x, y) in [(PointerEdge::Move, 400, 300), (PointerEdge::Down, 400, 300), (PointerEdge::Up, 400, 300)] { + deliver_pointer(&mut app, &mut fr, hosted, edge, x, y); + } + clock::set_replay(1_000); + deliver_wheel(&mut app, &mut fr, hosted, -2); + assert_eq!(app.inputs.is_empty(), replaying, + "a real pointer and wheel event queue exactly when no tape owns the input (replaying {replaying}, hosted {hosted})"); + if replaying { + assert!(!app.ptr.button_down && app.ptr.last_wheel == 0 + && app.ptr.prev_mx.to_bits() == Pointer::IDLE.prev_mx.to_bits(), + "and they leave the pointer's own state untouched"); + assert!(app.rec.failure().is_none(), "dropping them is no failure of the tape"); + } + } + } + } + // ---- W5b guard: a NATIVE key reaches the real consumer's effect ------------------------------ // // The tests above show that a hosted key and an SDL key agree. They cannot show that either is @@ -7292,14 +7786,20 @@ pub(in crate::app) mod lifecycle_regression_tests { use plx_screens::registry::BackCursorChange; let target = (MachineId::Instance(InstanceId(1)), 7); let replacement = (target.0, 8); + use std::sync::atomic::Ordering::Relaxed; for already_hidden in [false, true] { + let (platform, counted) = crate::app::platform::SwapShell::platform(); let mut ptr = Pointer::IDLE; ptr.cur_hidden = already_hidden; - ptr.sync_back_cursor(Some(target), Some((target, BackCursorChange::Hide))); + let shell = platform.shell; + ptr.sync_back_cursor(shell, Some(target), Some((target, BackCursorChange::Hide))); assert!(ptr.cur_hidden && ptr.click_is_ok(true, true)); - ptr.sync_back_cursor(Some(replacement), Some((target, BackCursorChange::Hide))); + assert_eq!(counted.hides.load(Relaxed), 1, "Back's Hide hides the pointer through the shell"); + ptr.sync_back_cursor(shell, Some(replacement), Some((target, BackCursorChange::Hide))); assert_eq!(ptr.cur_hidden, already_hidden, "cleanup restores only Back's cursor"); assert!(!ptr.click_is_ok(true, true), "the previous playback cannot keep the hold"); + assert_eq!((counted.hides.load(Relaxed), counted.shows.load(Relaxed)), (1, usize::from(!already_hidden)), + "the previous playback's stale Hide hides nothing more, and the cleanup shows the pointer only if Back's own Hide had hidden it"); } } @@ -7309,20 +7809,23 @@ pub(in crate::app) mod lifecycle_regression_tests { #[test] fn the_play_key_enters_dpad_mode_exactly_as_an_arrow_key_does() { let _serial=plx_base::testlock::serial(); + use std::sync::atomic::Ordering::Relaxed; for arrow in [false,true] { - let mut app=app(); + let (platform, counted) = crate::app::platform::SwapShell::platform(); + let mut app=app_on(platform); app.ptr.mot_accum=500.0; app.ptr.edge.moved(10.0,10.0,false); if arrow { let ps=plx_media::route::PlaybackSession::IDLE; let mut down_sym=0; - unsafe{ super::super::input::begin_fresh_press(&ps,Key::Down,plx_ui::consts::SDLK_DOWN,0,0,false,&mut down_sym,None,&mut app.ptr) }; + unsafe{ super::super::input::begin_fresh_press(&ps,Key::Down,plx_ui::consts::SDLK_DOWN,0,0,false,&mut down_sym,None,&mut app.ptr,app.platform.shell) }; } else { let mut bridge=app.runtime.bridge(&mut app.bridge); unsafe{ key_play(&mut app.player.session,&mut app.adapters.player,app.last_input, &mut app.player.lifecycle,&mut app.repause_at,&mut app.ptr,&mut app.pages,&mut bridge) }; } assert!(app.ptr.dpad_mode && app.ptr.cur_hidden,"arrow={arrow}"); + assert_eq!(counted.hides.load(Relaxed),1,"arrow={arrow}: both hide the pointer once, through the platform's shell"); assert_eq!(app.ptr.mot_accum,0.0,"arrow={arrow}: motion accumulated before D-pad entry must not carry over"); assert_eq!(app.ptr.edge.at(),None,"arrow={arrow}: the edge glide stops"); } diff --git a/rust-modules/src/dev.rs b/rust-modules/src/dev.rs index 69e81e91b8..7378101742 100644 --- a/rust-modules/src/dev.rs +++ b/rust-modules/src/dev.rs @@ -253,8 +253,8 @@ pub(crate) fn arm_gst_logging() { spec }; let log = plx_base::paths::in_runtime_dir(plx_base::paths::runtime_file::GST); - // SAFETY: single-threaded here by construction — `plex_run` has not yet minted a worker, and - // this runs before SDL init. `set_var` is only unsound against a concurrent reader. + // SAFETY: single-threaded here by construction — the entry (`run_application`) has not yet started + // a worker, and this runs before SDL init. `set_var` is only unsound against a concurrent reader. std::env::set_var("GST_DEBUG", &spec); std::env::set_var("GST_DEBUG_FILE", &log); std::env::set_var("GST_DEBUG_FILE_OVERWRITE", "enable"); diff --git a/rust-modules/src/platform_desktop.rs b/rust-modules/src/platform_desktop.rs index 4eae281b66..33d7aaa591 100644 --- a/rust-modules/src/platform_desktop.rs +++ b/rust-modules/src/platform_desktop.rs @@ -15,9 +15,9 @@ //! refusing `NoSink`. //! //! The shell and the frame probe are plain no-ops: SDL owns the window and its event loop, there is -//! no compositor to hint and no bus to pump. The secure store is `SecureHooks::NONE`: nothing seals, -//! so a session is the 0600 plaintext file the session layer writes itself, which the simulator's -//! harnesses plant and read. +//! no compositor to hint, no bus to pump and no remote pointer to hide. The secure store is +//! `SecureHooks::NONE`: nothing seals, so a session is the 0600 plaintext file the session layer +//! writes itself, which the simulator's harnesses plant and read. //! The storage group is `StorageHooks::NONE`: there is no storage helper, so the account's records //! live in files under the persistent state root. //! @@ -99,7 +99,8 @@ fn deliver_toast(_message: &str, identity: Identity) -> Sent { } /// The desktop shell: SDL owns the window and its event loop, so nothing is bound, grabbed, hinted -/// or pumped, and no surface is ever held. +/// or pumped, and no surface is ever held. The pointer is a mouse the application does not hide, so +/// hiding and showing it do nothing, and a click is always a real one (the hide is not a cursor swap). struct DesktopShell; impl Shell for DesktopShell { @@ -112,6 +113,11 @@ impl Shell for DesktopShell { fn opaque_route(&self, _player: bool) {} fn clear_opaque_region(&self) {} fn pump_bus(&self) {} + fn hide_pointer(&self) {} + fn show_pointer_after_motion(&self) {} + fn hide_is_cursor_swap(&self) -> bool { + false + } } /// The desktop frame probe: always unarmed, there is no compositor callback to clock. @@ -161,6 +167,17 @@ pub fn run(pms_host: &CStr, pms_port: u16) -> c_int { mod tests { use super::*; + /// **The desktop hides no pointer and says so**: its mouse is not the application's to hide, so a + /// hide and a show do nothing, and the hide is not a cursor swap, which is what makes a click + /// always a real one (`input::click_is_ok`). The simulator's pointer behaviour is exactly this. + #[test] + fn the_desktop_shell_hides_no_pointer_and_its_clicks_are_real() { + let shell: &dyn Shell = &DesktopShell; + shell.hide_pointer(); + shell.show_pointer_after_motion(); + assert!(!shell.hide_is_cursor_swap()); + } + /// A desktop has no storage helper: the session, the install's preferences and the consent record /// are files. The same value a host test reads from `Services::HOST_TEST`. #[test] diff --git a/rust-modules/src/port.rs b/rust-modules/src/port.rs index 53ac2cb740..8ce5310957 100644 --- a/rust-modules/src/port.rs +++ b/rust-modules/src/port.rs @@ -51,8 +51,9 @@ static SERVICES: plx_os::tv::Services = plx_os::tv::Services { }, }; -/// 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. +/// The webOS shell: the SDL window's Wayland surface, the opaque-region hint, the LS2 bus pump and the +/// Magic Remote's pointer. The bodies stay in `crate::system` (and `webos::bind_window`); this is the +/// table over them. struct WebosShell; impl Shell for WebosShell { @@ -77,6 +78,15 @@ impl Shell for WebosShell { fn pump_bus(&self) { crate::system::ls2_pump(); } + fn hide_pointer(&self) { + crate::system::hide_cursor(); + } + fn show_pointer_after_motion(&self) { + crate::system::show_cursor_after_motion(); + } + fn hide_is_cursor_swap(&self) -> bool { + crate::system::cursor_is_transparent() + } } /// The webOS frame probe, over `crate::system`'s compositor-callback clock. diff --git a/rust-modules/src/system.rs b/rust-modules/src/system.rs index 21c87081bc..48854b2031 100644 --- a/rust-modules/src/system.rs +++ b/rust-modules/src/system.rs @@ -232,9 +232,11 @@ struct RegistryListener { global_remove: unsafe extern "C" fn(*mut c_void, *mut c_void, c_uint), } -/// A libwayland symbol from the process's own scope. `libwayland-client` is linked normally, so it -/// is already mapped; this only avoids naming these particular symbols in `DT_NEEDED`. -fn wl_sym(name: &str) -> Option<*mut c_void> { +/// A symbol from the process's own scope, `None` if absent or NULL. `libwayland-client` is linked +/// normally, so its symbols are already mapped; this only avoids naming these particular ones in +/// `DT_NEEDED`. The Magic Remote's cursor door ([`cursor_door`]) resolves the system SDL's cursor +/// calls the same way, for the reason its doc gives. +fn self_sym(name: &str) -> Option<*mut c_void> { plx_base::dynlib::Handle::self_handle() .sym(name) .filter(|p| !p.is_null()) @@ -261,8 +263,8 @@ unsafe extern "C" fn on_global( // for more than the compositor advertises is a protocol error that kills the connection. let want = version.min(1); let (Some(iface), Some(bind)) = ( - wl_sym("wl_compositor_interface"), - wl_sym("wl_proxy_marshal_constructor_versioned"), + self_sym("wl_compositor_interface"), + self_sym("wl_proxy_marshal_constructor_versioned"), ) else { log("opaque: libwayland has no versioned constructor — cannot bind wl_compositor"); return; @@ -302,11 +304,11 @@ pub(crate) fn opaque_region_init() { return; } let (Some(ctor), Some(add_listener), Some(roundtrip), Some(destroy), Some(reg_iface)) = ( - wl_sym("wl_proxy_marshal_constructor"), - wl_sym("wl_proxy_add_listener"), - wl_sym("wl_display_roundtrip"), - wl_sym("wl_proxy_destroy"), - wl_sym("wl_registry_interface"), + self_sym("wl_proxy_marshal_constructor"), + self_sym("wl_proxy_add_listener"), + self_sym("wl_display_roundtrip"), + self_sym("wl_proxy_destroy"), + self_sym("wl_registry_interface"), ) else { log("opaque: libwayland is missing a registry entry point — experiment not armed"); return; @@ -354,7 +356,7 @@ pub(crate) fn opaque_region_init() { return; } - let Some(region_iface) = wl_sym("wl_region_interface") else { + let Some(region_iface) = self_sym("wl_region_interface") else { log("opaque: libwayland has no wl_region_interface — experiment not armed"); return; }; @@ -617,10 +619,10 @@ fn frame_syms() -> Option<&'static FrameSyms> { static SYMS: std::sync::OnceLock> = std::sync::OnceLock::new(); SYMS.get_or_init(|| { Some(FrameSyms { - ctor: wl_sym("wl_proxy_marshal_constructor")? as usize, - add_listener: wl_sym("wl_proxy_add_listener")? as usize, - callback_interface: wl_sym("wl_callback_interface")? as usize, - destroy: wl_sym("wl_proxy_destroy").map(|p| p as usize), + ctor: self_sym("wl_proxy_marshal_constructor")? as usize, + add_listener: self_sym("wl_proxy_add_listener")? as usize, + callback_interface: self_sym("wl_callback_interface")? as usize, + destroy: self_sym("wl_proxy_destroy").map(|p| p as usize), }) }) .as_ref() @@ -767,6 +769,155 @@ unsafe fn update_wayland_info(ok: c_int, info: &[u8; 512]) { display: Some(display_present), surface: Some(surface_present) }); } +// ------------------------------------------------------------------------------------------ +// The Magic Remote's pointer: hide it when the D-pad takes over, show it again on motion +// ------------------------------------------------------------------------------------------ +// +// Moved here from `app/boot.rs` (platform plan, W5c) with its hostsim arms removed, the desktop's +// `Shell` stating the no-op instead, and its three entry points made safe: the pointer's visibility is +// the platform's, so the loop reaches it through `Shell::{hide_pointer, show_pointer_after_motion, +// hide_is_cursor_swap}` and `port::WebosShell` is the table over these three. A desktop's pointer is +// a mouse the application does not hide, so `platform_desktop`'s shell states no-ops. + +/// Hide the Magic Remote's on-screen pointer. A webOS-only concept: there is no such cursor to +/// hide on a desktop, and `SDL_webOSCursorVisibility` exists in no SDL but LG's fork. +/// +/// One door rather than a branch at each caller, so the platform question is asked once +/// and the callers read the same on LG's extension and on the transparent-cursor path. +/// +/// Resolved at runtime rather than linked: webOS 3.4 ships SDL 2.0.3, which has none of LG's +/// `SDL_webOS*` extensions, and a strong reference there is a lazily-bound PLT slot that kills +/// the process on the first D-pad press (`tools/fwcompat.py --release 3.4.0`). +/// +/// **Without LG's extension the pointer is SDL's own cursor, and it is swapped for a transparent +/// one rather than switched off.** webOS 3.9.3 ships SDL 2.0.4 with no `SDL_webOS*` export at all, +/// and that SDL draws the pointer itself (its `.rodata` carries `/usr/share/im/cursorType*.png` +/// and `wl_starfish_pointer`). With nothing to call, every hide was a no-op and the pointer stayed +/// up until LG's ~5-minute idle timeout, issue #642. `SDL_ShowCursor(SDL_DISABLE)` does hide it +/// there, but measured on that set it also stops pointer motion reaching the app until the pointer +/// re-enters the window (opening and closing the Settings overlay), so no motion could bring it +/// back. With a transparent cursor the motion keeps arriving, and [`show_cursor_after_motion`] puts +/// the previous cursor back on the next one. Every SDL call is dlsym'd, so the binary gains no +/// import. +#[inline] +pub(crate) fn hide_cursor() { + // SAFETY: the door's functions are the process's own SDL exports (or LG's extension), resolved + // by `cursor_door` and called here on the loop thread, which is the thread every `Shell` call runs on. + unsafe { hide_through(cursor_door(), &SHOWN_CURSOR) } +} + +/// True where the pointer is hidden by swapping in a transparent cursor rather than by LG's call, +/// so the system's pointer stays up and the remote's OK arrives as a click (`input::click_is_ok`). +/// False wherever LG's extension exists, and where there is no way to hide it at all. +pub(crate) fn cursor_is_transparent() -> bool { + matches!(cursor_door(), CursorDoor::Sdl { .. }) +} + +/// Bring the pointer back after [`hide_cursor`] swapped in the transparent cursor. Call on pointer +/// motion while the cursor is hidden. A no-op wherever LG's extension exists: there the +/// compositor shows its own pointer on motion, as it always has. +#[inline] +pub(crate) fn show_cursor_after_motion() { + // SAFETY: as `hide_cursor`. + unsafe { show_through(cursor_door(), &SHOWN_CURSOR) } +} + +/// [`hide_cursor`] on a given door, the cursor it replaced kept in `shown`. Split out so the +/// bookkeeping is gradeable on the host with a door of fake functions. +unsafe fn hide_through(door: CursorDoor, shown: &std::sync::atomic::AtomicUsize) { + match door { + CursorDoor::Lg(f) => { + f(0); + } + CursorDoor::Sdl { set, get, def, blank } => { + let cur = get() as usize; + if cur != blank { + let keep = if cur != 0 { cur } else { def() as usize }; + if keep == 0 { + return; // nothing to put back, so the pointer would never return: leave it + } + shown.store(keep, std::sync::atomic::Ordering::Relaxed); + } + set(blank as *mut std::ffi::c_void); + } + CursorDoor::None => {} + } +} + +/// [`show_cursor_after_motion`] on a given door. +unsafe fn show_through(door: CursorDoor, shown: &std::sync::atomic::AtomicUsize) { + if let CursorDoor::Sdl { set, .. } = door { + let shown = shown.load(std::sync::atomic::Ordering::Relaxed); + if shown != 0 { + set(shown as *mut std::ffi::c_void); + } + } +} + +/// The cursor [`hide_cursor`] replaced with the transparent one, for the motion that restores it. +static SHOWN_CURSOR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +type CursorVisibilityFn = unsafe extern "C" fn(c_int) -> c_int; +type SetCursorFn = unsafe extern "C" fn(*mut std::ffi::c_void); +type GetCursorFn = unsafe extern "C" fn() -> *mut std::ffi::c_void; +type CreateCursorFn = + unsafe extern "C" fn(*const u8, *const u8, c_int, c_int, c_int, c_int) -> *mut std::ffi::c_void; + +/// Which call hides the pointer on this firmware, resolved once: LG's extension when the system +/// SDL has it (webOS 4+), else a transparent SDL cursor (webOS 3.x). +#[derive(Clone, Copy)] +enum CursorDoor { + Lg(CursorVisibilityFn), + /// `SDL_SetCursor` / `SDL_GetCursor` / `SDL_GetDefaultCursor`, and the transparent cursor. + Sdl { set: SetCursorFn, get: GetCursorFn, def: GetCursorFn, blank: usize }, + None, +} + +/// Resolved on the first hide, after `SDL_Init`, because `SDL_CreateCursor` needs the video +/// subsystem. +fn cursor_door() -> CursorDoor { + static DOOR: std::sync::OnceLock = std::sync::OnceLock::new(); + *DOOR.get_or_init(|| { + use std::ffi::c_void; + use std::mem::transmute; + // SAFETY: each symbol is transmuted to the signature SDL2's public API (or, for + // `SDL_webOSCursorVisibility`, LG's fork) gives it, and is called on the main thread. + let door = unsafe { + if let Some(f) = self_sym("SDL_webOSCursorVisibility") { + CursorDoor::Lg(transmute::<*mut c_void, CursorVisibilityFn>(f)) + } else if let (Some(set), Some(get), Some(def), Some(create)) = ( + self_sym("SDL_SetCursor"), + self_sym("SDL_GetCursor"), + self_sym("SDL_GetDefaultCursor"), + self_sym("SDL_CreateCursor"), + ) { + // 8x1 with every data and mask bit clear: SDL's transparent pixel throughout. + let bits = [0u8; 1]; + let create = transmute::<*mut c_void, CreateCursorFn>(create); + let blank = create(bits.as_ptr(), bits.as_ptr(), 8, 1, 0, 0); + if blank.is_null() { + CursorDoor::None + } else { + CursorDoor::Sdl { + set: transmute::<*mut c_void, SetCursorFn>(set), + get: transmute::<*mut c_void, GetCursorFn>(get), + def: transmute::<*mut c_void, GetCursorFn>(def), + blank: blank as usize, + } + } + } else { + CursorDoor::None + } + }; + log(match door { + CursorDoor::Lg(_) => "cursor: SDL_webOSCursorVisibility", + CursorDoor::Sdl { .. } => "cursor: transparent SDL cursor (no SDL_webOS* in this SDL)", + CursorDoor::None => "cursor: no way to hide the pointer", + }); + door + }) +} + #[cfg(test)] mod wayland_tests { use super::*; @@ -912,3 +1063,106 @@ mod wayland_tests { } } } + +#[cfg(test)] +mod cursor_door_tests { + use super::*; + use std::cell::{Cell, RefCell}; + use std::ffi::c_void; + use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; + + const BLANK: usize = 0x99; + + thread_local! { + static CURRENT: Cell = const { Cell::new(0) }; + static DEFAULT: Cell = const { Cell::new(0) }; + static SET: RefCell> = const { RefCell::new(Vec::new()) }; + static LG: RefCell> = const { RefCell::new(Vec::new()) }; + } + + unsafe extern "C" fn set(c: *mut c_void) { + SET.with(|s| s.borrow_mut().push(c as usize)); + CURRENT.with(|cur| cur.set(c as usize)); + } + unsafe extern "C" fn get() -> *mut c_void { + CURRENT.with(Cell::get) as *mut c_void + } + unsafe extern "C" fn def() -> *mut c_void { + DEFAULT.with(Cell::get) as *mut c_void + } + unsafe extern "C" fn lg(visible: c_int) -> c_int { + LG.with(|l| l.borrow_mut().push(visible)); + 0 + } + + /// A fresh door with SDL's current cursor and default cursor as given (0 = NULL). + fn sdl(current: usize, default: usize) -> CursorDoor { + CURRENT.with(|c| c.set(current)); + DEFAULT.with(|d| d.set(default)); + SET.with(|s| s.borrow_mut().clear()); + CursorDoor::Sdl { set, get, def, blank: BLANK } + } + fn installed() -> Vec { + SET.with(|s| s.borrow().clone()) + } + + #[test] + fn hiding_swaps_in_the_blank_cursor_and_motion_puts_the_previous_one_back() { + let shown = AtomicUsize::new(0); + let door = sdl(0x10, 0x20); + unsafe { + hide_through(door, &shown); + assert_eq!(installed(), [BLANK]); + show_through(door, &shown); + } + assert_eq!(installed(), [BLANK, 0x10]); + } + + #[test] + fn with_no_current_cursor_the_default_one_is_what_comes_back() { + let shown = AtomicUsize::new(0); + let door = sdl(0, 0x20); + unsafe { + hide_through(door, &shown); + show_through(door, &shown); + } + assert_eq!(installed(), [BLANK, 0x20]); + } + + #[test] + fn hiding_again_while_hidden_keeps_the_cursor_to_restore() { + let shown = AtomicUsize::new(0); + let door = sdl(0x10, 0x20); + unsafe { + hide_through(door, &shown); + hide_through(door, &shown); // `get` now answers the blank cursor + show_through(door, &shown); + } + assert_eq!(installed(), [BLANK, BLANK, 0x10]); + } + + /// With no current and no default cursor there is nothing to put back, so the pointer must not + /// be hidden: it would never come back. + #[test] + fn with_nothing_to_restore_the_cursor_is_left_alone() { + let shown = AtomicUsize::new(0); + let door = sdl(0, 0); + unsafe { + hide_through(door, &shown); + show_through(door, &shown); + } + assert_eq!(installed(), Vec::::new()); + assert_eq!(shown.load(Relaxed), 0); + } + + #[test] + fn lgs_extension_is_asked_to_hide_and_motion_leaves_it_to_the_compositor() { + let shown = AtomicUsize::new(0); + LG.with(|l| l.borrow_mut().clear()); + unsafe { + hide_through(CursorDoor::Lg(lg), &shown); + show_through(CursorDoor::Lg(lg), &shown); + } + assert_eq!(LG.with(|l| l.borrow().clone()), [0]); + } +} From 7a1e6c53c32a8dbca428b11e049ce95ffbe2b32d Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 18:24:28 +0300 Subject: [PATCH 15/26] The docs follow where the storage authority, pointer and wheel landed (#1493) This is a docs follow-up to the platform plan (discussion #1460). It corrects the sentences that W8a (#1488, #1490, #1491) and W5c (#1492) made false. It is prose only, plus one code comment. - rust-modules/plex/src/plex/CLAUDE.md and the session/persistence.rs module doc: - Seven public dispatchers hand the authority and NativeTransport to a *_via form. - cleanup_temporaries goes through cleanup_temporaries_for(authority) with no transport. Its Helper arm sweeps nothing. - docs/module-layers.md: - L15e reads "W5a to W5c and W6b landed". - L15g reads "W8a started" (#1488, #1490, #1491). - docs/platform-ports.md: - F39 says telemetry was re-keyed first, in #1490. - In Target shape 4, the gate sits above the storage-authority selection, not a target_arch selection. - The HostEvent list gains an "As landed (W5c)" note: Pointer { x, y, edge } and Wheel { dy }, with no buttons or shown field. - rust-modules/os/src/storage/mod.rs: the comment on StoreError's allow(dead_code) no longer claims a compiled-out half. Both arms compile on every build. No variant warns without the allow, because the enum is public and the storage module allows dead_code. The attribute is unchanged. Two review minors are left for W6's docs, which edit the same row: - The L15g row does not name telemetry's nine native.rs crash-capture sites, the follow-up for Tizen ARM retail builds. - The row does not say that the storage-authority part of W8a ran ahead of W7. plex/Cargo.toml's stale hostsim comment is certificate-pinned and goes with W8c. --- docs/module-layers.md | 4 ++-- docs/platform-ports.md | 11 +++++++++-- rust-modules/os/src/storage/mod.rs | 5 ++++- rust-modules/plex/src/plex/CLAUDE.md | 6 ++++-- rust-modules/plex/src/plex/session/persistence.rs | 6 ++++-- 5 files changed, 23 insertions(+), 9 deletions(-) diff --git a/docs/module-layers.md b/docs/module-layers.md index 6d78438251..5ce87d356f 100644 --- a/docs/module-layers.md +++ b/docs/module-layers.md @@ -334,9 +334,9 @@ proves the references are gone and nothing more; L15b is open. | **L15b** the OS-neutral port — **open** | — | An OS-neutral video sink with the ACB bind sequence behind it and the webOS facts the gate cannot see; the simulator became its own platform in W4. See below. | | **L15c** the platform value and the three contracts — **done** | — | Wave R (the rename that gave this page `os` and `[platform webos]`) landed as #1474; W2 landed (`tv::Port` became `tv::Services`, with four groups of hooks; the shell and the frame probes moved to `app::Platform`), and so did the three contracts, W3a to W3c: who may persist credentials (#1477), what evidence admits a URI player (#1478), who ends the process (#1479). See "L15c to L15h" below. | | **L15d** neutral types and the simulator as its own platform (L15b item 2) — **W3d and W4 landed** | — | W3d landed (the opaque `Backend` tag, `sandbox` to `native_video`, identity publishes a platform name and version, `device::Info` keeps its webOS fields in `WebosDetail`, and `devcaps` reads its files through the platform), and so did W4: `platform_desktop` (`rust-modules/src/platform_desktop.rs`, a second fence section, `[platform desktop]`) is the simulator's and the macOS app's own platform value, which `src/bin/sim.rs` enters through; the `hostsim` terms of the television's fence are gone, so the television's code is compiled into every build and the linker drops it from a desktop executable (`simulators.yml` links the macapp feature set to guard that until W7), and the stand-ins in `webos` and `keymanager` are test seams, compiled for tests and `test-support` (`docs/platform-ports.md`, W4). The desktop platform is the second implementation. | -| **L15e** events, the shell and composition — **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). | +| **L15e** events, the shell and composition — **W5a to W5c and W6b landed** | — | W5 (`HostEvent` with `Option`) landed in three PRs, lifecycle and quit (W5a, #1484), keys and text (W5b, #1487) and the pointer and wheel (W5c, #1492), and so did W6b (platform-supplied composition in two boot phases, #1489). W6 (`plx_shell_sdl`, a `[shell_sdl]` layer) and W6c (a URI-only and a two-driver composition play an ordinary title) are planned. | | **L15f** extract the platform crates — **planned** | — | W7: a narrow public `host` module in the application crate, `rust-modules/platform-webos` and `platform-desktop` as crates above `app`, and the gate learning "a platform is a crate above `app`". After L15d, before L15g and L15h. | -| **L15g** the webOS facts and the remaining `hostsim` (L15b item 3) — **planned** | — | W8: the `target_arch = "arm"` and `target_os = "linux"` sites sorted into "is webOS" (a platform value or runner) and "is 32-bit ARM" or "is Linux" (stays), then the library name lists, `paths`, the packaging and the `feature = "hostsim"` lines left in the tree (none of them in the fence now; `git grep -h 'feature = "hostsim"' -- '*.rs' | wc -l` counts them). | +| **L15g** the webOS facts and the remaining `hostsim` (L15b item 3) — **W8a started** | — | W8a has begun: the platform states where the account's records live (`tv::Services.storage`, #1488), and telemetry's consent store (#1490) and plex's session persistence (#1491) follow it instead of the `target_arch = "arm"` fence. Still planned: the rest of W8a, one PR per directory (`os`, `src`, `base`, `storage` and `play-feed`), sorting the `target_arch = "arm"` and `target_os = "linux"` sites into "is webOS" (a platform value or runner) and "is 32-bit ARM" or "is Linux" (stays); then W8b, the library name lists, `paths` and the packaging, and W8c, the `feature = "hostsim"` lines left in the tree (none of them in the fence now; `git grep -h 'feature = "hostsim"' -- '*.rs' | wc -l` counts them). | | **L15h** the OS-neutral Feed sink (L15b item 1) — **planned** | — | W11: `plx_acb` (an `[acb]` layer) takes the ACB plane owner and the URI media verbs out of `os`, the Feed-side ACB results become neutral, and the bind sequence moves behind a neutral sink. Needs the television. | ### L15: the webOS port diff --git a/docs/platform-ports.md b/docs/platform-ports.md index 889afccedb..37872e7640 100644 --- a/docs/platform-ports.md +++ b/docs/platform-ports.md @@ -462,7 +462,8 @@ Citations in this section quote the tree at e9924f0f9 with its old names (see "N `commit_data` `:288-308`); a Tizen ARM build would select the DB8 arm with no helper behind it (F12). The `MemoryOnly` gate sits above that selection. W8a re-keyed plex's 21 sites to `tv::authority::authority()`: `persistence.rs`'s dispatchers take the authority and the helper's transport, so a host test drives the helper - arm with a fake one; telemetry's sites follow in its own PR. + arm with a fake one. Telemetry's consent store was re-keyed first (#1490), and that PR installs the account-clear + sweep on every platform, so consent on a Tizen build takes the files arm, not DB8. ### Evidence from the second reviews: F40-F46 (each citation checked in the tree) @@ -907,6 +908,11 @@ Ecore names to `remote_token_key` pairs". retains them: a raw-only event keeps its original pair and edge, and the loop treats `action: None` as the raw path it is today; - `Text(String)` and `Edit`; `Pointer { x, y, buttons, shown }` and `Wheel { dy }` (carried explicitly, F33); + - As landed (W5c, #1492): `Pointer { x: f32, y: f32, edge: PointerEdge }`, `PointerEdge` being `Move | Down | + Up` (the SDL event type alone, for any button), and `Wheel { dy: i32 }`. There is no `buttons`, because the + loop never read which button was pressed: whether one is held is its own state (`Pointer::button_down`). There + is no `shown`, because that is the pointer machine's own `cur_hidden`, not event data (LG's hide arrives as a + key, `Action::PointerHidden`, and a show is a motion). See `app/events.rs`. - `Lifecycle(WillBackground | DidBackground | WillForeground | DidForeground)` and `Quit`; - `LocaleChanged`, `LowMemory` and `Launch(String)`. - `Action` names what callers consume, not a physical key: `Up Down Left Right Ok Back Play Pause PlayPause Stop @@ -970,7 +976,8 @@ Ecore names to `remote_token_key` pairs". (`update_guarded*`), revocation (`cache_revoked`) and clear (`clear_for_erase`): the `peek()` cache cell becomes the source of truth, `read_live_locked()` answers from it, and no durable credential read or write is reachable (the four writers, the canonical commit and `save_legacy_fallback_locked`'s plaintext arm). The gate - sits above the `target_arch = "arm"` selection (F39, F44). It adds no `cfg(test)` branch to `session.rs` + sits above the storage-authority selection (`tv::authority::authority()`, which replaced the `target_arch = "arm"` + fence in W8a; F39, F44). It adds no `cfg(test)` branch to `session.rs` (F44: a `forks` line) and extends the existing cache rather than adding a second static. - Outcome. A successful memory-only write reports a new ephemeral outcome (`LiveWrite` and `CompletionOutcome` gain `Ephemeral`; not `Durable`, not `Failed`). The auth owner treats it as signed in for this run: it diff --git a/rust-modules/os/src/storage/mod.rs b/rust-modules/os/src/storage/mod.rs index fdea1195d3..a5f9b94bea 100644 --- a/rust-modules/os/src/storage/mod.rs +++ b/rust-modules/os/src/storage/mod.rs @@ -142,7 +142,10 @@ pub enum CommitStage { /// A persistence failure that is safe to print: it has no path and never contains a payload. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -#[allow(dead_code)] // Helper-only variants are compiled out of host adapters and vice versa. +// Nothing needs this allow today: with it deleted, no variant warns on the host or on +// `armv7-unknown-linux-gnueabi`, because the enum is public and `lib.rs` allows `dead_code` on all of +// `storage` as well. Whether to drop it is the `os` directory's W8a PR's call. +#[allow(dead_code)] pub enum StoreError { Io { stage: CommitStage, errno: i32 }, RootNotDirectory, diff --git a/rust-modules/plex/src/plex/CLAUDE.md b/rust-modules/plex/src/plex/CLAUDE.md index a5f97c54df..a40c302695 100644 --- a/rust-modules/plex/src/plex/CLAUDE.md +++ b/rust-modules/plex/src/plex/CLAUDE.md @@ -631,9 +631,11 @@ a dead source is **absent** from Home and states itself in its own library secti (`Helper`: the LS2/DB8 storage helper, webOS; `Files`: the 0600 record files, the desktop, a host test and any platform with no helper), never the build's CPU or OS. `session/persistence.rs` reads it once per public call (`load`, `commit_data`, `commit_cleared`, `write_session`, `migrate_session`, `bootstrap`, - `cleanup_after_confirmed_clear`, `cleanup_temporaries`) and hands it to the `*_via(authority, helper, ..)` + `cleanup_after_confirmed_clear`) and hands it to the `*_via(authority, helper, ..)` form, so a test passes the authority it grades and, for `Helper`, a transport of its own (an in-memory - `Backend` or a closure); the real `NativeTransport` is named by those public forms and by two helpers + `Backend` or a closure); `cleanup_temporaries` also reads it once but dispatches through + `cleanup_temporaries_for(authority)`, which takes no transport, because the `Helper` arm sweeps nothing (DB8 + has no app-owned rename temporaries); the real `NativeTransport` is named by those seven public forms and by two helpers with no `_via` seam (`reset_cleared_language()`, which `clear_for_erase` calls under `Helper` and which is device-only, and `helper_commit`, which has no caller here), because on a Linux host it waits out a 12 s start deadline with no helper behind it. There is no process-global override. diff --git a/rust-modules/plex/src/plex/session/persistence.rs b/rust-modules/plex/src/plex/session/persistence.rs index 249a105b51..b019d84ffc 100644 --- a/rust-modules/plex/src/plex/session/persistence.rs +++ b/rust-modules/plex/src/plex/session/persistence.rs @@ -9,8 +9,10 @@ //! the desktop, a host test and a platform with no helper). Every dispatcher here reads it once per //! call, in its public form, and hands it to a `*_via(authority, helper, ..)` form that takes the //! authority and the helper's transport as parameters, so a host test grades the helper arm with a -//! fake transport and the files arm with a transport that fails the test if it is touched. The -//! helper's real transport (`NativeTransport`) is named by the dispatchers' public forms and by +//! fake transport and the files arm with a transport that fails the test if it is touched. The one +//! exception is `cleanup_temporaries`, which dispatches through `cleanup_temporaries_for(authority)` +//! with no transport, because the helper arm sweeps nothing. The helper's real transport +//! (`NativeTransport`) is named by the other dispatchers' public forms and by //! two helpers that have no `_via` seam: `reset_cleared_language()`, which `clear_for_erase` calls //! under `Helper` (device-only), and `helper_commit`, which has no caller in this crate. From 0354ce24ff61886e7020b6436219c341e556a019 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 20:53:00 +0300 Subject: [PATCH 16/26] ci: fall back to OpenRouter when Claude cannot label an issue (#1495) * ci: fall back to OpenRouter when Claude cannot label an issue When the Anthropic organization ran out of credit, every new issue got only `user-report` and a red run. The labeler now retries the same request through OpenRouter's Anthropic-compatible Messages endpoint: the same Haiku (anthropic/claude-haiku-5.5) billed from OpenRouter credit, with google/gemini-3.1-flash-lite as OpenRouter's own retry so an Anthropic outage is covered too. The fallback needs the repository secret OPENROUTER_API_KEY and is off without it. A run that fell back stays green with a ::warning::, and the Anthropic error body (e.g. "credit balance is too low") is now printed instead of a bare HTTP status. When every model fails the run still adds only `user-report` and exits 1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01P6ZnFdmaenGaJUBJBDz5WS * ci: run the OpenRouter fallback as its own job, in a main-only environment Review of #1495: a repository secret reaches a workflow_dispatch run from any branch, whose copy of the script could do anything with it. The key now lives in the `issue-labels` environment, limited to the default branch. An environment changes the job's OIDC subject away from `...:ref:refs/heads/main`, which the Anthropic federation rule matches, so the Anthropic job keeps no environment: it reports the issues it failed on (`failed` output) and a second job, holding the key and no id-token, labels exactly those with --provider openrouter. A run that fell back is green and keeps the Anthropic job's error annotations; errors now carry the failure reason. The header comments no longer claim the workflow holds no API key. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01P6ZnFdmaenGaJUBJBDz5WS --------- Co-authored-by: Claude Opus 5.5 --- .github/workflows/issue-labels.yml | 67 ++++++++++++- ci/label-issue.py | 149 +++++++++++++++++++++++++---- 2 files changed, 191 insertions(+), 25 deletions(-) diff --git a/.github/workflows/issue-labels.yml b/.github/workflows/issue-labels.yml index 00f3a86a0e..23b9cd0239 100644 --- a/.github/workflows/issue-labels.yml +++ b/.github/workflows/issue-labels.yml @@ -12,16 +12,28 @@ name: Issue labels # # The issue text is never interpolated into a shell line; the script reads it from the API, and # whatever the model answers is filtered down to the repository's own labels before anything is -# written. The token can write issues and nothing else. +# written. The GitHub token can write issues and nothing else. # -# Claude Haiku picks the labels through the Anthropic API. The job holds no API key: it signs in with +# Claude Haiku picks the labels through the Anthropic API. The job holds no Anthropic key: it signs in with # Workload Identity Federation (the `id-token: write` permission below; ci/label-issue.py exchanges # GitHub's identity token for a short-lived Anthropic token). The federation rule's ids are not # secrets; they live in the repository VARIABLES ANTHROPIC_FEDERATION_RULE_ID, # ANTHROPIC_ORGANIZATION_ID, ANTHROPIC_SERVICE_ACCOUNT_ID and, if the rule covers several # workspaces, ANTHROPIC_WORKSPACE_ID. The rule should accept only this repository's default branch. -# There is no keyword fallback: when sign-in or the model fails, only `user-report` is added and the -# job FAILS, so a broken rule shows up as a red run instead of weeks of silently wrong labels. +# +# Fallback: when Anthropic cannot answer (sign-in fails, or the organization is out of credit), the +# `fallback` job labels exactly the issues `label` failed on (its `failed` output) through +# OpenRouter: the same Haiku, billed from OpenRouter credit, with a non-Anthropic model as +# OpenRouter's own retry. The key is the secret OPENROUTER_API_KEY of the `issue-labels` +# ENVIRONMENT, whose deployment-branch rule admits only the default branch, so a run dispatched +# from another branch (whose copy of the script could do anything with the key) never receives it. +# It is a second job because an environment changes the job's OIDC subject from +# `...:ref:refs/heads/main`, which the federation rule matches, to `...:environment:issue-labels`: +# the Anthropic job must hold no environment, and the fallback job holds no `id-token`. +# A run that fell back finishes green and keeps `label`'s error annotations, so the Anthropic +# failure is still visible. Give the key a small credit limit on OpenRouter. +# There is no keyword fallback: when both fail, only `user-report` is added and the run FAILS, so a +# broken rule shows up as a red run instead of weeks of silently wrong labels. on: issues: @@ -52,6 +64,8 @@ jobs: name: label issues runs-on: ubuntu-latest timeout-minutes: 10 + outputs: + failed: ${{ steps.label.outputs.failed }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -59,6 +73,9 @@ jobs: ci/label-issue.py sparse-checkout-cone-mode: false - name: Label + id: label + # A failure hands its issues to `fallback`; the check below fails the job when it did not. + continue-on-error: true env: GITHUB_TOKEN: ${{ github.token }} ANTHROPIC_FEDERATION_RULE_ID: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }} @@ -87,3 +104,45 @@ jobs: [ "$ACTION" = "edited" ] && args+=(--only-if-unlabeled) fi python3 ci/label-issue.py "${args[@]}" + - name: Fail when no issue was handed to the fallback + # The script died before reporting which issues failed (e.g. a GitHub API error). + if: steps.label.outcome == 'failure' && steps.label.outputs.failed == '' + run: | + echo "::error::the labeler failed without naming its issues; see the Label step" >&2 + exit 1 + + fallback: + name: label issues (OpenRouter fallback) + needs: label + if: needs.label.outputs.failed != '' + runs-on: ubuntu-latest + timeout-minutes: 10 + # Holds OPENROUTER_API_KEY; its deployment-branch rule admits only the default branch. + environment: issue-labels + permissions: + contents: read + issues: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + sparse-checkout: | + ci/label-issue.py + sparse-checkout-cone-mode: false + - name: Label through OpenRouter + env: + GITHUB_TOKEN: ${{ github.token }} + OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }} + FAILED: ${{ needs.label.outputs.failed }} + EVENT: ${{ github.event_name }} + DRY_RUN: ${{ inputs.dry_run }} + run: | + set -euo pipefail + args=(--provider openrouter) + [ "$EVENT" = "workflow_dispatch" ] && [ "$DRY_RUN" = "true" ] && args+=(--dry-run) + for n in $FAILED; do + case "$n" in + *[!0-9]*|'') echo "not an issue number: $n" >&2; exit 1 ;; + *) args+=(--issue "$n") ;; + esac + done + python3 ci/label-issue.py "${args[@]}" diff --git a/ci/label-issue.py b/ci/label-issue.py index 6f61f4c652..65bf75a9c7 100755 --- a/ci/label-issue.py +++ b/ci/label-issue.py @@ -16,21 +16,31 @@ touching this file. The answer is untrusted text: anything that is not one of the candidate labels is dropped, at most one kind and MAX_AREAS areas survive. An issue that already carries a kind (the bug form files one as `bug`) is told so and never gets a second, different kind. -* The workflow holds no API key. It signs in with Workload Identity Federation: GitHub's OIDC token +* The workflow holds no Anthropic API key. It signs in with Workload Identity Federation: GitHub's OIDC token for the run is exchanged for a short-lived Anthropic access token (`federation_token`), by the federation rule named in the repository variables ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID, ANTHROPIC_SERVICE_ACCOUNT_ID and (optional) ANTHROPIC_WORKSPACE_ID. +* When Anthropic cannot answer (the sign-in or the request fails, e.g. the organization is out of + credit), the workflow's second job re-runs this script with `--provider openrouter` on exactly + the issues that failed (written to $GITHUB_OUTPUT as `failed`): the same request through + OpenRouter's Anthropic-compatible Messages endpoint with the secret OPENROUTER_API_KEY, the same + Haiku (OPENROUTER_MODEL), and OpenRouter's own retry on OPENROUTER_FALLBACKS (a non-Anthropic + model). It is a separate job because the key lives in a GitHub Environment limited to the default + branch, and an environment changes the OIDC subject the Anthropic federation rule matches + (`...:ref:refs/heads/main`), so the Anthropic job can hold no environment. A run that fell back + shows the Anthropic job's `::error::` annotations but finishes green. * There is no keyword fallback. A guess from single words ("play", "ass", "skip") put wrong areas on most issues, and a silent fallback hid that the model had stopped answering for weeks. When - the key is missing or the model fails or answers nonsense, only `user-report` is added, the - reason is printed, and the run exits 1 so the failed job is visible in Actions. + the model fails or answers nonsense, only `user-report` is added, the reason is printed, and + the run exits 1 so the failed job is visible in Actions (after the fallback, when it also fails). Triage outcomes (`duplicate`, `invalid`, `wontfix`, `good first issue`, `help wanted`) are a maintainer's call and are never candidates. `question` is retired (questions go to Discussions > Q&A) and is never a candidate either. ci/label-issue.py --issue 478 # label one issue (GITHUB_TOKEN, GITHUB_REPOSITORY, - # ACTIONS_ID_TOKEN_REQUEST_*, ANTHROPIC_* federation ids) + # ACTIONS_ID_TOKEN_REQUEST_*, ANTHROPIC_* federation ids, + # or --provider openrouter with OPENROUTER_API_KEY) ci/label-issue.py --unlabeled # label every open issue that has no labels ci/label-issue.py --issue 478 --dry-run # print the decision, change nothing ci/label-issue.py --selftest # pure logic, no network; `make check` runs it @@ -53,6 +63,13 @@ FEDERATION_VARS = ("ANTHROPIC_FEDERATION_RULE_ID", "ANTHROPIC_ORGANIZATION_ID", "ANTHROPIC_SERVICE_ACCOUNT_ID") # A label pick is a short classification over a few hundred tokens; the small model is plenty. MODEL = "claude-haiku-5-5" +# The fallback (`--provider openrouter`), run by the workflow only on issues Anthropic failed: the same +# model through OpenRouter, billed from OpenRouter credit, then (OpenRouter's own retry, the +# documented `fallbacks` field of its Messages endpoint, at most 3) a model from another vendor, so +# an Anthropic outage is covered too: https://openrouter.ai/docs/guides/routing/model-fallbacks +OPENROUTER_URL = "https://openrouter.ai/api/v1/messages" +OPENROUTER_MODEL = "anthropic/claude-haiku-5.5" +OPENROUTER_FALLBACKS = ("google/gemini-3.1-flash-lite",) KINDS = ("bug", "enhancement") USER_REPORT = "user-report" @@ -64,6 +81,13 @@ USER_ASSOCIATIONS = {"NONE", "FIRST_TIMER", "FIRST_TIME_CONTRIBUTOR"} # Characters of the body sent to the model; the first screenful of an issue carries its topic. BODY_LIMIT = 4000 +# Why the last model call gave no answer, for the `::error::` annotation that reports the issue. +LAST_FAILURE = {"reason": None} + + +def fail(reason): + LAST_FAILURE["reason"] = reason + print(reason, file=sys.stderr) def candidates(repo_labels): """`{name: description}` the classifier may pick from: the repository's labels minus NEVER and RETIRED.""" @@ -186,11 +210,11 @@ def federation_token(env): federation ids in `env`; the workspace id is only needed when the rule covers several.""" missing = [v for v in FEDERATION_VARS if not env.get(v)] if missing: - print(f"::error::missing {', '.join(missing)}: set them as repository variables", file=sys.stderr) + fail(f"missing {', '.join(missing)}: set them as repository variables") return None url, bearer = env.get("ACTIONS_ID_TOKEN_REQUEST_URL"), env.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN") if not url or not bearer: - print("::error::no GitHub identity token: the job needs `permissions: id-token: write`", file=sys.stderr) + fail("no GitHub identity token: the job needs `permissions: id-token: write`") return None try: # A fresh identity token per exchange: Anthropic accepts each one once. @@ -204,13 +228,25 @@ def federation_token(env): return request("POST", TOKEN_URL, None, body, {"content-type": "application/json"})["access_token"] except (urllib.error.URLError, KeyError, TypeError, ValueError, TimeoutError) as e: # A refused exchange is an opaque 401; the reason is on the Console's authentication history page. - print(f"::error::Anthropic sign-in failed ({e}); see Console > Workload identity > history", file=sys.stderr) + fail(f"Anthropic sign-in failed ({http_reason(e)}); see Console > Workload identity > history") return None -def model_asker(get_token): - """`ask(messages) -> str | None` against the Anthropic Messages API, signed in by `get_token()`; - None when there is no token or on an API error.""" +def http_reason(e): + """The useful part of an API error: for an HTTP error the status and the start of its body + (`credit balance is too low` lives there, not in the status line).""" + if isinstance(e, urllib.error.HTTPError): + try: + body = e.read().decode("utf-8", "replace") + except Exception: # noqa: BLE001 - a body we cannot read changes nothing + body = "" + return f"HTTP {e.code} {body[:300]}".strip() + return str(e) + + +def messages_asker(name, url, model, get_token, extra=None): + """`ask(messages) -> str | None` against a Messages-API endpoint signed in by `get_token()`; + None (reason printed) when there is no token or on an API error.""" def ask(messages): token = get_token() if not token: @@ -218,16 +254,34 @@ def ask(messages): system, user = messages[0]["content"], messages[1:] headers = {"authorization": f"Bearer {token}", "anthropic-version": "2023-06-01", "content-type": "application/json"} - payload = {"model": MODEL, "max_tokens": 600, "system": system, "messages": user} + payload = {"model": model, "max_tokens": 600, "system": system, "messages": user, **(extra or {})} try: - resp = request("POST", ANTHROPIC_URL, None, payload, headers) + resp = request("POST", url, None, payload, headers) + answered = resp.get("model") or model + if answered != model: + print(f"{name}: answered by {answered}", file=sys.stderr) return "".join(b.get("text", "") for b in resp["content"] if b.get("type") == "text") - except (urllib.error.URLError, KeyError, TypeError, ValueError, TimeoutError) as e: - print(f"Claude unavailable: {e}", file=sys.stderr) + except (urllib.error.URLError, KeyError, TypeError, ValueError, TimeoutError, AttributeError) as e: + fail(f"{name} unavailable: {http_reason(e)}") return None return ask +def model_asker(get_token): + """Claude through the Anthropic Messages API, signed in by `get_token()`.""" + return messages_asker("Claude", ANTHROPIC_URL, MODEL, get_token) + + +def openrouter_asker(key): + """The same request through OpenRouter's Messages endpoint, or None when there is no key + (reason recorded).""" + if not key: + fail("no OPENROUTER_API_KEY: add it to the `issue-labels` environment") + return None + return messages_asker("OpenRouter", OPENROUTER_URL, OPENROUTER_MODEL, lambda: key, + {"fallbacks": [{"model": m} for m in OPENROUTER_FALLBACKS]}) + + def label_issue(repo, number, token, repo_labels, ask, dry_run, only_if_unlabeled): issue = request("GET", f"{API}/repos/{repo}/issues/{number}", token) if "pull_request" in issue: @@ -245,14 +299,15 @@ def label_issue(repo, number, token, repo_labels, ask, dry_run, only_if_unlabele print(f"#{number} {issue.get('title', '')!r}: picks {', '.join(picks) or 'nothing'}; " f"would add {', '.join(add) or 'nothing'}") if not ok: - print(f"::error::#{number}: the model gave no usable answer") + print(f"::error::#{number}: the model gave no usable answer ({LAST_FAILURE['reason']})") return ok add, ok = decide(issue, repo_labels, ask) print(f"#{number} {issue.get('title', '')!r}: {', '.join(add) if add else 'nothing to add'}") if add: request("POST", f"{API}/repos/{repo}/issues/{number}/labels", token, {"labels": add}) if not ok: - print(f"::error::#{number}: the model gave no usable answer, so no kind or area was added") + print(f"::error::#{number}: the model gave no usable answer ({LAST_FAILURE['reason']}), " + "so no kind or area was added") return ok @@ -262,6 +317,8 @@ def main(): ap.add_argument("--unlabeled", action="store_true", help="every open issue with no labels") ap.add_argument("--only-if-unlabeled", action="store_true", help="skip an issue that has any label") ap.add_argument("--dry-run", action="store_true") + ap.add_argument("--provider", choices=("anthropic", "openrouter"), default="anthropic", + help="anthropic (federation sign-in) or openrouter (OPENROUTER_API_KEY), the fallback") ap.add_argument("--selftest", action="store_true") args = ap.parse_args() if args.selftest: @@ -279,11 +336,26 @@ def main(): print("every open issue already has a label") return 0 sys.exit("nothing to do: pass --issue N or --unlabeled") - print(f"classifier: {MODEL}") - ask = model_asker(lambda: federation_token(os.environ)) - results = [label_issue(repo, n, token, repo_labels, ask, args.dry_run, args.only_if_unlabeled or args.unlabeled) - for n in numbers] - return 0 if all(results) else 1 + if args.provider == "openrouter": + print(f"classifier: {OPENROUTER_MODEL} via OpenRouter (fallback; Claude failed on these issues)") + ask = openrouter_asker(os.environ.get("OPENROUTER_API_KEY")) or (lambda m: None) + else: + print(f"classifier: {MODEL}") + ask = model_asker(lambda: federation_token(os.environ)) + results = {n: label_issue(repo, n, token, repo_labels, ask, args.dry_run, args.only_if_unlabeled or args.unlabeled) + for n in numbers} + failed = [n for n, ok in results.items() if not ok] + report_failed(failed, os.environ.get("GITHUB_OUTPUT")) + if args.provider == "openrouter" and results and not failed: + print("::warning::Claude could not label these issues; OpenRouter did", file=sys.stderr) + return 1 if failed else 0 + + +def report_failed(failed, output): + """Hand the issues the model failed on to the workflow's fallback job (`failed=N M ...`).""" + if output: + with open(output, "a", encoding="utf-8") as f: + f.write(f"failed={' '.join(map(str, failed))}\n") # --- selftest ------------------------------------------------------------------------------------ @@ -392,6 +464,41 @@ def fake(method, url, token, payload=None, headers=None): def test_model_is_the_current_haiku(self): self.assertEqual(MODEL, "claude-haiku-5-5") + def test_no_openrouter_key_means_no_asker(self): + self.assertIsNone(openrouter_asker(None)) + self.assertIsNone(openrouter_asker("")) + self.assertIn("OPENROUTER_API_KEY", LAST_FAILURE["reason"]) + + def test_failed_issues_are_handed_to_the_fallback_job(self): + import tempfile + with tempfile.NamedTemporaryFile("r", suffix=".out") as out: + report_failed([478, 501], out.name) + report_failed([], out.name) + self.assertEqual(open(out.name).read(), "failed=478 501\nfailed=\n") + report_failed([1], None) # outside Actions: nothing to write + + def test_openrouter_request(self): + global request + real, calls = request, [] + + def fake(method, url, token, payload=None, headers=None): + calls.append((method, url, payload, headers)) + return {"model": OPENROUTER_MODEL, "content": [{"type": "text", "text": '{"labels": ["bug"]}'}]} + request = fake + try: + answer = openrouter_asker("sk-or-v1-x")(prompt(arabic, candidates(labels))) + finally: + request = real + self.assertEqual(answer, '{"labels": ["bug"]}') + method, url, payload, headers = calls[0] + self.assertEqual((method, url), ("POST", "https://openrouter.ai/api/v1/messages")) + self.assertEqual(headers["authorization"], "Bearer sk-or-v1-x") + self.assertEqual(payload["model"], "anthropic/claude-haiku-5.5") + self.assertEqual(payload["fallbacks"], [{"model": "google/gemini-3.1-flash-lite"}]) + self.assertLessEqual(len(payload["fallbacks"]), 3) + self.assertIn("triage GitHub issues", payload["system"]) + self.assertEqual([m["role"] for m in payload["messages"]], ["user"]) + def test_question_is_retired(self): # Questions live in Discussions > Q&A; the label may still exist, but is never applied. self.assertNotIn("question", KINDS) From 2b2fb2f7558bef170ad13ba555b10dcdaca19868 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Fri, 20 Nov 2026 21:28:25 +0300 Subject: [PATCH 17/26] docs/uri-mode.md records what the firmware does with Dolby Vision on a URI Load A Results row for the static reads behind #1399. On every image, the DolbyHdrInfo node on a URI Load is checked only for presence: it pins hdrType to DolbyVision and nothing reads profileId or trackType. Whether Dolby Vision is decoded is decided by the demuxer. qtdemux handles it on every major. matroskademux has no Dolby Vision code before 10.3; this was read in the code on 5.5.0, 5.6.2, 6.5.3, 7.6.0 and 9.2.4, and 10.3.x and 11.2 carry it. The 5.6.2 CX badge for a Profile 8.6 MKV played without the node is not explained by any userspace element, so it is recorded as open. Co-Authored-By: Claude Opus 5.5 --- docs/uri-mode.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/uri-mode.md b/docs/uri-mode.md index 344f8f9bb5..ac3627aa25 100644 --- a/docs/uri-mode.md +++ b/docs/uri-mode.md @@ -29,6 +29,7 @@ displayed its URI fixture on the 4.5 dev set, as recorded below. | webOS 7.6.0 (firmware major 7) | unpacked image `HE_DTV_W22P_AFADATAA` (webOS TV 7.6.0, release 7.6.0-1901); no tester run | **Admitted, bracketed, no tester run: major 7 is in `EXPORTED_STRATA`.** (a) The 7.6.0 image reads `option.windowId` at load: `libplayerAPIs.so.1.0.0` (sha256 prefix `0969903e`), `StarfishMediaAPIs::parseLoadMessage`. The string `option.windowId` (file offset 0x971d8) is referenced at 0x467c6 and is read as an optional string; when the key is present the function stores it at `MediaApiPrivate+0x90` and passes it to a virtual call (vtable slot +0x74 of the object at `MediaApiPrivate+0x5c`, not separately identified on this image). The same image's string table has `fail to create AVProxy` (0x98b9c). Addresses are file VAs. Bracketed: majors 5 and 10 are each admitted on a tester's product run, and they are the nearest major admitted on tester evidence on each side of 7. No tester run exists on a 7.x set, so there is no (b) and no (c), and no other 7.x release has been read. The boot line reads `major=7 evidence=table`. | | webOS 9.2.4 / 10.3.1 (33.31.68) | unpacked images; LG C2 on webOS 25 (10.x, 33.31.68; issue #1064: [the set](https://github.com/plxnative/plx-native/issues/1064#issuecomment-6507267775), [the drive probe](https://github.com/plxnative/plx-native/issues/1064#issuecomment-6749905096), [the first product run](https://github.com/plxnative/plx-native/issues/1064#issuecomment-6806253745), [the Dolby Vision product run](https://github.com/plxnative/plx-native/issues/1064#issuecomment-6834626267), [a DTS file](https://github.com/plxnative/plx-native/issues/1064#issuecomment-6834728153), [the wider-than-16:9 product run](https://github.com/plxnative/plx-native/issues/1064#issuecomment-6884620557)) | **Admitted: major 10 is in `EXPORTED_STRATA`, on tester evidence. Major 9 is admitted too, bracketed, no tester run.** Major 9, (a): the 9.2.4 image (`HE_DTV_W24G_AFABATAA`, webOS TV 9.2.4, release 9.2.4-48) reads `option.windowId` at load: `libplayerAPIs.so.1.0.0` (sha256 prefix `cc08e2b8`), `StarfishMediaAPIs::parseLoadMessage`. The string `option.windowId` (file offset 0x9a7c0) is referenced at 0x4385c and is read as an optional string; when the key is present the function stores it at `MediaApiPrivate+0x94` and passes it to a virtual call (vtable slot +0x78 of the object at `MediaApiPrivate+0x60`, not separately identified on this image). The same image's string table has `fail to create AVProxy` (0x99884). Addresses are file VAs. Bracketed: majors 5 and 10 are the nearest major admitted on tester evidence on each side of 9. No run exists on a 9.x set, so there is no (b) and no (c) for major 9, and no other 9.x release has been read. For major 10: (a) The 10.3 image (33.31.68) reads `option.windowId` at load (decompile, below). (b) The PRODUCT run of 2026-11-14 ([the tester's comment](https://github.com/plxnative/plx-native/issues/1064#issuecomment-6884620557)), on a debug build the tester does not name. It answers the maintainer's request of 2026-11-13 for the CI build of run 43421880266 (main at `2d565dc9f`, #1331's merge) with the override armed, Playback engine Experimental, quality Original and an original wider than 16:9 with one audio track and no subtitles. It opens "Everything was successful again: aspect ratio correct, picture is full width with black bars, audio is playing, pause, resume, seek working." and pastes the event log's `grep -E 'uri(probe)?: |ls2uri: '`: boot `uri: product binding=Exported { canvas: (1920, 1080) } mode=2 evidence=override` (the paste has no `uri: product binding=Unbound ... major=10 evidence=none` line before it, which the earlier Dolby Vision paste had, so no line of this paste names the firmware major: the run is attributed to this row by the tester's own answer in the thread, on their set); `uri: original declined (a trailer preview)`; `ls2uri: register shape=named ok after 2ms`; `uri: exported window placed src=1920x1080 rv=1`, then `uri: exported window placed src=3840x1608 rv=1` (3840x1608 is 2.39:1); `uri: audio index=0 is already selected (audioInfo); no selectTrack sent`; `uri: service playing`; `uri: control Seek(ContentTime(54901)) landed on the service's seekDone (its reply acknowledged first: yes)` and `uri: control Seek(ContentTime(130201)) landed on the service's seekDone (its reply acknowledged first: yes)`; `ls2uri: released`. This run meets rule (b): the override boot line; a picture placed from a 2.39:1 source, "full width with black bars" in the tester's words; sound ("audio is playing", with the audio and `service playing` lines logged); and controls, the two seeks logged landing on `seekDone`. Pause and resume rest on the tester's words alone: the paste has no pause line, and the backend logs none for the service's `paused` event. Two earlier product runs on the same set support it and are not relied on for the rule. On 2026-11-11 the first, answering the maintainer's request for the debug build of main at `68527cb2` (which carries #1314), pasted no lines and reported "I can confirm that everything worked: picture size/aspect, spinner clears, remaining time counts down, pause/ resume and seek also working." On 2026-11-12 the second, a 16:9 Dolby Vision MKV with one audio track and no subtitles, was "also successful" ("Audio plays, pause, resume and seek works"); its paste has the override line, `uri: exported window placed src=3840x2160 rv=1` and seeks at 31724 and 87765, after the boot line from before this entry, `uri: product binding=Unbound mode=2 handle=false ptype=10 initialized=false major=10 evidence=none`. (c) The drive probe, on an older build (the earlier grader), printed `load=ok playing=yes ... currentTime_advanced=yes ... window=exported ... shape=named end=script pause=unconfirmed ... resume=sent seek=hit seek_delta=-742 ... audio=ok ... pause_basis=reported_positions pause_samples=0 ... paused_event=yes`. Its lines: `drive pause pos=2410`, `ev=paused` at t=4701, no `currentTime` until after `drive resume pos=2410`, then `ev=currentTime value=2729`; `drive seek target=24937`, `ev=seekDone`, the first `currentTime` after it 24195; `drive selectTrack type=audio index=1`, `ev=trackSelected type=audio index=1` (its file had at least two audio tracks; the product runs' had one); `currentTime` in milliseconds about 1 s apart; the tester's answers: pause froze the picture and resume carried on from there ("Yes"), the seek "worked", "Subtitles worked, audio switch also worked" (the subtitles are the firmware's, not our overlay). The tester also reported on that probe run that the video "shows ‘connecting…’ and the buffering icon all the time" and the remaining time "only shows -0:00"; the first product run (2026-11-11) reports the spinner clearing and the remaining time counting down. **Amendment (1) is used.** The run printed `pause=unconfirmed`: with `pause_samples=0` the grader had no position to compare, because the service sends none while paused. The current grader's verdict on the run's recorded numbers stands in for the printed `pause=froze`: `uri_drive_webos_25_c2_run_replays_to_pause_froze_from_the_paused_event_and_resume` (`rust-modules/play-uri/src/uriprobe.rs`) replays them (a pause at 2410, a `paused` event inside the dwell, no samples, 2729 as the first position after the resume) and the current grader answers `pause=froze` on `pause_basis=paused_event_and_resume`; the same test shows that a resume more than 1000 ms from the paused position (3411, 1409) confirms nothing. That verdict is the test's, not a printed one. This older summary prints no `resume_from=` token, so rule (c)'s resume comparison is read from the log: first position after the resume 2729, 319 ms past the paused 2410, inside the bound. Amendment (2) is not used: no control failed. Extra datapoint, not part of the rule: a file with a DTS audio track also played as a direct play on this C2 (the tester says the set uses `dts_restore_plus`), and Diagnostics read `Audio dca -> unknown`: the row's third stage is what we declared to Starfish, and it reads `unknown` for a play on the URI backend (`feed_attempt` in `rust-modules/src/app/diagnostics.rs` on main today; the report names no build), which is expected on a URI play. Not checked: subtitles on the URI path through the product, HLS, audio-track switching through the product (a multi-audio original goes to Standard), end of stream, other 10.x minors, and a build with this table entry on a 10.x set. The 2026-11-14 run adds none of these: one audio track, no subtitles, no `evidence=table` line in its paste, and no end-of-stream line (the backend logs none for it, so a paste could not show one). | | webOS 26: set on 11.1.0-3701, mechanism read on the 11.2.0 image | LG G4 (issue #1064) | `windowId` in `load` → 4K picture, Dolby Vision and Atmos through the TV's pipeline, our overlays composited over it, correct size and place. The set runs 11.1.0-3701; 11.2.0 is the unpacked image the mechanism above was read from, not the set. | +| Dolby Vision on a URI Load (static reads 2026-11-17 and 2026-11-20; no device) | unpacked images 4.x, 5.5.0-19, 5.6.2-21, 6.5.3-47, 7.6.0-1901, 9.2.4-48, 10.3.1, 10.3.2, 11.2 | **The node is presence-only; the demuxer decides Dolby Vision, and MKV gets it from 10.3.** (a) `StarfishMediaAPIs::parseLoadMessage` (5.5.0 `libplayerAPIs` `51d91f5b` ref 0x3f2f6 and `starfish-media-pipeline` `9b122b13` ref 0x3ca9e; 5.6.2 `libplayerAPIs` `6a6f072d`, store 0x3f308) reads `option.externalStreamingInfo.contents.DolbyHdrInfo` only for existence and sets hdrType to DolbyVision (`hdr+4 = 2`). From then on `updateHdrInfo` drops later HdrInfo from the pipeline. It also passes `isDolbyVision` to `ResourceManager::acquireResources` (effect not determined), and on 9.x-11.x sends `setAppCloseInfo` with `hdrType` DolbyVision. `profileId`/`trackType` are read only by libpf `CustomPipeline::parseOptionStringSpi` (Feed). (b) LG `qtdemux` writes `dolby-vision=TRUE`/`dolby-vision-profile` from `dvcC`/`dvvC` when `platformSupportDolbyVision` is set, on every image read (5.5.0 `libgstisomp4` `a7272ce2` 0xd108; 5.6.2 `48df5a28` FUN_0001d108); from 5.5.0 on, a profile 7 file gets no DV caps. (c) `matroskademux` has no Dolby Vision code before 10.3. On 5.5.0 (`c68f381f`) and 5.6.2 (`60a0941b`, the same code) `gst_matroska_demux_parse_stream` (0x10548) skips every BlockAdditionMapping id as an unknown TrackEntry child. 6.5.3 (`9a6bd2f7`), 7.6.0 (`12966041`) and 9.2.4 (`07cfe1ee`) read the same way, and a constant scan of 19 builds from W16 to W24 finds no `dvcC`/`dvvC`. 10.3.1/10.3.2 (`54a03ad3`) parses BlockAdditionMapping, matches `dvcC`/`dvvC` as constants (0x12ab2), and writes `dolby-vision`/`dolby-vision-profile` caps (0x1616c/0x16186) when the `dolby-vision-support` smart property is set; profile 7 plays as HDR10. 11.2 carries the same code (scan). (d) On 5.6.2 no userspace element finds Dolby Vision from the HEVC stream: `lxvideodec`/`dvbin` (`6df64857`) never inspect NAL 62/63, h265parse (`25425376`) acts on NAL 62 only when its input caps already carry `dolby-vision`, and `gst_h265_parser_parse_dv_rpu` (`libgstcodecparsers` `696f79c4`) has no caller. The 5.6.2 CX row's Profile 8.6 MKV badge with no node is therefore **not explained by userspace**; the kernel VDEC / `libkadaptor` DOVI backend (driven by V4L2 events from `/dev/video240`) is a lead that cannot be read from the image. The `hdrType` the app's `videoInfo` reported during that play would tell the two apart; it was not recorded. (e) On 5.5.0-19 `dvbin` (rank 291) builds `dvsplitter` (`0cda1717`, IDR 19/20 first) for any URI stream that carries DV caps, with or without the node; on 6.5.3-47 `dvbin` builds no splitter. Not determined: `libcbe.so`, kernel-side RPU detection. Addresses are file VAs (Ghidra's are +0x10000). | | webOS 3.x | unpacked images | no `libSDL2` at all; out of scope. | ## What the 5+ firmware actually does with the load From d4e14102b69820a53848277e3294a677be713b2e Mon Sep 17 00:00:00 2001 From: Tiago Pereira <1698241+tiper@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:15:46 +0000 Subject: [PATCH 18/26] Item menu: Go to Movie keeps the card's focus while the menu closes (#1473) --- rust-modules/ui/src/containers/mod.rs | 14 ++++++++++---- rust-modules/ui/src/containers/tests.rs | 21 +++++++++++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/rust-modules/ui/src/containers/mod.rs b/rust-modules/ui/src/containers/mod.rs index 67fce7ba25..655ba12288 100644 --- a/rust-modules/ui/src/containers/mod.rs +++ b/rust-modules/ui/src/containers/mod.rs @@ -248,10 +248,16 @@ impl Navigation { /// routing performed here cannot drift. pub fn request(&mut self, op: NavOp, ret: ReturnState) -> Vec> { if self.moves_page(&op) { - let ret = if let Some(InputOwner::Entry(owner)) = self.modals.input_owner() { - if let Some(e) = self.modals.entry_mut(owner) { e.ret = ret; } - self.top_page().map(|e| e.ret.clone()).unwrap_or_default() - } else { ret }; + // `ret` lands on the page only when it was captured there: a live surface keeps its + // own, and one captured on a surface that has closed since is dropped. + let ret = match self.modals.input_owner() { + Some(InputOwner::Entry(owner)) => { + if let Some(e) = self.modals.entry_mut(owner) { e.ret = ret; } + None + } + _ if ret.focus.is_some_and(|f| self.top_page().map(|e| e.id) != Some(f.entry)) => None, + _ => Some(ret), + }.unwrap_or_else(|| self.top_page().map(|e| e.ret.clone()).unwrap_or_default()); self.tabs.stack.request(op, ret); return Vec::new(); } diff --git a/rust-modules/ui/src/containers/tests.rs b/rust-modules/ui/src/containers/tests.rs index 21a8059afa..f5bb070361 100644 --- a/rust-modules/ui/src/containers/tests.rs +++ b/rust-modules/ui/src/containers/tests.rs @@ -3187,3 +3187,24 @@ fn the_owner_after_dismissals_is_the_page_once_the_surfaces_dismiss_is_parked() assert_eq!(d.nav.input_owner(), Some(InputOwner::Entry(home))); assert_eq!(d.input_owner_after_dismissals(), d.nav.input_owner(), "after the commit the two agree"); } + +/// **A page op parked behind a menu's `Dismiss` keeps the host's return spot.** Go to Movie in the +/// item hold menu parks the menu's `Dismiss`, then the app's `Push`, both captured on the menu's +/// row. The row's key used to reach the host's `ret`, so its `Enter(Restored)` missed and the page +/// ran to its top while the menu closed, and BACK came back to the top instead of the card. +#[test] +fn a_push_parked_behind_a_surfaces_dismiss_keeps_the_hosts_return_spot() { + let (mut d, mut rig, _) = booted(); + let home = d.nav.top_page().unwrap().id; + let card = FocusKey { entry: home, elem: 3 }; + d.set_focus(Some(card)); + let menu = open_modal(&mut d, &mut rig, Style::Compact, 16); + let row = FocusKey { entry: menu, elem: 1 }; + d.set_focus(Some(row)); + assert_eq!(d.nav.entry(home).unwrap().ret.focus, Some(card), "captured at the Present"); + d.request(MachineId::Nav, NavOp::Dismiss(menu)); + d.request(MachineId::Nav, NavOp::Push(FixtureArg::Page(20))); + d.frame(&mut rig, tick(32), vec![], vec![], &mut NoTap); + assert_eq!(d.nav.entry(home).unwrap().ret.focus, Some(card), + "the closing menu's row did not replace the host's return spot"); +} From be456356040d027be415f24d89ccc252180bb3e7 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Sat, 21 Nov 2026 00:13:39 +0300 Subject: [PATCH 19/26] Background reads of an item by rating key send skipRefresh=1 so the server skips its synchronous refresh (#1496) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the app reads an item by rating key in the background, it now sends skipRefresh=1, so PMS skips the synchronous local media agent and analysis refresh it runs by default (docs/plex-openapi.json: skipRefresh defaults to false). Plex Web sends skipRefresh=1 on every re-read by key. - Client::metadata_many always sends it. Every caller is a background read: Home's re-read of a row by the keys it showed, the view-state read-back, the section shelves, the detail chain's batch reads and the person page's roles. - New Client::metadata_background: the detail read's parameters plus skipRefresh=1. The two guid lookups use it (viewstate.rs resolved_guid, stores/watchlist_job.rs). - Client::show_language_prefs's first read sends it. - Unchanged on the wire: the detail page's own reads, the play-time read, the trailer reads, and the re-read after the viewer's own subtitle write (subsearch.rs subtitle_rows), which compares streams before and after the install. - ci/plex-requests.ini classes metadata_background; docs/pms-api.md §4 gains "Reads by key — skipRefresh"; docs/plex-api-catalog.md and docs/watchlist.md say which reads send it. Part of #1458 (Home rows slow over a remote link while the server streamed "item processed" notifications). Closes #1458 --- ci/plex-requests.ini | 5 + docs/plex-api-catalog.md | 2 +- docs/pms-api.md | 14 +++ docs/watchlist.md | 2 +- rust-modules/data/src/person.rs | 8 +- rust-modules/data/src/stores/watchlist.rs | 2 +- rust-modules/data/src/stores/watchlist_job.rs | 2 +- rust-modules/data/src/subsearch.rs | 2 + rust-modules/data/src/viewstate.rs | 5 +- rust-modules/data/src/watchlist_guid_tests.rs | 2 +- rust-modules/plex/src/plex/library.rs | 110 +++++++++++++++--- rust-modules/plex/src/plex/models.rs | 2 +- rust-modules/src/app/watchlist.rs | 2 +- rust-modules/src/app/watchlist_press_tests.rs | 2 +- 14 files changed, 131 insertions(+), 29 deletions(-) diff --git a/ci/plex-requests.ini b/ci/plex-requests.ini index b7603060fe..628bc2dc6b 100644 --- a/ci/plex-requests.ini +++ b/ci/plex-requests.ini @@ -179,6 +179,11 @@ class = single reason = One item's full record. evidence = rust-modules/plex/src/plex/library.rs:157 +[library.rs::metadata_background] +class = single +reason = One item's full record, read in the background with skipRefresh=1. +evidence = rust-modules/plex/src/plex/library.rs:261 + [library.rs::metadata_many] class = whole reason = One row per requested key, read in one response; the caller chooses the key list, and a Home row's ledger re-reads a window of at most 24 keys through it. diff --git a/docs/plex-api-catalog.md b/docs/plex-api-catalog.md index a398675ac6..2ef9f57a3b 100644 --- a/docs/plex-api-catalog.md +++ b/docs/plex-api-catalog.md @@ -149,7 +149,7 @@ and `Directory[].key` — **confirmed** (Directory items are `librarySection`, n | name | in | required | type | note | |---|---|---|---|---| | `ids` | path | yes | **array** (CSV) | app passes a single id — a valid singleton | - | `checkFiles`, `skipRefresh`, `asyncCheckFiles`, `includeElements`, … | query | no | integer(0/1) | optional; app sends none | + | `checkFiles`, `skipRefresh`, `asyncCheckFiles`, `includeElements`, … | query | no | integer(0/1) | optional; the detail read sends none (background reads by key send `skipRefresh=1`: `docs/pms-api.md`, "Reads by key") | - **Response:** `mediaContainerWithMetadata` → `MediaContainer.Metadata[]` (app reads `[0]`). - **App reads (detail):** title/year/contentRating/summary/tagline/studio/ diff --git a/docs/pms-api.md b/docs/pms-api.md index 4dc8893de5..ef644df850 100644 --- a/docs/pms-api.md +++ b/docs/pms-api.md @@ -999,6 +999,20 @@ GET /library/metadata/{rk}?includeMarkers=1&includeChapters=1 playhead routinely stops short of — treat it as open-ended rather than exclusive, or an end-of-item prompt blinks out over the last frames. +### Reads by key — `skipRefresh` (the spec, and timed on one PMS) + +`plex-openapi.json` describes `skipRefresh=1` on `GET /library/metadata/{ids}` as skipping the synchronous +local media agent and analysis refresh, which the default (false) runs. This client's background reads by +key (`plex::Client::metadata_many`, which a Home row re-read, a hub or listing page's batch, the +view-state read-back after Mark Watched or a stopped play and a person's filmography go through, +`Client::metadata_background`, and the `includePreferences=1` show-preferences read of every episode play) +send `skipRefresh=1`; the preferences read still returns the same `Preferences` with it (3 shows on one +PMS). The detail read (`Client::metadata`), which a viewer opened, sends none. Plex Web 4.162.1 sends `skipRefresh=1` on its +re-reads by key and never takes the refresh. On one household PMS the first batch read without it took 138 +to 948 ms in four of five sets, and no read with it was slow; a field log over a remote link read 4 to 9 s +per Home row, with a timeline "item processed" notification about once a second while Home scrolled +(issue #1458). + ### Up Next — the `continuous=1` PlayQueue already carries it (verified live 2026-07-29) There is no "what plays next" endpoint to call: the `POST /playQueues?continuous=1` the app makes diff --git a/docs/watchlist.md b/docs/watchlist.md index 05ecdb9bd1..20d57fdcb0 100644 --- a/docs/watchlist.md +++ b/docs/watchlist.md @@ -125,7 +125,7 @@ copy a tile opens is chosen current server first, then owned, then shared, Reach **The other direction.** A `PmsMovie` carries `guid` and `show_guid` (an episode's `grandparentGuid`, a season's `parentGuid`: the server sends a season no `grandparentGuid`), each decoded once to `[u8; 12]`. The Detail and Home hero discs and the hold-menu rows use them to name the catalog id. `resolve_catalog_hex(known, fetch)` (`plex/models.rs`) is the helper for a row that lacks one: it -fetches `client.metadata(rk or show_rk).guid` only when the id is not already known. A hold-menu card +fetches `client.metadata_background(rk or show_rk).guid` only when the id is not already known. A hold-menu card whose row carries no guid asks for it (`WatchlistStore::want_hex`, a worker reading the item's own server record, an episode's SHOW record): the menu being opened omits the row, the next one offers it once the record named a portable id (tests in `app/watchlist_press_tests.rs`). The Detail disc reads diff --git a/rust-modules/data/src/person.rs b/rust-modules/data/src/person.rs index a09a7e3980..0f0bb65f38 100644 --- a/rust-modules/data/src/person.rs +++ b/rust-modules/data/src/person.rs @@ -4354,8 +4354,10 @@ fn sync_roster(&mut self) -> bool { owner.close(); } - /// Ten credits are one request, and it is the request the store made before chunking existed: - /// the same single `/library/metadata/{csv}` URL, the same keys in the same order. + /// Ten credits are one request, and its path is the one the store sent before chunking existed: + /// the same single `/library/metadata/{csv}`, the same keys in the same order. (The query behind + /// it has since gained `skipRefresh=1`, which this test does not pin: `plx_plex`'s + /// `skip_refresh_a_batched_read_…` does.) #[test] fn ten_credits_make_exactly_one_request_as_before() { let _g = plx_base::testlock::serial(); @@ -4372,7 +4374,7 @@ fn sync_roster(&mut self) -> bool { let csv: Vec = (0..10).map(|i| i.to_string()).collect(); assert!( paths[0].starts_with(&format!("/library/metadata/{}?", csv.join(","))), - "the single request is not today's: {}", + "the single request's path is not the pre-chunking one: {}", paths[0] ); let p = owner.current().unwrap(); diff --git a/rust-modules/data/src/stores/watchlist.rs b/rust-modules/data/src/stores/watchlist.rs index 853da1300e..39bfc75cd8 100644 --- a/rust-modules/data/src/stores/watchlist.rs +++ b/rust-modules/data/src/stores/watchlist.rs @@ -1062,7 +1062,7 @@ pub fn rematch_on(&mut self, sid: ServerId, asks: Vec<(String, Kind)>) -> bool { } /// A card row carried no catalog id: ask for it to be read off the item's own server record - /// (`client.metadata(rk).guid`, on a worker, at the next pump). Idempotent per `(server, rk)`. + /// (`client.metadata_background(rk).guid`, on a worker, at the next pump). Idempotent per `(server, rk)`. /// The answer is [`WatchlistView::resolved_hex`]; a menu opened after it lands offers the row. pub fn want_hex(&self, sid: ServerId, rk: &str) { let key = (sid, rk.to_owned()); diff --git a/rust-modules/data/src/stores/watchlist_job.rs b/rust-modules/data/src/stores/watchlist_job.rs index 574e3575f7..7c20e10cc5 100644 --- a/rust-modules/data/src/stores/watchlist_job.rs +++ b/rust-modules/data/src/stores/watchlist_job.rs @@ -96,7 +96,7 @@ pub fn finish_resolve_job(port: &ResolvePort, addr: Addr, req: ResolveReq, lookup: fn(ServerId) -> Option<&'static Client>) { let end = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let clients = KeyedClients::new(&req.keys, lookup); - let guid = clients.client(req.sid).and_then(|client| client.metadata(&req.rk)).map(|m| m.guid); + let guid = clients.client(req.sid).and_then(|client| client.metadata_background(&req.rk)).map(|m| m.guid); ResolveEnd::Answer(guid.map(|g| plx_plex::plex::resolve_catalog_hex(None, || Some(g)))) })).unwrap_or(ResolveEnd::Panicked); port.done(addr, end); diff --git a/rust-modules/data/src/subsearch.rs b/rust-modules/data/src/subsearch.rs index e46440c46f..cef758e638 100644 --- a/rust-modules/data/src/subsearch.rs +++ b/rust-modules/data/src/subsearch.rs @@ -610,6 +610,8 @@ fn run_job(client: &'static Client, rk: &str, work: Work) -> Landing { } /// The item's subtitle streams across every Media/Part, or `None` when the read failed. +/// Not `Client::metadata_background`: this read follows the viewer's own subtitle write, and whether a +/// skipped refresh could hide the stream that write just installed has not been measured. fn subtitle_rows(client: &Client, rk: &str) -> Option> { let item = client.metadata(rk)?; Some(item.media.iter().flat_map(|m| &m.part).flat_map(|p| &p.stream) diff --git a/rust-modules/data/src/viewstate.rs b/rust-modules/data/src/viewstate.rs index ad36fb482e..86caf1d3a8 100644 --- a/rust-modules/data/src/viewstate.rs +++ b/rust-modules/data/src/viewstate.rs @@ -1236,7 +1236,8 @@ fn fan_out( /// WORKER. The guid to fan out on: the one the press carried, or — when it carried none, which is /// every press from a Home / Library / Search card menu, since a catalog row (`pms::PmsMovie`) does -/// not hold one — the item's own record, read off its own server. +/// not hold one — the item's own record, read off its own server (`Client::metadata_background`: the +/// press needs a guid, not a refreshed record). /// /// The lookup is what makes the "resolve at write time" rule hold: the fan-out must not require a /// prior detail-page visit, because a card menu is a place no cross-source resolve has ever run. It @@ -1247,7 +1248,7 @@ fn resolved_guid(c: &plx_plex::plex::Client, rk: &str, given: &str) -> Option Option { if show_rk.is_empty() || !show_rk.bytes().all(|b| b.is_ascii_digit()) { return None; // a key is server data: only ever a plain ratingKey } - let path = QueryBuilder::new(format!("/library/metadata/{show_rk}")) - .int("includePreferences", 1) - .build(); + let path = show_language_prefs_path(show_rk); let deadline = std::time::Instant::now() + std::time::Duration::from_millis(1500); let read = |path: &str| match self.get_json_with_headers_until(path, &[], deadline) { super::client::JsonDeadlineOutcome::Response { parsed, .. } => parsed, @@ -240,13 +243,23 @@ impl Client { /// only show-level answer to "what's next": the client otherwise holds ONE season's episodes at a /// time, so anything it computed itself would change with the selected season tab. Verified live /// 2026-07-30 on rk 437 → S2E2 at 635510/3130720 while season 1 was the loaded tab. + /// + /// This is the read of an item the viewer opened or is about to play, so it sends no `skipRefresh` + /// and PMS runs its usual synchronous refresh of the item. The detail page's own reads (the item, its + /// trailer and its on-deck episode, including the re-read after a read-back), the play-time read and + /// the re-read after the viewer's own subtitle write use it; a background lookup of the record the + /// viewer did not open, such as a guid, goes through [`Client::metadata_background`] instead. pub fn metadata(&self, rating_key: &str) -> Option { - let path = QueryBuilder::new(format!("/library/metadata/{rating_key}")) - .int("includeChapters", 1) - .int("includeMarkers", 1) - .int("includeOnDeck", 1) - .build(); - self.get_json(&path)?.metadata.into_iter().next() + self.get_json(&metadata_path(rating_key, false))?.metadata.into_iter().next() + } + + /// [`Client::metadata`]'s read for a caller the viewer did not ask for: a guid looked up while a + /// press is being served, an item read again to find out what it carries. The same parameters, plus + /// `skipRefresh=1`: the spec's default (false) has PMS run its synchronous local media agent and + /// analysis refresh on every `GET /library/metadata/{id}`, and a read that wants only the record + /// as the server holds it should not pay for that on a remote link (`docs/pms-api.md`, "skipRefresh"). + pub fn metadata_background(&self, rating_key: &str) -> Option { + self.get_json(&metadata_path(rating_key, true))?.metadata.into_iter().next() } /// GET /library/metadata/{rating_key}/extras → clip rows (`subtype` trailer / behindTheScenes / …). @@ -274,15 +287,15 @@ impl Client { /// module passes in. (The server silently KEEPS `Image`, `UltraBlurColors` and `Field` whatever /// you ask, so they are not listed — naming them would just read as if they went.) /// + /// **Always `skipRefresh=1`.** Every caller is a background read, on a worker the viewer is not + /// waiting behind, and never the item a viewer opened: a listing's keys read again, or the view-state + /// read-back after Mark Watched or a stopped play. The spec's default (false) has PMS run its + /// synchronous local media agent and analysis refresh on a `GET /library/metadata/{ids}`, which a + /// field log on a remote link read as 4 to 9 s per Home row (`docs/pms-api.md`, "skipRefresh"). + /// /// Absent from `docs/plex-openapi.json`, which documents only the single-key form. pub fn metadata_many(&self, rating_keys: &[&str]) -> Option { - const EXCLUDE_ELEMENTS: &str = - "Media,Genre,Country,Collection,Director,Writer,Producer,Similar,Chapter,Marker,Guid,Rating,Review,Extras"; - let path = QueryBuilder::new(format!("/library/metadata/{}", rating_keys.join(","))) - .str("excludeElements", EXCLUDE_ELEMENTS) - .str("excludeFields", "summary,tagline") - .build(); - self.get_json(&path) + self.get_json(&metadata_many_path(rating_keys)) } /// GET /library/metadata/{rating_key}/children (D-5 undocumented but real) → `.metadata[]`. @@ -422,6 +435,39 @@ impl Client { } } +/// The path of [`Client::metadata`] (`skip_refresh` false, the detail read) and of +/// [`Client::metadata_background`] (`skip_refresh` true): one item with its chapters, markers and +/// on-deck episode. `skipRefresh=1` is the only difference between the two. +fn metadata_path(rating_key: &str, skip_refresh: bool) -> String { + QueryBuilder::new(format!("/library/metadata/{rating_key}")) + .int("includeChapters", 1) + .int("includeMarkers", 1) + .int("includeOnDeck", 1) + .opt_int("skipRefresh", i64::from(skip_refresh)) + .build() +} + +/// The path of [`Client::show_language_prefs`]'s first read: the show with its `Preferences`. A +/// background read, so it carries `skipRefresh=1`. +fn show_language_prefs_path(show_rk: &str) -> String { + QueryBuilder::new(format!("/library/metadata/{show_rk}")) + .int("includePreferences", 1) + .int("skipRefresh", 1) + .build() +} + +/// The path of [`Client::metadata_many`]: the CSV of keys, trimmed to the tag arrays. Every caller is a +/// background read and never the item a viewer opened, so it always carries `skipRefresh=1`. +fn metadata_many_path(rating_keys: &[&str]) -> String { + const EXCLUDE_ELEMENTS: &str = + "Media,Genre,Country,Collection,Director,Writer,Producer,Similar,Chapter,Marker,Guid,Rating,Review,Extras"; + QueryBuilder::new(format!("/library/metadata/{}", rating_keys.join(","))) + .str("excludeElements", EXCLUDE_ELEMENTS) + .str("excludeFields", "summary,tagline") + .int("skipRefresh", 1) + .build() +} + /// The request paths `find_by_guids` issues: only `plex://` guids, de-duplicated in order, in /// chunks of at most [`GUIDS_PER_REQUEST`]. Each guid is percent-encoded on its own and the chunk is /// joined with a literal `,` — the one separator PMS splits the `guid` param on (measured, @@ -559,6 +605,38 @@ mod tests { pairs.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect() } + /// `skipRefresh` is how a background read tells PMS not to run its synchronous refresh (the spec's + /// default does), so the batched read of many keys and the background single-key read both carry + /// it, with the batched read's trims kept; the detail read, which a viewer asked for, does not. + #[test] + fn skip_refresh_a_batched_read_asks_the_server_not_to_refresh() { + assert_eq!( + metadata_many_path(&["12", "34"]), + "/library/metadata/12,34\ + ?excludeElements=Media%2CGenre%2CCountry%2CCollection%2CDirector%2CWriter%2CProducer%2CSimilar\ + %2CChapter%2CMarker%2CGuid%2CRating%2CReview%2CExtras\ + &excludeFields=summary%2Ctagline&skipRefresh=1"); + } + + #[test] + fn skip_refresh_a_background_single_read_asks_the_server_not_to_refresh() { + assert_eq!( + metadata_path("12", true), + "/library/metadata/12?includeChapters=1&includeMarkers=1&includeOnDeck=1&skipRefresh=1"); + } + + #[test] + fn skip_refresh_the_detail_read_does_not_carry_it() { + assert_eq!(metadata_path("12", false), "/library/metadata/12?includeChapters=1&includeMarkers=1&includeOnDeck=1"); + } + + /// The show's language-settings read runs on every episode play and the viewer never opened that + /// record, so it is a background read and carries `skipRefresh=1` like the others. + #[test] + fn skip_refresh_the_show_preferences_read_asks_the_server_not_to_refresh() { + assert_eq!(show_language_prefs_path("42"), "/library/metadata/42?includePreferences=1&skipRefresh=1"); + } + /// A directory read without terms is byte-identical to what it always was, and the terms /// follow in the order given, as `/all` sends them. #[test] diff --git a/rust-modules/plex/src/plex/models.rs b/rust-modules/plex/src/plex/models.rs index 29339b4c7d..33cbbef732 100644 --- a/rust-modules/plex/src/plex/models.rs +++ b/rust-modules/plex/src/plex/models.rs @@ -503,7 +503,7 @@ pub fn catalog_hex_of_guid(guid: &str) -> Option<[u8; 12]> { } /// WORKER. The catalog id to write to: the one the row already carries, else the one the item's own -/// server record names. `fetch` is `|| client.metadata(rk).map(|m| m.guid)` (or `grandparent`'s +/// server record names. `fetch` is `|| client.metadata_background(rk).map(|m| m.guid)` (or `grandparent`'s /// `show_rk` read for an episode's show); it is not called when `known` is set, so a press from a /// row that was decoded with its guid costs no round trip. `None` is a server that did not answer /// or an item with no `plex://movie|show` identity. diff --git a/rust-modules/src/app/watchlist.rs b/rust-modules/src/app/watchlist.rs index 9a5bd2ad60..0011a7c314 100644 --- a/rust-modules/src/app/watchlist.rs +++ b/rust-modules/src/app/watchlist.rs @@ -444,7 +444,7 @@ impl Bridge<'_> { /// show (`from_episode` makes the labels say "Show"). /// /// A row that carries no catalog id is resolved through its own server record - /// (`client.metadata(rk or show_rk).guid`, `WatchlistStore::want_hex`): the read is asked for + /// (`client.metadata_background(rk or show_rk).guid`, `WatchlistStore::want_hex`): the read is asked for /// here and runs on a worker, so the menu being opened now omits the row and the next one /// offers it. A server that did not answer, or an item with no portable id, never does. pub(crate) fn watchlist_card_face( diff --git a/rust-modules/src/app/watchlist_press_tests.rs b/rust-modules/src/app/watchlist_press_tests.rs index d381fa9fe7..df185fcd43 100644 --- a/rust-modules/src/app/watchlist_press_tests.rs +++ b/rust-modules/src/app/watchlist_press_tests.rs @@ -487,7 +487,7 @@ fn the_catalog_status_follows_the_tile_state_and_moves_when_it_does() { } /// A card row that carries no catalog id is resolved through its own server record -/// (`client.metadata(rk or show_rk).guid`): the menu opened first omits the row and asks, the next +/// (`client.metadata_background(rk or show_rk).guid`): the menu opened first omits the row and asks, the next /// one offers it, and its press ends in the write for the RESOLVED id. #[test] fn watchlist_write_live_and_held_finish_in_the_emitting_drain_and_cancel_queued() { From c43ce654df71971070530fb26225477069b2133f Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Sat, 21 Nov 2026 00:32:32 +0300 Subject: [PATCH 20/26] A server's library entries refresh its lists once its feed goes quiet, not every 5 s (#1497) A server's library notifications now refresh its lists once, after its notification feed has gone quiet, instead of every 5 s for as long as entries keep coming. The #1458 reporter's server sent about one "item processed" entry per second while they scrolled Home; each entry owed a quiet Home refetch, a section-shelf invalidate, a re-list and a Watchlist re-match, and over their remote link the app kept re-reading Home, the shelves and the grids, so every row they scrolled to queued behind those reads. - data/src/stores/notify_map.rs: each server's library entries start one Settling { first, last, entries } wait. It ends after 10 s with no entry for that server (LIBRARY_QUIET_FRAMES) or 60 s after the oldest unspent entry (LIBRARY_LONGEST_WAIT_FRAMES), so a feed that never goes quiet still refreshes about once a minute. Its end owes the refetch, the invalidate and the re-list once and logs "notify: library settled sid= entries= waited=". - The Watchlist re-match waits for the same quiet. LibraryOwed's sweep flag becomes Sweep { No, AfterQuiet, Now }: only a feed gap's sweep (Now) skips the wait; a delete during the first Watchlist read sweeps its kind after the quiet. An owe whose wait has ended but which the store could not start that frame (another re-match or a list read out) is marked wait_over and starts as soon as it can, not held again by the wait the feed's next entry begins. - The listings spacing (listings_next) is removed: a re-list is owed only when a wait ends, and two waits of one server end at least 10 s apart. - Unchanged: held-item read-backs, a stop's quiet refetch and invalidate (never held by a library wait), the resync sweep, reread_allowed gating and the downstream 5 s spacings in pms.rs and browse/section_hubs.rs. - Docs: the module doc, docs/pms-api.md and docs/watchlist.md describe the new timing; tests/scenarios/watchlist_captures.json's library-add capture sleeps 14 s. Closes #1458 --- docs/pms-api.md | 18 +- docs/watchlist.md | 6 +- rust-modules/data/src/stores/notify_map.rs | 225 ++++++++--- .../data/src/stores/notify_map_tests.rs | 359 ++++++++++++++++-- rust-modules/data/src/stores/watchlist.rs | 16 +- .../src/app/browse_hubs_drain_tests.rs | 16 +- tests/scenarios/watchlist_captures.json | 4 +- 7 files changed, 540 insertions(+), 104 deletions(-) diff --git a/docs/pms-api.md b/docs/pms-api.md index ef644df850..fb1ea04393 100644 --- a/docs/pms-api.md +++ b/docs/pms-api.md @@ -1746,13 +1746,21 @@ What a hint does for the Watchlist: a session on a matched title that the page h any held card. A `timeline` create or delete does not read the item: it owes the Watchlist store ONE re-match of that server and kind (a delete of the item a tile is matched to asks again about that guid, a create asks again about the kind's titles the server was not seen to hold, `/library/all?type=T&guid=…` at 40 guids to a -request), deduplicated per pump, at most once per quiet-refetch spacing (5 s) per server and kind, only once -the Watchlist has loaded and only when `reread_allowed`; it stays queued otherwise. A feed that came back +request), deduplicated per server and kind, only once the Watchlist has loaded and only when `reread_allowed` +(it stays queued otherwise). A feed that came back after a gap re-asks the server's titles whole. The tile flips when the answer lands (`docs/watchlist.md`, *Live-update gaps*). The same create or delete also moves that server's lists: one quiet Home refetch -and one section-shelf invalidate (spaced like a `stopped`'s), and one `BrowseCmd::ListingsChanged` for its -library listings, at most once per quiet-refetch spacing per server (a change inside it stays owed and is -spent when due). PMS sends the same `finished` frame for a refreshed item as for a new one, so the open grid +and one section-shelf invalidate (coalesced like a `stopped`'s), and one `BrowseCmd::ListingsChanged` for its +library listings. **None of these four (the re-match, the refetch, the invalidate and the re-list) is made +when the entry arrives.** A scan delivers about one finished entry a second for minutes, and over a remote +link one row read takes seconds, so re-reading on each entry kept every read the viewer scrolled to stuck in +a queue (#1458). A server's entries wait for ITS feed to go quiet: the four are made once, when no library +entry for that server has arrived for 10 s (`LIBRARY_QUIET_FRAMES`) or when 60 s +(`LIBRARY_LONGEST_WAIT_FRAMES`) have passed since the oldest entry not yet spent, so a feed that never goes +quiet still refreshes about once a minute; the next entry starts a new wait. The wait is counted in pumped frames and holds only library entries: a `stopped` session's +refetch and invalidate, a feed gap's sweep and the read-backs above are not waited on, and the spacings +downstream (5 s per quiet refetch, per section shelf and per re-match) still apply. +PMS sends the same `finished` frame for a refreshed item as for a new one, so the open grid is never listed again while it is visible: it is marked stale, as a read-back that moves a row's membership marks it, and re-queried keeping the reader's place when a page covers it (at once when no Library page is on the navigation stack). The server's other sections forget their pages and fetch afresh on their next diff --git a/docs/watchlist.md b/docs/watchlist.md index 20d57fdcb0..d05f14b15c 100644 --- a/docs/watchlist.md +++ b/docs/watchlist.md @@ -326,8 +326,10 @@ What the PMS notification feed (`docs/pms-api.md` section 9) does and does not c `filters=playing,timeline`; a finished movie or show create or delete (`TimelineEntry` state 5 with no `metadataState`, and state 9, which is UNVERIFIED: no delete has been captured) owes the Watchlist one re-match of that server (`stores::notify_map`, plan §1.11 B(a)): a delete of the item a tile is matched to asks again about that guid, a create asks again about the - titles of that kind the server was not seen to hold (40 guids to a request). It is made at most once - per quiet-refetch spacing per server and kind, only once the list has loaded and only when a re-read + titles of that kind the server was not seen to hold (40 guids to a request). It is made once the + server's feed has gone quiet (no library entry for 10 s, or 60 s since the oldest unspent one, so a + scan that never stops still refreshes about once a minute; #1458), at most once per quiet-refetch + spacing per server and kind, only once the list has loaded and only when a re-read is allowed, and the tile flips when the answer lands, with the page open or not. A feed that came back after a gap re-asks the server's titles whole. The `timeline` frame shape was captured from an owned server (`docs/pms-api.md` section 9, with the measured frame rates); this path is tested against frames diff --git a/rust-modules/data/src/stores/notify_map.rs b/rust-modules/data/src/stores/notify_map.rs index f1b2dd1b4d..9c86461fb1 100644 --- a/rust-modules/data/src/stores/notify_map.rs +++ b/rust-modules/data/src/stores/notify_map.rs @@ -23,25 +23,43 @@ //! a Detail the viewer is looking at is not re-fetched for the sake of a card beneath it. The Detail //! itself is never touched here; only its landed read-back reaches it. //! +//! **Library changes wait for the feed to go quiet** (#1458). A server's finished library entries +//! ([`NotifyLibrary`]) owe four things: one quiet Home refetch of that server, one section-shelf +//! invalidate for it, one `BrowseCmd::ListingsChanged` for its library listings and one Watchlist +//! re-match. None is made when the entry arrives. A scan or a bulk add delivers about one finished +//! entry a second for minutes, and over a remote link one row read takes seconds, so re-reading +//! on every entry kept every read the viewer scrolled to stuck in a queue behind them. The owe is +//! made ONCE, when either no entry for that server has arrived for [`LIBRARY_QUIET_FRAMES`] (10 s), or +//! [`LIBRARY_LONGEST_WAIT_FRAMES`] (60 s) have passed since the oldest entry not yet spent, so a +//! feed that never goes quiet still refreshes about once a minute. After that the next entry starts a +//! new wait. The wait is one `Settling` value per server; it is where the three server-list owes wait, +//! and nothing else waits there, so a `stopped` session's refetch and invalidate (above) are never +//! held by it. A feed gap's sweep and the `playing`/`stopped` path are not waited on, and the +//! spacings downstream (the quiet refetch's and the section shelves', `pms::QUIET_SPACING_S`) still +//! apply. Two waits of one server end at least [`LIBRARY_QUIET_FRAMES`] apart, so no spacing of its +//! own is kept between its re-lists. +//! //! **Library changes follow the Watchlist** (plan §1.11). A finished movie or show created or -//! deleted on a server ([`NotifyLibrary`]) owes the Watchlist store one re-match of that server: a -//! DELETE of an item a tile is matched to asks again about that guid, a create asks again about the -//! titles of that kind the server was not seen to hold, in chunks of `GUIDS_PER_REQUEST`. The owe is -//! one per `(server, kind)` however many entries arrive, is made at most once per -//! [`LIBRARY_SPACING_FRAMES`] (the quiet-refetch spacing), waits for the Watchlist to have loaded +//! deleted on a server owes the Watchlist store one re-match of that server: a DELETE of the item a +//! tile is matched to asks again about that guid, a create asks again about the titles of that kind +//! the server was not seen to hold, in chunks of `GUIDS_PER_REQUEST`. The owe is one per +//! `(server, kind)` however many entries arrive, is made when the server's wait above is over and at +//! most once per [`LIBRARY_SPACING_FRAMES`] (the quiet-refetch spacing, which a feed gap's sweep right +//! after a re-match can still meet), waits for the Watchlist to have loaded //! (the first read matches the library as it is then: a change that arrives while the list is not //! ready and no read is out is dropped, since the read that follows asks after it; one that arrives //! while the first read is out is kept, since that read's matching may already have asked) and is made through the store's own -//! worker; the tile flips when the answer lands, through the same §1.5 derivation as any +//! worker. A delete kept that way cannot be followed to a tile, so it asks again about every title of +//! the kind, but it waits for its server's quiet like any other entry: only a feed gap's sweep skips +//! the wait. The tile flips when the answer lands, through the same §1.5 derivation as any //! re-match. //! -//! **Library changes also move the server's lists.** The same entries owe that server one quiet -//! Home refetch and one section-shelf invalidate (coalesced and spaced like a `stopped`'s), and its -//! library listings one `BrowseCmd::ListingsChanged`, spent at most once per -//! [`LIBRARY_SPACING_FRAMES`] per server (a change inside the spacing stays owed, coalesced, until -//! it is due). The open grid keeps its rows while a replacement wanted window is read, then -//! swaps in place. A change during that read owes one more re-list. The server's other sections, -//! and a section left while a re-list is outstanding, forget their pages. +//! **Library changes also move the server's lists.** When the wait is over the server's Home source +//! is refetched quietly once and its section shelves are invalidated once (coalesced, as a `stopped`'s +//! are), and its library listings are told once (`BrowseCmd::ListingsChanged`). The open grid keeps +//! its rows while a replacement wanted window is read, then swaps in place. A change during that +//! read owes one more re-list. The server's other sections, and a section left while a re-list is +//! outstanding, forget their pages. //! //! **Owed work is spent only when [`Stores::reread_allowed`]** (not under the player, not while a //! recording or replay is armed). Until then it is queued, not dropped, and coalesced. @@ -67,6 +85,15 @@ pub const MAX_SESSIONS: usize = 64; /// quiet-refetch spacing of a Home source (`pms::QUIET_SPACING_S`). pub const LIBRARY_SPACING_FRAMES: u64 = crate::pms::QUIET_SPACING_S as u64 * FRAMES_PER_S; +/// How long a server's feed must have been free of library entries before the refreshes those +/// entries owe are made, in pumped frames: 10 s. +pub const LIBRARY_QUIET_FRAMES: u64 = 10 * FRAMES_PER_S; + +/// The longest the refreshes library entries owe are held back, counted from the oldest entry not +/// yet spent, in pumped frames: 60 s. A feed that never goes quiet (a scan, or a bulk add) +/// still refreshes the server's lists about once a minute. +pub const LIBRARY_LONGEST_WAIT_FRAMES: u64 = 60 * FRAMES_PER_S; + type Key = (ServerId, String); /// Sessions whose state CHANGED this pump (what `observe` accepted), by state. A steady `playing` @@ -121,7 +148,8 @@ struct Owed { reads: Vec<(Key, bool)>, refetch: Vec, invalidate: Vec, - /// Servers whose library listings are out of date (`BrowseCmd::ListingsChanged`). + /// Servers whose library listings are out of date (`BrowseCmd::ListingsChanged`): the servers + /// whose library wait has ended. listings: Vec, } @@ -156,9 +184,61 @@ struct LibraryOwed { gone: Vec, /// An item was created: ask again about every title the server was not seen to hold. added: bool, - /// The exact change was not followed (the Watchlist had not loaded, or the feed had a gap): - /// ask again about every title of the kind. - sweep: bool, + /// Whether every title of the kind is asked again, because the exact change was not followed, and + /// whether that waits for the server's quiet. + sweep: Sweep, + /// The server's wait that this owe was held for has ended ([`NotifyMap::library_wait_over`], from + /// `release_settled_library`, and nowhere else). The owe then needs no later wait: a re-match the + /// store could not start that frame (another re-match or a list read is out) stays queued and is + /// made as soon as it can, not held again behind the wait the feed's next entry starts, which a + /// feed that never goes quiet would stretch to a minute a time. An entry that merges into an owe + /// already marked rides the re-match that is already due: what a re-match asks is worked out + /// when it starts, so it covers that entry too. + wait_over: bool, +} + +impl LibraryOwed { + /// Ask after every title of the kind, at least as eagerly as `how`. + fn sweep_to(&mut self, how: Sweep) { + self.sweep = self.sweep.max(how); + } +} + +/// How a `(server, kind)` owes the Watchlist a re-match of every title of the kind. The variants are in +/// the order of urgency, so two reasons to sweep merge into the more urgent one. +#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)] +enum Sweep { + /// The owe asks only about what the entries named (`gone`, `added`). + #[default] + No, + /// A delete could not be followed to a tile (the Watchlist had not loaded): the entries are still + /// waited for like any other library change, and the sweep is made at the server's quiet. + AfterQuiet, + /// The feed had a gap, so the exact changes were missed: made at once, not held for the wait. + Now, +} + +/// A server's finished library entries that have not been spent, waiting for its feed to go quiet. +/// The server has a value here only while it waits (there is no "idle" flag to forget to clear): it +/// starts with the server's first entry, moves on with each later one and ends when the refreshes +/// the entries owe are spent. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Settling { + /// The frame the oldest entry not yet spent arrived on. + first: u64, + /// The frame the newest one arrived on. + last: u64, + /// How many entries have arrived since `first` (counted for the log). + entries: usize, +} + +impl Settling { + /// Is the wait over at `frame`: the feed has been free of this server's entries for + /// [`LIBRARY_QUIET_FRAMES`], or the oldest has waited [`LIBRARY_LONGEST_WAIT_FRAMES`]? + fn over(&self, frame: u64) -> bool { + frame.saturating_sub(self.last) >= LIBRARY_QUIET_FRAMES + || frame.saturating_sub(self.first) >= LIBRARY_LONGEST_WAIT_FRAMES + } } #[derive(Default)] @@ -166,12 +246,14 @@ pub struct NotifyMap { /// `((server, sessionKey), (ratingKey, state))`, least recently seen first. last_state: Vec<((ServerId, String), (String, PlayState))>, owed: Owed, + /// The library entries each server's feed delivered that are not yet spent. This is the only + /// place the server-list refreshes they owe wait (never in `owed`, which a `stopped` session + /// spends at once), and the Watchlist re-matches below wait with it. + settling: Vec<(ServerId, Settling)>, /// Library re-matches owed to the Watchlist, one per `(server, kind)`. library: Vec<((ServerId, WatchKind), LibraryOwed)>, /// The frame from which a `(server, kind)` may be re-matched again. library_next: Vec<((ServerId, WatchKind), u64)>, - /// The frame from which a server's library listings may be told of a change again. - listings_next: Vec<(ServerId, u64)>, /// Calls of [`Stores::notify_map`] so far: the clock the spacing is counted in. frame: u64, } @@ -182,7 +264,7 @@ impl NotifyMap { } pub fn owed_is_empty(&self) -> bool { - self.owed.is_empty() && self.library.is_empty() + self.owed.is_empty() && self.library.is_empty() && self.settling.is_empty() } /// Forget everything: the identity changed. @@ -232,32 +314,44 @@ impl NotifyMap { &mut self.library[at].1 } - fn library_due(&self, sid: ServerId, kind: WatchKind) -> bool { - self.library_next.iter().find(|(k, _)| *k == (sid, kind)).is_none_or(|(_, at)| self.frame >= *at) + /// `entries` finished library entries of `sid` arrived this pump: start its wait, or move it on. + fn library_arrived(&mut self, sid: ServerId, entries: usize) { + let frame = self.frame; + match self.settling.iter_mut().find(|(s, _)| *s == sid) { + Some((_, wait)) => { + wait.last = frame; + wait.entries = wait.entries.saturating_add(entries); + } + None => self.settling.push((sid, Settling { first: frame, last: frame, entries })), + } } - /// Take the owed work that may be spent now: all of it but the listings of a server still inside - /// its spacing, which stay owed (a change that arrives meanwhile coalesces into them). - fn take_due(&mut self) -> Owed { - let mut owed = std::mem::take(&mut self.owed); - let (frame, next) = (self.frame, &self.listings_next); - let (due, waiting): (Vec<_>, Vec<_>) = owed - .listings - .drain(..) - .partition(|sid| next.iter().find(|(s, _)| s == sid).is_none_or(|(_, at)| frame >= *at)); - owed.listings = due; - self.owed.listings = waiting; - owed + /// Is `sid` still waiting for its feed to go quiet? + fn library_settling(&self, sid: ServerId) -> bool { + self.settling.iter().any(|(s, _)| *s == sid) } - fn listings_spent(&mut self, sid: ServerId) { - let next = self.frame + LIBRARY_SPACING_FRAMES; - match self.listings_next.iter_mut().find(|(s, _)| *s == sid) { - Some((_, at)) => *at = next, - None => self.listings_next.push((sid, next)), + /// `sid`'s wait ended: no re-match it has queued is held for a later wait any more. + fn library_wait_over(&mut self, sid: ServerId) { + for ((s, _), owe) in &mut self.library { + if *s == sid { + owe.wait_over = true; + } } } + /// End and return the waits that are over now; the rest go on. + fn take_settled(&mut self) -> Vec<(ServerId, Settling)> { + let frame = self.frame; + let (over, waiting): (Vec<_>, Vec<_>) = std::mem::take(&mut self.settling).into_iter().partition(|(_, w)| w.over(frame)); + self.settling = waiting; + over + } + + fn library_due(&self, sid: ServerId, kind: WatchKind) -> bool { + self.library_next.iter().find(|(k, _)| *k == (sid, kind)).is_none_or(|(_, at)| self.frame >= *at) + } + fn library_spent(&mut self, sid: ServerId, kind: WatchKind) { let next = self.frame + LIBRARY_SPACING_FRAMES; match self.library_next.iter_mut().find(|(k, _)| *k == (sid, kind)) { @@ -369,17 +463,14 @@ impl Stores { // Whatever the library did during the gap was missed. if self.watchlist.is_ready() { for kind in [WatchKind::Movie, WatchKind::Show] { - self.notify_map.library_owe(*sid, kind).sweep = true; + self.notify_map.library_owe(*sid, kind).sweep_to(Sweep::Now); } } } for library in &out.library { self.owe_library(library); - // The server's lists moved: its Home source, its section shelves and its grids. - let owed = &mut self.notify_map.owed; - owed.refetch(library.sid); - owed.invalidate(library.sid); - push_unique(&mut owed.listings, library.sid); + // The server's lists moved, but they are read once its feed has gone quiet. + self.notify_map.library_arrived(library.sid, library.entries.len()); } if !out.plays.is_empty() { let mut changed = Transitions::default(); @@ -442,7 +533,7 @@ impl Stores { LibraryState::Deleted => { deleted += 1; let Some(held) = &held else { - self.notify_map.library_owe(sid, kind).sweep = true; + self.notify_map.library_owe(sid, kind).sweep_to(Sweep::AfterQuiet); continue; }; let tile = e.item_id.trim().parse::().ok().and_then(|rk| held.get(&rk)); @@ -461,18 +552,25 @@ impl Stores { )); } - /// Spend the library re-matches that are due: the Watchlist has loaded, the `(server, kind)` is - /// outside its spacing and the store could start its worker. Anything else stays queued. + /// Spend the library re-matches that are due: the server's feed has gone quiet, the Watchlist has + /// loaded, the `(server, kind)` is outside its spacing and the store could start its worker. + /// Anything else stays queued. A feed gap's sweep is not held for the wait. fn spend_library_owed(&mut self) { let queued = std::mem::take(&mut self.notify_map.library); let mut kept = Vec::new(); for ((sid, kind), owe) in queued { - if !self.watchlist.is_ready() || !self.notify_map.library_due(sid, kind) { + // A feed gap's sweep asks after every title of the kind, so it covers every entry that has + // arrived; an entry still to come makes a new owe, which waits for its own quiet. It is not + // held. A delete that could not be followed sweeps too, but it is one of those entries. + // An owe whose own wait has ended (and could not be spent that frame) is not held for the + // wait the feed's next entry started since. + let waits = owe.sweep != Sweep::Now && !owe.wait_over && self.notify_map.library_settling(sid); + if !self.watchlist.is_ready() || waits || !self.notify_map.library_due(sid, kind) { kept.push(((sid, kind), owe)); continue; } let mut asks: Vec<(String, WatchKind)> = owe.gone.iter().map(|g| (g.clone(), kind)).collect(); - if owe.sweep { + if owe.sweep != Sweep::No { asks.extend(self.watchlist.rows_of(kind)); } else if owe.added { asks.extend(self.watchlist.unmatched_on(sid, kind)); @@ -492,15 +590,36 @@ impl Stores { self.notify_map.library = kept; } + /// End the waits whose feed has gone quiet (or whose oldest entry has waited long enough): each owes + /// its server one quiet Home refetch, one section-shelf invalidate and one re-list, spent by the + /// pass that follows. Logs one line per wait ended, never one per frame it waited. + fn release_settled_library(&mut self) { + for (sid, wait) in self.notify_map.take_settled() { + plx_base::eventlog::log(&format!( + "notify: library settled sid={} entries={} waited={}s", + sid.raw(), + wait.entries, + self.notify_map.frame.saturating_sub(wait.first) / FRAMES_PER_S + )); + self.notify_map.library_wait_over(sid); + let owed = &mut self.notify_map.owed; + owed.refetch(sid); + owed.invalidate(sid); + push_unique(&mut owed.listings, sid); + } + } + fn spend_notify_owed(&mut self, shown: Shown, directory: browse::DirectoryView<'_>, clients: &plx_plex::plex::ClientKeys) -> Spent { let mut spent = Spent::default(); if self.notify_map.owed_is_empty() || !self.reread_allowed() { return spent; } + self.release_settled_library(); self.spend_library_owed(); - // What waits only for a spacing is not spent, and is not logged every frame it waits. - let owed = self.notify_map.take_due(); + // What waits (for a feed to go quiet, for a spacing) is not spent, and is not logged every + // frame it waits. + let owed = std::mem::take(&mut self.notify_map.owed); if owed.is_empty() { return spent; } @@ -528,7 +647,6 @@ impl Stores { for sid in owed.listings { let cmd = browse::BrowseCmd::ListingsChanged { sid, library_on_stack: shown.library }; let _ = self.browse.borrow_mut().run(cmd, clients); - self.notify_map.listings_spent(sid); spent.relisted.push(sid); } for sid in owed.invalidate { @@ -546,6 +664,7 @@ impl Stores { all.extend(owed.invalidate.iter().map(|s| (*s, "invalidate".into()))); all.extend(owed.listings.iter().map(|s| (*s, "listings".into()))); all.extend(self.notify_map.library.iter().map(|((s, _), _)| (*s, "library".into()))); + all.extend(self.notify_map.settling.iter().map(|(s, _)| (*s, "settling".into()))); all } diff --git a/rust-modules/data/src/stores/notify_map_tests.rs b/rust-modules/data/src/stores/notify_map_tests.rs index f7b21fbe9e..70358200f2 100644 --- a/rust-modules/data/src/stores/notify_map_tests.rs +++ b/rust-modules/data/src/stores/notify_map_tests.rs @@ -148,7 +148,8 @@ fn created_or_removed_items_owe_the_servers_grids_one_re_list() { ], ..Default::default() }; - let spent = map(&mut stores, &out, &[]); + assert_eq!(map(&mut stores, &out, &[]), Default::default(), "nothing is read while the feed may still be busy"); + let spent = after_the_quiet(&mut stores); assert_eq!(spent.relisted, [SID], "two reports in one pump are one re-list"); assert_eq!(spent.refetched, [SID], "and one quiet Home refetch"); assert_eq!(spent.invalidated, [SID], "and one section-shelf invalidate"); @@ -520,8 +521,8 @@ fn a_watchlist_read_waits_for_the_network() { // ---- a library change re-matches the Watchlist (W-notify) ------------------------------------ use super::notify::NotifyLibrary; -use super::notify_map::LIBRARY_SPACING_FRAMES; -use super::watchlist::tests::{scripted_for_test, Script}; +use super::notify_map::{LIBRARY_QUIET_FRAMES, LIBRARY_SPACING_FRAMES}; +use super::watchlist::tests::{scripted_for_test, scripted_with_shows_for_test, Script}; use crate::watchlist::model::TileState; use plx_plex::plex::notify::{LibraryEntry, LibraryKind, LibraryState}; @@ -563,6 +564,15 @@ fn quiet_frames(stores: &mut Stores, n: u64) { } } +/// The pumps after one that delivered a library entry, up to the one that ends its wait: nothing is +/// spent before it, and what it spends is returned. +fn after_the_quiet(stores: &mut Stores) -> super::notify_map::Spent { + for _ in 1..LIBRARY_QUIET_FRAMES { + assert_eq!(map(stores, &NotifyOut::default(), &[]), Default::default(), "the feed has not been quiet for 10 s yet"); + } + map(stores, &NotifyOut::default(), &[]) +} + #[test] fn a_deleted_item_a_tile_is_matched_to_re_asks_that_guid_and_the_tile_flips() { let _g = plx_base::testlock::serial(); @@ -570,6 +580,8 @@ fn a_deleted_item_a_tile_is_matched_to_re_asks_that_guid_and_the_tile_flips() { assert_eq!(tile(&stores, 1), Some(TileState::Available)); script.drop_hold(sid, 1); map(&mut stores, &library(sid, vec![deleted("11")]), &[]); + assert!(script.asked().is_empty(), "not while the feed may still be busy"); + after_the_quiet(&mut stores); assert_eq!(script.asked(), [[Script::guid(1)]], "that guid only, one request"); stores.watchlist.pump(); assert_ne!(tile(&stores, 1), Some(TileState::Available), "the tile left 'on your servers' at the landing"); @@ -581,10 +593,12 @@ fn a_deleted_item_no_tile_is_matched_to_owes_nothing() { let _g = plx_base::testlock::serial(); let (mut stores, script, sid) = watchlist_of_three(); map(&mut stores, &library(sid, vec![deleted("999"), deleted("not a key")]), &[]); + after_the_quiet(&mut stores); assert!(script.asked().is_empty()); assert!(stores.notify_owed_for_test().is_empty()); // The same key on another server is not the matched copy either. map(&mut stores, &library(ServerId::from_raw(3), vec![deleted("11")]), &[]); + after_the_quiet(&mut stores); assert!(script.asked().is_empty()); } @@ -594,6 +608,7 @@ fn a_created_item_re_asks_only_the_titles_the_server_is_not_seen_to_hold() { let (mut stores, script, sid) = watchlist_of_three(); script.hold(sid, 2, "12"); map(&mut stores, &library(sid, vec![created("12")]), &[]); + after_the_quiet(&mut stores); let asked = script.asked(); assert_eq!(asked.len(), 1, "{asked:?}"); let mut guids = asked[0].clone(); @@ -609,6 +624,7 @@ fn an_add_of_a_kind_the_list_has_no_rows_of_asks_nothing() { let _g = plx_base::testlock::serial(); let (mut stores, script, sid) = watchlist_of_three(); map(&mut stores, &library(sid, vec![change(LibraryKind::Show, LibraryState::Created, "5")]), &[]); + after_the_quiet(&mut stores); assert!(script.asked().is_empty(), "the three rows are movies"); assert!(stores.notify_owed_for_test().is_empty(), "and nothing is left owed"); } @@ -626,6 +642,7 @@ fn a_burst_of_changes_is_one_re_match_per_server_and_kind() { ..Default::default() }; map(&mut stores, &burst, &[]); + after_the_quiet(&mut stores); let asked = script.asked(); assert_eq!(asked.len(), 1, "one request for the burst: {asked:?}"); let mut guids = asked[0].clone(); @@ -634,27 +651,67 @@ fn a_burst_of_changes_is_one_re_match_per_server_and_kind() { } #[test] -fn a_second_change_inside_the_spacing_waits_for_it() { +fn a_change_after_a_re_match_starts_a_new_wait() { let _g = plx_base::testlock::serial(); let (mut stores, script, sid) = watchlist_of_three(); map(&mut stores, &library(sid, vec![created("20")]), &[]); + after_the_quiet(&mut stores); assert_eq!(script.asked().len(), 1); stores.watchlist.pump(); map(&mut stores, &library(sid, vec![created("21")]), &[]); + quiet_frames(&mut stores, LIBRARY_QUIET_FRAMES - 1); + assert_eq!(script.asked().len(), 1, "the new entry waits for its own quiet"); + assert!(!stores.notify_owed_for_test().is_empty(), "queued, not dropped"); + quiet_frames(&mut stores, 1); + assert_eq!(script.asked().len(), 2, "made once the feed has been quiet for 10 s"); + assert!(stores.notify_owed_for_test().is_empty()); +} + +/// The spacing between two re-matches of one `(server, kind)` is not the wait's: a feed gap's sweep +/// is owed without an entry, and one right after a re-match still holds off for the spacing. +#[test] +fn a_feed_gap_right_after_a_re_match_waits_for_the_spacing() { + let _g = plx_base::testlock::serial(); + let (mut stores, script, sid) = watchlist_of_three(); + map(&mut stores, &library(sid, vec![created("20")]), &[]); + after_the_quiet(&mut stores); + assert_eq!(script.asked().len(), 1); + stores.watchlist.pump(); + map(&mut stores, &NotifyOut { resynced: vec![(sid, 1)], ..Default::default() }, &[]); quiet_frames(&mut stores, LIBRARY_SPACING_FRAMES - 3); assert_eq!(script.asked().len(), 1, "still inside the spacing"); assert!(!stores.notify_owed_for_test().is_empty(), "queued, not dropped"); quiet_frames(&mut stores, 3); - assert_eq!(script.asked().len(), 2, "made once the spacing has passed"); + assert_eq!(script.asked().len(), 2, "made once the spacing has passed, with no wait of its own"); assert!(stores.notify_owed_for_test().is_empty()); } +/// A feed gap's sweep is not the entries' owe: it is made at once, even with entries still waiting, +/// and it covers what they would have asked, so the wait's end asks the Watchlist nothing more. +#[test] +fn a_feed_gap_sweeps_at_once_while_entries_wait() { + let _g = plx_base::testlock::serial(); + let (mut stores, script, sid) = watchlist_of_three(); + map(&mut stores, &library(sid, vec![created("20")]), &[]); + assert!(script.asked().is_empty(), "the entry waits"); + map(&mut stores, &NotifyOut { resynced: vec![(sid, 1)], ..Default::default() }, &[]); + assert_eq!(script.asked().len(), 1, "the sweep does not"); + assert_eq!(script.asked()[0].len(), 3, "it asks about every title"); + stores.watchlist.pump(); + // The entry came two pumps ago. + quiet_frames(&mut stores, LIBRARY_QUIET_FRAMES - 2); + let at_the_end = map(&mut stores, &NotifyOut::default(), &[]); + assert_eq!(at_the_end.relisted, [sid], "the entry's lists are still read when its feed is quiet"); + assert_eq!(script.asked().len(), 1, "and the Watchlist is not asked a second time for it"); +} + #[test] fn a_re_match_waits_for_the_network_like_every_owed_read() { let _g = plx_base::testlock::serial(); let (mut stores, script, sid) = watchlist_of_three(); stores.hold_network(true); map(&mut stores, &library(sid, vec![created("20")]), &[]); + quiet_frames(&mut stores, LIBRARY_QUIET_FRAMES); assert!(script.asked().is_empty(), "nothing is spent under the player"); assert!(!stores.notify_owed_for_test().is_empty(), "queued, not dropped"); stores.hold_network(false); @@ -670,7 +727,7 @@ fn a_change_noted_before_the_first_load_is_not_asked_again_after_it() { let sid = ServerId::from_raw(0); // A create and a delete arrive while the page has never been read and no read is out. map(&mut stores, &library(sid, vec![created("20"), deleted("11")]), &[]); - quiet_frames(&mut stores, 5); + quiet_frames(&mut stores, LIBRARY_QUIET_FRAMES); assert!(stores.notify_owed_for_test().is_empty(), "the read to come already reflects both"); let (watchlist, script) = scripted_for_test(sid, 3, &[(1, "11")]); stores.watchlist = watchlist; @@ -686,7 +743,7 @@ fn a_change_that_arrives_while_the_first_read_is_out_is_kept_and_asked_after_it( let mut stores = Stores::default(); stores.watchlist = super::watchlist::tests::reading_for_test(sid, 3); map(&mut stores, &library(sid, vec![created("20")]), &[]); - quiet_frames(&mut stores, 5); + quiet_frames(&mut stores, LIBRARY_QUIET_FRAMES + 5); assert!(!stores.notify_owed_for_test().is_empty(), "that read's matching may have asked before the create"); let (watchlist, script) = scripted_for_test(sid, 3, &[(1, "11")]); stores.watchlist = watchlist; @@ -696,6 +753,32 @@ fn a_change_that_arrives_while_the_first_read_is_out_is_kept_and_asked_after_it( assert!(stores.notify_owed_for_test().is_empty()); } +/// A delete that arrives while the first read is out cannot be followed to a tile (the list is not +/// ready), so it asks after every title of the kind. That is not a feed gap's sweep: it waits for its +/// server's quiet like any other change, and the burst it belongs to is asked once, not twice. +#[test] +fn a_delete_during_the_first_read_waits_for_the_servers_quiet_and_asks_once() { + let _g = plx_base::testlock::serial(); + let sid = ServerId::from_raw(0); + let mut stores = Stores::default(); + stores.watchlist = super::watchlist::tests::reading_for_test(sid, 3); + map(&mut stores, &library(sid, vec![deleted("11")]), &[]); + // The first read lands while the server's feed is still settling. + let (watchlist, script) = scripted_for_test(sid, 3, &[(1, "11")]); + stores.watchlist = watchlist; + script.forget_asked(); + for _ in 1..LIBRARY_QUIET_FRAMES { + map(&mut stores, &NotifyOut::default(), &[]); + assert!(script.asked().is_empty(), "not while the feed may still be busy: {:?}", script.asked()); + } + map(&mut stores, &NotifyOut::default(), &[]); + assert_eq!(script.asked().len(), 1, "the burst is asked once, at the quiet: {:?}", script.asked()); + assert_eq!(script.asked()[0].len(), 3, "every title of the kind: the delete was not followed to a tile"); + quiet_frames(&mut stores, LIBRARY_QUIET_FRAMES); + assert_eq!(script.asked().len(), 1, "and not again: {:?}", script.asked()); + assert!(stores.notify_owed_for_test().is_empty()); +} + #[test] fn a_feed_that_came_back_after_a_gap_sweeps_the_titles_of_that_server() { let _g = plx_base::testlock::serial(); @@ -713,7 +796,8 @@ fn a_feed_that_came_back_after_a_gap_sweeps_the_titles_of_that_server() { fn a_library_change_moves_the_servers_lists_and_reads_no_item() { let _g = plx_base::testlock::serial(); let (mut stores, _script, sid) = watchlist_of_three(); - let spent = map(&mut stores, &library(sid, vec![created("20"), deleted("11")]), &[]); + map(&mut stores, &library(sid, vec![created("20"), deleted("11")]), &[]); + let spent = after_the_quiet(&mut stores); assert_eq!(spent.refetched, [sid], "one quiet Home refetch"); assert_eq!(spent.invalidated, [sid], "one section-shelf invalidate"); assert_eq!(spent.relisted, [sid], "one re-list of its grids"); @@ -734,7 +818,8 @@ fn a_refusal_the_quiet_refetch_step_settles_is_carried_out_of_the_pass() { let first = stores.hubs.run_with_directory(crate::stores::hubs::HubsCmd::RefetchHubs, dir.view(), &keys); assert!(first.endpoints.is_empty(), "the refusal is the runner's answer, not the kick's"); stores.hubs.refuse_jobs_for_test(); - let spent = map(&mut stores, &library(sid, vec![created("20")]), &[]); + map(&mut stores, &library(sid, vec![created("20")]), &[]); + let spent = after_the_quiet(&mut stores); assert_eq!(spent.refetched, [sid]); assert_eq!(spent.endpoints.iter().map(|r| r.sid).collect::>(), [sid]); plx_plex::plex::reset_servers_for_test(); @@ -748,42 +833,236 @@ fn owes_lines() -> usize { .count() } -/// A scan reports a create every few seconds: the server's listings are told once per spacing, the -/// change that lands inside it waits (one entry, however many arrive) and is spent when it is due, -/// and the waiting is not logged frame after frame. +fn settled_lines() -> Vec { + std::fs::read_to_string(plx_base::eventlog::events_log()) + .unwrap_or_default() + .lines() + .filter(|l| l.contains("notify: library settled")) + .map(|l| l.rsplit("notify: ").next().unwrap_or_default().to_owned()) + .collect() +} + +/// A scan reports a create every few seconds: the server's lists are read once when the feed goes +/// quiet, and the one line that says so counts the entries and the wait; the frames spent waiting +/// log nothing. #[test] -fn a_servers_listings_are_told_at_most_once_per_spacing() { +fn a_waited_for_refresh_logs_once_when_it_is_spent_and_never_per_waiting_frame() { let _g = plx_base::testlock::serial(); plx_base::eventlog::with_private_log(|| { let mut stores = holding(&[]); - let change = library(SID, vec![created("20")]); - let mut calls = 0u64; - let mut tick = |stores: &mut Stores, out: &NotifyOut| { - calls += 1; - (map(stores, out, &[]).relisted, calls) - }; - let (relisted, first) = tick(&mut stores, &change); - assert_eq!(relisted, [SID], "the first change is told at once"); - let logged = owes_lines(); - for _ in 0..3 { - assert!(tick(&mut stores, &NotifyOut::default()).0.is_empty()); + let change = library(SID, vec![created("20"), created("21")]); + let none = NotifyOut::default(); + for second in 0..20 { + map(&mut stores, if second % 4 == 0 { &change } else { &none }, &[]); + quiet_frames(&mut stores, FRAMES_PER_S - 1); } - for _ in 0..2 { - assert!(tick(&mut stores, &change).0.is_empty(), "inside the spacing it waits, coalesced"); + assert_eq!(owes_lines(), 0, "twenty seconds of waiting spent nothing and logged no owe"); + assert!(settled_lines().is_empty(), "nor a settle"); + quiet_frames(&mut stores, 2 * LIBRARY_QUIET_FRAMES); + assert_eq!(owes_lines(), 1, "one spend"); + assert_eq!(settled_lines(), [format!("library settled sid={} entries=10 waited=26s", SID.raw())]); + }); +} + +// ---- library entries wait for the feed to go quiet (#1458) ---------------------------------- + +use super::notify::FRAMES_PER_S; +use super::notify_map::{Spent, LIBRARY_LONGEST_WAIT_FRAMES}; + +/// How many times a server's lists were read over a run of pumps. +#[derive(Default, Debug, PartialEq, Clone, Copy)] +struct Tally { + refetched: usize, + invalidated: usize, + relisted: usize, +} + +impl Tally { + const ONE_OF_EACH: Self = Self { refetched: 1, invalidated: 1, relisted: 1 }; + + fn add(&mut self, sid: ServerId, spent: &Spent) { + let of = |servers: &[ServerId]| servers.iter().filter(|s| **s == sid).count(); + self.refetched += of(&spent.refetched); + self.invalidated += of(&spent.invalidated); + self.relisted += of(&spent.relisted); + } + + fn at_most_one_of_each(&self) -> bool { + self.refetched <= 1 && self.invalidated <= 1 && self.relisted <= 1 + } +} + +/// One pump of `out` on `SID`'s feed, reported as what it spent. +fn pump_tally(stores: &mut Stores, out: &NotifyOut) -> Tally { + let mut spent = Tally::default(); + spent.add(SID, &map(stores, out, &[])); + spent +} + +/// Pump `n` empty frames and sum what they spent. +fn quiet_tally(stores: &mut Stores, n: u64) -> Tally { + let mut sum = Tally::default(); + for _ in 0..n { + sum.add(SID, &map(stores, &NotifyOut::default(), &[])); + } + sum +} + +/// A feed that delivers one finished item a second for a minute used to re-read the server's Home, +/// its shelves and its grids every 5 s; over a remote link that kept every read the viewer scrolled +/// to stuck in the queue. They are made once the feed goes quiet, or once a minute when it never does. +#[test] +fn a_feed_that_streams_library_entries_refreshes_the_servers_lists_once_it_goes_quiet() { + let _g = plx_base::testlock::serial(); + let mut stores = holding(&[]); + let entry = library(SID, vec![created("20")]); + let mut run = Tally::default(); + for second in 0..65 { + run.add(SID, &map(&mut stores, &entry, &[])); + for _ in 1..FRAMES_PER_S { + run.add(SID, &map(&mut stores, &NotifyOut::default(), &[])); } - assert!(stores.notify_owed_for_test().contains(&(SID, "listings".to_string())), "owed, not dropped"); - let mut spent_at = Vec::new(); - for _ in 0..2 * LIBRARY_SPACING_FRAMES { - let (relisted, at) = tick(&mut stores, &NotifyOut::default()); - if !relisted.is_empty() { - assert_eq!(relisted, [SID]); - spent_at.push(at); - } + if second == 59 { + assert!(run.at_most_one_of_each(), "a minute of steady entries: {run:?}"); } - assert_eq!(spent_at, [first + LIBRARY_SPACING_FRAMES], "told once, the frame the spacing is up"); - assert!(stores.notify_owed_for_test().is_empty()); - // The refetch and the invalidate of the two changes inside the spacing are spent as they come - // (their own spacing is downstream), so those frames log; the frames that only wait do not. - assert_eq!(owes_lines() - logged, 3, "the two changes and the deferred listings: three lines, none per waiting frame"); - }); + } + assert_eq!(run, Tally::ONE_OF_EACH, "once, the pump the oldest entry had waited a minute"); + // The last entry was FRAMES_PER_S - 1 pumps ago. The stream stops: nothing until 10 s after it, + // then the one refresh the entries since then owe, and then nothing more. + let before = quiet_tally(&mut stores, LIBRARY_QUIET_FRAMES - FRAMES_PER_S); + assert_eq!(before, Tally::default(), "not before the feed has been quiet for 10 s"); + assert_eq!(quiet_tally(&mut stores, 1), Tally::ONE_OF_EACH, "once it has"); + assert_eq!(quiet_tally(&mut stores, 2 * LIBRARY_LONGEST_WAIT_FRAMES), Tally::default(), "and once only"); + assert!(stores.notify_owed_for_test().is_empty()); +} + +#[test] +fn a_lone_library_entry_is_spent_once_the_feed_has_been_quiet_for_ten_seconds() { + let _g = plx_base::testlock::serial(); + let mut stores = holding(&[]); + assert_eq!(pump_tally(&mut stores, &library(SID, vec![created("20")])), Tally::default(), "not at once"); + assert_eq!(quiet_tally(&mut stores, LIBRARY_QUIET_FRAMES - 1), Tally::default(), "not on the next pump, nor for 10 s"); + assert!(!stores.notify_owed_for_test().is_empty(), "waiting, not dropped"); + assert_eq!(quiet_tally(&mut stores, 1), Tally::ONE_OF_EACH, "the pump that makes it 10 s"); + assert_eq!(quiet_tally(&mut stores, 2 * LIBRARY_QUIET_FRAMES), Tally::default(), "spent once"); + assert!(stores.notify_owed_for_test().is_empty()); +} + +#[test] +fn a_feed_that_never_goes_quiet_still_refreshes_about_once_a_minute() { + let _g = plx_base::testlock::serial(); + let mut stores = holding(&[]); + let entry = library(SID, vec![created("20")]); + let none = NotifyOut::default(); + let mut released_at = Vec::new(); + for pump in 1..=190 * FRAMES_PER_S { + let out = if (pump - 1) % FRAMES_PER_S == 0 { &entry } else { &none }; + let spent = pump_tally(&mut stores, out); + if spent != Tally::default() { + assert_eq!(spent, Tally::ONE_OF_EACH, "pump {pump}"); + released_at.push(pump); + } + } + assert_eq!(released_at.len(), 3, "190 s of entries, a refresh a minute: {released_at:?}"); + assert_eq!(released_at[0], 1 + LIBRARY_LONGEST_WAIT_FRAMES, "the oldest entry has waited a minute"); + for pair in released_at.windows(2) { + assert!(pair[1] - pair[0] >= LIBRARY_LONGEST_WAIT_FRAMES, "after a refresh the next entry starts a new wait: {released_at:?}"); + } +} + +/// The store re-matches one thing at a time, so a server whose movies and shows both changed has one +/// re-match refused at the pump its wait ends. That one stays queued and its wait is over: it starts +/// when the one out finishes, not after the new wait the feed's next entry began a second later +/// (#1458). Held again each time, a feed that never goes quiet re-matched each kind about every two +/// minutes, not once a minute. +#[test] +fn a_re_match_refused_when_the_wait_ends_starts_when_the_one_out_finishes_not_a_minute_later() { + let _g = plx_base::testlock::serial(); + let sid = ServerId::from_raw(0); + let (watchlist, script) = scripted_with_shows_for_test(sid, 3, 2, &[(1, "11")]); + let mut stores = Stores::default(); + stores.watchlist = watchlist; + script.forget_asked(); + // A movie and a show finish every second, for as long as the test runs. + let entry = library(sid, vec![created("20"), change(LibraryKind::Show, LibraryState::Created, "21")]); + let none = NotifyOut::default(); + let mut pumps = 0; + let mut step = |stores: &mut Stores| { + pumps += 1; + map(stores, if (pumps - 1) % FRAMES_PER_S == 0 { &entry } else { &none }, &[]); + }; + for _ in 0..LIBRARY_LONGEST_WAIT_FRAMES { + step(&mut stores); + } + assert!(script.asked().is_empty(), "the oldest entry has not waited a minute"); + step(&mut stores); + let out = script.asked(); + assert_eq!(out.len(), 1, "one kind's re-match starts the pump the wait ends: {out:?}"); + assert!(out[0].contains(&Script::guid(2)), "the movies, which were owed first"); + // The re-match takes longer than a second (a remote link): the next entry arrives while it is out. + for _ in 0..FRAMES_PER_S { + step(&mut stores); + } + assert_eq!(script.asked().len(), 1, "the shows wait for the re-match that is out"); + stores.watchlist.pump(); + let mut waited = 0; + while script.asked().len() < 2 && waited < LIBRARY_LONGEST_WAIT_FRAMES { + step(&mut stores); + waited += 1; + } + assert!(waited <= FRAMES_PER_S, "the shows start {waited} pumps after the re-match ahead of them finished"); + let asked = script.asked(); + assert!(asked[1].contains(&Script::show_guid(4)), "and they ask about the shows: {asked:?}"); +} + +/// The wait belongs to the library entries: a `stopped` session's refetch and invalidate are spent +/// the pump it arrives, and the library's own refresh still comes when its feed is quiet. +#[test] +fn a_stop_is_never_held_by_the_library_wait() { + let _g = plx_base::testlock::serial(); + let mut stores = holding(&[]); + assert_eq!(pump_tally(&mut stores, &library(SID, vec![created("20")])), Tally::default()); + let stop = pump_tally(&mut stores, &one("1", "zzz", PlayState::Stopped)); + assert_eq!(stop, Tally { refetched: 1, invalidated: 1, relisted: 0 }, "a stop refetches and invalidates at once, and re-lists nothing"); + assert_eq!(quiet_tally(&mut stores, LIBRARY_QUIET_FRAMES - 2), Tally::default()); + assert_eq!(quiet_tally(&mut stores, 1), Tally::ONE_OF_EACH, "the entry's refresh, once its feed has been quiet"); +} + +#[test] +fn each_servers_library_wait_is_its_own() { + let _g = plx_base::testlock::serial(); + let other = ServerId::from_raw(1); + let mid = 1 + LIBRARY_QUIET_FRAMES / 2; + let mut stores = holding(&[]); + let (mut mine, mut theirs) = (Vec::new(), Vec::new()); + for pump in 1..=3 * LIBRARY_QUIET_FRAMES { + // The first server's entry, then the other's halfway through its wait. + let out = match pump { + 1 => library(SID, vec![created("20")]), + p if p == mid => library(other, vec![created("30")]), + _ => NotifyOut::default(), + }; + let spent = map(&mut stores, &out, &[]); + if spent.relisted.contains(&SID) { + mine.push(pump); + } + if spent.relisted.contains(&other) { + theirs.push(pump); + } + } + assert_eq!(mine, [1 + LIBRARY_QUIET_FRAMES], "10 s after its own entry, not pushed back by the other's"); + assert_eq!(theirs, [mid + LIBRARY_QUIET_FRAMES], "10 s after its own"); +} + +#[test] +fn a_library_wait_that_ends_under_the_player_is_spent_when_the_network_is_released() { + let _g = plx_base::testlock::serial(); + let mut stores = holding(&[]); + stores.hold_network(true); + map(&mut stores, &library(SID, vec![created("20")]), &[]); + assert_eq!(quiet_tally(&mut stores, 2 * LIBRARY_QUIET_FRAMES), Tally::default(), "nothing is spent under the player"); + assert!(!stores.notify_owed_for_test().is_empty(), "queued, not dropped"); + stores.hold_network(false); + assert_eq!(quiet_tally(&mut stores, 1), Tally::ONE_OF_EACH, "the pump the network frees up"); + assert!(stores.notify_owed_for_test().is_empty()); } diff --git a/rust-modules/data/src/stores/watchlist.rs b/rust-modules/data/src/stores/watchlist.rs index 39bfc75cd8..932015c00c 100644 --- a/rust-modules/data/src/stores/watchlist.rs +++ b/rust-modules/data/src/stores/watchlist.rs @@ -1369,6 +1369,10 @@ pub(super) mod tests { format!("plex://movie/{}", id(n)) } + fn show_guid(n: u8) -> String { + format!("plex://show/{}", id(n)) + } + fn item(n: u8, title: &str) -> WatchItem { WatchItem { hex: id(n), @@ -1603,7 +1607,14 @@ pub(in crate::stores) fn reading_for_test(sid: ServerId, titles: u8) -> Watchlis /// A scripted world a test outside this file drives: the server `sid`, `titles` movies on the list /// (numbered from 1) and the `(title number, ratingKey)` pairs `sid` holds, with the list read. pub(in crate::stores) fn scripted_for_test(sid: ServerId, titles: u8, held: &[(u8, &str)]) -> (WatchlistStore, Script) { - let mock = Mock::new((1..=titles).map(|n| item(n, "T")).collect()); + scripted_with_shows_for_test(sid, titles, 0, held) + } + + /// [`scripted_for_test`] with `shows` shows listed after the `titles` movies (numbered on from + /// them; [`Script::show_guid`] names one), so a server owes the list a re-match of both kinds. + pub(in crate::stores) fn scripted_with_shows_for_test(sid: ServerId, titles: u8, shows: u8, held: &[(u8, &str)]) -> (WatchlistStore, Script) { + let show = |n: u8| WatchItem { guid: show_guid(n), kind: Some(WatchKind::Show), ..item(n, "S") }; + let mock = Mock::new((1..=titles).map(|n| item(n, "T")).chain((titles + 1..=titles + shows).map(show)).collect()); *mock.roster.lock().unwrap() = vec![sid]; *mock.up.lock().unwrap() = vec![sid]; for (n, rk) in held { @@ -1627,6 +1638,9 @@ pub(in crate::stores) fn reading_for_test(sid: ServerId, titles: u8) -> Watchlis pub(in crate::stores) fn guid(n: u8) -> String { guid(n) } + pub(in crate::stores) fn show_guid(n: u8) -> String { + show_guid(n) + } /// The guids of every guid lookup since the list was read, per request. pub(in crate::stores) fn asked(&self) -> Vec> { self.0.found.lock().unwrap().clone() diff --git a/rust-modules/src/app/browse_hubs_drain_tests.rs b/rust-modules/src/app/browse_hubs_drain_tests.rs index 5b2cc86904..a6e6048158 100644 --- a/rust-modules/src/app/browse_hubs_drain_tests.rs +++ b/rust-modules/src/app/browse_hubs_drain_tests.rs @@ -15,7 +15,7 @@ use plx_data::stores::browse::{BrowseCmd, LibraryWork, SectionAddress}; use plx_data::stores::StoreJob; use plx_data::stores::notify_job::NotifyStreamReq; use crate::app::adapters::stores::NotifyTransport; -use plx_data::stores::notify_map::Shown; +use plx_data::stores::notify_map::{Shown, LIBRARY_QUIET_FRAMES}; use plx_ui::dispatch::Rig as _; use plx_plex::plex::notify::{LibraryEntry, LibraryKind, LibraryState, Notification}; use plx_plex::plex::{GrantEvidence, ServerId}; @@ -180,6 +180,20 @@ fn the_notify_pump_starts_the_read_a_library_change_asked_for() { plx_plex::plex::client_for, plx_plex::plex::server_facts, |_| None, |_| true); let (_, endpoints) = rig.bridge.bridge().notify_pump_captured(&[], Shown::ALL); assert!(endpoints.is_empty()); + // The refresh a library entry owes waits for its server's feed to go quiet (#1458). The frames + // up to the one that ends the wait go to the map alone (the script would deliver its entry again + // on a reconnect), and the pass that ends it is the pump's. + assert!(!rig.bridge.bridge().stores.browse.borrow().hubs_read_out_for_test(), "not while the feed may be busy"); + { + let bridge = rig.bridge.bridge(); + for _ in 1..LIBRARY_QUIET_FRAMES { + let quiet = plx_data::stores::notify::NotifyOut::default(); + let spent = bridge.stores.notify_map(&quiet, &[], Shown::ALL, bridge.retained.directory.view(), &bridge.retained.client_keys); + assert_eq!(spent, Default::default()); + } + } + let (_, endpoints) = rig.bridge.bridge().notify_pump_captured(&[], Shown::ALL); + assert!(endpoints.is_empty()); assert!(rig.bridge.bridge().stores.browse.borrow().hubs_read_out_for_test()); rig.assert_started(&["BrowseHubs", "Hubs"]); diff --git a/tests/scenarios/watchlist_captures.json b/tests/scenarios/watchlist_captures.json index 426432e7b3..2fac65c671 100644 --- a/tests/scenarios/watchlist_captures.json +++ b/tests/scenarios/watchlist_captures.json @@ -1,5 +1,5 @@ { - "comment": "The Watchlist wave-3 capture list: each ui-sim capture, the board it answers, the dev triggers armed in a fresh instance root, the mock state and the keys it sends. ONE CAPTURE RECIPE, automated by tools/watchlist_captures.py (`python3 tools/watchlist_captures.py --sim [--out DIR] [--only FILE ...]`): (1) tests/mock_pms.py starts in that process on loopback with authorize_after=2, and `POST /_mock/discover {\"list\": }` resets its Discover list to the capture's `mock` mode (`default` is the 14-title fixture, `empty` clears the list, `movies_only` keeps only the movie titles so Type = TV Shows matches nothing); (2) a fresh instance root gets `plxnative-plextv` and `plxnative-discover` aimed at the mock, and a prep boot with `plxnative-login` signs in through the app's own QR flow - the stored mock session is the account, so no `token` trigger is armed (a `token` boot reads the Watchlist as unavailable for the profile); (3) the capture's `triggers` are armed, the simulator boots, waits `boot_wait_s`, sends each `keys` entry as a FIFO token through `plxnative-remote` with `key_wait_s` between them (`hold` is `okdown`, 1.2 s, `okup`), checks `expect_focus` and then sends `shot`. A capture REACHES its target by an accessibility-id token, or by a boot trigger, and never by a direction key: no `keys` entry is `up`, `down`, `left` or `right`. `focus:` moves focus to the element an id names (`nav.watchlist`, `watchlist.grid.card.7`, `home.shelf.2.card.0`) and `press:` focuses it and presses OK (ids are the app's place-based dot paths, grammar in tools/a11y.py; a malformed one fails the run before anything boots). A press of an element that acts on a title it names (the ids are `SUBJECT_BEARING` in tools/a11y.py) names that title, `press:@`, the ratingKey of the title the press acts on, and the app refuses it when another title is there: `press:itemmenu.watchlist_remove@2001` (The Long Meridian, the mock's second Watchlist title) and `press:home.hero.watchlist@200622` (the first Continue Watching episode of the `catalog` mock) and `press:detail.hero.watchlist@1001` (the Detail page of Harbor Lights, the `first_movie_off` mock's first movie); the one bare title press is `watchlist.grid.card.7`, a coming-soon card with no key. The keys that stay are those whose subject is the key itself: `hold`, a timing such as `ok@0.12`, `back`; and the one capture that navigates by pointer, `w6/detail-offline.png`, whose `ck:,` clicks are its walk. `expect_focus` is the full id the app must have focused when the walk is done: the driver asks the app for a `state:` snapshot and fails the capture, naming both ids, when it differs (a walk that ends in a timed key is checked before that key, because the shot must follow it within the wait). A capture whose focus a boot trigger decides (an opener row: `account-menu-new.png`, `item-menu-new.png`) or a pointer click does (`w6/detail-offline.png`) leaves it out, and a refused id (`a11y: refused ...` in the event log) fails the capture either way. A `hold` on a tile (a Watchlist tile, a Home shelf card) opens its menu, so a hold capture's `expect_focus` is the menu's opening row (`itemmenu.`); (4) the instance root's shot-N.png becomes `/`, and a capture with `expect_write` fails unless the mock logged that write. `compare` names a baseline PNG (651035609 built the same way in a separate worktree) for the reader to put beside the new capture; the driver does not diff it. Build the simulator with `make sim-macos SIM_TDIR=` (debug; the release build serves as well). Nothing reaches plex.tv, a real server or a television. The PNGs are scratch output, never committed. WAVE 6 (Bump B) captures live under `w6/`: `board` names the Design board each answers; `mock_extra` is merged into the Discover reset (`guids: all` gives every library title a Discover guid so a card's menu offers Add), `unreachable` aims plex.tv at a closed port after the sign-in (the plex.tv-unreachable Detail), and a key `k@0.12` waits 0.12 s instead of key_wait_s (the mid-flip shot); `mock:` POSTs to /_mock/discover mid-walk, `sleep:` waits, and `ck:,` clicks at logical 1920x1080 pixels. DetailOffline is the catalog page of a title matched on the mock server that then went away: the Watchlist matches Harbor Lights, `{\"pms\":\"fail\"}` makes every PMS request answer 503, a click on Movies makes the library read fail (its failure is what commits the server Unreachable), a click on the Watchlist tab reads the list again (the read re-derives the tiles: ServerOffline), and a click on the first tile opens its catalog page. Run it from a release AND a debug simulator and grep each .log/.out for `panic`. HOME HERO captures live under `home-hero/` and answer the HomeHero board (canvas v44): the hero row's bookmark disc, second after Continue/Play, focused (`focus:home.hero.watchlist`, the hero's bookmark control); `heropin 0` holds the first hero and `mock_extra episode_shows: catalog` points every episode's show at the first catalogued show (The Long Meridian: on the `default` list, off the `empty` one), so the Continue Watching hero has a title the Discover stand-in knows. W-NOTIFY (library add flips a tile live) lives in `library-add-flips-tile.png`: the Watchlist tab stays open, `lib:{\"op\":\"add\",\"title\":\"Northbound Tide\"}` makes the mock library hold a title the list carries as coming soon and pushes the `timeline` frame a server would send (the captured three-frame add sequence; only its finished frame owes the re-match), the tile flips from Coming soon to its on-your-servers face with no key pressed, and `expect_log` fails the capture unless the app logged the library re-match.", + "comment": "The Watchlist wave-3 capture list: each ui-sim capture, the board it answers, the dev triggers armed in a fresh instance root, the mock state and the keys it sends. ONE CAPTURE RECIPE, automated by tools/watchlist_captures.py (`python3 tools/watchlist_captures.py --sim [--out DIR] [--only FILE ...]`): (1) tests/mock_pms.py starts in that process on loopback with authorize_after=2, and `POST /_mock/discover {\"list\": }` resets its Discover list to the capture's `mock` mode (`default` is the 14-title fixture, `empty` clears the list, `movies_only` keeps only the movie titles so Type = TV Shows matches nothing); (2) a fresh instance root gets `plxnative-plextv` and `plxnative-discover` aimed at the mock, and a prep boot with `plxnative-login` signs in through the app's own QR flow - the stored mock session is the account, so no `token` trigger is armed (a `token` boot reads the Watchlist as unavailable for the profile); (3) the capture's `triggers` are armed, the simulator boots, waits `boot_wait_s`, sends each `keys` entry as a FIFO token through `plxnative-remote` with `key_wait_s` between them (`hold` is `okdown`, 1.2 s, `okup`), checks `expect_focus` and then sends `shot`. A capture REACHES its target by an accessibility-id token, or by a boot trigger, and never by a direction key: no `keys` entry is `up`, `down`, `left` or `right`. `focus:` moves focus to the element an id names (`nav.watchlist`, `watchlist.grid.card.7`, `home.shelf.2.card.0`) and `press:` focuses it and presses OK (ids are the app's place-based dot paths, grammar in tools/a11y.py; a malformed one fails the run before anything boots). A press of an element that acts on a title it names (the ids are `SUBJECT_BEARING` in tools/a11y.py) names that title, `press:@`, the ratingKey of the title the press acts on, and the app refuses it when another title is there: `press:itemmenu.watchlist_remove@2001` (The Long Meridian, the mock's second Watchlist title) and `press:home.hero.watchlist@200622` (the first Continue Watching episode of the `catalog` mock) and `press:detail.hero.watchlist@1001` (the Detail page of Harbor Lights, the `first_movie_off` mock's first movie); the one bare title press is `watchlist.grid.card.7`, a coming-soon card with no key. The keys that stay are those whose subject is the key itself: `hold`, a timing such as `ok@0.12`, `back`; and the one capture that navigates by pointer, `w6/detail-offline.png`, whose `ck:,` clicks are its walk. `expect_focus` is the full id the app must have focused when the walk is done: the driver asks the app for a `state:` snapshot and fails the capture, naming both ids, when it differs (a walk that ends in a timed key is checked before that key, because the shot must follow it within the wait). A capture whose focus a boot trigger decides (an opener row: `account-menu-new.png`, `item-menu-new.png`) or a pointer click does (`w6/detail-offline.png`) leaves it out, and a refused id (`a11y: refused ...` in the event log) fails the capture either way. A `hold` on a tile (a Watchlist tile, a Home shelf card) opens its menu, so a hold capture's `expect_focus` is the menu's opening row (`itemmenu.`); (4) the instance root's shot-N.png becomes `/`, and a capture with `expect_write` fails unless the mock logged that write. `compare` names a baseline PNG (651035609 built the same way in a separate worktree) for the reader to put beside the new capture; the driver does not diff it. Build the simulator with `make sim-macos SIM_TDIR=` (debug; the release build serves as well). Nothing reaches plex.tv, a real server or a television. The PNGs are scratch output, never committed. WAVE 6 (Bump B) captures live under `w6/`: `board` names the Design board each answers; `mock_extra` is merged into the Discover reset (`guids: all` gives every library title a Discover guid so a card's menu offers Add), `unreachable` aims plex.tv at a closed port after the sign-in (the plex.tv-unreachable Detail), and a key `k@0.12` waits 0.12 s instead of key_wait_s (the mid-flip shot); `mock:` POSTs to /_mock/discover mid-walk, `sleep:` waits, and `ck:,` clicks at logical 1920x1080 pixels. DetailOffline is the catalog page of a title matched on the mock server that then went away: the Watchlist matches Harbor Lights, `{\"pms\":\"fail\"}` makes every PMS request answer 503, a click on Movies makes the library read fail (its failure is what commits the server Unreachable), a click on the Watchlist tab reads the list again (the read re-derives the tiles: ServerOffline), and a click on the first tile opens its catalog page. Run it from a release AND a debug simulator and grep each .log/.out for `panic`. HOME HERO captures live under `home-hero/` and answer the HomeHero board (canvas v44): the hero row's bookmark disc, second after Continue/Play, focused (`focus:home.hero.watchlist`, the hero's bookmark control); `heropin 0` holds the first hero and `mock_extra episode_shows: catalog` points every episode's show at the first catalogued show (The Long Meridian: on the `default` list, off the `empty` one), so the Continue Watching hero has a title the Discover stand-in knows. W-NOTIFY (library add flips a tile live) lives in `library-add-flips-tile.png`: the Watchlist tab stays open, `lib:{\"op\":\"add\",\"title\":\"Northbound Tide\"}` makes the mock library hold a title the list carries as coming soon and pushes the `timeline` frame a server would send (the captured three-frame add sequence; only its finished frame owes the re-match), the tile flips from Coming soon to its on-your-servers face with no key pressed (the re-match waits for the feed to be quiet for 10 s, so the walk sleeps 14 s after the add), and `expect_log` fails the capture unless the app logged the library re-match.", "output_dir": "/tmp/watchlist-captures", "boot_wait_s": 5, "key_wait_s": 2, @@ -325,7 +325,7 @@ "keys": [ "sleep:4", "lib:{\"op\":\"add\",\"title\":\"Northbound Tide\"}", - "sleep:4" + "sleep:14" ], "expect_focus": "watchlist.grid.card.0", "expect_log": "notify: library re-match" From 6c5ce1437f381b41ae9dacb6c9833a529ded6fce Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Sat, 21 Nov 2026 01:11:43 +0300 Subject: [PATCH 21/26] The SDL shell is a crate of its own, plx_shell_sdl, behind the app-private Shell and Surface (#1498) SDL's bring-up, the window and its GL context, the swap, the event poll and decode, the synthetic events the dev tooling pushes back, and the text-input calls leave the application crate for `rust-modules/shell-sdl`, a new crate in a new `[shell_sdl]` layer (`uses = base machine os`; the crate names `plx_base` alone). Step W6 of the platform plan (discussion #1460). The application keeps its own vocabulary: `Shell`, `Surface`, `HostEvent` and `KeyPress` stay app-private (W7a publishes them), and the television's LG half stays in `system.rs` and the webOS platform. The `SDL_SysWMinfo` over-allocation, the opaque region and the LS2 pump do not move, and the crate's pins fail if it ever names a Wayland or Luna symbol, the over-writing window query or its handshake. `Shell` gains `init` and `open`. `open` returns a `Surface` (window, swap, swap interval, poll, and an unsafe quit that `run::shutdown` calls), which `App` owns in place of the raw window pointer. The boot order is kept and pinned: SDL_Init and the GL request, then the stored session is read, then the window. The window's place and size are a value, `OpenAsk { title, placement, high_dpi }`, so the panel's size with its smaller fallback and the desktop fit (hostsim builds only) belong to the crate. The cursor-sleep hint before SDL_Init and the relaunch tap after it move into `system.rs` without their `hostsim` gates, and the webOS shell hands them to `init` as two hooks; the hint's SDL_SetHint goes through the crate's `set_hint`. The byte layouts are written once, in the crate, and both arms of every LG versus stock layout still compile in every build (`cfg!`, not `#[cfg]`). The byte-level tests moved with the code; the HostEvent-level tests stay in the application over re-exports. A new pin holds the application to declaring SDL functions in `system.rs` and `app/clock.rs` only. Three loop call sites into the shell that no test would have missed now have one each, each shown to fail with its call deleted: the idle pointer hidden over the video in `playback_tick`, `host_background`'s hand-back of the pointer Back hid, and a controlled pointer input's wake in `controlled_key_input`. `SCR_W` and `SCR_H` in `app/mod.rs` are now read only by the television's window request and tests, and share the gate `any(not(feature = "hostsim"), test)`; the devtools fps digits read `plx_base::surface::LOGICAL_W` directly. The lists that name layer crates gain the new one: the Makefile's suites and inputs, the CI workflow, the build-budget source list, `check-deps.sh`'s scans, `list-caps.ini` (five moved cap sites re-keyed, one new), the release-config hook and the module-layers config. Both read-only certificates are re-sealed over the new manifest set and lock file. The docs follow: the L15e row and the shell_sdl layer paragraph, the two points the #1493 review left in the L15g row, F14 and the W6 record in the platform plan, and the fw-compat reviewer's prompt, whose first-pass scan now reads the crate. On the development television, base and head played the Feed case `pipe_h264_aac_mp4` and the URI case `pipe_uri_product_hls_720p24_20m_bound` alike, and their SDL init lines are identical. The ARM binary's DT_NEEDED and undefined dynamic symbols equal base's. Non-incremental `make build-bench` rows are flat to better, with three more units for the new crate. --- .agents/agents/fw-compat-reviewer.md | 8 +- .agents/skills/ui-sim/SKILL.md | 2 +- .agents/skills/which-tier/SKILL.md | 4 +- .claude/hooks/release-config-check-test.py | 1 + .claude/hooks/release-config-check.py | 2 +- .github/workflows/ci.yml | 4 +- Makefile | 16 +- ci/build-budgets.json | 2 +- ci/check-build-budgets.py | 4 +- ci/check-deps.sh | 26 +- ci/list-caps.ini | 46 +- ci/mkmacapp.py | 2 +- ci/module-layers.ini | 16 +- ci/proofs/platform-generated-enums.json | 5 +- ci/proofs/serde-json-immutable.json | 5 +- ci/readonly_dependencies.py | 2 +- ci/readonly_generated.py | 2 +- ci/test_build_bench.py | 1 + ci/test_build_not_always_dirty.py | 4 +- ci/test_ci_split.py | 6 +- ci/test_no_host_staticlib.py | 4 +- ci/test_test_fast.py | 4 +- docs/agent-reference.md | 25 +- docs/distribution.md | 2 +- docs/lab-diagnostics.md | 2 +- docs/launch-links.md | 2 +- docs/macos-app.md | 2 +- docs/module-layers.md | 25 +- docs/platform-ports.md | 14 +- docs/remote-keys.md | 2 +- docs/search.md | 10 +- rust-modules/Cargo.lock | 8 + rust-modules/Cargo.toml | 23 +- rust-modules/base/src/surface.rs | 2 +- rust-modules/data/src/search.rs | 2 +- rust-modules/gfx/src/gfx.rs | 2 +- rust-modules/shell-sdl/Cargo.toml | 39 ++ rust-modules/shell-sdl/build.rs | 21 + rust-modules/shell-sdl/src/event.rs | 579 ++++++++++++++++++ rust-modules/shell-sdl/src/init.rs | 189 ++++++ rust-modules/shell-sdl/src/inject.rs | 232 ++++++++ rust-modules/shell-sdl/src/lib.rs | 109 ++++ rust-modules/shell-sdl/src/sys.rs | 81 +++ rust-modules/shell-sdl/src/testing.rs | 23 + rust-modules/shell-sdl/src/text.rs | 533 +++++++++++++++++ rust-modules/shell-sdl/src/window.rs | 510 ++++++++++++++++ rust-modules/src/app/boot.rs | 653 ++------------------- rust-modules/src/app/deeplink.rs | 2 +- rust-modules/src/app/events.rs | 480 +++------------ rust-modules/src/app/exit.rs | 4 +- rust-modules/src/app/mod.rs | 149 +---- rust-modules/src/app/platform.rs | 166 +++++- rust-modules/src/app/run.rs | 162 +++-- rust-modules/src/platform_desktop.rs | 23 +- rust-modules/src/port.rs | 59 +- rust-modules/src/system.rs | 152 ++++- rust-modules/src/textinput.rs | 492 +--------------- rust-modules/ui/src/consts.rs | 8 +- tools/build-bench.py | 4 +- tools/screenshots.py | 2 +- 60 files changed, 3172 insertions(+), 1787 deletions(-) create mode 100644 rust-modules/shell-sdl/Cargo.toml create mode 100644 rust-modules/shell-sdl/build.rs create mode 100644 rust-modules/shell-sdl/src/event.rs create mode 100644 rust-modules/shell-sdl/src/init.rs create mode 100644 rust-modules/shell-sdl/src/inject.rs create mode 100644 rust-modules/shell-sdl/src/lib.rs create mode 100644 rust-modules/shell-sdl/src/sys.rs create mode 100644 rust-modules/shell-sdl/src/testing.rs create mode 100644 rust-modules/shell-sdl/src/text.rs create mode 100644 rust-modules/shell-sdl/src/window.rs diff --git a/.agents/agents/fw-compat-reviewer.md b/.agents/agents/fw-compat-reviewer.md index e703609633..30f2bd3af1 100644 --- a/.agents/agents/fw-compat-reviewer.md +++ b/.agents/agents/fw-compat-reviewer.md @@ -127,8 +127,8 @@ the same SONAME on every release from 2.2.3 to 11.2.0. Moving a library into `dynlib!` **trades link-time symbol checking away** for version tolerance and is only worth it where the version actually varies. If a diff moves a stable library there, push back and ask for the `--inventory` output that justifies it. The precedent for the other direction is -`textinput.rs`: plain `extern "C"`, justified in its module doc by all 14 inventories exporting the -whole `SDL_*TextInput*` family. +`rust-modules/shell-sdl/src/sys.rs`: plain `extern "C"` (the `SDL_*TextInput*` calls among them), +justified in its module doc by all 14 inventories exporting the whole SDL2 family it names. ## WHAT `fwcompat.py` NEEDS BEFORE IT WILL ANSWER — settle this first, not at your third command @@ -163,7 +163,7 @@ git -C diff HEAD -- rust-modules/base/src/dynlib.rs rust-modules/media-co rust-modules/net/src/net.rs rust-modules/net/src/curlio.rs src/starfish.c src/video_plane.c src/starfish.h \ rust-modules/os/src/webos.rs rust-modules/os/src/webos/ls2/uri.rs Makefile \ ci/expected-dt-needed.txt ci/expected-dt-needed-uri.txt -grep -rn '#\[link\|extern "C"\|__asm__("' rust-modules/src rust-modules/media/src rust-modules/play-feed/src rust-modules/play-uri/src rust-modules/os/src rust-modules/media-codecs/src rust-modules/net/src src # against the diff, not the tree +grep -rn '#\[link\|extern "C"\|__asm__("' rust-modules/src rust-modules/shell-sdl/src rust-modules/media/src rust-modules/play-feed/src rust-modules/play-uri/src rust-modules/os/src rust-modules/media-codecs/src rust-modules/net/src src # against the diff, not the tree ``` ### 1. Decide, out loud, whether you are grading an ELF or grading source @@ -260,7 +260,7 @@ Reading the output: C++11 `std::string` ABI and are untested on a set apart from one 3.4.3 (webOS 1.x/2.x were never tried). They used to fail on two missing symbols, `SDL_webOSCursorVisibility` and `StarfishMediaAPIs::Feed`'s C++11 name, but since #578 both are `dlsym`'d at runtime - (`src/starfish.c`, `rust-modules/src/app/boot.rs`, and `rust-modules/src/system.rs`'s `cursor_door`), so the binary no longer imports them. Re-run + (`src/starfish.c`, and `rust-modules/src/system.rs`'s `webos3_cursor_sleep_hint` and `cursor_door`), so the binary no longer imports them. Re-run `tools/fwcompat.py` for what the old rows print now; they are still printed below the floor and do not set the exit status. * **Baseline as of 2026-08-23** (verified by running it): `15 DT_NEEDED, 319 undefined dynamic diff --git a/.agents/skills/ui-sim/SKILL.md b/.agents/skills/ui-sim/SKILL.md index 8d42232b2b..61885cbfab 100644 --- a/.agents/skills/ui-sim/SKILL.md +++ b/.agents/skills/ui-sim/SKILL.md @@ -80,7 +80,7 @@ state. Close other WSL work, run `wsl.exe --shutdown`, and retry; accept the run `use_gfxredir = 1`. **Ask for `SIM_W=1920 SIM_H=1080` on any shot you intend to JUDGE.** The window is otherwise sized -to fit the display (`app::boot::plan_desktop_window`), and on a 1x screen that divisor lands on 2, so +to fit the display (`plx_shell_sdl::window::plan_desktop_window`), and on a 1x screen that divisor lands on 2, so every screenshot comes back 960x540 — half the canvas the UI is authored at. A 1px edge-sheen, a hairline, a snapped glyph and a specular rim are exactly the things that do not survive that halving, which makes a shot at the default size evidence about layout and nothing else. The size is diff --git a/.agents/skills/which-tier/SKILL.md b/.agents/skills/which-tier/SKILL.md index ade82bff39..0273f40d24 100644 --- a/.agents/skills/which-tier/SKILL.md +++ b/.agents/skills/which-tier/SKILL.md @@ -80,7 +80,7 @@ but a photograph could show it (`gfx.rs`, at the `glBlendFuncSeparate` call). ### Tier 1 — `make check` -`cargo +$(RUST_TOOLCHAIN) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp`, preceded by `make lint` (three **named** clippy lints — +`cargo +$(RUST_TOOLCHAIN) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp`, preceded by `make lint` (three **named** clippy lints — `ifs_same_cond`, `same_functions_in_if_condition`, `if_same_then_else` — the shadowed-branch gate), and followed by **three** host checks that are easy to forget are in here: `python3 ci/flavor.py --selftest` (the flavour transform, whose central assertion is that the STABLE transform is the @@ -108,7 +108,7 @@ lock.) Do not write a new number here: measure it if you need one — this file Count it yourself if you need the number: ```sh -cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp -- --list | grep -c ': test' +cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp -- --list | grep -c ': test' ``` **Run it on the pinned toolchain.** `make check` uses `cargo +$(RUST_TOOLCHAIN)`, the `channel` of diff --git a/.claude/hooks/release-config-check-test.py b/.claude/hooks/release-config-check-test.py index 134742b1a2..c0f51c84e5 100755 --- a/.claude/hooks/release-config-check-test.py +++ b/.claude/hooks/release-config-check-test.py @@ -77,6 +77,7 @@ def edit(path, tool="Edit", key="file_path", **extra): (FIRE, "the media layer crate\\'s source", edit("/repo/rust-modules/media/src/player/mod.rs"), ROOT), (FIRE, "the appkit layer crate\\'s source", edit("/repo/rust-modules/appkit/src/player_hud/mod.rs"), ROOT), (FIRE, "the screens layer crate\\'s source", edit("/repo/rust-modules/screens/src/home/mod.rs"), ROOT), + (FIRE, "the shell_sdl layer crate's source", edit("/repo/rust-modules/shell-sdl/src/window.rs"), ROOT), (FIRE, "MultiEdit", edit("/repo/rust-modules/src/app/run.rs", tool="MultiEdit"), ROOT), (FIRE, "relative to root", edit("rust-modules/src/route.rs"), ROOT), (FIRE, "relative to a subdir", edit("src/plex/client.rs"), "/repo/rust-modules"), diff --git a/.claude/hooks/release-config-check.py b/.claude/hooks/release-config-check.py index 434e61775f..fd86d4c2a4 100755 --- a/.claude/hooks/release-config-check.py +++ b/.claude/hooks/release-config-check.py @@ -273,7 +273,7 @@ def rust_src_target(payload, root, cwd=None): src = os.path.realpath(os.path.join(root, "rust-modules", "src")) # The layer crates split out of `src` (docs/module-layers.md) are compiled by the same # `cargo check --lib` as a dependency, so an edit there is a release-configuration risk too. - layer_srcs = [os.path.realpath(os.path.join(root, "rust-modules", layer, "src")) for layer in ("base", "machine", "net", "os", "gfx", "ui", "plex", "telemetry", "data", "session", "media", "appkit", "screens")] + layer_srcs = [os.path.realpath(os.path.join(root, "rust-modules", layer, "src")) for layer in ("base", "machine", "net", "os", "gfx", "ui", "plex", "telemetry", "data", "session", "media", "appkit", "screens", "shell-sdl")] if not any(path.startswith(s + os.sep) for s in [src] + layer_srcs): return None # `--lib` compiles no bin target, and `sim.rs` needs `hostsim`, which the release set never has. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3e220bbe9d..dddcfbbb35 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -259,7 +259,7 @@ jobs: # (`cargo metadata` resolves; it compiles nothing), plus an informational line count. # The binary-size budget runs in cross-build, where the binary exists. Limits and how to # raise one deliberately: ci/build-budgets.json, docs/agent-reference.md. - run: python3 ci/check-build-budgets.py --graph --src rust-modules/src --src rust-modules/base/src --src rust-modules/machine/src --src rust-modules/net/src --src rust-modules/os/src --src rust-modules/gfx/src --src rust-modules/ui/src --src rust-modules/plex/src --src rust-modules/telemetry/src --src rust-modules/data/src --src rust-modules/session/src --src rust-modules/media/src --src rust-modules/playback-contract/src --src rust-modules/media-codecs/src --src rust-modules/play-feed/src --src rust-modules/play-uri/src --src rust-modules/appkit/src --src rust-modules/screens/src --src rust-modules/owp/src + run: python3 ci/check-build-budgets.py --graph --src rust-modules/src --src rust-modules/base/src --src rust-modules/machine/src --src rust-modules/net/src --src rust-modules/os/src --src rust-modules/gfx/src --src rust-modules/ui/src --src rust-modules/plex/src --src rust-modules/telemetry/src --src rust-modules/data/src --src rust-modules/session/src --src rust-modules/media/src --src rust-modules/playback-contract/src --src rust-modules/media-codecs/src --src rust-modules/play-feed/src --src rust-modules/play-uri/src --src rust-modules/appkit/src --src rust-modules/screens/src --src rust-modules/shell-sdl/src --src rust-modules/owp/src - name: Third-party notices vs the ARM runtime graph # `make check` runs only the OFFLINE half of this (ci/gen-third-party-notices.py --check), which @@ -310,7 +310,7 @@ jobs: # for plxnative-modules both ways), so the `cargo test --lib` below finds everything built # and this step is where the compile happens, not an extra one. The upload below carries it. shell: bash - run: cd rust-modules && cargo "+$RUST_TOOLCHAIN" test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp --no-run --timings + run: cd rust-modules && cargo "+$RUST_TOOLCHAIN" test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp --no-run --timings - name: make check-cargo-unit-default # Teed to a file so the size step below can read the `test result:` lines this run already diff --git a/Makefile b/Makefile index c14578a7fd..53d3663235 100644 --- a/Makefile +++ b/Makefile @@ -1050,7 +1050,7 @@ $(FFABI_STAMP): ci/ffabi-assert.c $(FFMPEG_INC)/libavformat/avformat.h Makefile # rule would leave every later `make` linking a library built by the OLD one. Cargo's own # `rerun-if-changed` cannot save that — it is only consulted when make decides to invoke cargo at # all, and this target is an ordinary timestamp comparison. -RUST_INPUTS := $(shell find rust-modules/src rust-modules/base rust-modules/machine rust-modules/net rust-modules/os rust-modules/gfx rust-modules/ui rust-modules/plex rust-modules/telemetry rust-modules/data rust-modules/session rust-modules/media rust-modules/playback-contract rust-modules/play-uri rust-modules/play-feed rust-modules/media-codecs rust-modules/appkit rust-modules/screens rust-modules/build_support locales assets -type f 2>/dev/null) +RUST_INPUTS := $(shell find rust-modules/src rust-modules/base rust-modules/machine rust-modules/net rust-modules/os rust-modules/gfx rust-modules/ui rust-modules/plex rust-modules/telemetry rust-modules/data rust-modules/session rust-modules/media rust-modules/playback-contract rust-modules/play-uri rust-modules/play-feed rust-modules/media-codecs rust-modules/appkit rust-modules/screens rust-modules/shell-sdl rust-modules/build_support locales assets -type f 2>/dev/null) $(RUST_LIB): LICENSE $(RUST_INPUTS) rust-modules/Cargo.toml rust-modules/Cargo.lock rust-modules/build.rs ci/install-identities.json rust-modules/.cargo/config.toml Makefile ci/check-staticlib-artifact.py $(FFABI_STAMP) @# BEFORE the mkdir: the seed is only ever cloned into a target dir that does not exist yet. $(CARGO_SEED) restore $(RUST_TDIR) rust-modules/$(RUST_TDIR) @@ -1717,7 +1717,7 @@ check-cargo-lint: lint @# gate has nothing to reuse a cache for. No `pkg/lab.json` is involved — that file is `make @# LAB=1`'s requirement (a live session secret), not the compiler's. @set -e; cd rust-modules && CARGO_INCREMENTAL=0 PATH="$$HOME/.cargo/bin:$$PATH" \ - cargo +$(RUST_TOOLCHAIN) check --lib --tests -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp --features lab-diagnostics + cargo +$(RUST_TOOLCHAIN) check --lib --tests -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp --features lab-diagnostics @# And the demo-video dump build's pixel oracle, `placeholder-sentinel`: in no default set and @# built only by `make site-video-sim`, which no gate runs and which compiles no `plx_ui` tests, so @# this line is what keeps it compiling (its code AND its tests, `--tests`). `plx_ui` is the only @@ -1736,7 +1736,7 @@ check-cargo-lint: lint # `-p` lists in the recipes below (those stay literal because ci/test_ci_split.py greps for them); # ci/test_test_crate.py pins the two equal. UNIT_RUN = python3 ../tools/cargo-test-parallel.py -UNIT_SUITE = plxnative-modules plx_base plx_machine plx_os plx_gfx plx_net plx_ui plx_plex plx_telemetry plx_data plx_session plx_media plx_playback_contract plx_play_uri plx_play_feed plx_media_codecs plx_appkit plx_screens plx_owp +UNIT_SUITE = plxnative-modules plx_base plx_machine plx_os plx_gfx plx_net plx_ui plx_plex plx_telemetry plx_data plx_session plx_media plx_playback_contract plx_play_uri plx_play_feed plx_media_codecs plx_appkit plx_screens plx_shell_sdl plx_owp # The `hostsim` pass runs only the crates that DECLARE a `hostsim` feature (HOSTSIM_SUITE, a subset of # UNIT_SUITE in the same order; ci/test_test_crate.py pins both the subset and the recipe). The eight that # do not (plx_net, plx_ui, plx_appkit, plx_screens, plx_media_codecs, plx_play_uri, plx_playback_contract, @@ -1748,7 +1748,7 @@ UNIT_SUITE = plxnative-modules plx_base plx_machine plx_os plx_gfx plx_net plx_u # none of their tests observes those dependency-side differences; the guard does not check that, it # checks that the crate declares no `hostsim` feature and has no `feature = "hostsim"` in its src, and # fails when one gains either, which is the moment it must join the list. -HOSTSIM_SUITE = plxnative-modules plx_base plx_machine plx_os plx_gfx plx_plex plx_telemetry plx_data plx_session plx_media plx_play_feed +HOSTSIM_SUITE = plxnative-modules plx_base plx_machine plx_os plx_gfx plx_plex plx_telemetry plx_data plx_session plx_media plx_play_feed plx_shell_sdl # The default-feature unit suite and everything that drives cargo through ci/ self-tests. check-cargo-unit-default: @@ -1777,7 +1777,7 @@ check-cargo-unit-default: cd rust-modules && PATH="$$HOME/.cargo/bin:$$PATH" PLXNATIVE_RUNTIME_DIR="$$d" \ $(TELEMETRY_ENV) \ $(HOST_ENV) \ - $(UNIT_RUN) -- cargo +$(RUST_TOOLCHAIN) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp + $(UNIT_RUN) -- cargo +$(RUST_TOOLCHAIN) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp RUST_TOOLCHAIN=$(RUST_TOOLCHAIN) python3 ci/test_storage_service_package.py cd rust-modules && PATH="$$HOME/.cargo/bin:$$PATH" cargo +$(RUST_TOOLCHAIN) test -p plxnative-storage --bin plxnative-storage @# The helper is its own package, so building it compiles no copy of the app library; this reads @@ -1811,7 +1811,7 @@ check-cargo-unit-hostsim: cd rust-modules && PATH="$$HOME/.cargo/bin:$$PATH" PLXNATIVE_RUNTIME_DIR="$$d" \ $(TELEMETRY_ENV) \ $(HOST_ENV) \ - $(UNIT_RUN) -- cargo +$(RUST_TOOLCHAIN) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_play_feed --features hostsim + $(UNIT_RUN) -- cargo +$(RUST_TOOLCHAIN) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_play_feed -p plx_shell_sdl --features hostsim # OPT-IN incremental inner loop: the default-feature unit suite (the same `cargo test --lib` as # `check-cargo-unit-default`, same throwaway runtime root and telemetry env) with @@ -1835,7 +1835,7 @@ test-fast: PATH="$$HOME/.cargo/bin:$$PATH" PLXNATIVE_RUNTIME_DIR="$$d" \ $(TELEMETRY_ENV) \ $(HOST_ENV) \ - $(UNIT_RUN) $(if $(T),--filter '$(T)') -- cargo +$(RUST_TOOLCHAIN) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp + $(UNIT_RUN) $(if $(T),--filter '$(T)') -- cargo +$(RUST_TOOLCHAIN) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp # `make test-crate C=plx_ui [T=filter] [DEPS=1]` -- build and run ONLY the named crate's lib tests, in # the same incremental `$(TEST_FAST_TDIR)` tree and with the same flags as `test-fast`, so the two @@ -2471,7 +2471,7 @@ SIM_SHOT ?= $(SIM_DIR)/shot.png # reason BOOT_SH exists for `run`/`run-stream`. # Size of the simulator's DRAWABLE in pixels, 1:1 on any pixel density (the window is ALLOW_HIGHDPI, so # on a Retina display it is half this many points; `fit_window_to_density` does the conversion). -# Empty = fit the display (see `plan_desktop_window`), which on a 1x screen is half the authored +# Empty = fit the display (see `plx_shell_sdl`'s `plan_desktop_window`), which on a 1x screen is half the authored # canvas and therefore half the resolution of every screenshot. Set both to look at the UI the # size it is drawn: # make sim-shot SIM_W=1920 SIM_H=1080 diff --git a/ci/build-budgets.json b/ci/build-budgets.json index d72fb5a550..f6667386e9 100644 --- a/ci/build-budgets.json +++ b/ci/build-budgets.json @@ -48,7 +48,7 @@ "headroom": "+3" }, "source_lines": { - "what": "Lines of Rust under rust-modules/src, rust-modules/base/src, rust-modules/machine/src, rust-modules/net/src, rust-modules/os/src, rust-modules/gfx/src, rust-modules/ui/src, rust-modules/plex/src, rust-modules/telemetry/src, rust-modules/data/src, rust-modules/session/src, rust-modules/media/src, rust-modules/playback-contract/src, rust-modules/media-codecs/src, rust-modules/play-feed/src, rust-modules/play-uri/src, rust-modules/appkit/src, rust-modules/screens/src and rust-modules/owp/src (every .rs file). Informational: exceeding it warns and never fails, because a growing feature is not a build-health defect by itself.", + "what": "Lines of Rust under rust-modules/src, rust-modules/base/src, rust-modules/machine/src, rust-modules/net/src, rust-modules/os/src, rust-modules/gfx/src, rust-modules/ui/src, rust-modules/plex/src, rust-modules/telemetry/src, rust-modules/data/src, rust-modules/session/src, rust-modules/media/src, rust-modules/playback-contract/src, rust-modules/media-codecs/src, rust-modules/play-feed/src, rust-modules/play-uri/src, rust-modules/appkit/src, rust-modules/screens/src, rust-modules/shell-sdl/src and rust-modules/owp/src (every .rs file). Informational: exceeding it warns and never fails, because a growing feature is not a build-health defect by itself.", "unit": "lines", "mode": "warn", "limit": 485000, diff --git a/ci/check-build-budgets.py b/ci/check-build-budgets.py index 6ea4444a9e..b2c2d3fe0e 100755 --- a/ci/check-build-budgets.py +++ b/ci/check-build-budgets.py @@ -15,7 +15,7 @@ * binary_bytes the stripped binary `make ipk` stages (measured in the cross-build job) * packages_* third-party packages the app crate compiles for the ARM target * duplicate_versions_* crate names in more than one version on the normal-edge graph -* source_lines lines of Rust in rust-modules/src and every split-out layer crate (rust-modules/base/src, rust-modules/machine/src, rust-modules/net/src, rust-modules/os/src, rust-modules/gfx/src, rust-modules/ui/src, rust-modules/plex/src, rust-modules/telemetry/src, rust-modules/data/src, rust-modules/session/src, rust-modules/media/src, rust-modules/playback-contract/src, rust-modules/media-codecs/src, rust-modules/play-feed/src, rust-modules/play-uri/src, rust-modules/appkit/src, rust-modules/screens/src, rust-modules/owp/src); mode "warn", never fails +* source_lines lines of Rust in rust-modules/src and every split-out layer crate (rust-modules/base/src, rust-modules/machine/src, rust-modules/net/src, rust-modules/os/src, rust-modules/gfx/src, rust-modules/ui/src, rust-modules/plex/src, rust-modules/telemetry/src, rust-modules/data/src, rust-modules/session/src, rust-modules/media/src, rust-modules/playback-contract/src, rust-modules/media-codecs/src, rust-modules/play-feed/src, rust-modules/play-uri/src, rust-modules/appkit/src, rust-modules/screens/src, rust-modules/shell-sdl/src, rust-modules/owp/src); mode "warn", never fails Exit status: 0 all within budget (warn-mode overruns print ::warning::), 1 a fail-mode budget is exceeded, 2 the budgets file or an input is unusable. @@ -243,7 +243,7 @@ def main(argv=None) -> int: ap.add_argument("--graph", action="store_true") ap.add_argument("--tree-default") ap.add_argument("--tree-no-default") - ap.add_argument("--src", action="append", help="a source directory to count; repeat for each crate (rust-modules/src, rust-modules/base/src, rust-modules/machine/src, rust-modules/net/src, rust-modules/os/src, rust-modules/gfx/src, rust-modules/ui/src, rust-modules/plex/src, rust-modules/telemetry/src, rust-modules/data/src, rust-modules/session/src, rust-modules/media/src, rust-modules/playback-contract/src, rust-modules/media-codecs/src, rust-modules/play-feed/src, rust-modules/play-uri/src, rust-modules/appkit/src, rust-modules/screens/src, rust-modules/owp/src)") + ap.add_argument("--src", action="append", help="a source directory to count; repeat for each crate (rust-modules/src, rust-modules/base/src, rust-modules/machine/src, rust-modules/net/src, rust-modules/os/src, rust-modules/gfx/src, rust-modules/ui/src, rust-modules/plex/src, rust-modules/telemetry/src, rust-modules/data/src, rust-modules/session/src, rust-modules/media/src, rust-modules/playback-contract/src, rust-modules/media-codecs/src, rust-modules/play-feed/src, rust-modules/play-uri/src, rust-modules/appkit/src, rust-modules/screens/src, rust-modules/shell-sdl/src, rust-modules/owp/src)") args = ap.parse_args(argv) try: budgets = load_budgets(Path(args.budgets)) diff --git a/ci/check-deps.sh b/ci/check-deps.sh index 8ebbf38ce1..d52975a4f6 100755 --- a/ci/check-deps.sh +++ b/ci/check-deps.sh @@ -152,6 +152,7 @@ SRC_MEDIA_CODECS=rust-modules/media-codecs/src SRC_APPKIT=rust-modules/appkit/src SRC_SCREENS=rust-modules/screens/src SRC_OWP=rust-modules/owp/src +SRC_SHELL_SDL=rust-modules/shell-sdl/src fails=0 fail() { echo "::error::check-deps: $*"; fails=$((fails+1)); } ok() { echo " ok — $*"; } @@ -353,6 +354,7 @@ wholly_test_files() { python3 ci/rust_test_modules.py "$SRC_APPKIT" python3 ci/rust_test_modules.py "$SRC_SCREENS" python3 ci/rust_test_modules.py "$SRC_OWP" + python3 ci/rust_test_modules.py "$SRC_SHELL_SDL" } # is_wholly_test : the `wholly_test` list as a builtin lookup. Three gates below asked this @@ -720,7 +722,7 @@ fi # metadata-owner # Wholly-test files (see `wholly_test_files`) are skipped like inline `#[cfg(test)]` blocks: a # test's reference colour maths is not logical state. if want libm; then -libm_lines=$(grep_code '\.(exp|ln|log|powf|powi|cbrt|sin|cos|tan|atan2|hypot|mul_add|sin_cos)\(' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" \ +libm_lines=$(grep_code '\.(exp|ln|log|powf|powi|cbrt|sin|cos|tan|atan2|hypot|mul_add|sin_cos)\(' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" "$SRC_SHELL_SDL" \ | grep -vE '\.log\((&|")' | grep -v "^$SRC_MACHINE/motion.rs:") libm_bad=0 while IFS= read -r line; do @@ -732,7 +734,7 @@ done <<< "$libm_lines" if [ "$libm_bad" -eq 0 ]; then ok "libm"; else fail "libm: $libm_bad line(s) outside ci/allow/libm.txt"; fi fi # libm -want ticks && gate ticks 'SDL_GetTicks\(' "$SRC" "$SRC_BASE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" +want ticks && gate ticks 'SDL_GetTicks\(' "$SRC" "$SRC_BASE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" "$SRC_SHELL_SDL" # Every data/session module is logic unless its exact reviewed IO/instrument file is in ports.ini. if want wall; then if python3 ci/check-ports.py; then ok "wall"; else fail "wall: outside exact ci/ports.ini files"; fi @@ -750,7 +752,7 @@ if [ "$n" -eq 1 ] && [ "$d" -eq 1 ]; then ok "present: one worker door"; else fa fi # present if want effect; then -if [ -n "$(grep_code '\bEffect::' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP")" ]; then fail "effect: \`Effect::\` is spelled (use Fx:: / AppFx::)"; else ok "effect"; fi +if [ -n "$(grep_code '\bEffect::' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" "$SRC_SHELL_SDL")" ]; then fail "effect: \`Effect::\` is spelled (use Fx:: / AppFx::)"; else ok "effect"; fi fi # effect # mutators: production lines of ui/, screens/ and app/ (everything before the file's first @@ -862,7 +864,7 @@ want nav && gate nav '(crate::ui|plx_ui)::nav::' "$SRC" "$SRC_UI" "$SRC_APPKIT" # Completed ownership migration: legacy publications and the old gate cannot return. if want ui-owner-legacy; then -ui_owner_hits=$(grep_code '(plx_ui|crate::ui)::press::|(plx_machine|crate)::idle::' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP") +ui_owner_hits=$(grep_code '(plx_ui|crate::ui)::press::|(plx_machine|crate)::idle::' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" "$SRC_SHELL_SDL") if [ -z "$ui_owner_hits" ]; then ok "ui-owner-legacy"; else printf '%s\n' "$ui_owner_hits" fail "ui-owner-legacy: retired global readers must not return" @@ -962,7 +964,7 @@ want uistorage && gate uistorage '(crate|super|plx_os)::storage::' "$SRC_UI" "$S # legacypage: the word itself, anywhere under src — a doc that still describes the type is as much # a hit as a declaration, which is the point (nothing compiles the prose either). if want legacypage; then -legacy_hits=$(grep -rn --include='*.rs' 'LegacyPage' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" 2>/dev/null || true) +legacy_hits=$(grep -rn --include='*.rs' 'LegacyPage' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" "$SRC_SHELL_SDL" 2>/dev/null || true) if [ -z "$legacy_hits" ]; then ok "legacypage"; else echo "$legacy_hits" | sed 's/^/ /' fail "legacypage: $(echo "$legacy_hits" | wc -l | tr -d ' ') mention(s) — the type is retired (§15.2)" @@ -1056,7 +1058,7 @@ fi # textmeasure # the documented intent (spec §4.2: the ONLY file licensed to touch a raw per-frame delta), not a # live carve-out. if want dt; then -dt_hits=$(grep_code 'idle::dt\(\)|(\+=|-=)\s*dt\b' "$SRC" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" | grep -v "^$SRC_MACHINE/motion.rs:") +dt_hits=$(grep_code 'idle::dt\(\)|(\+=|-=)\s*dt\b' "$SRC" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" "$SRC_SHELL_SDL" | grep -v "^$SRC_MACHINE/motion.rs:") if [ -z "$dt_hits" ]; then ok "dt"; else echo "$dt_hits" | sed 's/^/ /' fail "dt: $(echo "$dt_hits" | wc -l | tr -d ' ') line(s) — see rule comment above" @@ -1134,7 +1136,7 @@ while IFS= read -r f; do # REMOVES matches, so a file with no raw hit cannot fail this gate — and running its `awk` plus a # `grep` over all 420 files, to reach the two that mention the shape, was the single most expensive # rule in this script (4.8 s of its 17 s). -done < <(grep -rlE --include='*.rs' "$frame_pat" "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" 2>/dev/null | sort) +done < <(grep -rlE --include='*.rs' "$frame_pat" "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" "$SRC_SHELL_SDL" 2>/dev/null | sort) if [ "$frame_bad" -eq 0 ]; then ok "frame" else fail "frame: $frame_bad line(s) of a privileged OS-primitive call outside app/run.rs"; fi fi # frame @@ -1159,7 +1161,7 @@ while IFS= read -r line; do case "$p" in "$SRC_MEDIA"/player/*|"$SRC_OS"/tv/*|"$SRC_OS"/tv.rs|"$SRC_OS"/webos/*|"$SRC"/port.rs|"$SRC"/platform_desktop.rs|"$SRC"/app/adapters/backends.rs) continue ;; esac if is_wholly_test "$p"; then continue; fi echo " $line"; sink_bad=$((sink_bad+1)) -done < <(grep_code 'tv::sink::(installed|display_installed)|\b(VideoSink|DisplaySink)\b' "$SRC" "$SRC_OS" "$SRC_UI" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP") +done < <(grep_code 'tv::sink::(installed|display_installed)|\b(VideoSink|DisplaySink)\b' "$SRC" "$SRC_OS" "$SRC_UI" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" "$SRC_SHELL_SDL") if [ "$sink_bad" -eq 0 ]; then ok "sink" else fail "sink: $sink_bad line(s) naming the video sink outside playback execution, port.rs, platform_desktop.rs, tv.rs and tv/"; fi fi # sink @@ -1258,7 +1260,7 @@ while IFS= read -r f; do { print NR":"$0; prev=$0 }' "$f" | grep -E "$pat" | grep -vE '^[0-9]+:\s*//' || true) # ...over the files that spell `spawn(` at all — a superset of both matched spellings, and the `awk` # below only drops `#[cfg(test)] mod` blocks, so the count is unchanged. -done < <(grep -rlE --include='*.rs' '\bspawn\(' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" 2>/dev/null | grep -v "^$SRC_BASE/task.rs\$" | sort) +done < <(grep -rlE --include='*.rs' '\bspawn\(' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" "$SRC_SHELL_SDL" 2>/dev/null | grep -v "^$SRC_BASE/task.rs\$" | sort) threads_declared=$(sed -n 's/^# count: *//p' ci/allow/threads.txt | head -1) if [ "$threads_bad" -eq "${threads_declared:-0}" ]; then ok "threads" else fail "threads: $threads_bad line(s) outside ci/allow/threads.txt (declared count is exactly ${threads_declared:-0}, not a ceiling)"; fi @@ -1403,7 +1405,7 @@ EOF_STALE # `ci/ledger.awk` (the ledger machinery above). if want blocking; then blocking_sites=$( - grep -rlE --include='*.rs' 'allow_blocking' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" 2>/dev/null \ + grep -rlE --include='*.rs' 'allow_blocking' "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" "$SRC_SHELL_SDL" 2>/dev/null \ | grep -v "^$SRC_BASE/task/blocking.rs\$" | sort \ | LG_MODE=call LG_SITE='(^|[^A-Za-z0-9_])allow_blocking\(' LG_DEF='fn[[:space:]]+allow_blocking\(' \ LG_REF='(^|[^A-Za-z0-9_])allow_blocking([^A-Za-z0-9_(]|$)' LG_REEXPORT_FILE="$SRC_BASE/task.rs" \ @@ -1655,7 +1657,7 @@ fi # fxlanes # neither one is a `/tmp/plxnative-` literal in the first place and there is no second file to # name here (re-verify this if a log sink is ever given a hardcoded `/tmp/` path). if want tmppath; then -tmp_hits=$(python3 - "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" <<'PY' +tmp_hits=$(python3 - "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" "$SRC_SHELL_SDL" <<'PY' import os, sys src = sys.argv[1] @@ -1756,7 +1758,7 @@ fi # tmppath # classification above) and `#[cfg(test)]` items, found from tokens so a literal inside a string is # never mistaken for a comment. Zero, no allowlist. Scans every crate root, not only plex's. if want paging; then -paging_hits=$(WHOLLY_TEST="$wholly_test" python3 - "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" <<'PY' +paging_hits=$(WHOLLY_TEST="$wholly_test" python3 - "$SRC" "$SRC_BASE" "$SRC_MACHINE" "$SRC_OS" "$SRC_GFX" "$SRC_NET" "$SRC_UI" "$SRC_PLEX" "$SRC_TELEMETRY" "$SRC_DATA" "$SRC_SESSION" "$SRC_MEDIA" "$SRC_PLAYBACK_CONTRACT" "$SRC_PLAY_URI" "$SRC_PLAY_FEED" "$SRC_MEDIA_CODECS" "$SRC_APPKIT" "$SRC_SCREENS" "$SRC_OWP" "$SRC_SHELL_SDL" <<'PY' import os, sys sys.path.insert(0, "ci") from rust_test_modules import close, lex diff --git a/ci/list-caps.ini b/ci/list-caps.ini index 1972afd6ce..c9066e8348 100644 --- a/ci/list-caps.ini +++ b/ci/list-caps.ini @@ -998,6 +998,32 @@ reason = Generations of a PIN-poll supersede counter. class = not-a-list reason = Distinct incident keys a launch remembers; state-growth guard on the closed kind-by-link space. +# ---- shell-sdl ------------------------------------------------------------ + +[shell-sdl/src/event.rs::SYNTH_WINDOW] +class = not-a-list +reason = SYNTH_WINDOW: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. + +[shell-sdl/src/text.rs::TEXT_CAP] +class = not-a-list +reason = TEXT_CAP: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. + +[shell-sdl/src/text.rs::drop_cut_tail] +class = not-a-list +reason = drop_cut_tail: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. + +[shell-sdl/src/window.rs::SDL_WINDOW_ALLOW_HIGHDPI] +class = not-a-list +reason = SDL_WINDOW_ALLOW_HIGHDPI: one window-flag bit of SDL's own (the desktop window asks for the display's pixel density), not a count and not a list the user browses. + +[shell-sdl/src/window.rs::SDL_WINDOW_FLAGS] +class = not-a-list +reason = SDL_WINDOW_FLAGS: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. + +[shell-sdl/src/window.rs::SDL_WINDOW_INPUT_FOCUS] +class = not-a-list +reason = SDL_WINDOW_INPUT_FOCUS: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. + # ---- src ------------------------------------------------------------ [src/app/adapters/poster.rs::AHEAD_MAX] @@ -1060,18 +1086,6 @@ reason = LEFT_ROWS: application/dev tooling bound (scenario period, text input b class = not-a-list reason = RIGHT_ROWS: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. -[src/app/events.rs::SYNTH_WINDOW] -class = not-a-list -reason = SYNTH_WINDOW: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. - -[src/app/mod.rs::SDL_WINDOW_FLAGS] -class = not-a-list -reason = SDL_WINDOW_FLAGS: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. - -[src/app/mod.rs::SDL_WINDOW_INPUT_FOCUS] -class = not-a-list -reason = SDL_WINDOW_INPUT_FOCUS: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. - [src/app/run.rs::log_raw_input_event] class = not-a-list reason = log_raw_input_event: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. @@ -1116,14 +1130,6 @@ reason = MAX_WAIT_MS: application/dev tooling bound (scenario period, text input class = not-a-list reason = MAX_PENDING: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. -[src/textinput.rs::TEXT_CAP] -class = not-a-list -reason = TEXT_CAP: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. - -[src/textinput.rs::drop_cut_tail] -class = not-a-list -reason = drop_cut_tail: application/dev tooling bound (scenario period, text input buffer, capture or event header); not a list the user browses. - # ---- telemetry ------------------------------------------------------------ [telemetry/src/diag/mod.rs::DEFERRED_CAP] diff --git a/ci/mkmacapp.py b/ci/mkmacapp.py index a8df0451de..808a262569 100755 --- a/ci/mkmacapp.py +++ b/ci/mkmacapp.py @@ -155,7 +155,7 @@ def write_icon(res: Path): def write_plist(contents: Path, ver: str): - """`NSHighResolutionCapable` is the half that makes `app.rs`'s ALLOW_HIGHDPI window real: with + """`NSHighResolutionCapable` is the half that makes `plx_shell_sdl`'s ALLOW_HIGHDPI window real: with it the 960x540-point window gets a 1920x1080 drawable, i.e. `surface::scale() == 1.0` — the same 1:1 texel contract the television renders under. Without it the OS hands back a half-resolution surface and doubles the whole interface.""" diff --git a/ci/module-layers.ini b/ci/module-layers.ini index 00325a7bd3..c515843672 100644 --- a/ci/module-layers.ini +++ b/ci/module-layers.ini @@ -73,6 +73,20 @@ members = webos storage keymanager devcaps imgcache i18n labcfg tv playback_trac uses = base machine os members = gfx egl text rtl img svg gpu_timer hwcnt overdraw dump +[shell_sdl] +# EXTRACTED: this layer is the workspace crate `plx_shell_sdl` (rust-modules/shell-sdl/); ci/module_graph.py +# reads it as part of the same module tree through the manifest's `mount = "shell_sdl"` (a path +# `plx_shell_sdl::event::decode` names module `shell_sdl::event`), like `plx_play_uri`. +# The stock-SDL shell the application opens its window through: SDL's init, the window and its GL context, +# the swap, the event queue, the key, pointer, wheel and text layouts of both SDLs, and the synthetic +# events pushed back onto the queue. It names no `ui`, no application type and none of [platform webos]; the +# application drives it through its own `Shell` and `Surface` (`app::platform`), and the television's LG half +# (the SysWMinfo handshake, the Wayland surface, the boot hooks around `SDL_Init`) stays in `system`. The crate +# names nothing of `machine` or `os` today, so it depends on `plx_base` only; the ceiling stays (the same +# ruling `[gfx]` records for `os`). +uses = base machine os +members = shell_sdl + [net] # EXTRACTED: this layer is the workspace crate `plx_net` (rust-modules/net/), the fifth split of # docs/module-layers.md; ci/module_graph.py reads it as part of the same module tree (a path @@ -188,7 +202,7 @@ members = screens [app] # The loop, its adapters and every dev/diagnostic surface; lib.rs's own items are the facade. -uses = base machine os gfx net plex telemetry ui data session media appkit screens playback_contract play_uri play_feed media_codecs +uses = base machine os gfx net plex telemetry ui data session media appkit screens shell_sdl playback_contract play_uri play_feed media_codecs members = crate app dev lab capture remote focusprobe hud_cli hud_tools shot coldstart textinput system release_line port platform_desktop diff --git a/ci/proofs/platform-generated-enums.json b/ci/proofs/platform-generated-enums.json index 37bed563b4..5c26e2a350 100644 --- a/ci/proofs/platform-generated-enums.json +++ b/ci/proofs/platform-generated-enums.json @@ -30,10 +30,10 @@ } }, "include": "include!(concat!(env!(\"OUT_DIR\"), \"/languages.rs\"));", - "lock": "4c8ae319c8db665085f3fe744a30ae925f744feba2e64c3c38de51a94d762b16", + "lock": "800367e4065771c60d1fe5c722e209b2483247a620f382b2248e150bf00b3ad0", "machine_newtype": "reviewed local newtype macro emits pub struct Name(pub u32); doc attributes only", "manifests": { - "Cargo.toml": "1143141629f93032567e2cbf0e119ec0e4381ff32ea84f27f458ae661d715f31", + "Cargo.toml": "88f7b3a976961d5ed784878f2d968330d64a7d034aad87f3fa71672bcf9a41ac", "appkit/Cargo.toml": "5cc1214cba7746fe0f2d4cfa5047b599e0d5124abe7bdaebe210381021b88c4a", "base/Cargo.toml": "ebe0b95553bd44f33f422f7d8e22b75ddeb53c7ee81bbe738f675690694568f7", "data/Cargo.toml": "74f79e6240f0965069ec34916ae276b3f7e5f4b944cf16a0846570a6b115afa0", @@ -50,6 +50,7 @@ "plex/Cargo.toml": "5cdb185265b7f7217cff08e54ef683a827735c9b3ae7c50161850f7064667b66", "screens/Cargo.toml": "cd42484a49fac394244ebc7b81f30f7e4f9a31cdf7bc1ace5c3fae21afd6d511", "session/Cargo.toml": "ecb49fc9f44177be6de36715ad70845b8929799cdbeb5ce9d6939be741704db0", + "shell-sdl/Cargo.toml": "9bccdb0abdb2ce9afdc030af9454117ed53884f9b50e1ee35a21bcfe6459e9a1", "storage/Cargo.toml": "4b8576b04a5877e95d084a49a16b30224c275ae29b4a192c40725ac819500150", "telemetry/Cargo.toml": "9e514e64ae4a35619294621f22534b5e5b109d9dd3b729b94ed20112f47197bf", "ui/Cargo.toml": "7375c6a73cb2558c7c0f62da7b0bd4beb2a5b78f5460ee35e93b1045c0e80eec" diff --git a/ci/proofs/serde-json-immutable.json b/ci/proofs/serde-json-immutable.json index 567f2930e1..1fd2577724 100644 --- a/ci/proofs/serde-json-immutable.json +++ b/ci/proofs/serde-json-immutable.json @@ -371,9 +371,9 @@ ".cargo/config": null, ".cargo/config.toml": "82f061c716740e16cfee63a74d87159e0e0dc253e1092b87c54190c603515b14" }, - "lock_sha256": "4c8ae319c8db665085f3fe744a30ae925f744feba2e64c3c38de51a94d762b16", + "lock_sha256": "800367e4065771c60d1fe5c722e209b2483247a620f382b2248e150bf00b3ad0", "manifests": { - "Cargo.toml": "1143141629f93032567e2cbf0e119ec0e4381ff32ea84f27f458ae661d715f31", + "Cargo.toml": "88f7b3a976961d5ed784878f2d968330d64a7d034aad87f3fa71672bcf9a41ac", "appkit/Cargo.toml": "5cc1214cba7746fe0f2d4cfa5047b599e0d5124abe7bdaebe210381021b88c4a", "base/Cargo.toml": "ebe0b95553bd44f33f422f7d8e22b75ddeb53c7ee81bbe738f675690694568f7", "data/Cargo.toml": "74f79e6240f0965069ec34916ae276b3f7e5f4b944cf16a0846570a6b115afa0", @@ -390,6 +390,7 @@ "plex/Cargo.toml": "5cdb185265b7f7217cff08e54ef683a827735c9b3ae7c50161850f7064667b66", "screens/Cargo.toml": "cd42484a49fac394244ebc7b81f30f7e4f9a31cdf7bc1ace5c3fae21afd6d511", "session/Cargo.toml": "ecb49fc9f44177be6de36715ad70845b8929799cdbeb5ce9d6939be741704db0", + "shell-sdl/Cargo.toml": "9bccdb0abdb2ce9afdc030af9454117ed53884f9b50e1ee35a21bcfe6459e9a1", "storage/Cargo.toml": "4b8576b04a5877e95d084a49a16b30224c275ae29b4a192c40725ac819500150", "telemetry/Cargo.toml": "9e514e64ae4a35619294621f22534b5e5b109d9dd3b729b94ed20112f47197bf", "ui/Cargo.toml": "7375c6a73cb2558c7c0f62da7b0bd4beb2a5b78f5460ee35e93b1045c0e80eec" diff --git a/ci/readonly_dependencies.py b/ci/readonly_dependencies.py index ba17d3b914..df79c466ca 100644 --- a/ci/readonly_dependencies.py +++ b/ci/readonly_dependencies.py @@ -18,7 +18,7 @@ import tarfile CERTIFICATE_PATH = Path(__file__).with_name('proofs') / 'serde-json-immutable.json' -CERTIFICATE_SHA256 = '47228bf8faff2b162797c50c24d9516efb67ba2f2be928be16f0bb722132fec9' +CERTIFICATE_SHA256 = '75f6923e03ff9d17819d6d921c8715c0e6c3dd6496f6b37274390e62752db121' SCHEMA = 'plx.readonly.locked-json.v1' REGISTRY = 'registry+https://github.com/rust-lang/crates.io-index' SUPPORTED = ['alloc', 'arbitrary_precision', 'default', 'float_roundtrip', 'raw_value', 'std', 'unbounded_depth'] diff --git a/ci/readonly_generated.py b/ci/readonly_generated.py index a2acdad80a..c670b10cfa 100644 --- a/ci/readonly_generated.py +++ b/ci/readonly_generated.py @@ -13,7 +13,7 @@ from readonly_dependencies import _local_sha, _sha, _json, _manifest_paths, _configs, _workspace_hashes, WORKSPACE_HASHING CERTIFICATE_PATH = Path(__file__).with_name('proofs') / 'platform-generated-enums.json' -CERTIFICATE_SHA256 = '55e6b3ace139479c22ac26a81134a934daafd9bff6f1db53beae24c619d7a718' +CERTIFICATE_SHA256 = '986f3f070a1d3b219e06c5da96677688d0cede10bc636a5b791b0082bfe560fc' SOURCES = ['os/Cargo.toml', 'os/src/lib.rs', 'os/src/i18n/mod.rs', 'os/build.rs', 'os/build_support/catalog.rs', 'build_support/install_identities.rs', 'machine/src/lib.rs', 'machine/src/machine.rs'] diff --git a/ci/test_build_bench.py b/ci/test_build_bench.py index 054a3f6355..db51bfc9b9 100644 --- a/ci/test_build_bench.py +++ b/ci/test_build_bench.py @@ -108,6 +108,7 @@ def art(pkg_path, name, version): art('/media-codecs', 'plx_media_codecs', '0.0.0') art('/appkit', 'plx_appkit', '0.0.0') art('/screens', 'plx_screens', '0.0.0') + art('/shell-sdl', 'plx_shell_sdl', '0.0.0') art('/owp', 'plx_owp', '0.0.0') art('', 'plxnative-modules', '0.7.0') elif args[0] == "rustc": diff --git a/ci/test_build_not_always_dirty.py b/ci/test_build_not_always_dirty.py index 81012b0934..53aeee5b5e 100644 --- a/ci/test_build_not_always_dirty.py +++ b/ci/test_build_not_always_dirty.py @@ -67,9 +67,9 @@ NIGHTLY = pinned() # the repo's one toolchain (historic name) -# The invocation `make check`'s lab line runs (Makefile, "cargo check --lib --tests -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp --features +# The invocation `make check`'s lab line runs (Makefile, "cargo check --lib --tests -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp --features # lab-diagnostics"); identical arguments and CARGO_INCREMENTAL make the first run here a reuse. -LIB_ARGS = ["check", "--lib", "--tests", "-p", "plxnative-modules", "-p", "plx_base", "-p", "plx_machine", "-p", "plx_os", "-p", "plx_gfx", "-p", "plx_net", "-p", "plx_ui", "-p", "plx_plex", "-p", "plx_telemetry", "-p", "plx_data", "-p", "plx_session", "-p", "plx_media", "-p", "plx_playback_contract", "-p", "plx_play_uri", "-p", "plx_play_feed", "-p", "plx_media_codecs", "-p", "plx_appkit", "-p", "plx_screens", "-p", "plx_owp", "--features", "lab-diagnostics"] +LIB_ARGS = ["check", "--lib", "--tests", "-p", "plxnative-modules", "-p", "plx_base", "-p", "plx_machine", "-p", "plx_os", "-p", "plx_gfx", "-p", "plx_net", "-p", "plx_ui", "-p", "plx_plex", "-p", "plx_telemetry", "-p", "plx_data", "-p", "plx_session", "-p", "plx_media", "-p", "plx_playback_contract", "-p", "plx_play_uri", "-p", "plx_play_feed", "-p", "plx_media_codecs", "-p", "plx_appkit", "-p", "plx_screens", "-p", "plx_shell_sdl", "-p", "plx_owp", "--features", "lab-diagnostics"] def cargo_env(): diff --git a/ci/test_ci_split.py b/ci/test_ci_split.py index 4e20b035b1..173fb1ebd0 100644 --- a/ci/test_ci_split.py +++ b/ci/test_ci_split.py @@ -55,16 +55,16 @@ def rule(target): # Each cargo gate, as a regex over a target's whole (comment-free) recipe, and the one target that # owns it. `lint` is a prerequisite rather than a recipe line, handled separately. GATES = { - "check-cargo-lint": [r"cargo \+\$\(RUST_TOOLCHAIN\) check --lib --tests -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp --features lab-diagnostics"], + "check-cargo-lint": [r"cargo \+\$\(RUST_TOOLCHAIN\) check --lib --tests -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp --features lab-diagnostics"], "check-cargo-unit-default": [ - r"cargo \+\$\(RUST_TOOLCHAIN\) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp\n", + r"cargo \+\$\(RUST_TOOLCHAIN\) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp\n", r"ci/test_storage_service_package\.py", r"test -p plxnative-storage --bin plxnative-storage", r"ci/test_storage_package_isolated\.py", r"ci/test_no_host_staticlib\.py", r"ci/test_build_not_always_dirty\.py", ], - "check-cargo-unit-hostsim": [r"cargo \+\$\(RUST_TOOLCHAIN\) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_play_feed --features hostsim"], + "check-cargo-unit-hostsim": [r"cargo \+\$\(RUST_TOOLCHAIN\) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_play_feed -p plx_shell_sdl --features hostsim"], } diff --git a/ci/test_no_host_staticlib.py b/ci/test_no_host_staticlib.py index 4a763bb0c4..3fd00eec24 100644 --- a/ci/test_no_host_staticlib.py +++ b/ci/test_no_host_staticlib.py @@ -37,12 +37,12 @@ CRATE = "plxnative_modules" # The layer crates split out of the app crate (docs/module-layers.md), each a dependency of it and # each held to the same rule: an rlib, never an archive. One archive is linked, and it is the app's. -LAYER_CRATES = ("plx_base", "plx_machine", "plx_net", "plx_os", "plx_gfx", "plx_ui", "plx_plex", "plx_telemetry", "plx_data", "plx_session", "plx_media", "plx_playback_contract", "plx_play_uri", "plx_play_feed", "plx_media_codecs", "plx_appkit", "plx_screens") +LAYER_CRATES = ("plx_base", "plx_machine", "plx_net", "plx_os", "plx_gfx", "plx_ui", "plx_plex", "plx_telemetry", "plx_data", "plx_session", "plx_media", "plx_playback_contract", "plx_play_uri", "plx_play_feed", "plx_media_codecs", "plx_appkit", "plx_screens", "plx_shell_sdl") TOOLCHAIN = pinned() # the repo's one toolchain # What the workspace needs for cargo to resolve (not compile) the app package: the manifest and # lockfile, the `.cargo/config.toml` that cargo finds from the working directory, and the sources # the manifest names. A mutated copy replaces `Cargo.toml` only. -WORKSPACE_FILES = (".cargo", "Cargo.lock", "build.rs", "build_support", "src", "storage", "base", "machine", "net", "os", "gfx", "ui", "plex", "telemetry", "data", "session", "media", "playback-contract", "play-uri", "play-feed", "media-codecs", "appkit", "screens", "owp") +WORKSPACE_FILES = (".cargo", "Cargo.lock", "build.rs", "build_support", "src", "storage", "base", "machine", "net", "os", "gfx", "ui", "plex", "telemetry", "data", "session", "media", "playback-contract", "play-uri", "play-feed", "media-codecs", "appkit", "screens", "shell-sdl", "owp") def offences(unit_graph=None, metadata=None): diff --git a/ci/test_test_fast.py b/ci/test_test_fast.py index 6f89e3e378..0693cffe7e 100644 --- a/ci/test_test_fast.py +++ b/ci/test_test_fast.py @@ -162,7 +162,7 @@ def test_incremental_in_its_own_target_dir_and_forwards_the_filter(self): self.assertEqual(call["target_dir"], TDIR) self.assertTrue(call["cwd"].endswith("rust-modules"), call["cwd"]) self.assertEqual(call["runtime_dir_set"], "yes") - self.assertRegex(call["args"], r"^\+\S+ test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp --no-run --message-format=json-render-diagnostics$") + self.assertRegex(call["args"], r"^\+\S+ test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp --no-run --message-format=json-render-diagnostics$") # The filter goes to each test binary (the runner builds first, then runs), not to cargo. self.assertEqual(len(fake.bin_calls()), call["args"].split().count("-p")) self.assertTrue(all(line.endswith("args=route::") for line in fake.bin_calls()), fake.bin_calls()) @@ -171,7 +171,7 @@ def test_no_filter_runs_the_whole_default_feature_suite(self): with FakeCargoHome() as fake: self.assertEqual(fake.run("test-fast").returncode, 0) (call,) = fake.calls() - self.assertRegex(call["args"], r"^\+\S+ test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp --no-run --message-format=json-render-diagnostics$") + self.assertRegex(call["args"], r"^\+\S+ test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp --no-run --message-format=json-render-diagnostics$") self.assertNotIn("--features", call["args"]) self.assertEqual(len(fake.bin_calls()), call["args"].split().count("-p")) self.assertTrue(all(line.endswith("args=") for line in fake.bin_calls()), fake.bin_calls()) diff --git a/docs/agent-reference.md b/docs/agent-reference.md index 70bedc6cb6..e66f458104 100644 --- a/docs/agent-reference.md +++ b/docs/agent-reference.md @@ -221,7 +221,7 @@ the pinned Sentry Native cross-build), and `sshpass` (Homebrew; deploy/run use y what the user can reach, which is the only class that is tracked rather than accepted; `--sites` lists every hit with its class. CI runs the three cargo targets plus those two as five parallel jobs (`host-lint`, `host-unit-default`, `host-unit-hostsim`, `host-python`, `host-python-harness`) behind an aggregator named - `host checks (NOT a device gate)`; `ci/test_ci_split.py` pins that no gate falls between them. The cargo half runs `cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp` + `host checks (NOT a device gate)`; `ci/test_ci_split.py` pins that no gate falls between them. The cargo half runs `cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp` **on the default feature set, and again with `--features hostsim` for the crates that declare it (`HOSTSIM_SUITE`: all of `UNIT_SUITE` except `plx_net`, `plx_ui`, `plx_appkit`, `plx_screens`, `plx_media_codecs`, `plx_play_uri`, `plx_playback_contract` and `plx_owp`, which have no `hostsim` cfg and run the @@ -267,7 +267,7 @@ the pinned Sentry Native cross-build), and `sshpass` (Homebrew; deploy/run use y SDL event loop where no host test can see it. Needs the **clippy component of the pinned toolchain** (`make setup-rust` installs it with `--profile minimal --component clippy`). - `make test-fast [T=filter]` — **opt-in** incremental inner loop: the same default-feature - `cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp` as `check-cargo-unit-default` (throwaway runtime root, telemetry env), but + `cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp` as `check-cargo-unit-default` (throwaway runtime root, telemetry env), but with `CARGO_INCREMENTAL=1` in its own `rust-modules/target-fast` (gitignored). `T=route::` is the test-name filter, handed to every one of the per-crate test binaries; each prints its own libtest `test result:` line (the counts are per crate, never one total), followed by the wrapper's summary line. Use it for a long series of @@ -383,12 +383,12 @@ the pinned Sentry Native cross-build), and `sshpass` (Homebrew; deploy/run use y - **CI build health** — four tools keep the build from growing unnoticed, and none of them is a device gate. - *Timings artifact.* `host-unit-default` compiles the test binary in its own step with - `cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp --no-run --timings`, then `make check-cargo-unit-default` runs against what that + `cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp --no-run --timings`, then `make check-cargo-unit-default` runs against what that built (`--timings` is not part of cargo's fingerprint: checked 2026-10-02 by building with and without it and getting `Fresh` for `plxnative-modules` both ways, so the step moves the compile rather than adding one). Download `cargo-timings-host-unit-default` from the run page ("Artifacts", kept 14 days) and open `cargo-timing.html`: it names the crates on the critical - path. Locally: `cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp --no-run --timings` writes + path. Locally: `cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp --no-run --timings` writes `target/cargo-timings/cargo-timing.html`. - *Trends.* `tools/ci-durations.py [--runs 30] [--recent 5] [--json]` reads the last 30 successful `main` runs of CI and Simulator CI through `gh api` and prints, per job, the median and p90 and @@ -464,7 +464,7 @@ the pinned Sentry Native cross-build), and `sshpass` (Homebrew; deploy/run use y before/after table instead of an ad-hoc scratch-script number. It prints a Markdown table (median / min / max over `--runs`, default 3, the scenarios interleaved round by round) and, with `--json`, a machine-readable document (git sha, `rustc -V` of the pinned toolchain, host, per-run load and swap). Rows: - a **no-op** host test build (`cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp --no-run`; it reports from cargo's JSON `fresh` + a **no-op** host test build (`cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp --no-run`; it reports from cargo's JSON `fresh` flag whether the app crate was rebuilt and flags a recompile as UNEXPECTED, the `ci/test_build_not_always_dirty.py` hazard); an **edit-rebuild** after appending a comment to a leaf file of each crate (`plx_base`'s `cbuf.rs`, `plx_machine`'s `landgate.rs`, `plx_os`'s `devcaps.rs`, `plx_gfx`'s `overdraw.rs`, `plx_net`'s `stream_redirect.rs`, `plx_ui`'s `dwell.rs`, `plx_plex`'s `retry.rs`, `plx_telemetry`'s `window.rs`, `plx_data`'s `tape.rs`, `plx_session`'s `scripted.rs`, `plx_media`'s `units.rs`, `plx_appkit`'s `skip_pill.rs`, `plx_screens`'s `clock_readout.rs`, the application's `coldstart.rs`) and to a hub (`plx_ui`'s `lib.rs`), non-incremental (`CARGO_INCREMENTAL=0`, the @@ -943,7 +943,7 @@ the pinned Sentry Native cross-build), and `sshpass` (Homebrew; deploy/run use y rather than the only one — it catches the break before the push, and CI does not run in somebody else's checkout. It type-checks the bare `--no-default-features` set, which drops `play-uri` and `play-feed` too (a build with no playback backend), so it does not replace `make check-nodef`, which passes the Makefile's `RUST_BACKEND_FEATURES`. It type-checks after - every edit to a `rust-modules/src/**.rs` or one of the thirteen layer crates it lists (it does not watch `playback-contract`, `media-codecs`, + every edit to a `rust-modules/src/**.rs` or one of the fourteen layer crates it lists (it does not watch `playback-contract`, `media-codecs`, `play-feed` or `play-uri`, for which `make check-nodef` is the only gate that compiles them in the shipping set, nor `owp`, which the application does not link yet); it costs well under a second warm, because cargo keys fingerprints by feature set and the two configurations coexist in one `target/`. The hazard it guards is hand-written `#[cfg(feature = "devtriggers")]` PAIRS, where a spliced-in function @@ -1144,8 +1144,9 @@ glow, HUD widgets, seven-segment FPS) and a text shader that samples glyph textures (cached by string+size): SDL2_ttf renders every run except Arabic and Hebrew, which libass-plx shapes and rasterizes into the same texture (`gfx/src/rtl.rs`). Critically-damped springs animate focus scale and shelf scroll. -Fonts are the `appfont*.ttf` faces deployed next to the binary, in the fallback chain `gfx/src/text.rs` opens (Inter, CJK, emoji, Arabic, Hebrew; Inter, Arabic and Hebrew with bold cuts; `ci/test_shipped_faces.py` holds every staging list to it), so a missing libass-plx costs Arabic and Hebrew UI text as well as text subtitles; the subtitle renderer additionally loads the per-script Noto faces from `fonts/subs/` (`docs/ass-subtitles.md`, cut by `tools/cut-noto-subs.py`, staged by `SUBS_FONT_FILES` in the Makefile). (Wayland surface setup + -input decoding live in `system.rs` / `app/events.rs` + `app/input.rs`, not the C shim — see the gotchas below.) +Fonts are the `appfont*.ttf` faces deployed next to the binary, in the fallback chain `gfx/src/text.rs` opens (Inter, CJK, emoji, Arabic, Hebrew; Inter, Arabic and Hebrew with bold cuts; `ci/test_shipped_faces.py` holds every staging list to it), so a missing libass-plx costs Arabic and Hebrew UI text as well as text subtitles; the subtitle renderer additionally loads the per-script Noto faces from `fonts/subs/` (`docs/ass-subtitles.md`, cut by `tools/cut-noto-subs.py`, staged by `SUBS_FONT_FILES` in the Makefile). (The SDL window, the event decode and the text-input calls live in +`rust-modules/shell-sdl/` (crate `plx_shell_sdl`), the Wayland surface setup in `system.rs`, and the key ladders in +`app/events.rs` + `app/input.rs`, not the C shim — see the gotchas below.) **Video playback (summary — `rust-modules/media/src/player/CLAUDE.md` is the deep-dive: pipeline, threading model, the Starfish/ACB ABI + bind-order gotchas, seek/PTS rebase. Read it before @@ -1262,7 +1263,7 @@ every thin back-edge with `file:line` (the work list for breaking it up); `--dot `abnormal`, like a freeze's; one made after backgrounding (the PLX-NATIVE-1P shape) finds no open session, because backgrounding already ended it `exited` (`telemetry::session`), so only the `error` event exists. -- `rust-modules/src/` — the app core (Rust): `app/` (`mod.rs` the `run_application` shim + `struct App`, `boot.rs` the bring-up, `run.rs` the frame loop and its phase functions, `events.rs`/`input.rs` the input decode and key ladders, `lifecycle.rs`, `playback.rs`, `content.rs`, `bridge.rs` the seam onto the container and the ONE navigation vocabulary, `words.rs` the heartbeat's `route=`/`overlay=` alphabet — `nav.rs` is gone with `enum Route` since restructure phase 12), `system.rs` (wayland), +- `rust-modules/src/` — the app core (Rust): `app/` (`mod.rs` the `run_application` shim + `struct App`, `boot.rs` the bring-up, `run.rs` the frame loop and its phase functions, `events.rs`/`input.rs` the input decode and key ladders, `lifecycle.rs`, `playback.rs`, `content.rs`, `bridge.rs` the seam onto the container and the ONE navigation vocabulary, `words.rs` the heartbeat's `route=`/`overlay=` alphabet — `nav.rs` is gone with `enum Route` since restructure phase 12), `system.rs` (wayland), `rust-modules/shell-sdl/` (crate `plx_shell_sdl`: `SDL_Init`, the window, the GL swap, the event decode and the text-input calls, which `app/platform.rs`'s `Shell` opens as the app-private `Surface`), and, in the media layer (`rust-modules/media/`, crate `plx_media`, which the application links), `player/` (buffer-feed engine + worker threads — **`rust-modules/media/src/player/CLAUDE.md` is the playback deep-dive; read it before touching playback**), `abr/` and `route/`, and `ff.rs`, which @@ -1622,7 +1623,7 @@ every thin back-edge with `file:line` (the work list for breaking it up); `--dot the same leak by a shorter route. The escape hatch is a prefix on the command, and an agent reaching for it is doing the thing the hook exists to prevent. - **LG's SDL fork has a shifted `SDL_KeyboardEvent`.** `e.key.keysym` is unreliable; the handler - (`app.rs`, via `rd_u32`) reads raw bytes off the event: `+16` = state (u32), `+20` = webOS keycode + (`rust-modules/shell-sdl/src/event.rs`, via `rd_u32`) reads raw bytes off the event: `+16` = state (u32), `+20` = webOS keycode (u32), `+24` = sym (u32). State low byte = pressed(1)/released(0); bit `0x100` = auto-repeat. Magic-Remote buttons are matched by these `wcode`s (e.g. PAUSE=72, PLAY=450, BACK=461/482, stop=413, D-pad L/R alt 412/417; the wcodes live in `ui/consts.rs`, as `WCODE_*` — true of the L/R pair only @@ -1950,7 +1951,7 @@ behaviour; real GL copies, glyphs and presentation still need a device capture w There **is** a host unit suite, and it is not the real gate — both halves matter, and conflating them is how this section used to be wrong in three files at once. -**Tier 1 — `make check` (host).** `cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp` (a bare `cargo test --lib` runs the application crate only and skips every layer crate: `plx_base`, `plx_machine`, `plx_os`, `plx_gfx`, `plx_net`, `plx_ui`, `plx_plex`, `plx_telemetry`, `plx_data`, `plx_session`, `plx_media`, `plx_appkit`, `plx_screens`) runs the whole +**Tier 1 — `make check` (host).** `cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp` (a bare `cargo test --lib` runs the application crate only and skips every layer crate: `plx_base`, `plx_machine`, `plx_os`, `plx_gfx`, `plx_net`, `plx_ui`, `plx_plex`, `plx_telemetry`, `plx_data`, `plx_session`, `plx_media`, `plx_appkit`, `plx_screens`, `plx_shell_sdl`) runs the whole host suite on the dev Mac, no TV involved — and `make check` runs the crates that declare `hostsim` (`HOSTSIM_SUITE`, a subset of that list) a SECOND time under `--features hostsim`, because the host feed seam only exists there and the tests that need it are compiled out of the first pass (the build @@ -1960,7 +1961,7 @@ documented 59 before that, which was five times stale before anyone noticed — of this paragraph was stale within one *commit*, because two agents were adding tests to the same batch that documented it. Three numbers have now rotted here, so do not add a fourth: the only count worth having is the one you take yourself, with -`cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp -- --list | grep -c ': test'`. **The per-module counts +`cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp -- --list | grep -c ': test'`. **The per-module counts below have the same disease and are worse**, because a stale one reads as precise rather than round — several were written when the module was a third its present size, and two bullets have now outlived the file they named: `ui/home.rs` (retired to `screens/home/`) and `route.rs` (split in diff --git a/docs/distribution.md b/docs/distribution.md index 5fad25fd6f..3c37180fce 100644 --- a/docs/distribution.md +++ b/docs/distribution.md @@ -753,7 +753,7 @@ world-readable `/tmp` on the TV across many runs. crash log, but the default hook prints the raw message to stderr, so a future `unwrap()` on an `Err` that embeds a URL or token would still land there verbatim. Two things could not be settled without the television: whether LG's SDL logs committed keyboard text at `SDL_LOG_CATEGORY_INPUT` / - `SDL_LOG_PRIORITY_DEBUG`, which `textinput::trace_driver` enables in every build (the five + `SDL_LOG_PRIORITY_DEBUG`, which `plx_shell_sdl::text::trace_driver` (called from `textinput::bind`) enables in every build (the five message formats the driver is documented to print carry a state number, never text), and what the closed TV libraries (libplayerAPIs, libAcbAPI, libpf) write to fd 2. diff --git a/docs/lab-diagnostics.md b/docs/lab-diagnostics.md index d74a00ee2f..f9e331887d 100644 --- a/docs/lab-diagnostics.md +++ b/docs/lab-diagnostics.md @@ -441,7 +441,7 @@ not pretending the old filesystem contract exists. * `make check` is green in both configurations. **Take the counts yourself** — this repository has rotted four written test counts already and the fifth is not going to be this one: - `cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp -- --list | grep -c ': test'`, with and without + `cd rust-modules && cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp -- --list | grep -c ': test'`, with and without `--features lab-diagnostics`. What the feature's own tests cover: the ring's two caps and its `dropped` delta, the `lab.json` parse and each refusal it names, the five scrub rewrites and the outright refusal (including the bare address and the household name the device test found), the diff --git a/docs/launch-links.md b/docs/launch-links.md index d5c9e60f17..72c91b8233 100644 --- a/docs/launch-links.md +++ b/docs/launch-links.md @@ -50,7 +50,7 @@ the window and never reads the parameters. The app cannot hold that subscription on webOS 9.2.2, LG C2: SAM answers an anonymous client `cannot find caller id`, the app-id service name is already taken in the process, and `LSCallFromApplication` is refused as unprivileged). -Instead, `app::boot::tap_relaunch_payloads` wraps the pointer slot LG's SDL reads each reply's +Instead, `system::tap_relaunch_payloads` wraps the pointer slot LG's SDL reads each reply's payload through (`HELPER_HLunaServiceMessage`, exported by its `libSDL2` and filled in `SDL_Init`). A relaunch payload is passed to the link code and returned unchanged, so SDL still raises the window. The link then replaces wherever the app was, with Home underneath. A relaunch without a diff --git a/docs/macos-app.md b/docs/macos-app.md index 735dd796ef..3844984914 100644 --- a/docs/macos-app.md +++ b/docs/macos-app.md @@ -70,7 +70,7 @@ Four things, and three of them were bugs that had been sitting in the tree unrea recipe are untouched. The window changed too, though that is taste rather than a bug: it opens at an exact integer -divisor of the 1920x1080 canvas (`app::boot::plan_desktop_window`) with ALLOW_HIGHDPI, and is not +divisor of the 1920x1080 canvas (`plx_shell_sdl::window::plan_desktop_window`) with ALLOW_HIGHDPI, and is not resizable. The window's pixel density is measured from the window itself (`SDL_GetDisplayDPI` is unreliable on macOS), and the window is then sized in points for the drawable it should give, so a display of any size lands on the same result. On a Retina display that means a 960x540-point window diff --git a/docs/module-layers.md b/docs/module-layers.md index 5ce87d356f..5091866d86 100644 --- a/docs/module-layers.md +++ b/docs/module-layers.md @@ -110,6 +110,7 @@ telemetry plex net + os m plex net + os machine base net + os base gfx + os machine base +shell_sdl + os machine base play_feed net playback_contract media_codecs + os base play_uri playback_contract + os base media_codecs playback_contract + base @@ -198,6 +199,18 @@ vendored conformance vectors in `rust-modules/owp/fixtures/`. The WebSocket unde application does not name the crate yet. `ci/check-deps.sh` reads the whole crate for the same IO and clock gates as every other layer, and as machine code. +`shell_sdl` is a twentieth layer, declared the same way. Its crate is `plx_shell_sdl` (`rust-modules/shell-sdl/`); +its layer may use `base`, `machine` and `os` and the crate names `plx_base` alone. It is the SDL half of the shell that the +television and the simulator share: `SDL_Init` and the GL request, the window (the panel's size and its smaller +fallback, and under `hostsim` the desktop fit), the swap and its interval, the event poll and decode (LG's fork layout +on the device, stock SDL2 under `hostsim`), the synthetic key, pointer, wheel and lifecycle events the remote FIFO, Lab Control, replay and the cursor-swap OK push back +into the queue (a text event is built as bytes and handed to the decode, never pushed: pushing one crashes the Mac's SDL), and the text-input calls. The LG half does not move: the `SDL_SysWMinfo` buffer, the `wl_proxy_marshal` +opaque region and the LS2 pump stay in `system.rs`, a member of `[platform webos]`, and a pin in the crate's `lib.rs` fails +if the crate names the query that overruns it. The application reaches it through `app/platform.rs`, whose `Shell` opens a +`Surface` over the crate's `Window`; `Shell`, `Surface` and `HostEvent` stay application-private until W7a. +`ci/check-deps.sh` reads the whole crate for the same clock, statics and thread gates as every other layer, and not as one of the +sans-IO areas: the shell is an IO crate by definition. + The Watchlist adds two data modules and no new edge. `watchlist` (rows, match table, `TileState`, intent ledger, comparator; with `stores::watchlist`) and `catalog` (the Discover-only item page; with `stores::catalog`) name only layers below data, chiefly `plx_plex`: `plex::watchlist`, `Client::find_by_guids`, `plex::session` @@ -334,9 +347,9 @@ proves the references are gone and nothing more; L15b is open. | **L15b** the OS-neutral port — **open** | — | An OS-neutral video sink with the ACB bind sequence behind it and the webOS facts the gate cannot see; the simulator became its own platform in W4. See below. | | **L15c** the platform value and the three contracts — **done** | — | Wave R (the rename that gave this page `os` and `[platform webos]`) landed as #1474; W2 landed (`tv::Port` became `tv::Services`, with four groups of hooks; the shell and the frame probes moved to `app::Platform`), and so did the three contracts, W3a to W3c: who may persist credentials (#1477), what evidence admits a URI player (#1478), who ends the process (#1479). See "L15c to L15h" below. | | **L15d** neutral types and the simulator as its own platform (L15b item 2) — **W3d and W4 landed** | — | W3d landed (the opaque `Backend` tag, `sandbox` to `native_video`, identity publishes a platform name and version, `device::Info` keeps its webOS fields in `WebosDetail`, and `devcaps` reads its files through the platform), and so did W4: `platform_desktop` (`rust-modules/src/platform_desktop.rs`, a second fence section, `[platform desktop]`) is the simulator's and the macOS app's own platform value, which `src/bin/sim.rs` enters through; the `hostsim` terms of the television's fence are gone, so the television's code is compiled into every build and the linker drops it from a desktop executable (`simulators.yml` links the macapp feature set to guard that until W7), and the stand-ins in `webos` and `keymanager` are test seams, compiled for tests and `test-support` (`docs/platform-ports.md`, W4). The desktop platform is the second implementation. | -| **L15e** events, the shell and composition — **W5a to W5c and W6b landed** | — | W5 (`HostEvent` with `Option`) landed in three PRs, lifecycle and quit (W5a, #1484), keys and text (W5b, #1487) and the pointer and wheel (W5c, #1492), and so did W6b (platform-supplied composition in two boot phases, #1489). W6 (`plx_shell_sdl`, a `[shell_sdl]` layer) and W6c (a URI-only and a two-driver composition play an ordinary title) are planned. | -| **L15f** extract the platform crates — **planned** | — | W7: a narrow public `host` module in the application crate, `rust-modules/platform-webos` and `platform-desktop` as crates above `app`, and the gate learning "a platform is a crate above `app`". After L15d, before L15g and L15h. | -| **L15g** the webOS facts and the remaining `hostsim` (L15b item 3) — **W8a started** | — | W8a has begun: the platform states where the account's records live (`tv::Services.storage`, #1488), and telemetry's consent store (#1490) and plex's session persistence (#1491) follow it instead of the `target_arch = "arm"` fence. Still planned: the rest of W8a, one PR per directory (`os`, `src`, `base`, `storage` and `play-feed`), sorting the `target_arch = "arm"` and `target_os = "linux"` sites into "is webOS" (a platform value or runner) and "is 32-bit ARM" or "is Linux" (stays); then W8b, the library name lists, `paths` and the packaging, and W8c, the `feature = "hostsim"` lines left in the tree (none of them in the fence now; `git grep -h 'feature = "hostsim"' -- '*.rs' | wc -l` counts them). | +| **L15e** events, the shell and composition — **W5a to W5c, W6 and W6b landed** | — | W5 (`HostEvent` with `Option`) landed in three PRs, lifecycle and quit (W5a, #1484), keys and text (W5b, #1487) and the pointer and wheel (W5c, #1492), and so did W6b (platform-supplied composition in two boot phases, #1489) and W6 (`plx_shell_sdl`, a `[shell_sdl]` layer: SDL's bring-up, the window, the swap, the event decode and the text-input calls moved out of the application behind its private `Shell` and `Surface`, and the LG half stays in `system.rs`). W6c (a URI-only and a two-driver composition play an ordinary title) is planned. | +| **L15f** extract the platform crates — **planned** | — | W7: a narrow public `host` module in the application crate, `rust-modules/platform-webos` and `platform-desktop` as crates above `app`, and the gate learning "a platform is a crate above `app`". After L15d, before L15g and L15h (the storage-authority part of W8a, #1488, #1490 and #1491, landed ahead of W7; the rest of W8 still follows W7). | +| **L15g** the webOS facts and the remaining `hostsim` (L15b item 3) — **W8a started** | — | W8a has begun: the platform states where the account's records live (`tv::Services.storage`, #1488), and telemetry's consent store (#1490) and plex's session persistence (#1491) follow it instead of the `target_arch = "arm"` fence. Still planned: the rest of W8a, one PR per directory (`os`, `src`, `base`, `storage` and `play-feed`; telemetry's nine `target_arch = "arm"` lines in `telemetry/src/telemetry/native.rs`, the Sentry Native crash capture, are not among them and no step owns them yet, the follow-up for Tizen ARM retail builds that #1490 names), sorting the `target_arch = "arm"` and `target_os = "linux"` sites into "is webOS" (a platform value or runner) and "is 32-bit ARM" or "is Linux" (stays); then W8b, the library name lists, `paths` and the packaging, and W8c, the `feature = "hostsim"` lines left in the tree (none of them in the fence now; `git grep -h 'feature = "hostsim"' -- '*.rs' | wc -l` counts them). | | **L15h** the OS-neutral Feed sink (L15b item 1) — **planned** | — | W11: `plx_acb` (an `[acb]` layer) takes the ACB plane owner and the URI media verbs out of `os`, the Feed-side ACB results become neutral, and the bind sequence moves behind a neutral sink. Needs the television. | ### L15: the webOS port @@ -446,8 +459,8 @@ still webOS's. Three things were left, and item 2 is done: host build of what is not one (the media seam's host sink, the GL context request, the window flags and the keyboard event decode), while the television's wayland and glib calls, like the rest of the television's arms, are compiled in every build and the linker drops them from a host executable. - The comment on the feature in `rust-modules/Cargo.toml` still lists those calls under what it - switches; the certificate pins that file, so W7 rewords it when it re-seals. The + The comment on the feature in `rust-modules/Cargo.toml` says the same since W6, which re-sealed the + certificate with it. The webOS-shaped types in `tv` needed neutral shapes then, and have them since W3d: `tv::secure::Backend` is an opaque tag that stays a string on the wire (the two webOS spellings are constants, and a tag no installed platform knows is refused on open), `tv::sandbox` is `tv::native_video` with a verdict that is @@ -492,7 +505,7 @@ section is `[platform X]`, and the plan calls its crates `plx_platform_webos`, ` The order is L15c; then L15d and L15e, which overlap (W3d then W4 runs beside W5, and W6b, W6 and W6c wait for both); then L15f; then L15g and L15h. So the extraction (L15f, W7) follows item 2 (L15d, W4), and item 3 (L15g, W8) and item 1 (L15h, W11) come afterwards. The earlier order put the extraction after all of L15b, which would have made W7 -wait for the neutral sink: item 1 needs the television and gates nothing the other platforms need, and W8 follows W7. +wait for the neutral sink: item 1 needs the television and gates nothing the other platforms need, and W8 follows W7 (but the storage-authority part of W8a, #1488, #1490 and #1491, landed ahead of it). The steps are L15b's three items and the moves that serve them: the contracts they rest on (L15c), the events and composition (L15e) and the extraction (L15f). The other workstreams are not steps of this table: W0 (the record of the plan, this amendment), W1 (the `PLATFORM` build axis), W9 (the Tizen platform, which adds `plx_platform_tizen` and a diff --git a/docs/platform-ports.md b/docs/platform-ports.md index 37872e7640..c236b7001c 100644 --- a/docs/platform-ports.md +++ b/docs/platform-ports.md @@ -180,7 +180,10 @@ Citations in this section quote the tree at e9924f0f9 with its old names (see "N - the swap is at `app/run.rs:974` and the poll at `app/run.rs:1066-1069`. Source-text pins search for those calls: tests at `app/boot.rs:705-785` look for `"SDL_Init("` and - `"SDL_CreateWindow("`, and `app/run.rs:11467` looks for `"SDL_GL_SwapWindow(app.win);"`. + `"SDL_CreateWindow("`, and `app/run.rs:11467` looks for `"SDL_GL_SwapWindow(app.win);"`. W6 moved the extern block, + the window, the swap and the poll into `plx_shell_sdl` (`sys.rs`, `window.rs`, `event.rs`); the application crate declares + SDL functions in two files only now, `system.rs` (the `SDL_SysWMinfo` handshake and the GL attribute read) and + `app/clock.rs` (`SDL_GetTicks`), and its swap pin reads `app.surface.swap();`. - F15. SDL is also below `app`: - `base/src/surface.rs:38-39`; - `base/src/diag/heartbeat.rs:30-31`; @@ -1599,6 +1602,15 @@ W3d. Neutral types (L15b item 2 prerequisites; part of item 3). - Test: `make test-hostsim`; a build-bench table; `check-nodef`, the ARM cross-build and fw-compat-reviewer; a TV lease: boot log diff and the video plane still showing through (opaque region); frame claims only via `profile-tv`. Risk: the SysWMinfo overrun (`system.rs:4-5`); that code moves verbatim. +- As landed: `Shell` gained `init` and `open`, and `open` returns the application-private `Surface` (`window`, `swap`, + `set_swap_interval`, `poll` and an unsafe `quit` that `run::shutdown` calls). The bring-up order is kept: `SDL_Init` and the + GL request come before the stored session is read, the window after it. The placement is a value, `OpenAsk { title, + placement, high_dpi }`, so the panel's size with its smaller fallback and the desktop fit (`Placement::Desktop`, `hostsim` + builds only) are the crate's; the webOS shell hands `init` two hooks, the cursor-sleep hint before `SDL_Init` and the + relaunch tap after it (`system::webos3_cursor_sleep_hint` and `system::tap_relaunch_payloads`, moved without their `hostsim` + gates), and the desktop shell none. Text-input state stays in `textinput.rs`; the crate owns the byte layouts and the SDL + calls. The pins moved with their code: the init order into the crate's `init`, the window order into its + `open_order_tests`, and the session-before-window order stays in `app/boot.rs`. ### W6b (N, accepted T). Platform-supplied composition, two phases - Goal: `app::Platform.media` (Target shape 6a). `acb_init` moves behind `early_init` at its present call site diff --git a/docs/remote-keys.md b/docs/remote-keys.md index cbffb39ca6..ceb3d5fcc0 100644 --- a/docs/remote-keys.md +++ b/docs/remote-keys.md @@ -20,7 +20,7 @@ done offline is read out of the television's own harvested `libSDL2`, which is s ## 1. How a press reaches the app An `SDL_KEYDOWN` / `SDL_KEYUP` from LG's SDL fork is read by raw byte offset, because the fork's -`SDL_KeyboardEvent` is **shifted four bytes** against the headers (`app/events.rs::decode_key`, and the +`SDL_KeyboardEvent` is **shifted four bytes** against the headers (`plx_shell_sdl::event::decode_key` in `rust-modules/shell-sdl/src/event.rs`, and the gotcha in `docs/agent-reference.md`): | offset | field | the app calls it | diff --git a/docs/search.md b/docs/search.md index 582fc339f7..041a09e5e8 100644 --- a/docs/search.md +++ b/docs/search.md @@ -277,7 +277,7 @@ backend is not in the webOS extension API at all — it is inside **LG's Wayland `Wayland_CreateDevice` writes four real hooks into `SDL_VideoDevice` (`WebOSHasScreenKeyboardSupport`, `Show`, `Hide`, `IsShown`), `SDL_StartTextInput` dispatches to the second, and `WebOSShowScreenKeyboard` is a complete `text_model` IME client. Typed text comes back -as an ordinary **`SDL_TEXTINPUT`** event, so `app.rs`'s existing `SDL_PollEvent` loop already sees +as an ordinary **`SDL_TEXTINPUT`** event, so the existing `SDL_PollEvent` loop (`plx_shell_sdl::event`) already sees it. moonlight-tv 1.5.8 shipped exactly this against the TV's own SDL. **Linking is the plain `extern "C"` case, not `dynlib!`.** Verified with @@ -308,7 +308,7 @@ Both halves are checkable on the dev Mac without a television: declares `{ type, timestamp, windowID, inputSource /* webOS specific field */, text[] }` — text at **+16**. -This is the same class of bug as the `SDL_KeyboardEvent` shift `app.rs` already reads around with +This is the same class of bug as the `SDL_KeyboardEvent` shift `plx_shell_sdl::event` already reads around with raw offsets, and it has the same fix: read the bytes, do not trust the struct. Note the offset is a `cfg`, not a constant — under `hostsim` desktop SDL2 is stock and the offset really is +12, so a single hard-coded number ships garbage on one of the two platforms. @@ -317,7 +317,7 @@ single hard-coded number ships garbage on one of the two platforms. `SDL_StartTextInput` looks for a window carrying `0x200` (`SDL_video.h` in the SDK sysroot's `usr/include/SDL2/`) before dispatching to the driver hook. Our window is created with -`SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN` and nothing else — `app.rs`'s `SDL_WINDOW_FLAGS` is +`SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN` and nothing else — `plx_shell_sdl`'s `SDL_WINDOW_FLAGS` (`shell-sdl/src/window.rs`) is `0x2 | 0x1` on the device — so it carries neither `SHOWN` nor a focus flag at creation. **If the flag is clear the panel never rises, silently and with no error return.** That is why the boot probe logs the flag rather than trusting it: a keyboard that does not appear and a keyboard that appeared and @@ -339,8 +339,8 @@ Two host-side findings, recorded because both cost time today and neither is a s television. **The boot probe's answer on macOS is `keyboard: support=0 active=1 focus=0 winflags=0x26`.** That -is **trap 2 observed**: `0x26` is `OPENGL | SHOWN | RESIZABLE` (`app.rs`'s `hostsim` arm asks for -`0x2 | 0x20`; SDL adds `SHOWN`), and `0x200` — `SDL_WINDOW_INPUT_FOCUS` — is not in it. The trap is +is **trap 2 observed**: `0x26` is `OPENGL | SHOWN | RESIZABLE` (the `hostsim` arm asked for +`0x2 | 0x20` when this was measured, and is `plx_shell_sdl`'s `SDL_WINDOW_FLAGS` now; SDL adds `SHOWN`), and `0x200` — `SDL_WINDOW_INPUT_FOCUS` — is not in it. The trap is therefore reproducible without a television, which is the useful part; what it does **not** tell you is anything about the TV's own answer, since `support=0` here just means desktop SDL has no screen keyboard at all. diff --git a/rust-modules/Cargo.lock b/rust-modules/Cargo.lock index c7e1c8f2a0..d283d70388 100644 --- a/rust-modules/Cargo.lock +++ b/rust-modules/Cargo.lock @@ -971,6 +971,13 @@ dependencies = [ "serde_json", ] +[[package]] +name = "plx_shell_sdl" +version = "0.0.0" +dependencies = [ + "plx_base", +] + [[package]] name = "plx_telemetry" version = "0.0.0" @@ -1019,6 +1026,7 @@ dependencies = [ "plx_plex", "plx_screens", "plx_session", + "plx_shell_sdl", "plx_telemetry", "plx_ui", "serde", diff --git a/rust-modules/Cargo.toml b/rust-modules/Cargo.toml index 5d4f2b25ba..5bf6addbd6 100644 --- a/rust-modules/Cargo.toml +++ b/rust-modules/Cargo.toml @@ -1,5 +1,5 @@ # A cargo workspace with this package as its ROOT; the other members are the storage helper and the -# layer crates split out of the application (everything under `rust-modules/*/` with a `[package.metadata.plx] mount`: base/, machine/, net/, os/, gfx/, ui/, plex/, telemetry/, data/, session/, media/, play-feed/, appkit/, screens/, owp/ and the contract and codec crates; +# layer crates split out of the application (everything under `rust-modules/*/` with a `[package.metadata.plx] mount`: base/, machine/, net/, os/, gfx/, ui/, plex/, telemetry/, data/, session/, media/, play-feed/, appkit/, screens/, shell-sdl/, owp/ and the contract and codec crates; # docs/module-layers.md). # The root keeps the literal `version` below (release tooling reads it), `make`/CI run their usual # commands from this directory against this package (a bare `cargo test`/`check`/`build` here still @@ -25,6 +25,7 @@ members = [ "media-codecs", "appkit", "screens", + "shell-sdl", "owp", "storage", ] @@ -173,11 +174,12 @@ placeholder-sentinel = ["plx_ui/placeholder-sentinel"] # a mutually-exclusive partner feature; the television is the DEFAULT, and the simulator opts in. # # What it changes, and nothing else: the media seam (29 symbols that exist only on a television), -# the GL context request (macOS has no GLES2 driver), the window flags, the keyboard event decode -# (LG's SDL fork shifts SDL_KeyboardEvent; stock SDL2 does not), and the wayland/glib calls that -# have no host equivalent. Everything else — all of `ui/`, the whole Plex data layer, the demux -# orchestration — is compiled identically for both. -hostsim = ["dep:xxhash-rust", "plx_base/hostsim", "plx_machine/hostsim", "plx_os/hostsim", "plx_gfx/hostsim", "plx_plex/hostsim", "plx_telemetry/hostsim", "plx_data/hostsim", "plx_session/hostsim", "plx_media/hostsim", "plx_play_feed?/hostsim"] +# the GL context request (macOS has no GLES2 driver), the window flags and the keyboard event decode +# (LG's SDL fork shifts SDL_KeyboardEvent; stock SDL2 does not), the last three now `plx_shell_sdl`'s, +# and, since W4, `platform_desktop` as the platform (the wayland/glib calls are no longer switched +# by this feature: they compile in every build and the desktop never reaches them). Everything else +# — all of `ui/`, the whole Plex data layer, the demux orchestration — is compiled identically for both. +hostsim = ["dep:xxhash-rust", "plx_base/hostsim", "plx_machine/hostsim", "plx_os/hostsim", "plx_gfx/hostsim", "plx_plex/hostsim", "plx_telemetry/hostsim", "plx_data/hostsim", "plx_session/hostsim", "plx_media/hostsim", "plx_play_feed?/hostsim", "plx_shell_sdl/hostsim"] # Warnings are ERRORS, for both workspace packages, in every cargo invocation — build, check, test, clippy, the # ARM cross-build and the simulator alike. The tree reached zero warnings in all four @@ -275,6 +277,13 @@ plx_appkit = { path = "appkit" } # the registry that names them. It links nothing on the television; its build script is for the host # test binary. plx_screens = { path = "screens" } +# The shell_sdl layer (ci/module-layers.ini `[shell_sdl]`): the stock-SDL shell the application opens its +# window through: SDL's init, the window and its GL context, the swap, the event queue, the stock +# key, pointer, wheel and text layouts of both SDLs, and the synthetic events pushed back onto the +# queue. It names no application type and none of the webOS platform (`system`, `port`); the +# application drives it through its own `Shell` and `Surface`. Its `hostsim` feature is forwarded +# above; its build script links SDL2 into a host test binary only. +plx_shell_sdl = { path = "shell-sdl" } # safe pure-Rust JPEG/PNG decoders — replaces vendored stb_image.h (~8k lines C) image = { version = "0.25", default-features = false, features = ["jpeg", "png"] } # raw socket/libc FFI for the stream module (correct constants + struct layouts) @@ -376,3 +385,5 @@ plx_media_codecs = { path = "media-codecs", features = ["test-support"] } plx_appkit = { path = "appkit", features = ["test-support"] } # Likewise the screens layer's seams (`account_menu::overscan_rects`, `registry::every_surface_arg`, ...). plx_screens = { path = "screens", features = ["test-support"] } +# Likewise the shell crate's SDL stubs (`text::start_input` and the rest of the panel calls, which a host test binary must not reach) and its event-subsystem scaffold. +plx_shell_sdl = { path = "shell-sdl", features = ["test-support"] } diff --git a/rust-modules/base/src/surface.rs b/rust-modules/base/src/surface.rs index bbffb8debb..cea941f336 100644 --- a/rust-modules/base/src/surface.rs +++ b/rust-modules/base/src/surface.rs @@ -466,7 +466,7 @@ pub fn probe(win: *mut c_void) { // not the canvas is either a webOS 1-3 owner's smaller Interface resolution (or the debug drawable trigger) or a firmware doing // something no set has been seen to do. On a desktop // it is the ordinary case — the window is an exact divisor of the canvas by design - // (`app::boot::plan_desktop_window`) — and asking a Mac user for their webOS version + // (`plx_shell_sdl::window::plan_desktop_window`) — and asking a Mac user for their webOS version // reads as a malfunction. Same measurement either way; only the sentence differs. let tail = if cfg!(feature = "hostsim") { "This is expected on a desktop: the window is a whole fraction of the canvas." diff --git a/rust-modules/data/src/search.rs b/rust-modules/data/src/search.rs index 3f5837a54e..44c7af0066 100644 --- a/rust-modules/data/src/search.rs +++ b/rust-modules/data/src/search.rs @@ -439,7 +439,7 @@ pub fn terms(q: &str) -> Option<&str> { /// and `CString::new` refuses it at the far end, so the field's run and the empty statement both /// blank over a query the app still believes it is holding. Borrowed when there is nothing to /// remove, which is every keystroke: the television's panel cannot commit one -/// (`textinput::decode_text_at` ends its string AT the NUL) and a remembered term is refused by +/// (`plx_shell_sdl::text`'s `decode_text_at` ends its string AT the NUL) and a remembered term is refused by /// `recents::usable`, so the seed path is the only way one gets in — and that path now enters /// through the STORE rather than through a screen's mount. pub fn sanitize_query(q: &str) -> std::borrow::Cow<'_, str> { diff --git a/rust-modules/gfx/src/gfx.rs b/rust-modules/gfx/src/gfx.rs index 177e13c46f..b20e289972 100644 --- a/rust-modules/gfx/src/gfx.rs +++ b/rust-modules/gfx/src/gfx.rs @@ -328,7 +328,7 @@ extern "C" { #[cfg(feature = "devtriggers")] fn glFlush(); fn glGenTextures(n: c_int, textures: *mut c_uint); - // `#[allow(dead_code)]` — the same shape as `app/mod.rs`'s SDL text-input externs: the sole + // `#[allow(dead_code)]` — the same shape as `plx_shell_sdl`'s SDL text-input externs (`sys.rs`): the sole // caller (`delete_tex`, below) compiles its real call out under `cfg(test)`, so this // declaration loses its only use in the TEST build alone and warns there. It stays live on // device and in the simulator, where `delete_tex` still calls it for real. diff --git a/rust-modules/shell-sdl/Cargo.toml b/rust-modules/shell-sdl/Cargo.toml new file mode 100644 index 0000000000..03f79e00f8 --- /dev/null +++ b/rust-modules/shell-sdl/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "plx_shell_sdl" +version = "0.0.0" +edition = "2021" +license = "GPL-3.0-or-later" +description = "PlxNative stock-SDL shell: SDL bring-up, the window and GL context, the swap, the event drain, the key, pointer, wheel and text layouts of both SDLs (LG's fork on the television, stock SDL2 under hostsim), and synthetic-event injection." +repository = "https://github.com/GLinnik21/plx-native" +publish = false +build = "build.rs" + +[package.metadata.plx] +mount = "shell_sdl" + +[lib] +name = "plx_shell_sdl" +# An rlib the application crate links, never an archive of its own: the one staticlib is the +# application crate's (ci/test_no_host_staticlib.py holds that line for this crate too). +crate-type = ["rlib"] + +[features] +default = [] +# Forwarded from the application crate, which is the only one that sets it. It selects the +# stock-SDL2 event layouts and the desktop window arithmetic that a simulator runs (the +# television's SDL fork lays its keyboard, text and wheel events out differently), plus the GL +# context request. Both arms of every layout stay compiled either way (`cfg!`). +hostsim = ["plx_base/hostsim"] +# Stubs for the four text-input calls that a host test binary must not reach (no window, no +# panel) and the SDL event-queue guard the application's loop tests drive. Enabled from the +# dependents' `[dev-dependencies]`; never in a shipped build. +test-support = ["plx_base/test-support"] + +[dependencies] +plx_base = { path = "../base" } + +[dev-dependencies] +plx_base = { path = "../base", features = ["test-support"] } + +[lints] +workspace = true diff --git a/rust-modules/shell-sdl/build.rs b/rust-modules/shell-sdl/build.rs new file mode 100644 index 0000000000..fa699ca8cd --- /dev/null +++ b/rust-modules/shell-sdl/build.rs @@ -0,0 +1,21 @@ +//! Host link configuration for the shell-sdl layer's own test binary, and nothing else. +//! +//! `plx_shell_sdl` declares the SDL2 symbols its window, event and text code call. Its `--test` +//! binary is a real executable that can reach them (the event-queue round trips push and poll +//! real SDL events), so on the host it needs the same SDL object the application crate's build +//! script supplies to the application's binaries. The lines are the same ones, from the same file +//! (`../build_support/host_link.rs`), so the crates cannot disagree. +//! +//! On the television this script prints no `rustc-link-*` line at all: the ARM build is a +//! staticlib the Makefile links, and `host_link::emit` returns before emitting anything for +//! `target_arch = "arm"`. No environment variable is read except cargo's own target description, +//! so an ordinary rebuild never re-runs it. + +#[path = "../build_support/host_link.rs"] +mod host_link; + +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-changed=../build_support/host_link.rs"); + host_link::emit(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")); +} diff --git a/rust-modules/shell-sdl/src/event.rs b/rust-modules/shell-sdl/src/event.rs new file mode 100644 index 0000000000..205ce782cc --- /dev/null +++ b/rust-modules/shell-sdl/src/event.rs @@ -0,0 +1,579 @@ +//! SDL's events as the application reads them: the event-type codes, the raw-offset readers, the key, +//! pointer, wheel and text layouts of BOTH SDLs this project runs on, and the queue's `poll`/`push`. +//! +//! The decode stops at neutral values ([`Decoded`]): a key is `(state, wcode, sym)`, never an +//! `Action`, because naming one is the application's vocabulary (`ui::consts`) and a shell may not +//! name `ui`. The application maps a [`Decoded`] onto its own `HostEvent`; the tape's format is the +//! SDL code each [`Lifecycle`] edge arrived as ([`Lifecycle::sdl_code`]), so those pairs live here, +//! where the decode table is. +use crate::sys; +use plx_base::surface::to_logical; +use std::os::raw::c_void; + +// event types +pub const SDL_QUIT: u32 = 0x100; +pub const SDL_KEYDOWN: u32 = 0x300; +pub const SDL_KEYUP: u32 = 0x301; +pub const SDL_MOUSEMOTION: u32 = 0x400; +pub const SDL_MOUSEBUTTONDOWN: u32 = 0x401; +pub const SDL_MOUSEBUTTONUP: u32 = 0x402; +pub const SDL_MOUSEWHEEL: u32 = 0x403; +/// The IME's in-progress COMPOSITION. Not acted on — the search field shows what has been +/// committed, so a preedit would put characters on screen the query does not contain — but LOGGED, +/// because the panel's word prediction is a replace and this is where its delete half would arrive +/// if it arrives at all. See the `"edit"` arm in the application's event ladder. +pub const SDL_TEXTEDITING: u32 = 0x302; +/// Text COMMITTED by the system keyboard — the application's `textinput`. +pub const SDL_TEXTINPUT: u32 = 0x303; + +/// SDL's application events (`SDL_APP_*`), the four the loop acts on: the compositor taking the +/// screen (WILL and DID enter background) and giving it back (WILL and DID enter foreground). +pub const SDL_APP_WILLENTERBACKGROUND: u32 = 0x103; +pub const SDL_APP_DIDENTERBACKGROUND: u32 = 0x104; +pub const SDL_APP_WILLENTERFOREGROUND: u32 = 0x105; +pub const SDL_APP_DIDENTERFOREGROUND: u32 = 0x106; + +/// Poll SDL's one process-wide event queue into `ev`. `true` when an event was written. SDL writes +/// at most `sizeof(SDL_Event)` (56 bytes) of the 128 the buffer holds, so the rest is whatever the +/// last, larger event left behind. +pub fn poll(ev: &mut [u8; 128]) -> bool { + unsafe { sys::SDL_PollEvent(ev.as_mut_ptr() as *mut c_void) != 0 } +} + +/// Push one event onto SDL's own queue, so the existing poll loop consumes it as if it had come off +/// the wayland input path. The only caller is `inject.rs`. +pub(crate) fn push(ev: &[u8; 128]) { + unsafe { sys::SDL_PushEvent(ev.as_ptr() as *const c_void) }; +} + +#[inline] +pub fn rd_u32(ev: &[u8], off: usize) -> u32 { + u32::from_ne_bytes([ev[off], ev[off + 1], ev[off + 2], ev[off + 3]]) +} + +#[inline] +pub fn rd_i32(ev: &[u8], off: usize) -> i32 { + i32::from_ne_bytes([ev[off], ev[off + 1], ev[off + 2], ev[off + 3]]) +} + +#[inline] +pub fn rd_f32(ev: &[u8], off: usize) -> f32 { + f32::from_ne_bytes([ev[off], ev[off + 1], ev[off + 2], ev[off + 3]]) +} + +/// A keyboard event's `(state, wcode, sym)`, decoded from the raw event bytes. The `wcode` is +/// `None` only on the host layout, for a press that carries no injected one: stock SDL has no webOS +/// keycode at all, so the application applies its desktop stand-in (`host_wcode`, a `ui` table this +/// crate may not name) exactly where this decode used to. The television's layout always has one. +/// +/// **The two SDLs disagree about this struct, and nothing warns you.** LG's fork writes +/// `state` (u32) at +16, the webOS keycode at +20 and the SDL sym at +24. Stock SDL2 — +/// what the host simulator links — has `SDL_KeyboardEvent { type, timestamp, windowID, +/// state:u8@12, repeat:u8@13, pad, pad, keysym{ scancode:u32@16, sym:i32@20, … } }`, so +/// every field the app reads is at a different offset and there is no webOS keycode at all. +/// Reading the fork's offsets out of a stock event yields the window id as a keystate and +/// a scancode as a sym — plausible-looking garbage rather than a crash. +/// +/// `cfg!` rather than `#[cfg]` deliberately: both arms stay compiled on both platforms, so +/// the one nobody is currently building cannot rot. This is the single site that knows the +/// layout — `rd_u32`'s callers elsewhere read pointer events, whose offsets already agree. +/// +/// **The `wcode` this returns is LG's SCANCODE**, which is worth saying because the name suggests +/// otherwise. Every field measured off the dev set is the SDL scancode of the key beside it — +/// backspace 42, Clear 156, ◀/▶ 80/79, OK 40 — so the fork's shift puts an ordinary +/// `SDL_Keysym { scancode, sym }` at +20/+24 rather than inventing a webOS keycode namespace. That +/// is why the codes above SDL's own range (450 play, 482 back, 505 exit) carry no sym at all: they +/// are LG-private scancodes the keymap has no keycode for. `docs/remote-keys.md` has the account. +/// +/// # The simulator's carrier moved, because the old one was silently DEAD +/// +/// A synthetic press from the remote FIFO has to get its wcode across `SDL_PushEvent`, and on the +/// host that queue is not SDL2's: macOS `libSDL2` is **sdl2-compat forwarding into SDL3**, so every +/// pushed event is converted out and back. Measured 2026-08-23 by dumping the polled bytes of a +/// press whose every spare field carried a distinct value: +/// +/// | field | offset | survives | +/// |------------------------------|--------|----------| +/// | `windowID` | +8 | yes | +/// | `padding2` / `padding3` | +14/15 | no | +/// | `keysym.scancode` | +16 | **no** — comes back 0 | +/// | `keysym.mod` | +24 | yes | +/// | `keysym.unused` | +28 | **no** — comes back 1 | +/// +/// It used to be `unused`, so **every wcode-ONLY token was dead**: `play`, `pause`, `stop`, `ff`, +/// `rew`, `playpause`, `exit`, `chup`, `chdown` all decoded as wcode 1 and did nothing at all, and +/// `tests/keytable.json` recorded three of them as `moved: false` — which reads as "that key does +/// nothing on that screen" and actually meant the press never arrived. An instrument silent by +/// construction: prove it can see the thing before reading its silence. +/// +/// `scancode` would have been the honest home (it is what a wcode IS) and it is the one field the +/// compat layer recomputes. So a synthetic press carries the value in `mod` and a MARKER in +/// `windowID` ([`SYNTH_WINDOW`]) — two fields, because the value alone cannot say whether it is +/// one: a real press puts its modifier bitmask in `mod`, so `mod != 0` means "shift is down" at +/// least as often as it means "injected". The marker restores the priority the `unused` field used +/// to express — **injected first, the desktop stand-in only as a fallback** — which is load-bearing +/// and not a preference: `host_wcode(8)` is BACK, while the `backspace` token is `(8, 42)`, so +/// asking the stand-in first turns the panel's delete key into a navigation. That priority is why +/// this returns the injected wcode or `None` and never a stand-in of its own: the caller's +/// `unwrap_or_else(host_wcode)` can only ever apply to a press that carried none. +/// Clobbering `windowID` is safe here and nowhere else: this arm is `hostsim`-only, the simulator +/// has one window, and nothing in the event loop reads that field. +#[inline] +pub fn decode_key(ev: &[u8]) -> (u32, Option, u32) { + if cfg!(feature = "hostsim") { + let pressed = *ev.get(12).unwrap_or(&0) as u32; + let repeat = *ev.get(13).unwrap_or(&0) as u32; + let sym = rd_u32(ev, 20); + // Rebuild the fork's packed state byte-for-byte: low byte pressed(1)/released(0), + // bit 0x100 auto-repeat. Everything downstream tests exactly those two. + let state = pressed | if repeat != 0 { 0x100 } else { 0 }; + let injected = if rd_u32(ev, 8) == SYNTH_WINDOW { + u32::from(u16::from_ne_bytes([ev[24], ev[25]])) + } else { + 0 // a real desktop press: `mod` there is the modifier bitmask, not a wcode + }; + // The stand-in is the only way a physical Mac keyboard reaches a key the remote has and a + // keyboard does not (space = PAUSE), and it applies to real presses alone. + let wcode = if injected != 0 { Some(injected) } else { None }; + (state, wcode, sym) + } else { + (rd_u32(ev, 16), Some(rd_u32(ev, 20)), rd_u32(ev, 24)) + } +} + +/// The `windowID` a SYNTHETIC key event carries on the host, marking it as one — see [`decode_key`] +/// for why the wcode needs a marker beside it rather than standing on its own. Any value no real +/// window can have; SDL numbers windows from 1. +/// +/// Defined unconditionally, like both halves of [`decode_key`]: the arm that uses it is behind +/// `cfg!` rather than `#[cfg]`, precisely so the configuration nobody is currently building cannot +/// rot. +pub const SYNTH_WINDOW: u32 = 0x504c_584b; // "PLXK" + +/// What a pointer event did. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PointerEdge { + /// `SDL_MOUSEMOTION`. + Move, + /// `SDL_MOUSEBUTTONDOWN`, any button. + Down, + /// `SDL_MOUSEBUTTONUP`, any button. + Up, +} + +/// One edge of the window's visibility. Both background edges park the tree (the second finds +/// nothing left to park); WILL foreground un-parks the tree, and DID foreground alone reacquires the +/// window and restores playback. A platform that sends only DID background is enough on its own +/// (`WindowActivity`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Lifecycle { + WillBackground, + DidBackground, + WillForeground, + DidForeground, +} + +impl Lifecycle { + /// The SDL event type this edge arrives as, and so the code the SDL-coded readers take: the + /// recorder's tape (`enc_lifecycle`, whose recorded codes ARE the tape format), the window gate + /// and telemetry's crash steps and session. The inverse of [`decode`]'s table; the tests pin the + /// four pairs. + pub const fn sdl_code(self) -> u32 { + match self { + Lifecycle::WillBackground => SDL_APP_WILLENTERBACKGROUND, + Lifecycle::DidBackground => SDL_APP_DIDENTERBACKGROUND, + Lifecycle::WillForeground => SDL_APP_WILLENTERFOREGROUND, + Lifecycle::DidForeground => SDL_APP_DIDENTERFOREGROUND, + } + } +} + +/// One SDL event as neutral values. `Key` carries the bytes' own `(state, wcode, sym)` (see +/// [`decode_key`] for the `Option`), and the application turns that into its `KeyPress`. +#[derive(Clone, Debug, PartialEq)] +pub enum Decoded { + /// `SDL_QUIT`. + Quit, + /// One edge of a key: the fork's packed `state` (low byte 1 is down, bit 0x100 is the + /// auto-repeat), the wcode where the bytes carry one, and the sym. + Key { state: u32, wcode: Option, sym: u32 }, + /// One commit from the system keyboard: the decoded string, possibly empty (SDL delivers a + /// commit for the IME's own bookkeeping too, and the loop ignores an empty one). + Text(String), + /// One pointer event at authored 1920x1080 coordinates ([`ptr_xy`]). + Pointer { x: f32, y: f32, edge: PointerEdge }, + /// One tick of the wheel in the signed whole ticks the loop reads ([`decode_wheel_dy`]). + Wheel { dy: i32 }, + /// The window left or came back to the screen. + Lifecycle(Lifecycle), +} + +/// An SDL event decoded: `SDL_QUIT`, the four application lifecycle types, a key edge +/// (`SDL_KEYDOWN`/`SDL_KEYUP`, through [`decode_key`], so both layouts), a text commit +/// (`SDL_TEXTINPUT`, through [`crate::text::decode`]), a pointer event (motion, button down and +/// button up, through [`ptr_xy`]) and a wheel tick (through [`decode_wheel_dy`]). `None` for +/// everything else, which the loop reads raw (the IME's pre-edit, and the SDL events nothing acts +/// on). Beside [`decode_key`], the other place that knows SDL's event bytes. +#[inline] +pub fn decode(ev: &[u8]) -> Option { + Some(match rd_u32(ev, 0) { + SDL_QUIT => Decoded::Quit, + SDL_KEYDOWN | SDL_KEYUP => { + let (state, wcode, sym) = decode_key(ev); + Decoded::Key { state, wcode, sym } + } + SDL_TEXTINPUT => Decoded::Text(crate::text::decode(ev)), + SDL_MOUSEMOTION => pointer_event(ev, PointerEdge::Move), + SDL_MOUSEBUTTONDOWN => pointer_event(ev, PointerEdge::Down), + SDL_MOUSEBUTTONUP => pointer_event(ev, PointerEdge::Up), + SDL_MOUSEWHEEL => Decoded::Wheel { dy: decode_wheel_dy(ev) }, + SDL_APP_WILLENTERBACKGROUND => Decoded::Lifecycle(Lifecycle::WillBackground), + SDL_APP_DIDENTERBACKGROUND => Decoded::Lifecycle(Lifecycle::DidBackground), + SDL_APP_WILLENTERFOREGROUND => Decoded::Lifecycle(Lifecycle::WillForeground), + SDL_APP_DIDENTERFOREGROUND => Decoded::Lifecycle(Lifecycle::DidForeground), + _ => return None, + }) +} + +/// A pointer event's position and edge. The coordinates are read at +20 and +24 in both layouts (the +/// pointer offsets agree, [`ptr_xy`]), and the button at +16 and its state at +17 are not read: the +/// edge is the event type, for any button, as the loop has always taken it. +#[inline] +fn pointer_event(ev: &[u8], edge: PointerEdge) -> Decoded { + let (x, y) = ptr_xy(ev); + Decoded::Pointer { x, y, edge } +} + +/// A wheel event's vertical tick count, in the signed whole ticks the loop reads. +/// +/// **The host reads a DIFFERENT offset, and this one is not the LG-fork +/// shift `decode_key` documents — it is macOS `libSDL2` again being +/// sdl2-compat forwarding into SDL3.** `SDL_MouseWheelEvent` on real SDL2 +/// (what the television runs) carries a plain `Sint32 y` at +20, which is +/// what production code always read. Measured 2026-09-02 by dumping the +/// polled bytes of an injected -40 tick on this host: `+20` came back 0, and +/// -40.0 arrived instead as the FLOAT `preciseY` field at `+32` — SDL2's own +/// struct gained that field in 2.0.18 for fractional trackpad scroll, and +/// sdl2-compat's round trip apparently only forwards it, leaving the legacy +/// integer field zeroed for both a genuine trackpad tick and anything +/// `SDL_PushEvent`d in this shape (item 13's `wheel:` FIFO token hit +/// this the first time anything synthesized a wheel event at all — nothing +/// needed one before). `cfg!`, not `#[cfg]`, so both arms keep compiling. +#[inline] +pub fn decode_wheel_dy(ev: &[u8]) -> i32 { + if cfg!(feature = "hostsim") { + rd_f32(ev, 32).round() as i32 + } else { + rd_i32(ev, 20) + } +} + +/// An SDL pointer event's position, converted from window pixels to the authored 1920x1080 canvas. +/// +/// THE one place event coordinates enter the UI, so the conversion cannot be forgotten at a new +/// call site: `pointer_event` is the only caller, and a second one would have to convert for itself. +/// `surface::to_logical` is the identity while the drawable is 1920x1080, which it is 1:1 unless +/// a webOS 1-3 owner picks a smaller Interface resolution (or the debug drawable trigger asks for one). +#[inline] +pub fn ptr_xy(ev: &[u8]) -> (f32, f32) { + to_logical(rd_i32(ev, 20) as f32, rd_i32(ev, 24) as f32) +} + +/// Is this SDL event type INPUT — a key, text, pointer or wheel event — as opposed to a lifecycle, +/// window or quit event? The one classification `Dispatcher::input_scope` rests on: input under +/// an open modal is the modal's, a lifecycle event is the app's and may change the page beneath. +pub fn is_input_event(et: u32) -> bool { + matches!( + et, + SDL_KEYDOWN + | SDL_KEYUP + | SDL_TEXTINPUT + | SDL_TEXTEDITING + | SDL_MOUSEMOTION + | SDL_MOUSEBUTTONDOWN + | SDL_MOUSEBUTTONUP + | SDL_MOUSEWHEEL + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::inject::{encode_key, encode_key_repeat, encode_pointer}; + + fn event_of(code: u32) -> [u8; 128] { + let mut ev = [0u8; 128]; + ev[..4].copy_from_slice(&code.to_ne_bytes()); + ev + } + + /// The wcode a decode reports for an injected one: always on the television, and on the host + /// only when the carrier is set (a wcode of 0 is "no injected wcode" there). + fn carried(wcode: u32) -> Option { + if cfg!(feature = "hostsim") && wcode == 0 { + None + } else { + Some(wcode) + } + } + + /// `encode_key` and `decode_key` must agree, in whichever layout this build compiled. The + /// regression test for a bug that shipped: the two ends disagreed about `SDL_KeyboardEvent`'s + /// field offsets, so every remote-FIFO token was accepted, decoded into nonsense and silently + /// dropped. Nothing in the compiler couples a reader and a writer of raw byte offsets, so this + /// does. `make check` builds the television layout; a hostsim run grades the stock one. + #[test] + fn key_bytes_round_trip() { + // `(8, 42)` is the backspace token and must survive as the pair it is: the application's + // desktop stand-in claims sym 8, so a decode that consulted it first would turn the panel's + // delete key into a navigation. Here that is: the injected wcode is reported as such. + for (sym, wcode) in [ + (0x4000_0051, 0), + (13, 0), + (0, 72), + (8, 482), + (8, 42), + (32, 44), + (112, 19), + (115, 22), + ] { + for down in [true, false] { + let (state, got_wcode, got_sym) = decode_key(&encode_key(sym, wcode, down)); + assert_eq!(got_sym, sym, "sym lost (wcode={wcode}, down={down})"); + assert_eq!(got_wcode, carried(wcode), "wcode lost (sym={sym}, down={down})"); + assert_eq!(state & 0xff, u32::from(down), "press/release lost (sym={sym})"); + assert_eq!(state & 0x100, 0, "a synthetic edge must never look like auto-repeat"); + } + let (state, got_wcode, got_sym) = decode_key(&encode_key_repeat(sym, wcode)); + assert_eq!((got_sym, got_wcode), (sym, carried(wcode))); + assert_eq!(state, 0x101, "a repeat is a DOWN edge with the repeat bit"); + } + } + + /// The key layout, byte for byte and written out a second time rather than through + /// `encode_key`. LG's fork: `state` u32 at +16, wcode at +20, sym at +24. Stock SDL (the + /// simulator): `state` u8 at +12, `repeat` u8 at +13, sym at +20, and a synthetic press carries + /// its wcode in `mod` at +24 under the `SYNTH_WINDOW` marker at +8. + #[test] + fn the_key_layout_is_pinned_byte_for_byte() { + // UP (0x40000052) with no wcode, and PLAY (wcode 450 = 0x1c2) with no sym. + let (up_sym, play_wcode) = ([0x52, 0x00, 0x00, 0x40], [0xc2, 0x01, 0x00, 0x00]); + let mut up = [0u8; 128]; + let mut play = [0u8; 128]; + let mut repeat = [0u8; 128]; + for ev in [&mut up, &mut play, &mut repeat] { + ev[0..4].copy_from_slice(&0x300u32.to_ne_bytes()); + } + if cfg!(feature = "hostsim") { + for ev in [&mut up, &mut play, &mut repeat] { + ev[12] = 1; + ev[8..12].copy_from_slice(&0x504c_584bu32.to_ne_bytes()); + } + up[20..24].copy_from_slice(&up_sym); + play[24..26].copy_from_slice(&450u16.to_ne_bytes()); + repeat[20..24].copy_from_slice(&up_sym); + repeat[13] = 1; + } else { + for ev in [&mut up, &mut play, &mut repeat] { + ev[16] = 1; + } + up[24..28].copy_from_slice(&up_sym); + play[20..24].copy_from_slice(&play_wcode); + repeat[24..28].copy_from_slice(&up_sym); + repeat[17] = 1; // state 0x101 + } + assert_eq!(decode_key(&up), (1, carried(0), 0x4000_0052)); + assert_eq!(decode_key(&play), (1, Some(450), 0)); + assert_eq!(decode_key(&repeat), (0x101, carried(0), 0x4000_0052)); + // a desktop press (no marker) never carries a wcode, whatever `mod` holds + if cfg!(feature = "hostsim") { + let mut real = up; + real[8..12].copy_from_slice(&1u32.to_ne_bytes()); + real[24..26].copy_from_slice(&0x1000u16.to_ne_bytes()); // a modifier bitmask + assert_eq!(decode_key(&real).1, None); + } + } + + /// SDL's quit and application events, decoded. The SDL codes are literals: the table is the + /// contract with SDL and with the tape, so it is not read back from the mapping it grades. + #[test] + fn quit_and_the_four_lifecycle_types_decode_and_the_lifecycle_codes_round_trip() { + for (code, event) in [ + (0x100, Decoded::Quit), + (0x103, Decoded::Lifecycle(Lifecycle::WillBackground)), + (0x104, Decoded::Lifecycle(Lifecycle::DidBackground)), + (0x105, Decoded::Lifecycle(Lifecycle::WillForeground)), + (0x106, Decoded::Lifecycle(Lifecycle::DidForeground)), + ] { + assert_eq!(decode(&event_of(code)), Some(event.clone()), "{code:#x}"); + assert!(!is_input_event(code), "{code:#x}: a window event is never a modal's input"); + if let Decoded::Lifecycle(edge) = event { + assert_eq!(edge.sdl_code(), code, "the code a decoded edge is read back as"); + } + } + } + + /// Everything the loop still reads raw stays raw: the IME's pre-edit (0x302), the SDL events + /// nothing acts on, and the types either side of the pointer and wheel block. + #[test] + fn every_other_event_stays_on_the_raw_path() { + for code in [0, 0x101, 0x102, 0x107, 0x200, 0x302, 0x3ff, 0x404, u32::MAX] { + assert_eq!(decode(&event_of(code)), None, "{code:#x}"); + } + } + + /// The boundary `Dispatcher::input_scope` rests on: every input kind is in, and the lifecycle + /// events, window events and quit are out. + #[test] + fn input_events_are_the_modals_and_lifecycle_events_are_the_apps() { + for et in [ + SDL_KEYDOWN, + SDL_KEYUP, + SDL_TEXTINPUT, + SDL_TEXTEDITING, + SDL_MOUSEMOTION, + SDL_MOUSEBUTTONDOWN, + SDL_MOUSEBUTTONUP, + SDL_MOUSEWHEEL, + ] { + assert!(is_input_event(et), "{et:#x} is input"); + } + for et in [SDL_QUIT, 0x101, 0x103, 0x104, 0x105, 0x106, 0x200] { + assert!(!is_input_event(et), "{et:#x} is the app's, not a modal's"); + } + } + + /// A pointer event as SDL lays it out, written by hand: `type` at +0, the window id at +8, the + /// button at +16 and its state at +17, then `Sint32 x` at +20 and `Sint32 y` at +24. LG's fork + /// and stock SDL2 agree on all of it (the keyboard event is the one that shifts), which is why + /// the decoder has one reading for both. + fn pointer_bytes(code: u32, button: u8, state: u8, x: i32, y: i32) -> [u8; 128] { + let mut ev = [0u8; 128]; + ev[0..4].copy_from_slice(&code.to_ne_bytes()); + ev[8..12].copy_from_slice(&7u32.to_ne_bytes()); + ev[16] = button; + ev[17] = state; + ev[20..24].copy_from_slice(&x.to_ne_bytes()); + ev[24..28].copy_from_slice(&y.to_ne_bytes()); + ev + } + + fn pointer(x: f32, y: f32, edge: PointerEdge) -> Option { + Some(Decoded::Pointer { x, y, edge }) + } + + const POINTERS: [(u32, PointerEdge); 3] = [ + (SDL_MOUSEMOTION, PointerEdge::Move), + (SDL_MOUSEBUTTONDOWN, PointerEdge::Down), + (SDL_MOUSEBUTTONUP, PointerEdge::Up), + ]; + + /// **The decode table.** Each of the three SDL types, at the corners and the middle of the + /// canvas and just outside it (a drag past the edge reports negative and over-large positions), + /// decodes to its edge and its position. The surface is the identity here (1920x1080, the + /// default), so the position is what the bytes say. + #[test] + fn an_sdl_pointer_event_decodes_to_its_edge_and_its_position() { + let _serial = plx_base::testlock::serial(); + for (code, edge) in POINTERS { + for (x, y) in [(0, 0), (960, 540), (1919, 1079), (1400, 870), (-3, 1085), (2000, -1)] { + assert_eq!( + decode(&pointer_bytes(code, 1, 1, x, y)), + pointer(x as f32, y as f32, edge), + "{code:#x} at ({x}, {y})" + ); + } + } + } + + /// **The edge is the event type alone**, for any button and whatever its state byte says: a + /// button-up carrying state 1, a button-down carrying state 0 and a motion with a button byte + /// set are still an up, a down and a move. Bytes the decoder must not read are noise here. + #[test] + fn the_edge_is_the_event_type_whatever_the_button_bytes_say() { + let _serial = plx_base::testlock::serial(); + for button in [0u8, 1, 2, 3, 255] { + for state in [0u8, 1] { + for (code, edge) in POINTERS { + let mut ev = pointer_bytes(code, button, state, 640, 360); + ev[28..64].fill(0xa5); + assert_eq!(decode(&ev), pointer(640.0, 360.0, edge), "{code:#x} button {button} state {state}"); + } + } + } + } + + /// The bytes the synthesis writes (`encode_pointer`) decode to the position and edge they were + /// built from. The encoder and the decoder shipped apart once for keys; this is what couples + /// them for the pointer. + #[test] + fn the_synthesized_pointer_bytes_round_trip() { + let _serial = plx_base::testlock::serial(); + for (code, edge) in POINTERS { + for (x, y) in [(0, 0), (1400, 870), (1919, 1079), (-200, 400)] { + let ev = encode_pointer(code, x, y); + assert_eq!(rd_u32(&ev, 0), code); + assert_eq!(decode(&ev), pointer(x as f32, y as f32, edge), "{code:#x}"); + if code != SDL_MOUSEMOTION { + assert_eq!(ev[16], 1, "the left button survives SDL's event queue"); + assert_eq!(ev[17], u8::from(code == SDL_MOUSEBUTTONDOWN)); + } + } + } + } + + /// A wheel event as the television's SDL2 lays it out: `Sint32 y` at +20. + fn wheel_lg(dy: i32) -> [u8; 128] { + let mut ev = event_of(SDL_MOUSEWHEEL); + ev[20..24].copy_from_slice(&dy.to_ne_bytes()); + ev + } + + /// A wheel event as the simulator's stock SDL2 (sdl2-compat over SDL3) delivers it: the count + /// in the float `preciseY` at +32, with the legacy integer at +20 left at zero. + fn wheel_stock(precise_y: f32) -> [u8; 128] { + let mut ev = event_of(SDL_MOUSEWHEEL); + ev[32..36].copy_from_slice(&precise_y.to_ne_bytes()); + ev + } + + fn wheel(dy: i32) -> Option { + Some(Decoded::Wheel { dy }) + } + + /// **Each layout's wheel, and the one this build does not read.** The television's integer at + /// +20 is the count in the default build and is ignored in the simulator's; the simulator's + /// float at +32 is the count there (rounded to whole ticks) and is ignored on the television. + #[test] + fn a_wheel_tick_is_read_from_the_offset_this_hosts_sdl_carries_it_at() { + for dy in [-40, -3, -1, 1, 2, 120] { + if cfg!(feature = "hostsim") { + assert_eq!(decode(&wheel_stock(dy as f32)), wheel(dy), "stock layout, {dy}"); + assert_eq!(decode(&wheel_lg(dy)), wheel(0), "the television's field is not this host's: {dy}"); + } else { + assert_eq!(decode(&wheel_lg(dy)), wheel(dy), "LG layout, {dy}"); + assert_eq!(decode(&wheel_stock(dy as f32)), wheel(0), "the simulator's field is not read here: {dy}"); + } + } + } + + /// A fractional trackpad tick keeps the sign of what it rounds to, and a half tick or less is + /// no tick (the loop records a zero and ignores it). Only the simulator's layout carries one. + #[cfg(feature = "hostsim")] + #[test] + fn a_fractional_trackpad_tick_rounds_to_whole_ticks() { + for (precise, dy) in [(-0.4, 0), (0.4, 0), (-0.6, -1), (0.6, 1), (-1.4, -1), (2.5, 3), (-40.0, -40)] { + assert_eq!(decode(&wheel_stock(precise)), wheel(dy), "{precise}"); + } + } + + /// A key edge decodes with its packed state and the carrier's wcode, a text commit with this + /// build's offset, and the events nothing reads stay `None`. + #[test] + fn a_key_and_a_text_commit_decode_to_their_neutral_values() { + let key = decode(&encode_key(0x4000_0052, 0, true)); + assert_eq!(key, Some(Decoded::Key { state: 1, wcode: carried(0), sym: 0x4000_0052 })); + assert_eq!(decode(&crate::text::encode_event("star wars")), Some(Decoded::Text("star wars".into()))); + assert_eq!(decode(&event_of(SDL_TEXTEDITING)), None); + } +} diff --git a/rust-modules/shell-sdl/src/init.rs b/rust-modules/shell-sdl/src/init.rs new file mode 100644 index 0000000000..89eb46b4d5 --- /dev/null +++ b/rust-modules/shell-sdl/src/init.rs @@ -0,0 +1,189 @@ +//! SDL's process-level lifecycle: bring-up, the GL context request, the hint door, the idle sleep +//! and the quit. Everything here runs on the SDL main thread, which the caller proves with the +//! `&MainThread` it was handed. +use crate::sys; +use plx_base::eventlog::log; +use plx_base::task::MainThread; +use std::ffi::CStr; +use std::os::raw::c_int; + +/// The two steps a platform runs around `SDL_Init` (`before`: it reads hints SDL consults while it +/// initialises; `after`: it uses what `SDL_Init` set up). Plain function pointers, so the crate +/// names nothing of the platform that supplies them: the television's are LG-fork code, and a +/// desktop's are no-ops ([`InitHooks::NONE`]). +#[derive(Clone, Copy)] +pub struct InitHooks { + pub before: unsafe fn(), + pub after: unsafe fn(), +} + +impl InitHooks { + /// A platform with nothing to do around `SDL_Init`. + pub const NONE: InitHooks = InitHooks { before: noop, after: noop }; +} + +unsafe fn noop() {} + +/// `SDL_Init` refused (the reason is the log line `SDL_Init failed`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InitFailed; + +const SDL_INIT_VIDEO: u32 = 0x20; + +// SDL_GLattr enum +const A_RED: c_int = 0; +const A_GREEN: c_int = 1; +const A_BLUE: c_int = 2; +const A_ALPHA: c_int = 3; +const A_BUFFER_SIZE: c_int = 4; +const A_DEPTH: c_int = 6; +const A_STENCIL: c_int = 7; +const A_CTX_MAJOR: c_int = 17; +const A_CTX_MINOR: c_int = 18; +const A_CTX_PROFILE_MASK: c_int = 21; +const CTX_PROFILE_ES: c_int = 0x0004; +/// `SDL_GL_CONTEXT_PROFILE_CORE` — the simulator's only option on macOS. See [`request_gl`]. +const CTX_PROFILE_CORE: c_int = 0x0001; + +/// Bring SDL's video subsystem up: tell SDL the entry point is ours, state the screensaver intent, +/// run `hooks.before`, `SDL_Init(VIDEO)`, run `hooks.after`, and log the driver it picked. +/// +/// # Safety +/// Once, before any other SDL call (the `&MainThread` is the proof of the thread); and `hooks` +/// must be sound to call on that thread at those two points. +pub unsafe fn init(_mt: &MainThread, hooks: InitHooks) -> Result<(), InitFailed> { + sys::SDL_SetMainReady(); + // DEAD END, measured 2026-07-31 — do not re-try this. The obvious answer to "a parked TV + // should blank itself" is to stop inhibiting the platform screensaver here (and re-allow it + // per route, since webOS BACKGROUNDS the app to run one and `0x103` suspends the + // buffer-feed, so it could never be on during playback). It does not work, for a reason + // upstream of this app: the TV's SDL 2.0.4 fork carries the + // `SDL_VIDEO_ALLOW_SCREENSAVER` hint STRING but implements no wayland idle-inhibit + // (`strings libSDL2-2.0.so.0` finds no `idle_inhibit`/`suspend_screensaver` symbol), so + // this call and `SDL_EnableScreenSaver` are both no-ops. Soaked 34 min on Home with the + // TV's own `screenSaverEnabled: on`: no screensaver, no `LIFECYCLE: background`, CPU flat, + // our UI still at full brightness on the panel. webOS does not blank a foreground native + // app, and nothing reachable from SDL changes that. The line stays because it costs + // nothing and states the intent; it is not what keeps the screensaver away. + sys::SDL_SetHint(c"SDL_VIDEO_ALLOW_SCREENSAVER".as_ptr(), c"0".as_ptr()); + (hooks.before)(); + if sys::SDL_Init(SDL_INIT_VIDEO) != 0 { + log("SDL_Init failed"); + return Err(InitFailed); + } + (hooks.after)(); + { + let d = sys::SDL_GetCurrentVideoDriver(); + if !d.is_null() { + log(&format!( + "video driver: {}", + std::ffi::CStr::from_ptr(d).to_string_lossy() + )); + } + } + Ok(()) +} + +/// Ask SDL for the GL context [`crate::window::Window::open`] will create. It is its own call +/// because the application reads the stored session between the request and the window (the +/// window size is a setting), and that order is pinned. +/// +pub fn request_gl(_mt: &MainThread) { + unsafe { request_gl_attributes() } +} + +unsafe fn request_gl_attributes() { + // The television has a real GLES2 driver (a shim over libmali). macOS has none at all — + // Apple ships desktop GL only, capped at 4.1 core — so asking for ES here fails context + // creation outright. 4.1 core is the closest thing that exists, and it is a superset for + // everything this renderer does: a real VBO (never client arrays) and RGBA/UNSIGNED_BYTE + // textures, both core-profile-legal. The shader sources are adapted at compile time by + // `gfx::glsl_preamble`, which reads the driver's GLSL version rather than assuming. + if cfg!(feature = "hostsim") { + sys::SDL_GL_SetAttribute(A_CTX_PROFILE_MASK, CTX_PROFILE_CORE); + sys::SDL_GL_SetAttribute(A_CTX_MAJOR, 4); + sys::SDL_GL_SetAttribute(A_CTX_MINOR, 1); + } else { + sys::SDL_GL_SetAttribute(A_CTX_PROFILE_MASK, CTX_PROFILE_ES); + sys::SDL_GL_SetAttribute(A_CTX_MAJOR, 2); + sys::SDL_GL_SetAttribute(A_CTX_MINOR, 0); + } + // full 32-bit RGBA so the video plane shows through + sys::SDL_GL_SetAttribute(A_RED, 8); + sys::SDL_GL_SetAttribute(A_GREEN, 8); + sys::SDL_GL_SetAttribute(A_BLUE, 8); + sys::SDL_GL_SetAttribute(A_ALPHA, 8); + sys::SDL_GL_SetAttribute(A_BUFFER_SIZE, 32); + // ...and NO depth or stencil, which SDL would otherwise give us anyway: its defaults are + // 16 bits of depth and 0 of stencil, and asking for neither had simply never been written + // down. **This renderer has no use for either.** There is no `GL_DEPTH_TEST`, no + // `glDepthFunc`, no `glDepthMask` and no `glClear(GL_DEPTH_BUFFER_BIT)` anywhere in the + // crate — every screen is painter's-algorithm 2-D, drawn back to front — and the one + // scissor user (`gfx::clip_set`) is a scissor, not a stencil. + // + // On a TILER this is not merely 4 MB of address space. Midgard allocates the depth buffer + // per tile alongside colour and, unless the driver proves it dead, RESOLVES it to memory at + // end-of-frame: 1920x1080x2 bytes written per presented frame for a buffer nothing ever + // reads. The application's `system.rs` logs what the config actually came back with — a + // request is not a grant, and the only honest confirmation is `FB bits: … depth=0`. + sys::SDL_GL_SetAttribute(A_DEPTH, 0); + sys::SDL_GL_SetAttribute(A_STENCIL, 0); +} + +/// `SDL_SetHint`: the one way a platform's own boot code states a hint to SDL (LG's +/// `SDL_WEBOS_CURSOR_SLEEP_TIME`, read in `SDL_Init`). `true` when SDL took it. +pub fn set_hint(name: &CStr, value: &CStr) -> bool { + unsafe { sys::SDL_SetHint(name.as_ptr(), value.as_ptr()) != 0 } +} + +/// `SDL_Quit`. The caller decides WHEN (the application's `shutdown` skips it while a native +/// worker is still inside firmware): this only does it. +/// +/// # Safety +/// Main thread, after SDL's last use; nothing may call into SDL afterwards. +pub unsafe fn quit() { + sys::SDL_Quit(); +} + +/// `SDL_Delay`: the idle loop's sleep. +pub fn delay_ms(ms: u32) { + unsafe { sys::SDL_Delay(ms) }; +} + +#[cfg(test)] +mod tests { + /// A hostile platform step is the caller's to get right, but the shape the crate promises is + /// that `init` runs `before` ahead of `SDL_Init` and `after` behind it; the source order is the + /// proof, because no host test can run `SDL_Init` on the video subsystem. + #[test] + fn the_before_hook_runs_ahead_of_sdl_init_and_the_after_hook_behind_it() { + let source = include_str!("init.rs"); + let body = source + .split_once(concat!("pub unsafe fn ", "init(")) + .expect("init") + .1 + .split_once(concat!("pub fn ", "request_gl(")) + .expect("the end of init") + .0; + let before = body.find(concat!("(hooks.", "before)()")).expect("init runs the before hook"); + let call = body.find(concat!("sys::SDL_Init(", "SDL_INIT_VIDEO)")).expect("init calls SDL_Init"); + let after = body.find(concat!("(hooks.", "after)()")).expect("init runs the after hook"); + assert!(before < call && call < after, "before < SDL_Init < after"); + assert_eq!(body.matches(concat!("sys::SDL_Init(", "SDL_INIT_VIDEO)")).count(), 1); + } + + /// `SDL_Init` is the only video bring-up this crate makes, and the GL request must not ride + /// inside it: the application reads the stored session between the two. + #[test] + fn the_gl_request_is_not_part_of_init() { + let source = include_str!("init.rs"); + let body = source + .split_once(concat!("pub unsafe fn ", "init(")) + .expect("init") + .1 + .split_once(concat!("pub fn ", "request_gl(")) + .expect("the end of init") + .0; + assert!(!body.contains(concat!("SDL_GL_Set", "Attribute")), "init must not request the GL context"); + } +} diff --git a/rust-modules/shell-sdl/src/inject.rs b/rust-modules/shell-sdl/src/inject.rs new file mode 100644 index 0000000000..52f41a024a --- /dev/null +++ b/rust-modules/shell-sdl/src/inject.rs @@ -0,0 +1,232 @@ +//! Synthetic input: the bytes of a key, pointer, wheel or lifecycle event in whichever layout +//! [`crate::event`] reads, and the pushes that put them on SDL's own queue so the existing poll loop +//! consumes them as if they had come off the wayland input path. These are the crate's only +//! `SDL_PushEvent` sites. The remote FIFO, Lab Control and the replay driver call them (through the +//! application's token parser, which owns the vocabulary), and so does the production cursor-swap OK. +//! +//! **A synthetic text event is never pushed**: see `text.rs`. `encode_event` builds the bytes and the +//! application's `txt:` token hands them to the decode directly. +//! +//! The encoders are pure and separate from the pushes that consume them, so their tests need no +//! queue; one test here does drive SDL's real queue (`EventsOnly`). +use crate::event::{ + push, rd_u32, SDL_KEYDOWN, SDL_KEYUP, SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP, SDL_MOUSEMOTION, + SDL_MOUSEWHEEL, SYNTH_WINDOW, +}; +use std::os::raw::c_uint; + +/// The bytes a synthetic key event needs, in whichever layout [`crate::event::decode_key`] reads. +/// +/// **The inverse of `decode_key`, and the pair is only correct together.** They already shipped +/// disagreeing once: the simulator accepted every FIFO token and never moved, because this end +/// wrote LG's fork layout while the reading end had been taught stock SDL2's. Nothing in the +/// compiler couples them, so `key_bytes_round_trip` (in `event.rs`) is what does. +/// +/// Pure, and separate from the `SDL_PushEvent` that consumes it, so that test needs no queue and +/// runs on any host. +pub fn encode_key(sym: c_uint, wcode: c_uint, down: bool) -> [u8; 128] { + let mut ev = [0u8; 128]; + ev[0..4].copy_from_slice(&if down { SDL_KEYDOWN } else { SDL_KEYUP }.to_ne_bytes()); + if cfg!(feature = "hostsim") { + ev[12] = u8::from(down); // state + ev[13] = 0; // repeat + ev[20..24].copy_from_slice(&sym.to_ne_bytes()); + // The wcode rides `SDL_Keysym.mod` (event offset +24, a `Uint16`), under a marker in + // `windowID` that says this press is synthetic at all. Several tokens carry ONLY a wcode + // (`pause` is sym 0, wcode 72), so deriving it from the sym is not an option. + // `decode_key`'s doc has the measurement behind both fields — the short version is that of + // the spare places to put a value, these two are the ones sdl2-compat does not discard. + ev[8..12].copy_from_slice(&SYNTH_WINDOW.to_ne_bytes()); + ev[24..26].copy_from_slice(&(wcode as u16).to_ne_bytes()); + } else { + ev[16..20].copy_from_slice(&if down { 1u32 } else { 0 }.to_ne_bytes()); // state + ev[20..24].copy_from_slice(&wcode.to_ne_bytes()); + ev[24..28].copy_from_slice(&sym.to_ne_bytes()); + } + ev +} + +/// The bytes a synthetic HARDWARE AUTO-REPEAT edge carries — `encode_key`'s down edge with the +/// 0x101 shape (`state & 0x100 != 0`) the loop's repeat arm requires, in whichever layout +/// `decode_key` reads. `encode_key` itself must never produce this (`key_bytes_round_trip` pins +/// that a synthetic EDGE "must never look like auto-repeat"), so it is a second, deliberately +/// separate function rather than a third argument threaded through the first — item 13's +/// `holdrep:` FIFO token is the only caller, and it exists so a script can exercise the +/// `Edge::Repeat` a screen receives without a real remote's own repeat cadence. +pub fn encode_key_repeat(sym: c_uint, wcode: c_uint) -> [u8; 128] { + let mut ev = encode_key(sym, wcode, true); + if cfg!(feature = "hostsim") { + ev[13] = 1; // the `repeat` byte `decode_key`'s hostsim arm folds into `state & 0x100` + } else { + let state = rd_u32(&ev, 16) | 0x100; + ev[16..20].copy_from_slice(&state.to_ne_bytes()); + } + ev +} + +/// SDL pointer bytes shared by clicks, held-pointer FIFO edges and recorded-event replay. +/// The inverse of `ptr_xy`: convert authored coordinates exactly once, including window scaling +/// and letterboxing. Replay may carry a real off-canvas motion, so only the token parser clamps. +/// ABI: SDL's `SDL_events.h` (stock and the NDK's) mouse-event declarations put four +/// Uint32 fields before button@16/state@17 and Sint32 x@20/y@24. ARM32 NDK syntax-only +/// `offsetof` assertions verified these offsets; see `docs/testing-player-pointer.md`. +pub fn encode_pointer(et: u32, x: i32, y: i32) -> [u8; 128] { + let mut ev = [0u8; 128]; + let (px, py) = plx_base::surface::to_physical(x as f32, y as f32); + ev[0..4].copy_from_slice(&et.to_ne_bytes()); + ev[20..24].copy_from_slice(&(px.round() as i32).to_ne_bytes()); + ev[24..28].copy_from_slice(&(py.round() as i32).to_ne_bytes()); + if matches!(et, SDL_MOUSEBUTTONDOWN | SDL_MOUSEBUTTONUP) { + ev[16] = 1; // SDL_BUTTON_LEFT + ev[17] = u8::from(et == SDL_MOUSEBUTTONDOWN); + } + ev +} + +/// The bytes of one app lifecycle event (`0x103`–`0x106`), as the compositor would send it. +pub fn encode_lifecycle(code: u32) -> [u8; 128] { + let mut ev = [0u8; 128]; + ev[0..4].copy_from_slice(&code.to_ne_bytes()); + ev +} + +/// The bytes of one scroll-wheel tick, in the plain, real-SDL2 shape (`Sint32 y` at `+20`) +/// unconditionally: it is the READING side that has to branch by platform now, not this one — see +/// [`crate::event::decode_wheel_dy`] on why `+20` decodes to 0 on this host and where the value +/// actually lands after `SDL_PushEvent` round-trips it. +pub fn encode_wheel(dy: i32) -> [u8; 128] { + let mut ev = [0u8; 128]; + ev[0..4].copy_from_slice(&SDL_MOUSEWHEEL.to_ne_bytes()); + ev[20..24].copy_from_slice(&dy.to_ne_bytes()); + ev +} + +/// Synthesize a Magic-Remote pointer click at authored 1920x1080 coords (the browser +/// remote's click-on-the-stream): two motion events, then button down+up. The first +/// motion is a >=120px jitter so the accumulated pointer distance defeats the +/// D-pad-mode pointer gate (`Pointer::mot_accum < 120` swallows small motions after D-pad use); +/// the second lands on the target. The LG SDL fork's mouse events carry x@20 / y@24 +/// (i32) — the only fields the handlers read. +/// +/// The browser still sends clicks only: forwarding hover moved app focus on every pass of the +/// mouse over the streamed picture. A driver can explicitly send `pm:`/`pd:`/`pu:` instead to +/// separate HUD reveal from a press or to hold a drag across frames. Those edges add no jitter. +pub fn synth_ptr(x: i32, y: i32) { + let jx = if x >= 200 { x - 200 } else { x + 200 }; + synth_pointer(SDL_MOUSEMOTION, jx, y); + synth_pointer(SDL_MOUSEMOTION, x, y); + synth_pointer(SDL_MOUSEBUTTONDOWN, x, y); + synth_pointer(SDL_MOUSEBUTTONUP, x, y); +} + +/// ONE pointer event in authored coordinates, shared by the FIFO and replay. Unlike `ck:`, +/// these primitives add no motion or release: `pd:` stays held until a separate `pu:` arrives. +pub fn synth_pointer(et: u32, x: i32, y: i32) { + push(&encode_pointer(et, x, y)); +} + +/// One app lifecycle event (`0x103`–`0x106`), as the compositor would send it — the replay +/// driver's re-injection of a recorded background/foreground edge. +pub fn synth_lifecycle(code: u32) { + push(&encode_lifecycle(code)); +} + +/// Synthesize a full remote-key press (key-down then key-up) and push both onto SDL's +/// own event queue, so the existing poll loop consumes them as if they came off the +/// wayland input path. The LG SDL fork's `SDL_KeyboardEvent` carries state@16 / +/// wcode@20 / sym@24 (native-endian; the TV is LE), and the handler reads press vs +/// release from `state & 0xff` — so the down carries state=1, the up state=0. Both +/// are required: a grid-card OK arms on down and *commits on release*. +pub fn synth_key(sym: c_uint, wcode: c_uint) { + synth_key_edge(sym, wcode, true); + synth_key_edge(sym, wcode, false); +} + +/// ONE edge of a remote key press. Split out for the `okdown`/`okup` FIFO tokens, because a +/// **press-and-hold** is only expressible as two tokens with real time between them: the item menu +/// opens on `press::is_long`, which measures the interval between the down and the up. The paired +/// [`synth_key`] above is this called twice back to back (a tap). +pub fn synth_key_edge(sym: c_uint, wcode: c_uint, down: bool) { + push(&encode_key(sym, wcode, down)); +} + +/// ONE hardware auto-repeat edge — item 13's `holdrep:` FIFO token, which lets a script +/// exercise a held key's `Edge::Repeat` (the Settings family's paced focus walk, the player +/// scrubber's continuous scrub) without a real remote's own repeat cadence. Only recognised as a +/// repeat by the loop's key arm when `App::down_sym` already equals `sym` — i.e. after a +/// `holddown:` and before its matching `holdup:`, the same split `okdown`/`okup` +/// already uses for a press-and-hold. +pub fn synth_key_repeat(sym: c_uint, wcode: c_uint) { + push(&encode_key_repeat(sym, wcode)); +} + +/// Synthesize one Magic-Remote scroll-wheel tick — item 13's `wheel:` FIFO token, so a script +/// can drive the wheel with no mouse in the room. See [`encode_wheel`] for the layout. +pub fn synth_wheel(dy: i32) { + push(&encode_wheel(dy)); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::event::{decode_wheel_dy, rd_i32, SDL_QUIT}; + + #[test] + fn a_key_event_carries_its_type_and_a_repeat_is_never_a_plain_edge() { + assert_eq!(rd_u32(&encode_key(5, 6, true), 0), SDL_KEYDOWN); + assert_eq!(rd_u32(&encode_key(5, 6, false), 0), SDL_KEYUP); + assert_ne!(encode_key(5, 6, true), encode_key_repeat(5, 6)); + assert_eq!(rd_u32(&encode_key_repeat(5, 6), 0), SDL_KEYDOWN); + } + + /// The `wheel:` token writes the television's shape unconditionally: the count at +20 and the + /// float the simulator's decoder reads left empty, which is why it decodes to zero there. + #[test] + fn the_wheel_bytes_are_the_television_shape_whatever_the_build() { + let ev = encode_wheel(-3); + assert_eq!(rd_u32(&ev, 0), SDL_MOUSEWHEEL); + assert_eq!(rd_i32(&ev, 20), -3); + assert_eq!(decode_wheel_dy(&ev), if cfg!(feature = "hostsim") { 0 } else { -3 }); + } + + #[test] + fn a_lifecycle_event_is_its_code_and_nothing_else() { + let ev = encode_lifecycle(0x104); + assert_eq!(rd_u32(&ev, 0), 0x104); + assert!(ev[4..].iter().all(|&b| b == 0)); + assert_eq!(rd_u32(&encode_lifecycle(SDL_QUIT), 0), SDL_QUIT); + } + + /// **The queue really carries what is pushed.** A click is four events through SDL's own queue: + /// a motion at least 120 px away (it defeats the D-pad-mode pointer gate), the motion onto the + /// target, then the button down and up, in that order. This is the one test that reaches + /// `SDL_PushEvent` and `SDL_PollEvent`, which is what links `sys.rs`'s event externs for real. + #[test] + fn a_click_is_four_events_in_order_through_sdl_s_own_queue() { + use crate::event::{decode, poll, Decoded, PointerEdge}; + let _serial = plx_base::testlock::serial(); + let _events = crate::testing::EventsOnly::init(); + let mut ev = [0u8; 128]; + while poll(&mut ev) {} // whatever an earlier test left behind + synth_ptr(1400, 870); + let mut got = Vec::new(); + while poll(&mut ev) { + got.push(decode(&ev)); + } + let edges: Vec<_> = got + .iter() + .map(|d| match d { + Some(Decoded::Pointer { x, y, edge }) => (*edge, *x, *y), + other => panic!("a click pushes pointer events only, got {other:?}"), + }) + .collect(); + assert_eq!( + edges.iter().map(|e| e.0).collect::>(), + [PointerEdge::Move, PointerEdge::Move, PointerEdge::Down, PointerEdge::Up] + ); + assert!((edges[0].1 - 1400.0).abs() >= 120.0, "the first motion is the jitter: {:?}", edges[0]); + for e in &edges[1..] { + assert_eq!((e.1, e.2), (1400.0, 870.0), "the rest land on the target"); + } + } +} diff --git a/rust-modules/shell-sdl/src/lib.rs b/rust-modules/shell-sdl/src/lib.rs new file mode 100644 index 0000000000..507abe9c38 --- /dev/null +++ b/rust-modules/shell-sdl/src/lib.rs @@ -0,0 +1,109 @@ +//! PlxNative's stock-SDL shell: SDL's bring-up and quit, the window and its GL context, the swap, +//! the event queue, the key, pointer, wheel and text layouts of both SDLs this project runs on, and +//! the synthetic events that go back into that queue. +//! +//! This is the half of the platform that is SDL2 and nothing else. The television's LG half (its +//! Wayland handles, the opaque region, the pointer hide, the cursor-sleep hint) is webOS code and +//! stays in the application crate's `system.rs`, reached only through the webOS platform; this +//! crate names none of it, and none of `ui`, `machine`, `os` or any application type. The contract +//! between the two halves is one raw `SDL_Window*` ([`window::Window::raw`]) and the order of calls +//! on one thread. [`init::InitHooks`] is the one place the platform reaches INTO SDL's bring-up, +//! as two plain function pointers the television fills and a desktop leaves empty. +//! +//! The crate is a mounted module of the `shell_sdl` layer (`ci/module-layers.ini`), which may use +//! `base`, `machine` and `os`; the crate names `base` alone. The application's `Shell` and `Surface` traits and its `HostEvent` stay app-private +//! (`docs/platform-ports.md`, Target shapes 1 and 8); [`window::Window`] is the one SDL +//! implementation of that `Surface`, and [`event::Decoded`] is the neutral value the application maps +//! onto its own event type. +//! +//! ## One crate, both SDLs +//! +//! The television's SDL is a fork (LG's fork of SDL2) that lays its keyboard, text and wheel events +//! out differently from the stock SDL2 a desktop links. The choice is `cfg!(feature = "hostsim")` +//! and never `#[cfg]`, so both arms of every layout compile in every build and the one nobody is +//! building cannot rot; the `hostsim` feature is forwarded from the application crate, which is the +//! only one that sets it. +//! +//! ## Tests +//! +//! `cfg(test)` does not cross a crate boundary, so the dependents' test builds get the stubs and the +//! event-queue guard through the `test-support` feature ([`testing`]); a shipped build has neither. +pub mod event; +pub mod init; +pub mod inject; +mod sys; +pub mod text; +#[cfg(any(test, feature = "test-support"))] +pub mod testing; +pub mod window; + +pub use init::{set_hint, InitFailed, InitHooks}; +pub use window::{OpenAsk, OpenFailed, Placement, Window}; + +#[cfg(test)] +mod pins { + /// Every source file of this crate, by name, for the tests that read source. A new file that is + /// not listed here is not scanned, which is why the list is checked against the directory. + const SOURCES: [(&str, &str); 8] = [ + ("lib.rs", include_str!("lib.rs")), + ("sys.rs", include_str!("sys.rs")), + ("init.rs", include_str!("init.rs")), + ("window.rs", include_str!("window.rs")), + ("event.rs", include_str!("event.rs")), + ("inject.rs", include_str!("inject.rs")), + ("text.rs", include_str!("text.rs")), + ("testing.rs", include_str!("testing.rs")), + ]; + + #[test] + fn every_source_file_is_scanned() { + let mut on_disk: Vec = std::fs::read_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/src")) + .expect("the crate's src directory") + .map(|e| e.expect("a directory entry").file_name().to_string_lossy().into_owned()) + .collect(); + on_disk.sort(); + let mut listed: Vec<&str> = SOURCES.iter().map(|s| s.0).collect(); + listed.sort(); + assert_eq!(on_disk, listed, "a source file this crate gained is not read by the pins below"); + } + + /// **The television's SDL writes a LARGER `SDL_SysWMinfo` than the headers declare**, so a bare + /// struct on the stack is the "modular-split crash" and the over-allocated buffer with its + /// version handshake lives in the application crate's `system.rs`, beside the rest of the LG + /// half. Nothing in this crate may call it: not for the window, not for a size, not "just to + /// read the display". The SDL version query that handshake is built on belongs to the same + /// half and is pinned with it. + #[test] + fn this_crate_never_calls_the_wayland_info_query() { + for needle in [concat!("SDL_GetWindow", "WMInfo"), concat!("SDL_Get", "Version")] { + for (name, text) in SOURCES { + assert!(!text.contains(needle), "{name} names {needle}, the television's over-writing query or its handshake"); + } + } + } + + /// The crate links SDL plainly (`sys.rs`), and it must not grow a Wayland, glib or LG-fork call + /// of its own: those are the television's half and are fenced to the webOS platform by + /// `ci/check-module-layers.py`, which cannot see an `extern` block. The needles are the + /// Wayland proxy, display and surface names, the Luna register and call families, glib's main + /// context, and the LG fork's own webOS-prefixed SDL entry points and helper-prefixed bridge + /// names; each is split so this file, which the scan reads too, does not name the thing it + /// forbids. + #[test] + fn this_crate_names_no_wayland_or_luna_symbol() { + for needle in [ + concat!("wl_", "proxy"), + concat!("wl_", "display"), + concat!("wl_", "surface"), + concat!("LS", "Register"), + concat!("LS", "Call"), + concat!("g_main_", "context"), + concat!("SDL_", "webOS"), + concat!("HELPER", "_"), + ] { + for (name, text) in SOURCES { + assert!(!text.contains(needle), "{name} names {needle}"); + } + } + } +} diff --git a/rust-modules/shell-sdl/src/sys.rs b/rust-modules/shell-sdl/src/sys.rs new file mode 100644 index 0000000000..8d82a472c3 --- /dev/null +++ b/rust-modules/shell-sdl/src/sys.rs @@ -0,0 +1,81 @@ +//! Every SDL2 symbol this crate calls, declared once. A PLAIN link, not `dynlib!`: the rule in +//! `plx_base::dynlib` is for libraries whose SONAME moves, and these are stock public SDL2 API: +//! every name declared outside the `hostsim` block is exported by all 14 firmware inventories +//! (`tools/fwcompat.py --lib libSDL2-2.0.so.0`), so there is nothing here for a runtime bind to +//! tolerate. The one `hostsim` name the inventories do not all carry is `SDL_GetDisplayUsableBounds`: +//! 1.2.0 through 3.9.2 lack it and 4.4.2 onward have it, and the ARM binary never imports it. +//! +//! The Wayland and `SDL_SysWMinfo` calls are NOT here and never may be: the television's SDL fork +//! writes a larger `SDL_SysWMinfo` than the headers declare, and that over-allocated buffer +//! lives in the application crate's `system.rs` with the rest of the LG half (a pin in `lib.rs` +//! keeps this file from naming it). +#![allow(non_snake_case)] +use std::os::raw::{c_char, c_int, c_void}; + +extern "C" { + pub(crate) fn SDL_SetMainReady(); + pub(crate) fn SDL_SetHint(name: *const c_char, value: *const c_char) -> c_int; + pub(crate) fn SDL_Init(flags: u32) -> c_int; + pub(crate) fn SDL_GetCurrentVideoDriver() -> *const c_char; + pub(crate) fn SDL_GL_SetAttribute(attr: c_int, value: c_int) -> c_int; + pub(crate) fn SDL_CreateWindow( + title: *const c_char, + x: c_int, + y: c_int, + w: c_int, + h: c_int, + flags: u32, + ) -> *mut c_void; + pub(crate) fn SDL_DestroyWindow(win: *mut c_void); + pub(crate) fn SDL_GL_CreateContext(win: *mut c_void) -> *mut c_void; + pub(crate) fn SDL_GL_SetSwapInterval(interval: c_int) -> c_int; + pub(crate) fn SDL_Delay(ms: u32); + pub(crate) fn SDL_PollEvent(event: *mut c_void) -> c_int; + pub(crate) fn SDL_PushEvent(event: *const c_void) -> c_int; + pub(crate) fn SDL_GL_SwapWindow(win: *mut c_void); + pub(crate) fn SDL_Quit(); +} + +// Desktop-only window management. Apart for the mirror-image reason: a television owns the whole +// panel and never asks how big a display is, so on that build these would be dead code — which +// `[workspace.lints.rust] warnings = "deny"` makes a build failure, not a warning. +#[cfg(feature = "hostsim")] +extern "C" { + /// `SDL_GetDisplayUsableBounds` — the display minus the menu bar and the Dock, which is what + /// a window may actually occupy. The out parameter is an `SDL_Rect`: exactly four `c_int`. + pub(crate) fn SDL_GetDisplayUsableBounds(display: c_int, rect: *mut c_int) -> c_int; + /// `SDL_SetWindowSize` / `SDL_SetWindowPosition` — `window::fit_window_to_density` re-sizes + /// and re-centres the window once the display's pixel density has been measured from it. + pub(crate) fn SDL_SetWindowSize(win: *mut c_void, w: c_int, h: c_int); + pub(crate) fn SDL_SetWindowPosition(win: *mut c_void, x: c_int, y: c_int); +} + +// The system on-screen keyboard (`text`). The text-input family is stock public SDL2 API. +// +// Under `cfg(test)` and the `test-support` feature the four calls a host test could reach are +// swapped for `text::host_test_sdl`, so these declarations lose their last use there and warn; the +// `allow(dead_code)` is narrower than it looks: a real orphan would be silent in every +// configuration, and these are live on device. +extern "C" { + #[allow(dead_code)] + pub(crate) fn SDL_StartTextInput(); + #[allow(dead_code)] + pub(crate) fn SDL_StopTextInput(); + pub(crate) fn SDL_IsTextInputActive() -> c_int; + #[allow(dead_code)] + pub(crate) fn SDL_HasScreenKeyboardSupport() -> c_int; + /// LG's `WebOSIsScreenKeyboardShown`, the fourth of the four hooks its Wayland driver installs. + /// Exported by all 14 inventories, and **it does not answer the question its name asks** on this + /// firmware — the app's `textinput` note has the measurement and what replaced it. Declared, + /// unused, and kept so the next person finds the finding before they find the symbol. + #[allow(dead_code)] + pub(crate) fn SDL_IsScreenKeyboardShown(w: *mut c_void) -> c_int; + #[allow(dead_code)] + pub(crate) fn SDL_GetWindowFlags(w: *mut c_void) -> u32; + /// Turn the DRIVER's own tracing on for one category. LG's `WebOSShowScreenKeyboard` / + /// `Hide` / `TextModelLeave` / `TextModelInputPanelState` all log through SDL at + /// `SDL_LOG_CATEGORY_INPUT`, which is silent at the default priority — so this is how the + /// keyboard's real lifecycle becomes readable without patching SDL. + #[allow(dead_code)] // test build only — see the note above `SDL_StartTextInput` + pub(crate) fn SDL_LogSetPriority(category: c_int, priority: c_int); +} diff --git a/rust-modules/shell-sdl/src/testing.rs b/rust-modules/shell-sdl/src/testing.rs new file mode 100644 index 0000000000..d033e01ef0 --- /dev/null +++ b/rust-modules/shell-sdl/src/testing.rs @@ -0,0 +1,23 @@ +//! Test scaffolding for the code that polls or pushes SDL events: only SDL's event subsystem, with +//! no window, renderer, boot or device. Compiled for this crate's own tests and, through the +//! `test-support` feature, for the dependents' test builds (the application's loop tests poll SDL +//! when a by-id token drains it first). Never in a shipped build. +use crate::sys; + +/// SDL's event subsystem alone (`SDL_INIT_EVENTS`), brought up for the duration of a test and +/// quit when dropped. A test that holds one serialises on `plx_base::testlock::serial()` first, +/// because SDL's queue is process-wide. +pub struct EventsOnly; + +impl EventsOnly { + pub fn init() -> Self { + assert_eq!(unsafe { sys::SDL_Init(0x4000) }, 0); + Self + } +} + +impl Drop for EventsOnly { + fn drop(&mut self) { + unsafe { sys::SDL_Quit() }; + } +} diff --git a/rust-modules/shell-sdl/src/text.rs b/rust-modules/shell-sdl/src/text.rs new file mode 100644 index 0000000000..2a0c8c7667 --- /dev/null +++ b/rust-modules/shell-sdl/src/text.rs @@ -0,0 +1,533 @@ +//! The text-input half that is SDL: the bytes of an `SDL_TEXTINPUT` event in this build's layout, +//! and the calls that raise and dismiss the system keyboard. The state a field's editing leaves +//! behind (what the application has asked for, the queue of commits, the focus handshake) is the +//! application's own `textinput` module; this file is only what knows SDL. +//! +//! **Trap 1, the offset.** webOS inserts a `Uint32 inputSource` at `+12` of `SDL_TextInputEvent`, +//! so the UTF-8 text starts at **+16** on the television, not the `+12` that stock SDL 2.0.4's +//! `SDL_events.h` declares and that a desktop's SDL2 really uses. That header lies about the LG +//! build; the NDK sysroot's fork copy is the proof. [`TEXT_OFF`] is that choice, `cfg!` and not +//! `#[cfg]` so both arms stay compiled and the one nobody is building cannot rot, and +//! `decode_text_at` takes the offset as an argument so `make check` grades both layouts. A single +//! hard-coded number ships garbage on one of the two platforms and fails nothing. +//! +//! The calls are stock public SDL2 API, so they are a plain link (`sys.rs`); whether the PANEL rises +//! is a firmware question the application probes at run time ([`has_screen_keyboard`]) rather than +//! assumes. +//! +//! **Do not fake the event with `SDL_PushEvent`** (measured 2026-08-14, recorded in the +//! application's `textinput` module). The Mac's `libSDL2` is sdl2-compat forwarding into SDL3, whose +//! text event carries a `char *text` pointer where SDL2's carries an inline `char text[32]`; the +//! compat layer dereferences it while converting the pushed event and SIGSEGVs inside SDL. So +//! [`encode_event`] builds the bytes and the `txt:` token hands them to the decode directly, and +//! nothing in `inject.rs` ever pushes a text event. +//! +//! Under `cfg(test)` and the `test-support` feature the four calls a host test could reach are +//! replaced by [`host_test_sdl`]'s stubs: a host test has no window and no panel. +use crate::event::SDL_TEXTINPUT; +use crate::sys; +#[cfg(not(any(test, feature = "test-support")))] +use crate::sys::{ + SDL_GetWindowFlags, SDL_HasScreenKeyboardSupport, SDL_StartTextInput, SDL_StopTextInput, +}; +#[cfg(any(test, feature = "test-support"))] +use host_test_sdl::{ + SDL_GetWindowFlags, SDL_HasScreenKeyboardSupport, SDL_StartTextInput, SDL_StopTextInput, +}; +use std::os::raw::c_void; + +/// The four SDL entry points the keyboard calls reach, stubbed for a HOST TEST BINARY. +/// +/// A host test cannot call them: no window exists, and on a desktop `SDL_StartTextInput` would +/// switch text events on for the rest of the process. `cfg(test)` does not cross a crate boundary, +/// so the application's own tests get these stubs through the `test-support` feature, which its +/// `[dev-dependencies]` enable and no shipped build does. +/// +/// **Only a test is stubbed.** `hostsim` links desktop SDL2 and takes the real arm, which is the +/// whole point: the simulator is where the decode path is exercised by typing. +// the stubs carry SDL's own C names ON PURPOSE: `use`d unqualified by the arms above, so the call +// sites read identically in both builds and a signature drift shows up as a type error there +#[allow(non_snake_case)] +#[cfg(any(test, feature = "test-support"))] +mod host_test_sdl { + use std::os::raw::{c_int, c_void}; + /// No window, so no focus bit: the application's `has_focus` answers `Some(false)` under test, + /// the same answer a real television gives when the panel cannot rise. + pub(super) unsafe fn SDL_GetWindowFlags(_w: *mut c_void) -> u32 { + 0 + } + /// No panel on the host, matching what the simulator's own boot probe reports (`support=0`). + pub(super) unsafe fn SDL_HasScreenKeyboardSupport() -> c_int { + 0 + } + pub(super) unsafe fn SDL_StartTextInput() {} + pub(super) unsafe fn SDL_StopTextInput() {} +} + +/// `SDL_TEXTINPUTEVENT_TEXT_SIZE` — `char text[32]`, inline in the event rather than a pointer. +/// Both headers agree on the size; they disagree only about where it starts (trap 1). +pub const TEXT_CAP: usize = 32; + +/// Where that array begins in the raw event bytes. **Trap 1**, and the only number in this file +/// that is wrong on the platform you are not currently building. +/// +/// `cfg!` and not `#[cfg]`, matching [`crate::event::decode_key`]: both arms stay compiled on both +/// platforms, so the one nobody is building cannot rot into a compile error nobody sees for a month. +pub const TEXT_OFF: usize = if cfg!(feature = "hostsim") { 12 } else { 16 }; + +/// `SDL_LOG_CATEGORY_INPUT` / `SDL_LOG_PRIORITY_DEBUG`, from `SDL_log.h`. +#[cfg(not(any(test, feature = "test-support")))] +const SDL_LOG_CATEGORY_INPUT: std::os::raw::c_int = 3; +#[cfg(not(any(test, feature = "test-support")))] +const SDL_LOG_PRIORITY_DEBUG: std::os::raw::c_int = 2; + +/// Ask LG's SDL to narrate its own keyboard lifecycle into stderr (`/tmp/plxnative-stderr.log`). +/// +/// The driver already logs `[WebOSShowScreenKeyboard] called`, `[TextModelLeave] called`, +/// `[TextModelInputPanelState] called - state: %d` and `[WebOSHideScreenKeyboard] called` at +/// `INPUT`/`DEBUG`, which is below the default priority, so none of it prints. One call makes the +/// whole sequence readable without patching SDL. Cheap and permanent: a handful of lines per +/// keyboard session, on a log that is already the primary debugging surface. A no-op under a test. +pub fn trace_driver() { + #[cfg(not(any(test, feature = "test-support")))] + unsafe { + sys::SDL_LogSetPriority(SDL_LOG_CATEGORY_INPUT, SDL_LOG_PRIORITY_DEBUG); + } +} + +/// `SDL_StartTextInput`: raise the system keyboard (the caller keeps its own "have I asked" edge). +pub fn start_input() { + unsafe { SDL_StartTextInput() }; +} + +/// `SDL_StopTextInput`: dismiss it. +pub fn stop_input() { + unsafe { SDL_StopTextInput() }; +} + +/// Does this build/firmware claim a system keyboard? `SDL_HasScreenKeyboardSupport`, which a +/// firmware answers however it likes: the caller probes it, never assumes it. +pub fn has_screen_keyboard() -> bool { + unsafe { SDL_HasScreenKeyboardSupport() != 0 } +} + +/// `SDL_GetWindowFlags` of `win`: the one way to read `SDL_WINDOW_INPUT_FOCUS`, which is what +/// decides whether the panel rises and is never reported as an error. +pub fn window_flags(win: *mut c_void) -> u32 { + unsafe { SDL_GetWindowFlags(win) } +} + +/// What the boot log's `keyboard:` line reports about the system keyboard. The fields are SDL's own +/// numbers, unconverted, so the line keeps printing exactly what it always has. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct KeyboardProbe { + /// `SDL_HasScreenKeyboardSupport()`. + pub support: i32, + /// `SDL_IsTextInputActive()`. + pub active: i32, + /// `SDL_GetWindowFlags(win)`. + pub wflags: u32, +} + +/// Read the three facts the `keyboard:` boot line prints, in one call. +pub fn keyboard_probe(win: *mut c_void) -> KeyboardProbe { + unsafe { + KeyboardProbe { + support: SDL_HasScreenKeyboardSupport(), + active: sys::SDL_IsTextInputActive(), + wflags: SDL_GetWindowFlags(win), + } + } +} + +/// What [`encode_event`]'s inverse reads out of these bytes, at THIS platform's offset. Exposed so a +/// caller can log the decode without duplicating the choice of offset, which is the one thing in +/// this file that must never be written down twice. +pub fn decode(ev: &[u8]) -> String { + decode_text_at(ev, TEXT_OFF) +} + +/// The bytes an `SDL_TEXTINPUT` event carries for `text`, in whichever layout [`decode_text_at`] +/// reads — the inverse of it, and, like [`crate::inject::encode_key`] and +/// [`crate::event::decode_key`], the pair is only ever correct together. Nothing in the compiler +/// couples them; `encode_decode_round_trips` does. +/// +/// It exists so this seam can be DRIVEN, by the application's `txt:` remote token. A real +/// `SDL_TEXTINPUT` needs a human at a keyboard — no trigger raises the panel, and typing into the +/// simulator means somebody physically typing — so without it nothing automated could ever put a +/// character in the search field, on either platform. +/// +/// The bytes are a faithful event in THIS platform's layout, and `txt:` hands them to the decode +/// rather than to `SDL_PushEvent`: pushing a synthetic `SDL_TEXTINPUT` segfaults inside the Mac's +/// SDL, for the reason in the module doc. +pub fn encode_event(text: &str) -> [u8; 128] { + let mut ev = [0u8; 128]; + ev[0..4].copy_from_slice(&SDL_TEXTINPUT.to_ne_bytes()); + // `text[32]` holds at most 31 bytes plus its terminator — and the cut must land on a CHAR + // BOUNDARY. Slicing a codepoint in half would make the decoder answer U+FFFD for text that + // was perfectly valid when it was written, which reads as a decoder bug and is not one. + let mut n = text.len().min(TEXT_CAP - 1); + while n > 0 && !text.is_char_boundary(n) { + n -= 1; + } + ev[TEXT_OFF..TEXT_OFF + n].copy_from_slice(&text.as_bytes()[..n]); + ev +} + +/// The committed text in a raw `SDL_TEXTINPUT` event whose `text[]` begins at `off`. +/// +/// Pure, and offset-parameterised rather than reading [`TEXT_OFF`] itself, so `make check` can +/// grade BOTH platforms' layouts on a host that only ever builds one of them — the same reason +/// `event::decode_key` and `inject::encode_key` are pure and tested as a pair. +/// +/// Every failure mode here is a byte string somebody else chose: the panel's own IME writes this +/// field, and the app cannot afford a panic inside the SDL event loop (see `remote.rs`, where +/// exactly that class took the app down). So a short buffer, a missing NUL and invalid UTF-8 are +/// all answers, not faults. +fn decode_text_at(ev: &[u8], off: usize) -> String { + // `min(ev.len())` before the slice, not after: `text[32]` is the LAST field of the event, so a + // truncated or short buffer is the ordinary case at the end of the struct, not a malformed one. + let end = off.saturating_add(TEXT_CAP).min(ev.len()); + let Some(field) = ev.get(off..end) else { + return String::new(); // off past the end — `get` refuses the inverted range rather than panicking + }; + // NUL-terminated INSIDE a fixed array: the terminator is the length, and everything after it + // is whatever the last, longer commit left behind. + let n = field.iter().position(|&b| b == 0).unwrap_or(field.len()); + // The two edges of a codepoint the fixed array may have CUT — see `drop_cut_tail`. The tail + // rule is conditional on the array being FULL (`n == TEXT_CAP`), which is the signature of a + // cut; the head rule is unconditional, because no UTF-8 string may begin with a continuation + // byte under any circumstances. Deliberately NOT `n == field.len()`, which is also true when + // the CALLER's buffer ran out before `text[32]` did — a short buffer is the reader's limit, + // not the panel's, and there is nothing to say the panel cut anything at all. + let text = drop_orphan_head(&field[..n]); + let text = if n == TEXT_CAP { + drop_cut_tail(text) + } else { + text + }; + // Lossy, never `from_utf8`: a single bad byte would otherwise discard the whole commit — and + // an IME that emits one is a keystroke the user typed, not an attack. + String::from_utf8_lossy(text).into_owned() +} + +/// Drop a trailing UTF-8 sequence that is well-formed so far but CUT SHORT by the end of the +/// buffer. Everything else — a lone continuation byte, an overlong or out-of-range lead, a +/// surrogate — is left for `from_utf8_lossy` to answer with U+FFFD, because a replacement character +/// is the only visible signal that something arrived broken and it must not be swallowed. +/// +/// **This is LG checklist row #16** (`docs/lg-self-checklist.md` §2), which asks that the character +/// which arrives be the character that was pressed. `text[32]` is a fixed array, so a commit that +/// fills it is cut at a BYTE, and that cut lands mid-codepoint for any query that is not pure +/// ASCII. Decoded lossily, the surviving half becomes a `` the user never typed, in their search +/// field — exactly the substitution the row is about. Nothing can recover the character (its other +/// half is not in this event), so the honest answer is the text that WAS whole. +/// +/// **The classification is `std`'s, not ours.** `Utf8Error::error_len() == None` is precisely +/// "valid so far, ended mid-sequence", and `valid_up_to()` is where to cut — where a hand-rolled +/// lead-byte width table accepts `0xC0`, `0xF5..=0xF7` and surrogate pairs as merely "incomplete" +/// and deletes real corruption without a trace. Only the LAST sequence is offered to it (walk back +/// at most four bytes to the first non-continuation byte; no sequence is longer), so an interior +/// error earlier in the commit cannot suppress the tail rule. +/// +/// **Belt-and-braces for a case this project has not settled.** Stock SDL2 fills `text[32]` with +/// `SDL_utf8strlcpy`, which truncates on a character boundary and always terminates — so on stock +/// SDL this branch is unreachable, and `encode_event` cuts on a boundary too, which is why nothing +/// the simulator or the `txt:` token can drive reaches it either. Whether **LG's fork** does the +/// same is a question for the television's own `libSDL2`, not for a header or another client: +/// `.agents/skills/decompile-tv-lib/` is how the `+16 inputSource` offset above was settled, and it +/// is how this would be. Until then the branch costs one comparison and cannot make a correct +/// commit wrong. +fn drop_cut_tail(b: &[u8]) -> &[u8] { + for back in 1..=b.len().min(4) { + let i = b.len() - back; + if b[i] & 0xC0 == 0x80 { + continue; // a continuation byte — the sequence it belongs to starts further back + } + return match std::str::from_utf8(&b[i..]) { + Err(e) if e.error_len().is_none() => &b[..i], + _ => b, + }; + } + b // nothing but continuation bytes: garbage, and `from_utf8_lossy`'s to answer +} + +/// The other edge of the same cut: drop a leading run of continuation bytes. +/// +/// If the panel really does split a codepoint at `text[32]`, the half [`drop_cut_tail`] discards +/// arrives at the START of the NEXT commit — orphaned, with its lead byte in the event before it. +/// Left alone those bytes are one U+FFFD each, which is the row-#16 substitution again, one +/// character later; dropping the head is what makes the rule whole rather than one-sided. +/// +/// Unconditional, and safe to be: **no UTF-8 string may begin with a continuation byte**, so this +/// can only ever remove bytes that were already unreadable — never a character the user typed. +fn drop_orphan_head(b: &[u8]) -> &[u8] { + let n = b.iter().take_while(|&&c| c & 0xC0 == 0x80).count(); + &b[n..] +} + +// --------------------------------------------------------------------------------------- +#[cfg(test)] +mod tests { + use super::*; + + /// A synthetic event in one platform's layout: type at +0, the text at `off`, NUL-terminated + /// if it fits. `[u8; 128]` because that is what `event::poll` reads into. + fn ev_with(off: usize, text: &[u8]) -> [u8; 128] { + let mut ev = [0u8; 128]; + ev[0..4].copy_from_slice(&0x303u32.to_ne_bytes()); // SDL_TEXTINPUT + ev[off..off + text.len()].copy_from_slice(text); + ev + } + + /// **The trap this whole file is shaped around.** LG's fork inserts `Uint32 inputSource` at + /// +12, so the text is at +16 on the television and at +12 on a desktop. A single hard-coded + /// offset does not fail loudly on the wrong platform — it reads four bytes of `windowID` (or + /// of the text's own head) and commits plausible garbage into the search field. + #[test] + fn the_text_decodes_at_both_platforms_offsets() { + assert_eq!(decode_text_at(&ev_with(16, b"webos"), 16), "webos"); + assert_eq!(decode_text_at(&ev_with(12, b"desktop"), 12), "desktop"); + // …and reading one layout with the other's offset is exactly the silent corruption above: + // at +16 a stock event is four bytes into the text, and at +12 a fork event is inside + // `inputSource`, which is zero — an empty commit. + assert_eq!(decode_text_at(&ev_with(12, b"desktop"), 16), "top"); + assert_eq!(decode_text_at(&ev_with(16, b"webos"), 12), ""); + } + + /// The ordinary case: a short string in a fixed 32-byte array, terminated by NUL. Everything + /// after the terminator is the tail of some LONGER earlier commit, and must not be returned. + #[test] + fn a_nul_terminates_the_string_inside_the_fixed_array() { + let mut ev = ev_with(16, b"ab\0cdefghijklmnop"); + ev[16 + 31] = b'!'; // …up to and including the last byte of text[32] + assert_eq!(decode_text_at(&ev, 16), "ab"); + } + + /// A commit that fills `text[32]` completely has NO terminator — the array is the length. A + /// decoder that insists on finding a NUL reads past the field into `SDL_Event`'s padding. + #[test] + fn a_full_32_byte_commit_has_no_terminator() { + let text = [b'x'; TEXT_CAP]; + let ev = ev_with(16, &text); + assert_eq!(decode_text_at(&ev, 16), "x".repeat(TEXT_CAP)); + } + + /// Invalid UTF-8 must not panic. This runs inside the SDL event loop, where a panic unwinds + /// out of `plex_run` and takes the app with it — `remote.rs` lost the app exactly this way to + /// a multi-byte whitespace. The bytes come from the television's own IME, so "that cannot + /// happen" is not a thing this file gets to assume. + #[test] + fn invalid_utf8_is_replaced_rather_than_panicking() { + let s = decode_text_at(&ev_with(16, b"a\xffb"), 16); + assert_eq!(s, "a\u{fffd}b"); + // A bad byte in the MIDDLE keeps its replacement whatever surrounds it — it is neither + // edge of a cut, so neither trim rule can claim it. (A LEADING continuation byte is the + // orphan case and IS dropped; `a_commit_orphaned_from_its_lead_byte_is_dropped_rather_ + // than_replaced` owns that, and `\x80` alone belongs to it rather than here.) + assert_eq!(decode_text_at(&ev_with(16, b"x\x80y"), 16), "x\u{fffd}y"); + assert_eq!(decode_text_at(&ev_with(16, b"x\xc0y"), 16), "x\u{fffd}y"); + } + + /// **Row #16: a codepoint the fixed array CUT must not arrive as a character nobody typed.** + /// `text[32]` has no room for the tail of a sequence that starts at its last byte, so a lossy + /// decode puts a `` in the user's query — the exact substitution the checklist row is about. + /// The whole prefix is kept; only the half codepoint goes. + #[test] + fn a_codepoint_cut_by_the_end_of_the_field_is_dropped_not_replaced() { + // Each width of lead byte, cut at every point that leaves it incomplete. + for (lead, whole) in [(0xc3u8, "é"), (0xe5, "千"), (0xf0, "🎬")] { + let need = whole.len(); + for kept in 1..need { + let mut raw = vec![b'y'; TEXT_CAP - kept]; + raw.extend_from_slice(&whole.as_bytes()[..kept]); + assert_eq!(raw.len(), TEXT_CAP); + let got = decode_text_at(&ev_with(16, &raw), 16); + assert_eq!( + got, + "y".repeat(TEXT_CAP - kept), + "lead {lead:#x}, {kept} of {need} bytes" + ); + assert!( + !got.contains('\u{fffd}'), + "a cut must not invent a character" + ); + } + // …and the same codepoint that FITS is untouched, which is what proves the rule cuts + // only what was actually truncated. + let mut raw = vec![b'y'; TEXT_CAP - need]; + raw.extend_from_slice(whole.as_bytes()); + assert_eq!( + decode_text_at(&ev_with(16, &raw), 16), + format!("{}{whole}", "y".repeat(TEXT_CAP - need)) + ); + } + } + + /// A TERMINATED commit is as long as the panel meant it to be, so a malformed tail inside one + /// is genuine garbage and keeps the defensive replacement — the cut rule must not swallow it. + /// Neither may a SHORT BUFFER be read as a cut: that is the caller's limit, not the panel's. + #[test] + fn a_bad_tail_before_a_terminator_still_replaces_rather_than_vanishing() { + // `ab` + a bare 3-byte lead + NUL: nothing cut this, the byte is simply wrong. + assert_eq!(decode_text_at(&ev_with(16, b"ab\xe5\0"), 16), "ab\u{fffd}"); + // …and a buffer that ends mid-codepoint is the READER running out, so the tail rule stays + // off and the bad byte is still reported. + assert_eq!( + decode_text_at(&ev_with(16, "é".as_bytes())[..17], 16), + "\u{fffd}" + ); + } + + /// **A byte no cut could have produced keeps its replacement.** The rule is "valid so far, + /// ended mid-sequence" and nothing looser — a hand-rolled lead-byte width table calls all of + /// these merely incomplete and deletes them, which turns real corruption from the panel's IME + /// into a silent shortening with no signal at all. `std::str::from_utf8` draws the line. + #[test] + fn corruption_that_is_not_a_cut_is_reported_rather_than_deleted() { + for (name, tail) in [ + ("overlong lead", &[0xC0u8][..]), + ("out-of-range lead", &[0xF5][..]), + ("never-a-lead byte", &[0xFF][..]), + ("surrogate half", &[0xED, 0xA0][..]), + ] { + let mut raw = vec![b'y'; TEXT_CAP - tail.len()]; + raw.extend_from_slice(tail); + let got = decode_text_at(&ev_with(16, &raw), 16); + assert!( + got.contains('\u{fffd}'), + "{name} must survive as a replacement, got {got:?}" + ); + } + } + + /// The other edge of the same cut: a commit ORPHANED from its lead byte — the remainder of a + /// codepoint the previous event was cut inside — must not arrive as one U+FFFD per byte, which + /// is the row-#16 substitution again, one character later. + #[test] + fn a_commit_orphaned_from_its_lead_byte_is_dropped_rather_than_replaced() { + // "🎬" is F0 9F 8E AC; cut after F0, the next commit opens with its three tail bytes. + assert_eq!( + decode_text_at(&ev_with(16, b"\x9f\x8e\xacstar"), 16), + "star" + ); + // …and a commit that is nothing BUT an orphaned remainder yields nothing, rather than one + // replacement character per byte. + assert_eq!(decode_text_at(&ev_with(16, b"\x80"), 16), ""); + // …and a commit that legitimately STARTS with a multi-byte character is untouched. + assert_eq!( + decode_text_at(&ev_with(16, "🎬star".as_bytes()), 16), + "🎬star" + ); + } + + /// **Capital and small letters transfer as themselves.** The panel's Shift/Caps is resolved on + /// the television — it commits the CASED character — so the app's whole obligation is to carry + /// the bytes through without touching them, and this is what proves it does. (A decoder that + /// normalised case would be invisible until someone searched for a title that differs only by + /// it.) Deliberately cites no checklist row number: `docs/lg-self-checklist.md` records no such + /// row, and a number this repo cannot corroborate does not belong in a permanent comment. + #[test] + fn letter_case_transfers_exactly_as_the_panel_committed_it() { + for s in [ + "A", "a", "Wallace", "WALLACE", "wallace", "WaLlAcE", "Ç", "ç", "Ä", "ä", + ] { + assert_eq!(decode_text_at(&ev_with(16, s.as_bytes()), 16), s); + assert_eq!(decode_text_at(&encode_event(s), TEXT_OFF), s); + } + } + + /// **Row #16, its own worked example.** The checklist names the full-width `\` (U+FF3C) and + /// asks that it not arrive as a backslash — the substitution a keyboard stack makes when it + /// folds full-width forms to ASCII, and the one a byte-oriented decoder makes when it reads one + /// of the three bytes of a full-width form on its own. + /// + /// The `lookalike` column is not a second assertion (the equality above already implies it); + /// it is the table saying what each row is FOR, so the next reader can tell a deliberate pair + /// from an arbitrary one. The rest are the characters a VKB commonly substitutes or a layer + /// below eats — the shell and URL metacharacters, and the quote pair a keyboard "smartens". + #[test] + fn a_full_width_character_is_not_folded_to_its_ascii_lookalike() { + for (typed, _lookalike) in [ + ("\", "\\"), // U+FF3C FULLWIDTH REVERSE SOLIDUS — the row's own example + ("¥", "\\"), // U+FFE5, the same key on a JP panel, and the same wrong answer + ("/", "/"), + (":", ":"), + (" ", " "), // U+3000 IDEOGRAPHIC SPACE + ("“", "\""), + ("’", "'"), + ("-", "-"), + ] { + let got = decode_text_at(&ev_with(16, typed.as_bytes()), 16); + assert_eq!( + got, typed, + "the character pressed must be the character that arrives" + ); + assert_eq!(decode_text_at(&encode_event(typed), TEXT_OFF), typed); + } + // The ASCII originals still arrive as themselves — nothing here rewrites in either + // direction. `\` is the one the row calls out, and the rest are what a URL layer or a + // shell would eat if anything on the path were not byte-transparent. + for s in [ + "\\", "/", "&", "%", "+", "#", "?", "=", "\"", "'", "<", ">", " ", "\t", + ] { + assert_eq!(decode_text_at(&ev_with(16, s.as_bytes()), 16), s); + } + } + + /// A buffer that ends before (or inside) the text field is an answer, not a fault. `SDL_Event` + /// is a union and nothing guarantees a caller polled into 128 bytes. + #[test] + fn a_short_buffer_yields_an_empty_string() { + assert_eq!(decode_text_at(&[0u8; 8], 16), ""); + assert_eq!(decode_text_at(&[], 16), ""); + // Ending mid-field returns the part that IS there, rather than nothing. + let ev = ev_with(16, b"abcdef"); + assert_eq!(decode_text_at(&ev[..19], 16), "abc"); + } + + /// Multi-byte UTF-8 survives intact — the field is bytes, not characters, and a European or + /// CJK query is the normal case for a media library. + #[test] + fn multibyte_text_round_trips() { + assert_eq!( + decode_text_at(&ev_with(16, "Amélie".as_bytes()), 16), + "Amélie" + ); + assert_eq!( + decode_text_at(&ev_with(16, "千と千尋".as_bytes()), 16), + "千と千尋" + ); + } + + /// The encoder writes what the decoder reads, on whichever platform this is — the pair that + /// nothing but this test couples. `app.rs` already lost the simulator's whole remote FIFO to + /// exactly this: `encode_key` wrote LG's layout while `decode_key` had been taught stock + /// SDL2's, so every token was accepted and nothing moved. + #[test] + fn encode_decode_round_trips() { + for s in ["a", "wallace", "Amélie", "千と千尋", "star wars"] { + assert_eq!(decode_text_at(&encode_event(s), TEXT_OFF), s); + } + } + + /// Over-long text is cut to fit `text[32]`, and the cut lands on a CHAR BOUNDARY — a codepoint + /// sliced in half would come back as U+FFFD and look like a decoder fault. + #[test] + fn an_over_long_commit_is_cut_on_a_char_boundary() { + let long = "x".repeat(100); + assert_eq!( + decode_text_at(&encode_event(&long), TEXT_OFF), + "x".repeat(TEXT_CAP - 1) + ); + // 16 CJK codepoints = 48 bytes: the 31-byte limit falls mid-codepoint, so the cut must + // back up to 30 bytes (10 characters) rather than emit a replacement character. + let cjk = "千".repeat(16); + let got = decode_text_at(&encode_event(&cjk), TEXT_OFF); + assert_eq!(got, "千".repeat(10)); + assert!( + !got.contains('\u{fffd}'), + "the cut must not split a codepoint" + ); + } +} diff --git a/rust-modules/shell-sdl/src/window.rs b/rust-modules/shell-sdl/src/window.rs new file mode 100644 index 0000000000..69047bcf01 --- /dev/null +++ b/rust-modules/shell-sdl/src/window.rs @@ -0,0 +1,510 @@ +//! The window and its GL context: asking SDL for one (with the one retry a stored size needs), the +//! desktop's window arithmetic, the swap, and the swap interval. +//! +//! [`Window`] is the one SDL implementation of the application's `Surface`. It holds the raw +//! `SDL_Window*` and nothing else: it has no destructor, so it never frees or nulls itself when the +//! compositor takes the screen away (the application is leaked at exit and a worker may still hold +//! the handle), and `init::quit` is explicit. The handle is the single contract with the television's +//! Wayland half, which lives in the application crate's `system.rs`: that code receives +//! [`Window::raw`] and the order of calls on one thread, and nothing here ever names the Wayland or +//! `SDL_SysWMinfo` calls (the television's SDL writes a larger info struct than the headers declare; +//! `system.rs` has the buffer that survives that, and a pin in `lib.rs` keeps this crate off it). +use crate::sys; +#[cfg(feature = "hostsim")] +use crate::sys::{SDL_GetDisplayUsableBounds, SDL_SetWindowPosition, SDL_SetWindowSize}; +use plx_base::eventlog::log; +use plx_base::task::MainThread; +use std::ffi::CStr; +use std::os::raw::{c_int, c_void}; + +/// OPENGL | FULLSCREEN on the television, which owns the whole panel. +/// +/// The desktop asks for OPENGL | ALLOW_HIGHDPI — no fullscreen grab (hostile on a laptop) and +/// **not RESIZABLE**: `surface::probe` reads the drawable once, at boot, so a dragged edge would +/// leave the viewport describing a window that no longer exists, and the interface would sit in a +/// 1920x1080-shaped corner of the new one with every pointer hit landing somewhere else. The window +/// opens at an exact divisor of the canvas instead — see `plan_desktop_window`. +/// +/// ALLOW_HIGHDPI is what makes that divisor land on a **1:1 surface** on the Mac people actually +/// have: without it a Retina display gives a drawable equal to the window in POINTS, which the +/// compositor then doubles, so the whole interface is an upscale of a half-size render. With it, +/// `fit_window_to_density` measures the pixels per point once the window exists and sizes +/// it in points for the drawable it should give: 960x540 points for a 1920x1080 drawable on a 2x +/// display, so `surface::scale() == 1.0`, the same 1:1 texel contract the television gets. +pub const SDL_WINDOW_FLAGS: u32 = if cfg!(feature = "hostsim") { + 0x2 | 0x2000 +} else { + 0x2 | 0x1 +}; +/// `SDL_WINDOW_ALLOW_HIGHDPI`, the one bit of [`SDL_WINDOW_FLAGS`] a frame dump clears. +const SDL_WINDOW_ALLOW_HIGHDPI: u32 = 0x2000; +/// `SDL_WINDOW_INPUT_FOCUS`. Note it is NOT among the flags requested above — no window flag can +/// ask for it; SDL sets it when the compositor gives this surface the keyboard. Read, never asked +/// for, and read by exactly one thing: the application's `textinput`, whose panel it silently gates. +pub const SDL_WINDOW_INPUT_FOCUS: u32 = 0x200; + +// The window we ASK SDL for. `surface::probe` then reads back what we actually got. +#[cfg(any(feature = "hostsim", test))] +const SCR_W: c_int = plx_base::surface::LOGICAL_W as c_int; +#[cfg(any(feature = "hostsim", test))] +const SCR_H: c_int = plx_base::surface::LOGICAL_H as c_int; + +/// Where, and how big, to ask for the window. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Placement { + /// The television: placed at 0,0 at exactly `size` and takes the panel. `fallback` is the one + /// size to retry at when the window or its GL context is refused at `size`. + /// + /// **A stored size the set will not give must never brick launch.** If the window or its GL + /// context is refused at a smaller size the owner chose, free whatever was made and retry ONCE + /// at the native canvas; only a refused native window is fatal. + Panel { size: (c_int, c_int), fallback: Option<(c_int, c_int)> }, + /// A desktop: centred at whatever fits the display (`plan_desktop_window`), sized for the + /// display's pixel density once the window exists (`fit_window_to_density`). The request is the + /// desktop's own size, not a setting, so there is no retry here. Only a simulator build has the + /// SDL calls that read a display's size. + #[cfg(feature = "hostsim")] + Desktop, +} + +/// What the application asks for. Plain data: the title the platform chooses, where and how big, and +/// whether the desktop window may be HiDPI. +#[derive(Clone, Copy, Debug)] +pub struct OpenAsk<'a> { + pub title: &'a CStr, + pub placement: Placement, + /// `false` clears `SDL_WINDOW_ALLOW_HIGHDPI`. A frame dump's drawable is exactly the window's + /// size in points: it is the one desktop window that does not ask for it, so its window is the + /// 1920x1080 points of the canonical Linux host on a Retina display too, and + /// `fit_window_to_density` finds nothing to correct. A no-op for the television's flags, which + /// never carry the bit. (Absent from every shipping build.) + pub high_dpi: bool, +} + +/// SDL refused the window or its GL context at the native size (the reason is in the log lines +/// `CreateWindow failed at WxH` / `GL ctx failed at WxH`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct OpenFailed; + +/// An open SDL window, current on this thread's GL context. `!Send`/`!Sync` (it is a raw pointer): +/// the swap, the poll and the interval are the SDL main thread's. +#[derive(Debug)] +pub struct Window { + win: *mut c_void, +} + +impl Window { + /// A window that does not exist: the test rig's and the host shells'. Its swap is + /// `SDL_GL_SwapWindow(NULL)`, which SDL answers with an error and nothing else, exactly as the + /// rig's null handle always has. + pub const DETACHED: Window = Window { win: std::ptr::null_mut() }; + + /// Ask SDL for the window and its GL context, correct it for the display's density where the + /// platform has one to correct, and probe the drawable it actually gave. + /// + /// Called after [`crate::init::init`] and [`crate::init::request_gl`], and after the + /// application has read the stored session, which the placement may depend on: that order is + /// the application's and is pinned there. + pub fn open(_mt: &MainThread, ask: &OpenAsk) -> Result { + // The television is placed at 0,0 at exactly canvas size (unless a webOS 1-3 owner picked a + // smaller Interface resolution) and takes the panel. A desktop window is centred + // (`SDL_WINDOWPOS_CENTERED`) at whatever fits — see `plan_desktop_window`. The density is not + // known until a window exists, so this is the 1x answer; `fit_window_to_density` below + // corrects it on a display where that was wrong. + #[cfg(feature = "hostsim")] + let mut desktop_ask: Option = None; + let (wx, wy, ww_req, wh_req, mut fallback) = match ask.placement { + Placement::Panel { size: (w, h), fallback } => (0, 0, w, h, fallback), + #[cfg(feature = "hostsim")] + Placement::Desktop => { + let planned = desktop_window_ask(); + desktop_ask = Some(planned); + let (w, h) = plan_desktop_window(planned, Density::UNIT); + (WINDOWPOS_CENTERED, WINDOWPOS_CENTERED, w, h, None) + } + }; + let window_flags = if ask.high_dpi { + SDL_WINDOW_FLAGS + } else { + SDL_WINDOW_FLAGS & !SDL_WINDOW_ALLOW_HIGHDPI + }; + let (mut ww_try, mut wh_try) = (ww_req, wh_req); + let win = unsafe { + loop { + let win = + sys::SDL_CreateWindow(ask.title.as_ptr(), wx, wy, ww_try, wh_try, window_flags); + if win.is_null() { + log(&format!("CreateWindow failed at {ww_try}x{wh_try}")); + } else { + let ctx = sys::SDL_GL_CreateContext(win); + if !ctx.is_null() { + break win; + } + log(&format!("GL ctx failed at {ww_try}x{wh_try}")); + sys::SDL_DestroyWindow(win); + } + let Some((w, h)) = fallback.take() else { + return Err(OpenFailed); + }; + log(&format!("surface: retrying the window at the native {w}x{h}")); + (ww_try, wh_try) = (w, h); + } + }; + // Correct the size for the display's density now: `surface::probe` below reads the drawable once. + #[cfg(feature = "hostsim")] + if let Some(desktop_ask) = desktop_ask { + unsafe { fit_window_to_density(win, desktop_ask) }; + } + plx_base::surface::probe(win); + Ok(Window { win }) + } + + /// The raw `SDL_Window*`: the handle the application's `Shell` hands to the television's + /// Wayland half and to `textinput`. Null for [`Window::DETACHED`]. + pub fn raw(&self) -> *mut c_void { + self.win + } + + /// `SDL_GL_SetSwapInterval` for the current context: 1 locks the frame rate to the panel + /// refresh, 0 uncaps it. The caller computes the value (vsync, `/tmp/plxnative-novsync`, a + /// frame dump) because those are application triggers. + pub fn set_swap_interval(&self, interval: i32) { + unsafe { sys::SDL_GL_SetSwapInterval(interval) }; + } + + /// `SDL_GL_SwapWindow`: present the frame. The compositor commit of the opaque-region request + /// the application made just before it is this swap's, not a call of its own. + pub fn swap(&self) { + unsafe { sys::SDL_GL_SwapWindow(self.win) }; + } +} + + +/// What a DESKTOP window is asked to be, before the display's pixel density is known. +#[cfg(any(feature = "hostsim", test))] +#[derive(Clone, Copy)] +enum WindowAsk { + /// `PLXNATIVE_WIN=x`: a DRAWABLE of exactly this many pixels, on any display. + Drawable(c_int, c_int), + /// No override: the largest whole fraction of the canvas whose window fits this usable display + /// area (`SDL_GetDisplayUsableBounds`, in points). + Fit(c_int, c_int), +} + +/// How many drawable pixels a window point is worth on this display, as the integer pair SDL +/// reported for a window that exists: `window_w` points wide, `drawable_w` pixels wide. +/// +/// Integers, never a float multiplied back: 960 points of a 2x window must come out as exactly +/// 1920 pixels, and a ratio that is not a whole number (a 150% Windows display) must round the +/// same way on the way out as on the way in. +#[cfg(any(feature = "hostsim", test))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Density { + window_w: c_int, + drawable_w: c_int, +} + +#[cfg(any(feature = "hostsim", test))] +impl Density { + /// One pixel per point: every 1x display, and what is assumed until a window has been measured. + const UNIT: Density = Density { window_w: 1, drawable_w: 1 }; + + /// The measured pair. A drawable that is not larger than the window (a 1x display) is + /// [`Density::UNIT`]: a drawable never has fewer pixels than points, and a window is never + /// grown to make up for one that seems to. + fn measured(window_w: c_int, drawable_w: c_int) -> Density { + if window_w <= 0 || drawable_w <= window_w { + Density::UNIT + } else { + Density { window_w, drawable_w } + } + } + + /// The window size, in points, whose drawable is `px` pixels: the nearest whole number of + /// points, and one fewer if rounding up would make the drawable LARGER than asked (never + /// larger than the canvas is the contract; a pixel short is a letterbox, a pixel over is not). + fn points(self, px: c_int) -> c_int { + let (w, d) = (i64::from(self.window_w), i64::from(self.drawable_w)); + let pt = ((i64::from(px) * w + d / 2) / d).max(1) as c_int; + if pt > 1 && self.pixels(pt) > px { + pt - 1 + } else { + pt + } + } + + /// The drawable, in pixels, of a window `pt` points wide. + fn pixels(self, pt: c_int) -> c_int { + let (w, d) = (i64::from(self.window_w), i64::from(self.drawable_w)); + ((i64::from(pt) * d + w / 2) / w) as c_int + } +} + +/// `PLXNATIVE_WIN`'s value: `x`, both positive. Anything else is no override. +#[cfg(any(feature = "hostsim", test))] +fn parse_window_override(v: &str) -> Option<(c_int, c_int)> { + let (w, h) = v.split_once(['x', 'X'])?; + match (w.trim().parse::(), h.trim().parse::()) { + (Ok(w), Ok(h)) if w > 0 && h > 0 => Some((w, h)), + _ => None, + } +} + +/// The window a DESKTOP should open at, in points, for a display of this pixel `density`: the +/// pure arithmetic of the size, so the Retina cases are testable without a Retina display. +/// +/// **The drawable is what is sized; the window follows from it.** The UI is authored at a 1920x1080 +/// canvas and every glyph, icon mask and poster is rasterized for 1:1 texels against it +/// (`gfx::snap`, the crispness contract in `theme.rs`), so a drawable LARGER than the canvas is +/// not a sharper picture: it is the same atlas stretched, with every drawable-sized buffer (the +/// page snapshot, the glass sources) four times the television's, which is how a 2x display once +/// breached the render-set ceiling on every frame (`ui/src/frame/render_set.rs`). +/// +/// * `Drawable` is that drawable, exactly. The fit below is chosen for a HUMAN looking at a +/// window, and a screenshot is not that: on a 1x display its divisor lands on 2 and every shot +/// comes back 960x540, half the canvas the UI is authored at, so a shot taken to JUDGE the +/// interface asks for full size (`make sim-shot SIM_W=1920 SIM_H=1080`). Off-screen edges are +/// fine for a headless grab: the drawable is the window's own framebuffer. +/// * `Fit` is **an exact divisor, never a best fit**: the largest of 1/1, 1/2 and 1/3 of the canvas +/// whose window, in points, fits the usable area. `surface::scale` will letterbox any drawable it +/// is given, so an arbitrary size would *work*, but a fractional scale resamples all of the above. +/// The bounds are in points, so the window is `canvas / div / density` of them. +/// +/// The television asks for the canvas itself (1:1) unless the owner picked a smaller Interface +/// resolution in Settings on webOS 1-3 (`requested_drawable`), in which case the compositor fills the panel. +/// A Mac is the case the `surface` doc was written against — 1920x1080 exceeds the usable area of +/// every laptop display Apple ships, so asking for it flatly would put the title bar above the +/// screen and the bottom of the interface under the Dock. +#[cfg(any(feature = "hostsim", test))] +fn plan_desktop_window(ask: WindowAsk, density: Density) -> (c_int, c_int) { + let points = |(w, h): (c_int, c_int)| (density.points(w), density.points(h)); + match ask { + WindowAsk::Drawable(w, h) => points((w, h)), + WindowAsk::Fit(uw, uh) => { + // A little headroom under the usable bounds: a window flush against them reads as a + // fullscreen that went wrong rather than as a deliberate size. + let (max_w, max_h) = ((uw as f32 * 0.95) as c_int, (uh as f32 * 0.95) as c_int); + let fits = |div| { + let (w, h) = points((SCR_W / div, SCR_H / div)); + w <= max_w && h <= max_h + }; + let div = (1..3).find(|&div| fits(div)).unwrap_or(3); + points((SCR_W / div, SCR_H / div)) + } + } +} + +/// `SDL_WINDOWPOS_CENTERED` on display 0. +#[cfg(feature = "hostsim")] +const WINDOWPOS_CENTERED: c_int = 0x2FFF_0000u32 as c_int; + +/// What this process is asked for: `PLXNATIVE_WIN` if it holds a size, else the fit to the display, +/// or the canvas itself if SDL cannot say how big the display is. +#[cfg(feature = "hostsim")] +fn desktop_window_ask() -> WindowAsk { + if let Some((w, h)) = std::env::var_os("PLXNATIVE_WIN").and_then(|v| parse_window_override(&v.to_string_lossy())) { + return WindowAsk::Drawable(w, h); + } + let mut r = [0 as c_int; 4]; // SDL_Rect: x, y, w, h + let ok = unsafe { SDL_GetDisplayUsableBounds(0, r.as_mut_ptr()) } == 0 && r[2] > 0 && r[3] > 0; + if ok { + WindowAsk::Fit(r[2], r[3]) + } else { + WindowAsk::Drawable(SCR_W, SCR_H) + } +} + +/// Size the just-created desktop `win` for the pixel density of the display it opened on. +/// +/// `SDL_GetDisplayDPI` is unreliable on macOS, so the density is MEASURED instead: the window was +/// opened at the 1x answer of [`plan_desktop_window`], and `SDL_GL_GetDrawableSize` over +/// `SDL_GetWindowSize` says how many pixels that bought per point. On a 1x display nothing happens. +/// On a 2x display the window is resized (and put back in the middle of the display, since it was +/// centred at the old size) to the points that give the drawable that was asked for: +/// `PLXNATIVE_WIN=1920x1080` is a 960x540-point window, not a 1920x1080-point one with a 3840x2160 +/// drawable. Called before `surface::probe`, which reads the drawable once and for good. +#[cfg(feature = "hostsim")] +unsafe fn fit_window_to_density(win: *mut c_void, ask: WindowAsk) { + let ((ww, wh), (dw, dh)) = plx_base::surface::window_and_drawable_size(win); + let density = Density::measured(ww, dw); + if density == Density::UNIT { + return; + } + let (pw, ph) = plan_desktop_window(ask, density); + if (pw, ph) == (ww, wh) { + return; + } + SDL_SetWindowSize(win, pw, ph); + SDL_SetWindowPosition(win, WINDOWPOS_CENTERED, WINDOWPOS_CENTERED); + let ((nw, nh), (gw, gh)) = plx_base::surface::window_and_drawable_size(win); + log(&format!( + "surface: {:.3} pixels per point (a {ww}x{wh} point window read back a {dw}x{dh} drawable); \ + resized to {pw}x{ph} points, which now reads {nw}x{nh} points / {gw}x{gh} drawable", + f64::from(dw) / f64::from(ww) + )); +} + +#[cfg(test)] +mod desktop_window_tests { + use super::WindowAsk::{Drawable, Fit}; + use super::{parse_window_override, plan_desktop_window, Density, WindowAsk, SCR_H, SCR_W}; + + /// A window of 1920 points whose drawable reads back 3840 pixels: macOS Retina, the case this + /// module exists for. (macOS always reports a whole backing factor, even in a "scaled" mode.) + fn retina() -> Density { + Density::measured(1920, 3840) + } + + /// The window the planner opens, in points, and the drawable that window gives. + fn plan(ask: WindowAsk, density: Density) -> ((i32, i32), (i32, i32)) { + let points = plan_desktop_window(ask, density); + (points, (density.pixels(points.0), density.pixels(points.1))) + } + + /// `PLXNATIVE_WIN=1920x1080` on a 1x display is the 1920x1080 window it always was. + #[test] + fn a_1x_display_gives_the_override_as_asked() { + assert_eq!(plan(Drawable(1920, 1080), Density::UNIT), ((1920, 1080), (1920, 1080))); + } + + /// THE BUG: `PLXNATIVE_WIN=1920x1080` on a 2x display was a 1920x1080-POINT window, whose + /// drawable is 3840x2160 (`scale=2.000`) and which breached the render-set ceiling on every + /// frame of a Library scroll. The override is the DRAWABLE, so the window is half of it. + #[test] + fn the_override_is_the_drawable_on_a_2x_display() { + assert_eq!(plan(Drawable(1920, 1080), retina()), ((960, 540), (1920, 1080))); + } + + /// A 2x laptop (usable ~1512x945 points): 960x540 points, a 1:1 drawable. What it always got, + /// by the coincidence of div=2 meeting a 2x density; now by arithmetic. + #[test] + fn a_2x_laptop_fits_960x540_points_for_a_1_to_1_drawable() { + assert_eq!(plan(Fit(1512, 945), retina()), ((960, 540), (1920, 1080))); + } + + /// THE SECOND HOLE: a 5K/4K display "looking like 2560x1440" has usable ~2560x1415 points, so + /// the fit in points took div=1 -- a 1920x1080-point window, a 3840x2160 drawable -- with no + /// override at all. The fit is of the DRAWABLE, measured in the points it occupies. + #[test] + fn a_large_2x_display_gives_the_same_1_to_1_drawable_without_any_override() { + assert_eq!(plan(Fit(2560, 1415), retina()), ((960, 540), (1920, 1080))); + } + + /// Nothing changes on a 1x display: the divisor lands where it did, on every size. + #[test] + fn a_1x_display_fits_exactly_as_it_did() { + // a 1080p display's usable area under a menu bar and a Dock: div=2 + assert_eq!(plan(Fit(1920, 1050), Density::UNIT), ((960, 540), (960, 540))); + // a display big enough for the canvas itself (div=1) needs 5% headroom: 1920 / 0.95 = 2021.05 + assert_eq!(plan(Fit(2022, 1140), Density::UNIT), ((1920, 1080), (1920, 1080))); + assert_eq!(plan(Fit(2020, 1140), Density::UNIT), ((960, 540), (960, 540))); + // a small one: div=3 + assert_eq!(plan(Fit(100, 100), Density::UNIT), ((640, 360), (640, 360))); + } + + /// A density that is not a whole number (a 150% Windows display, a fractional Wayland scale): + /// the window is the drawable over the ratio, exactly where that is exact. + #[test] + fn a_fractional_density_is_divided_out_too() { + let d150 = Density::measured(1280, 1920); + assert_eq!(plan(Drawable(1920, 1080), d150), ((1280, 720), (1920, 1080))); + // 1280x720 points is over 95% of a 1280x800 display, so the half (960x540 px) wins + assert_eq!(plan(Fit(1280, 800), d150), ((640, 360), (960, 540))); + } + + /// Whatever the ratio, the window never gives a drawable LARGER than the one asked for: a + /// pixel short is a letterbox, a pixel over is a texture that is not the canvas. + #[test] + fn the_drawable_is_never_larger_than_asked_on_any_density() { + for (window_w, drawable_w) in [(1000, 1100), (1000, 1250), (1000, 1333), (1000, 1750), (1000, 2000), (1000, 2500), (1000, 3000), (1920, 2880), (1366, 2049)] { + let d = Density::measured(window_w, drawable_w); + for (w, h) in [(1920, 1080), (960, 540), (640, 360), (1280, 720)] { + let (_, got) = plan(Drawable(w, h), d); + assert!(got.0 <= w && got.1 <= h, "{window_w}->{drawable_w} asked {w}x{h}: {got:?}"); + // and no more than a point short of it, in either axis + let point = (drawable_w + window_w - 1) / window_w; + assert!(w - got.0 < point && h - got.1 < point, "{window_w}->{drawable_w} asked {w}x{h}: {got:?}"); + } + for (uw, uh) in [(1280, 720), (1512, 945), (1920, 1050), (2560, 1415), (3840, 2100)] { + let (_, got) = plan(Fit(uw, uh), d); + assert!(got.0 <= SCR_W && got.1 <= SCR_H, "{window_w}->{drawable_w} usable {uw}x{uh}: {got:?}"); + } + } + } + + /// A drawable that is not larger than the window is no HiDPI at all, however it got that way: + /// a window is never grown to cover for a measurement that failed. + #[test] + fn a_drawable_no_larger_than_the_window_is_unit_density() { + assert_eq!(Density::measured(1920, 1920), Density::UNIT); + assert_eq!(Density::measured(0, 1920), Density::UNIT); + assert_eq!(Density::measured(1920, 960), Density::UNIT); + } + + #[test] + fn the_override_parses_a_positive_size_and_nothing_else() { + assert_eq!(parse_window_override("1920x1080"), Some((1920, 1080))); + assert_eq!(parse_window_override(" 640X360 "), Some((640, 360))); + assert_eq!(parse_window_override("1920 x 1080"), Some((1920, 1080))); + for bad in ["", "1920", "x", "0x1080", "1920x0", "-1x5", "axb", "1920x1080x2"] { + assert_eq!(parse_window_override(bad), None, "{bad:?}"); + } + } +} + +/// The order `Window::open` does its work in, and the one thing this file must never grow. Each +/// test reads the source, because no host test can open a window; the needles are split with +/// `concat!` so this module's own text, which `include_str!` reads too, can never be what they match. +#[cfg(test)] +mod open_order_tests { + fn source() -> &'static str { + include_str!("window.rs") + } + + /// The body of `Window::open`, from its signature to the next method. + fn open_body() -> &'static str { + source() + .split_once(concat!("pub fn ", "open(")) + .expect("Window::open") + .1 + .split_once(concat!("pub fn ", "raw(")) + .expect("the method after open") + .0 + } + + /// `surface::probe` reads the drawable once, at boot, for good: the desktop window has to be + /// sized for the display's pixel density BEFORE it, or a 2x display keeps the 3840x2160 + /// drawable the 1x size gave it. + #[test] + fn the_desktop_window_is_fitted_to_the_density_before_the_drawable_is_probed() { + let body = open_body(); + let create = body.find(concat!("sys::SDL_CreateWindow", "(")).expect("creates the window"); + let fit = body.find(concat!("fit_window_to_", "density(win")).expect("fits the window to the density"); + let probe = body.find(concat!("surface::", "probe(win)")).expect("probes the drawable"); + assert!(create < fit && fit < probe, "create the window, fit it to the density, then probe the drawable"); + assert_eq!(body.matches(concat!("surface::", "probe(")).count(), 1, "one probe"); + } + + /// `open` frees a half-made window before it retries (a leaked one would keep the display), and + /// does it inside the creation loop, ahead of the probe. + #[test] + fn open_destroys_a_half_made_window_before_the_retry() { + let body = open_body(); + let create = body.find(concat!("sys::SDL_CreateWindow", "(")).expect("creates the window"); + let context = body.find(concat!("sys::SDL_GL_CreateContext", "(")).expect("creates the context"); + let destroy = body.find(concat!("sys::SDL_DestroyWindow", "(win)")).expect("destroys a half-made window"); + let retry = body.find(concat!("fallback.", "take()")).expect("takes the one fallback size"); + let probe = body.find(concat!("surface::", "probe(win)")).expect("probes the drawable"); + assert!(create < context && context < destroy && destroy < retry && retry < probe, + "create, context, destroy the half-made window, retry at the fallback, then probe"); + } + + /// **`Window` has no destructor.** The application is leaked at exit and a worker may still hold + /// the handle, so a window that destroyed itself (or nulled itself when the compositor took the + /// screen) would free a surface under a live reader. `init::quit` is the explicit end. + #[test] + fn window_has_no_destructor() { + assert!(!source().contains(concat!("impl Dr", "op for Window")), "a Window must never free itself"); + assert!(!source().contains(concat!("fn dr", "op(&mut self)")), "no destructor of any shape"); + } +} diff --git a/rust-modules/src/app/boot.rs b/rust-modules/src/app/boot.rs index d8436dd07b..a4da245509 100644 --- a/rust-modules/src/app/boot.rs +++ b/rust-modules/src/app/boot.rs @@ -1,281 +1,11 @@ -//! Boot-time helpers of the app core: the desktop window size, the panic logger, the replay -//! budget, the direct-server trigger, the cursor and the loop-rate tick. Moved out of `app.rs` -//! verbatim in phase 1a of the UI restructure (a pure move; `pub(crate)` widening only). +//! Boot-time helpers of the app core: the panic logger, the window a stored setting asks for, the +//! replay budget, the direct-server trigger and the loop-rate tick. Moved out of `app.rs` +//! verbatim in phase 1a of the UI restructure (a pure move; `pub(crate)` widening only). The SDL +//! shell's own steps (the window, the GL context, the display's density) moved on to +//! `plx_shell_sdl`, and the LG SDL's two boot hooks to `system`. use super::*; -use super::platform::Platform; - -/// What a DESKTOP window is asked to be, before the display's pixel density is known. -#[cfg(any(feature = "hostsim", test))] -#[derive(Clone, Copy)] -enum WindowAsk { - /// `PLXNATIVE_WIN=x`: a DRAWABLE of exactly this many pixels, on any display. - Drawable(c_int, c_int), - /// No override: the largest whole fraction of the canvas whose window fits this usable display - /// area (`SDL_GetDisplayUsableBounds`, in points). - Fit(c_int, c_int), -} - -/// How many drawable pixels a window point is worth on this display, as the integer pair SDL -/// reported for a window that exists: `window_w` points wide, `drawable_w` pixels wide. -/// -/// Integers, never a float multiplied back: 960 points of a 2x window must come out as exactly -/// 1920 pixels, and a ratio that is not a whole number (a 150% Windows display) must round the -/// same way on the way out as on the way in. -#[cfg(any(feature = "hostsim", test))] -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct Density { - window_w: c_int, - drawable_w: c_int, -} - -#[cfg(any(feature = "hostsim", test))] -impl Density { - /// One pixel per point: every 1x display, and what is assumed until a window has been measured. - const UNIT: Density = Density { window_w: 1, drawable_w: 1 }; - - /// The measured pair. A drawable that is not larger than the window (a 1x display) is - /// [`Density::UNIT`]: a drawable never has fewer pixels than points, and a window is never - /// grown to make up for one that seems to. - fn measured(window_w: c_int, drawable_w: c_int) -> Density { - if window_w <= 0 || drawable_w <= window_w { - Density::UNIT - } else { - Density { window_w, drawable_w } - } - } - - /// The window size, in points, whose drawable is `px` pixels: the nearest whole number of - /// points, and one fewer if rounding up would make the drawable LARGER than asked (never - /// larger than the canvas is the contract; a pixel short is a letterbox, a pixel over is not). - fn points(self, px: c_int) -> c_int { - let (w, d) = (i64::from(self.window_w), i64::from(self.drawable_w)); - let pt = ((i64::from(px) * w + d / 2) / d).max(1) as c_int; - if pt > 1 && self.pixels(pt) > px { - pt - 1 - } else { - pt - } - } - - /// The drawable, in pixels, of a window `pt` points wide. - fn pixels(self, pt: c_int) -> c_int { - let (w, d) = (i64::from(self.window_w), i64::from(self.drawable_w)); - ((i64::from(pt) * d + w / 2) / w) as c_int - } -} - -/// `PLXNATIVE_WIN`'s value: `x`, both positive. Anything else is no override. -#[cfg(any(feature = "hostsim", test))] -fn parse_window_override(v: &str) -> Option<(c_int, c_int)> { - let (w, h) = v.split_once(['x', 'X'])?; - match (w.trim().parse::(), h.trim().parse::()) { - (Ok(w), Ok(h)) if w > 0 && h > 0 => Some((w, h)), - _ => None, - } -} - -/// The window a DESKTOP should open at, in points, for a display of this pixel `density`: the -/// pure arithmetic of the size, so the Retina cases are testable without a Retina display. -/// -/// **The drawable is what is sized; the window follows from it.** The UI is authored at a 1920x1080 -/// canvas and every glyph, icon mask and poster is rasterized for 1:1 texels against it -/// (`gfx::snap`, the crispness contract in `theme.rs`), so a drawable LARGER than the canvas is -/// not a sharper picture: it is the same atlas stretched, with every drawable-sized buffer (the -/// page snapshot, the glass sources) four times the television's, which is how a 2x display once -/// breached the render-set ceiling on every frame (`ui/src/frame/render_set.rs`). -/// -/// * `Drawable` is that drawable, exactly. The fit below is chosen for a HUMAN looking at a -/// window, and a screenshot is not that: on a 1x display its divisor lands on 2 and every shot -/// comes back 960x540, half the canvas the UI is authored at, so a shot taken to JUDGE the -/// interface asks for full size (`make sim-shot SIM_W=1920 SIM_H=1080`). Off-screen edges are -/// fine for a headless grab: the drawable is the window's own framebuffer. -/// * `Fit` is **an exact divisor, never a best fit**: the largest of 1/1, 1/2 and 1/3 of the canvas -/// whose window, in points, fits the usable area. `surface::scale` will letterbox any drawable it -/// is given, so an arbitrary size would *work*, but a fractional scale resamples all of the above. -/// The bounds are in points, so the window is `canvas / div / density` of them. -/// -/// The television asks for the canvas itself (1:1) unless the owner picked a smaller Interface -/// resolution in Settings on webOS 1-3 (`requested_drawable`), in which case the compositor fills the panel. -/// A Mac is the case the `surface` doc was written against — 1920x1080 exceeds the usable area of -/// every laptop display Apple ships, so asking for it flatly would put the title bar above the -/// screen and the bottom of the interface under the Dock. -#[cfg(any(feature = "hostsim", test))] -fn plan_desktop_window(ask: WindowAsk, density: Density) -> (c_int, c_int) { - let points = |(w, h): (c_int, c_int)| (density.points(w), density.points(h)); - match ask { - WindowAsk::Drawable(w, h) => points((w, h)), - WindowAsk::Fit(uw, uh) => { - // A little headroom under the usable bounds: a window flush against them reads as a - // fullscreen that went wrong rather than as a deliberate size. - let (max_w, max_h) = ((uw as f32 * 0.95) as c_int, (uh as f32 * 0.95) as c_int); - let fits = |div| { - let (w, h) = points((SCR_W / div, SCR_H / div)); - w <= max_w && h <= max_h - }; - let div = (1..3).find(|&div| fits(div)).unwrap_or(3); - points((SCR_W / div, SCR_H / div)) - } - } -} - -/// `SDL_WINDOWPOS_CENTERED` on display 0. -#[cfg(feature = "hostsim")] -const WINDOWPOS_CENTERED: c_int = 0x2FFF_0000u32 as c_int; - -/// What this process is asked for: `PLXNATIVE_WIN` if it holds a size, else the fit to the display, -/// or the canvas itself if SDL cannot say how big the display is. -#[cfg(feature = "hostsim")] -fn desktop_window_ask() -> WindowAsk { - if let Some((w, h)) = std::env::var_os("PLXNATIVE_WIN").and_then(|v| parse_window_override(&v.to_string_lossy())) { - return WindowAsk::Drawable(w, h); - } - let mut r = [0 as c_int; 4]; // SDL_Rect: x, y, w, h - let ok = unsafe { SDL_GetDisplayUsableBounds(0, r.as_mut_ptr()) } == 0 && r[2] > 0 && r[3] > 0; - if ok { - WindowAsk::Fit(r[2], r[3]) - } else { - WindowAsk::Drawable(SCR_W, SCR_H) - } -} - -/// Size the just-created desktop `win` for the pixel density of the display it opened on. -/// -/// `SDL_GetDisplayDPI` is unreliable on macOS, so the density is MEASURED instead: the window was -/// opened at the 1x answer of [`plan_desktop_window`], and `SDL_GL_GetDrawableSize` over -/// `SDL_GetWindowSize` says how many pixels that bought per point. On a 1x display nothing happens. -/// On a 2x display the window is resized (and put back in the middle of the display, since it was -/// centred at the old size) to the points that give the drawable that was asked for: -/// `PLXNATIVE_WIN=1920x1080` is a 960x540-point window, not a 1920x1080-point one with a 3840x2160 -/// drawable. Called before `surface::probe`, which reads the drawable once and for good. -#[cfg(feature = "hostsim")] -unsafe fn fit_window_to_density(win: *mut c_void, ask: WindowAsk) { - let ((ww, wh), (dw, dh)) = plx_base::surface::window_and_drawable_size(win); - let density = Density::measured(ww, dw); - if density == Density::UNIT { - return; - } - let (pw, ph) = plan_desktop_window(ask, density); - if (pw, ph) == (ww, wh) { - return; - } - SDL_SetWindowSize(win, pw, ph); - SDL_SetWindowPosition(win, WINDOWPOS_CENTERED, WINDOWPOS_CENTERED); - let ((nw, nh), (gw, gh)) = plx_base::surface::window_and_drawable_size(win); - log(&format!( - "surface: {:.3} pixels per point (a {ww}x{wh} point window read back a {dw}x{dh} drawable); \ - resized to {pw}x{ph} points, which now reads {nw}x{nh} points / {gw}x{gh} drawable", - f64::from(dw) / f64::from(ww) - )); -} - -#[cfg(test)] -mod desktop_window_tests { - use super::WindowAsk::{Drawable, Fit}; - use super::{parse_window_override, plan_desktop_window, Density, WindowAsk, SCR_H, SCR_W}; - - /// A window of 1920 points whose drawable reads back 3840 pixels: macOS Retina, the case this - /// module exists for. (macOS always reports a whole backing factor, even in a "scaled" mode.) - fn retina() -> Density { - Density::measured(1920, 3840) - } - - /// The window the planner opens, in points, and the drawable that window gives. - fn plan(ask: WindowAsk, density: Density) -> ((i32, i32), (i32, i32)) { - let points = plan_desktop_window(ask, density); - (points, (density.pixels(points.0), density.pixels(points.1))) - } - - /// `PLXNATIVE_WIN=1920x1080` on a 1x display is the 1920x1080 window it always was. - #[test] - fn a_1x_display_gives_the_override_as_asked() { - assert_eq!(plan(Drawable(1920, 1080), Density::UNIT), ((1920, 1080), (1920, 1080))); - } - - /// THE BUG: `PLXNATIVE_WIN=1920x1080` on a 2x display was a 1920x1080-POINT window, whose - /// drawable is 3840x2160 (`scale=2.000`) and which breached the render-set ceiling on every - /// frame of a Library scroll. The override is the DRAWABLE, so the window is half of it. - #[test] - fn the_override_is_the_drawable_on_a_2x_display() { - assert_eq!(plan(Drawable(1920, 1080), retina()), ((960, 540), (1920, 1080))); - } - - /// A 2x laptop (usable ~1512x945 points): 960x540 points, a 1:1 drawable. What it always got, - /// by the coincidence of div=2 meeting a 2x density; now by arithmetic. - #[test] - fn a_2x_laptop_fits_960x540_points_for_a_1_to_1_drawable() { - assert_eq!(plan(Fit(1512, 945), retina()), ((960, 540), (1920, 1080))); - } - - /// THE SECOND HOLE: a 5K/4K display "looking like 2560x1440" has usable ~2560x1415 points, so - /// the fit in points took div=1 -- a 1920x1080-point window, a 3840x2160 drawable -- with no - /// override at all. The fit is of the DRAWABLE, measured in the points it occupies. - #[test] - fn a_large_2x_display_gives_the_same_1_to_1_drawable_without_any_override() { - assert_eq!(plan(Fit(2560, 1415), retina()), ((960, 540), (1920, 1080))); - } - - /// Nothing changes on a 1x display: the divisor lands where it did, on every size. - #[test] - fn a_1x_display_fits_exactly_as_it_did() { - // a 1080p display's usable area under a menu bar and a Dock: div=2 - assert_eq!(plan(Fit(1920, 1050), Density::UNIT), ((960, 540), (960, 540))); - // a display big enough for the canvas itself (div=1) needs 5% headroom: 1920 / 0.95 = 2021.05 - assert_eq!(plan(Fit(2022, 1140), Density::UNIT), ((1920, 1080), (1920, 1080))); - assert_eq!(plan(Fit(2020, 1140), Density::UNIT), ((960, 540), (960, 540))); - // a small one: div=3 - assert_eq!(plan(Fit(100, 100), Density::UNIT), ((640, 360), (640, 360))); - } - - /// A density that is not a whole number (a 150% Windows display, a fractional Wayland scale): - /// the window is the drawable over the ratio, exactly where that is exact. - #[test] - fn a_fractional_density_is_divided_out_too() { - let d150 = Density::measured(1280, 1920); - assert_eq!(plan(Drawable(1920, 1080), d150), ((1280, 720), (1920, 1080))); - // 1280x720 points is over 95% of a 1280x800 display, so the half (960x540 px) wins - assert_eq!(plan(Fit(1280, 800), d150), ((640, 360), (960, 540))); - } - - /// Whatever the ratio, the window never gives a drawable LARGER than the one asked for: a - /// pixel short is a letterbox, a pixel over is a texture that is not the canvas. - #[test] - fn the_drawable_is_never_larger_than_asked_on_any_density() { - for (window_w, drawable_w) in [(1000, 1100), (1000, 1250), (1000, 1333), (1000, 1750), (1000, 2000), (1000, 2500), (1000, 3000), (1920, 2880), (1366, 2049)] { - let d = Density::measured(window_w, drawable_w); - for (w, h) in [(1920, 1080), (960, 540), (640, 360), (1280, 720)] { - let (_, got) = plan(Drawable(w, h), d); - assert!(got.0 <= w && got.1 <= h, "{window_w}->{drawable_w} asked {w}x{h}: {got:?}"); - // and no more than a point short of it, in either axis - let point = (drawable_w + window_w - 1) / window_w; - assert!(w - got.0 < point && h - got.1 < point, "{window_w}->{drawable_w} asked {w}x{h}: {got:?}"); - } - for (uw, uh) in [(1280, 720), (1512, 945), (1920, 1050), (2560, 1415), (3840, 2100)] { - let (_, got) = plan(Fit(uw, uh), d); - assert!(got.0 <= SCR_W && got.1 <= SCR_H, "{window_w}->{drawable_w} usable {uw}x{uh}: {got:?}"); - } - } - } - - /// A drawable that is not larger than the window is no HiDPI at all, however it got that way: - /// a window is never grown to cover for a measurement that failed. - #[test] - fn a_drawable_no_larger_than_the_window_is_unit_density() { - assert_eq!(Density::measured(1920, 1920), Density::UNIT); - assert_eq!(Density::measured(0, 1920), Density::UNIT); - assert_eq!(Density::measured(1920, 960), Density::UNIT); - } - - #[test] - fn the_override_parses_a_positive_size_and_nothing_else() { - assert_eq!(parse_window_override("1920x1080"), Some((1920, 1080))); - assert_eq!(parse_window_override(" 640X360 "), Some((640, 360))); - assert_eq!(parse_window_override("1920 x 1080"), Some((1920, 1080))); - for bad in ["", "1920", "x", "0x1080", "1920x0", "-1x5", "axb", "1920x1080x2"] { - assert_eq!(parse_window_override(bad), None, "{bad:?}"); - } - } -} +use super::platform::{OpenAsk, Placement, Platform}; /// Log every Rust panic (message + source location + thread) to the event log AND the /// persistent crash log BEFORE it unwinds. A panic that crosses an extern "C" boundary @@ -441,27 +171,6 @@ pub(crate) fn install_plex_seams() { plx_plex::plex::session::install_account_clear_cleanup(plx_telemetry::telemetry::cleanup_after_account_clear); } -#[cfg(test)] -mod relaunch_tap_tests { - use super::slot_holds; - - #[test] - fn relaunch_slot_must_hold_libhelpers() { - assert!(slot_holds(0x1000, Some(0x1000)), "the slot holds libhelpers' function"); - assert!(!slot_holds(0x1000, Some(0x1001)), "a different value, even by the Thumb bit"); - assert!(!slot_holds(0x1000, None), "libhelpers is not mapped or lacks the symbol"); - assert!(!slot_holds(0, None)); - } - - #[test] - fn the_slot_must_be_word_aligned() { - use super::slot_aligned; - let word = core::mem::align_of::(); - assert!(slot_aligned(0x1000) && slot_aligned(word)); - assert!(!slot_aligned(0x1000 + 1) && !slot_aligned(word + word / 2)); - } -} - #[cfg(test)] mod seam_order_tests { /// `plx_plex` reports the version it is handed (`plex::identity::set_version`) and, in a @@ -623,25 +332,11 @@ mod seam_order_tests { assert!(user_agent < init, "set_user_agent must come before net::global_init"); } - /// SDL reads `SDL_WEBOS_CURSOR_SLEEP_TIME` in `SDL_Init`, so the hint set after it does nothing. - #[test] - fn the_cursor_sleep_hint_is_set_before_sdl_init() { - // Split with `concat!` for the reason the test above gives. - let source = include_str!("boot.rs"); - let body = source - .split_once(concat!("pub(crate) unsafe fn ", "construct(")) - .expect("construct") - .1; - let hint = body - .find(concat!("webos3_cursor_", "sleep_hint()")) - .expect("construct must set the cursor sleep hint"); - let init = body.find(concat!("SDL_Init(", "SDL_INIT_VIDEO)")).expect("construct's SDL_Init"); - assert!(hint < init, "the cursor sleep hint must come before SDL_Init"); - } - /// The Interface resolution is read from the stored session, so the session has to be read - /// BEFORE `SDL_CreateWindow` (the one place the window size is applied) and the window request - /// has to come from it. Reads the source for the reason the tests above give. + /// BEFORE the window is created (`Shell::open`, the one place the window size is applied) and the + /// window request has to come from it. SDL itself comes up before the session is read, as it always + /// has (`plx_shell_sdl::init` pins the order of its own steps). Reads the source for the reason the + /// tests above give. #[test] fn the_stored_session_is_read_before_the_window_is_created() { let source = include_str!("boot.rs"); @@ -655,8 +350,10 @@ mod seam_order_tests { let request = body .find(concat!("requested_drawable(", "&session)")) .expect("the window request is derived from the session"); - let window = body.find(concat!("SDL_CreateWindow(", "title")).expect("construct creates the window"); - assert!(load < request && request < window, "session read, then request, then SDL_CreateWindow"); + let window = body.find(concat!("shell.", "open(")).expect("construct opens the window"); + assert!(load < request && request < window, "session read, then request, then Shell::open"); + let init = body.find(concat!("shell.", "init(")).expect("construct brings the platform's SDL up"); + assert!(init < load, "SDL comes up before the session is read, the order boot has always had"); } /// Automatic is the native canvas on every set and asks for no smaller window. The other @@ -697,30 +394,18 @@ mod seam_order_tests { assert_eq!(super::window_fallback((super::SCR_W, super::SCR_H)), None, "the native canvas has no fallback"); } - /// `surface::probe` reads the drawable once, at boot, for good: the desktop window has to be - /// sized for the display's pixel density BEFORE it, or a 2x display keeps the 3840x2160 - /// drawable the 1x size gave it. Reads the source for the reason the tests above give. - #[test] - fn the_desktop_window_is_fitted_to_the_density_before_the_drawable_is_probed() { - let source = include_str!("boot.rs"); - let body = source.split_once(concat!("pub(crate) unsafe fn ", "construct(")).expect("construct").1; - let create = body.find(concat!("SDL_CreateWindow(", "title")).expect("creates the window"); - let fit = body.find(concat!("fit_window_to_", "density(win")).expect("fits the window to the density"); - let probe = body.find(concat!("surface::", "probe(win)")).expect("probes the drawable"); - assert!(create < fit && fit < probe, "create the window, fit it to the density, then probe the drawable"); - } - - /// `construct` frees a half-made window before it retries (a leaked one would keep the display). + /// The smaller-window retry is armed before the first window is asked for, from the size that + /// request carries: `construct` evaluates `window_fallback(` as part of the placement it hands + /// `Shell::open`. The retry loop itself, the destroy of a half-made window before it, and the + /// density fit before the drawable probe are the shell crate's (`plx_shell_sdl::Window::open`, + /// which pins their order). Reads the source for the reason the tests above give. #[test] - fn construct_destroys_a_half_made_window_before_the_retry() { + fn the_smaller_window_fallback_is_armed_before_the_window_is_opened() { let source = include_str!("boot.rs"); let body = source.split_once(concat!("pub(crate) unsafe fn ", "construct(")).expect("construct").1; - let create = body.find(concat!("SDL_CreateWindow(", "title")).expect("creates the window"); - let destroy = body.find(concat!("SDL_DestroyWindow(", "win)")).expect("destroys a half-made window"); - let retry = body.find(concat!("window_fallback(", "(ww_req")).expect("asks for the fallback size"); - assert!(create < destroy && destroy < body[create..].find("probe(win)").map(|i| i + create).unwrap(), - "the half-made window is destroyed inside the creation loop, before `surface::probe`"); - assert!(retry < create, "the retry is armed before the first attempt"); + let retry = body.find(concat!("window_fallback(", "size)")).expect("asks for the fallback size"); + let open = body.find(concat!("shell.", "open(")).expect("opens the window"); + assert!(retry < open, "the retry is armed before the first attempt"); } } @@ -772,145 +457,6 @@ fn drawable_for_setting(major: u32, chosen: plx_plex::plex::session::UiResolutio if plx_os::tv::device::offers_ui_resolution(major) { chosen.size() } else { None } } - -/// **webOS 3.x: shorten LG's own idle hide from about five minutes to five seconds.** Without -/// LG's extension, LG's SDL hides its pointer by itself after `SDL_WEBOS_CURSOR_SLEEP_TIME` of -/// stillness, and its default is about five minutes (timed on a 3.9.3 set, issue #642), where -/// every other app on that television hides it within seconds. Measured on the same set: the value -/// is milliseconds, `5000` hides a still pointer after about five seconds, and a deliberate -/// movement brings it back. Set only where `SDL_webOSCursorVisibility` is absent, so webOS 4+ -/// keeps its SDL's own behaviour. Must run before `SDL_Init`, which reads the hint. -#[cfg(not(feature = "hostsim"))] -unsafe fn webos3_cursor_sleep_hint() { - if let Some(ms) = cursor_sleep_hint(self_sym("SDL_webOSCursorVisibility").is_some()) { - SDL_SetHint(c"SDL_WEBOS_CURSOR_SLEEP_TIME".as_ptr(), ms.as_ptr()); - log("cursor: SDL_WEBOS_CURSOR_SLEEP_TIME=5000 (no SDL_webOS* in this SDL)"); - } -} -#[cfg(feature = "hostsim")] -unsafe fn webos3_cursor_sleep_hint() {} - -/// The idle-hide time to ask SDL for, in milliseconds as a string; `None` where LG's extension is -/// present and its SDL keeps its own behaviour. -#[cfg(not(feature = "hostsim"))] -fn cursor_sleep_hint(has_lg_extension: bool) -> Option<&'static std::ffi::CStr> { - (!has_lg_extension).then_some(c"5000") -} - -/// A symbol of the running process (the system SDL), resolved at runtime; `None` if absent or NULL. -#[cfg(not(feature = "hostsim"))] -fn self_sym(name: &str) -> Option<*mut std::ffi::c_void> { - plx_base::dynlib::Handle::self_handle().sym(name).filter(|p| !p.is_null()) -} - -/// **A warm launch's parameters, read where LG's SDL reads its `registerApp` replies.** SAM sends a -/// relaunch's parameters only to the `registerApp` subscriber, which is LG's SDL; its handler -/// (`callback_RegistNativeApp`) raises the window and never reads `parameters`. It fetches every -/// reply's payload through `HELPER_HLunaServiceMessage`, an exported pointer slot that -/// `LoadWEBOSBASELibrary` fills from `libhelpers.so.2` inside `SDL_Init` and that the handler -/// reloads on every call. Wrapping that slot hands a relaunch payload to `tv::launch` and returns -/// it unchanged, so SDL still raises the window. No new Luna registration: SAM refuses the app's -/// own (`tv::launch`). The firmware inventories have the slot from webOS 7.4 on; where it is missing -/// or empty (webOS 4.x to 6.x), nothing changes and callers keep closing the app first. -/// The tap installs only when the slot holds the address `libhelpers.so.2` (already mapped, -/// `RTLD_NOLOAD`) exports as `HLunaServiceMessage` ([`slot_holds`]); any other value is left alone. -#[cfg(not(feature = "hostsim"))] -unsafe fn tap_relaunch_payloads() { - use std::sync::atomic::{AtomicUsize, Ordering}; - let Some(slot) = self_sym("HELPER_HLunaServiceMessage") else { - log("relaunch tap: no HELPER_HLunaServiceMessage in this SDL"); - return; - }; - // An atomic reference to a misaligned address is undefined behaviour: refuse a symbol that is - // not a word-aligned slot before forming it. - if !slot_aligned(slot as usize) { - log("relaunch tap: slot misaligned \u{2014} not installed"); - return; - } - // SDL's Luna thread may read the slot while it is replaced: store it atomically, after the - // function it forwards to is published. - let slot = &*(slot as *const AtomicUsize); - let wrapped = wrapped_message as *const () as usize; - let current = slot.load(Ordering::Acquire); - if current == 0 || current == wrapped { - log(if current == 0 { "relaunch tap: HELPER_HLunaServiceMessage is empty" } - else { "relaunch tap: already installed" }); - return; - } - // The slot is only ours to wrap while it holds libhelpers' own `HLunaServiceMessage`: another - // value (a different SDL build, a slot of some other type) would be called as a function - // pointer it is not. - let expected = plx_base::dynlib::Handle::open_loaded(&["libhelpers.so.2"]) - .and_then(|(h, _)| h.sym("HLunaServiceMessage")) - .filter(|p| !p.is_null()) - .map(|p| p as usize); - if !slot_holds(current, expected) { - log("relaunch tap: slot does not hold libhelpers' HLunaServiceMessage \u{2014} not installed"); - return; - } - REAL_MESSAGE.store(current, Ordering::Release); - MAIN_THREAD.store(libc::pthread_self() as usize, Ordering::Relaxed); - slot.store(wrapped, Ordering::Release); - log("relaunch tap: installed"); -} -#[cfg(feature = "hostsim")] -unsafe fn tap_relaunch_payloads() {} - -/// Does the SDL slot hold exactly the function `libhelpers.so.2` exports as `HLunaServiceMessage`? -/// The Thumb bit is compared as `dlsym` and the slot both carry it. `expected` is `None` when -/// libhelpers is not mapped or lacks the symbol, and then nothing holds. -#[cfg(any(test, not(feature = "hostsim")))] -fn slot_holds(current: usize, expected: Option) -> bool { - expected == Some(current) -} - -/// Is `addr` aligned for the `AtomicUsize` the slot is read and written as? -#[cfg(any(test, not(feature = "hostsim")))] -fn slot_aligned(addr: usize) -> bool { - addr % core::mem::align_of::() == 0 -} - -#[cfg(not(feature = "hostsim"))] -type LunaMessageFn = unsafe extern "C" fn(*mut std::ffi::c_void) -> *const std::ffi::c_char; -#[cfg(not(feature = "hostsim"))] -static REAL_MESSAGE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -#[cfg(not(feature = "hostsim"))] -static MAIN_THREAD: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - -/// SDL's payload read, passed through. Every Luna reply SDL subscribed to comes through here, so -/// anything that is not a relaunch costs one substring scan and nothing else. -#[cfg(not(feature = "hostsim"))] -unsafe extern "C" fn wrapped_message(msg: *mut std::ffi::c_void) -> *const std::ffi::c_char { - let real = REAL_MESSAGE.load(std::sync::atomic::Ordering::Acquire); - if real == 0 { - return std::ptr::null(); - } - let real: LunaMessageFn = std::mem::transmute(real); - let p = real(msg); - if !p.is_null() { - let payload = std::ffi::CStr::from_ptr(p).to_string_lossy(); - if payload.contains("\"relaunch\"") { - let main = libc::pthread_self() as usize == MAIN_THREAD.load(std::sync::atomic::Ordering::Relaxed); - log(&format!("relaunch tap: {} bytes on the {} thread, parameters={}", - payload.len(), if main { "main" } else { "other" }, payload.contains("\"parameters\""))); - plx_os::tv::launch::offer(&payload); - } - } - p -} - -#[cfg(all(test, not(feature = "hostsim")))] -mod cursor_sleep_hint_tests { - use super::*; - - #[test] - fn the_idle_hide_hint_is_asked_for_only_where_lgs_extension_is_absent() { - assert_eq!(cursor_sleep_hint(false), Some(c"5000")); - assert_eq!(cursor_sleep_hint(true), None); - } -} - - /// Advance the once-per-second LOOP-RATE window: bump `iters_ct` and, when a full second has /// elapsed, recompute `loop_shown`, reset the window, and return `true` so the caller logs the /// heartbeat with its own route/overlay tag. Shared by the player and home/detail draw paths. @@ -1208,73 +754,13 @@ pub(crate) unsafe fn construct( initial.home.restore(&mt).map_err(|_| Exit::refused(1))?; plx_plex::plex::Client::restore_generation_seed(initial.primary_client).map_err(|_| Exit::refused(1))?; } - SDL_SetMainReady(); - // DEAD END, measured 2026-07-31 — do not re-try this. The obvious answer to "a parked TV - // should blank itself" is to stop inhibiting the platform screensaver here (and re-allow it - // per route, since webOS BACKGROUNDS the app to run one and `0x103` suspends the - // buffer-feed, so it could never be on during playback). It does not work, for a reason - // upstream of this app: the TV's SDL 2.0.4 fork carries the - // `SDL_VIDEO_ALLOW_SCREENSAVER` hint STRING but implements no wayland idle-inhibit - // (`strings libSDL2-2.0.so.0` finds no `idle_inhibit`/`suspend_screensaver` symbol), so - // this call and `SDL_EnableScreenSaver` are both no-ops. Soaked 34 min on Home with the - // TV's own `screenSaverEnabled: on`: no screensaver, no `LIFECYCLE: background`, CPU flat, - // our UI still at full brightness on the panel. webOS does not blank a foreground native - // app, and nothing reachable from SDL changes that. The line stays because it costs - // nothing and states the intent; it is not what keeps the screensaver away. - SDL_SetHint(c"SDL_VIDEO_ALLOW_SCREENSAVER".as_ptr(), c"0".as_ptr()); - webos3_cursor_sleep_hint(); - if SDL_Init(SDL_INIT_VIDEO) != 0 { - log("SDL_Init failed"); - return Err(Exit::refused(1)); - } - tap_relaunch_payloads(); - { - let d = SDL_GetCurrentVideoDriver(); - if !d.is_null() { - log(&format!( - "video driver: {}", - std::ffi::CStr::from_ptr(d).to_string_lossy() - )); - } - } - // The television has a real GLES2 driver (a shim over libmali). macOS has none at all — - // Apple ships desktop GL only, capped at 4.1 core — so asking for ES here fails context - // creation outright. 4.1 core is the closest thing that exists, and it is a superset for - // everything this renderer does: a real VBO (never client arrays) and RGBA/UNSIGNED_BYTE - // textures, both core-profile-legal. The shader sources are adapted at compile time by - // `gfx::glsl_preamble`, which reads the driver's GLSL version rather than assuming. - if cfg!(feature = "hostsim") { - SDL_GL_SetAttribute(A_CTX_PROFILE_MASK, CTX_PROFILE_CORE); - SDL_GL_SetAttribute(A_CTX_MAJOR, 4); - SDL_GL_SetAttribute(A_CTX_MINOR, 1); - } else { - SDL_GL_SetAttribute(A_CTX_PROFILE_MASK, CTX_PROFILE_ES); - SDL_GL_SetAttribute(A_CTX_MAJOR, 2); - SDL_GL_SetAttribute(A_CTX_MINOR, 0); - } - // full 32-bit RGBA so the video plane shows through - SDL_GL_SetAttribute(A_RED, 8); - SDL_GL_SetAttribute(A_GREEN, 8); - SDL_GL_SetAttribute(A_BLUE, 8); - SDL_GL_SetAttribute(A_ALPHA, 8); - SDL_GL_SetAttribute(A_BUFFER_SIZE, 32); - // ...and NO depth or stencil, which SDL would otherwise give us anyway: its defaults are - // 16 bits of depth and 0 of stencil, and asking for neither had simply never been written - // down. **This renderer has no use for either.** There is no `GL_DEPTH_TEST`, no - // `glDepthFunc`, no `glDepthMask` and no `glClear(GL_DEPTH_BUFFER_BIT)` anywhere in the - // crate — every screen is painter's-algorithm 2-D, drawn back to front — and the one - // scissor user (`gfx::clip_set`) is a scissor, not a stencil. - // - // On a TILER this is not merely 4 MB of address space. Midgard allocates the depth buffer - // per tile alongside colour and, unless the driver proves it dead, RESOLVES it to memory at - // end-of-frame: 1920x1080x2 bytes written per presented frame for a buffer nothing ever - // reads. `system.rs` logs what the config actually came back with — a request is not a - // grant, and the only honest confirmation is `FB bits: … depth=0`. - SDL_GL_SetAttribute(A_DEPTH, 0); - SDL_GL_SetAttribute(A_STENCIL, 0); + // SDL up: the screensaver hint, the platform's two steps around `SDL_Init`, the GL context request. + // The platform's (`Shell::init`; `plx_shell_sdl::init` is the one SDL implementation, and it pins the + // order inside it) and FIRST: before the stored session is read and before the window exists. + platform.shell.init(&mt)?; // **The stored session is read HERE, before the window.** The window size is a setting // (Settings > System > Interface resolution, install-wide: `Session::ui_resolution`), and - // `SDL_CreateWindow` below is the only moment it can be applied, so the record has to be read + // the window's creation (`Shell::open`) is the only moment it can be applied, so the record has to be read // first. `peek_settled` would not do: it only reads the cache, which the session owner fills // after boot, so its first call answers "not yet". The seams `load` consults (`install_plex_seams`) are installed by // `enter_application`, before `boot`. A replay or captured boot brings its own session. @@ -1283,21 +769,19 @@ pub(crate) unsafe fn construct( None => plx_plex::plex::session::load(), }; // The television is placed at 0,0 at exactly canvas size (unless a webOS 1-3 owner picked a smaller - // Interface resolution, `requested_drawable`) and takes the panel. A desktop - // window is centred (`SDL_WINDOWPOS_CENTERED`) at whatever fits — see `plan_desktop_window`. - // The density is not known until a window exists, so this is the 1x answer; `fit_window_to_density` - // below corrects it on a display where that was wrong. - #[cfg(feature = "hostsim")] - let desktop_ask = desktop_window_ask(); + // Interface resolution, `requested_drawable`) and takes the panel. A desktop window is centred at + // whatever fits the display: `Placement::Desktop`, which the shell plans and corrects for the + // display's pixel density once a window exists (`plx_shell_sdl::window`). + // **A stored size the set will not give must never brick launch.** If the window or its GL + // context is refused at a smaller size the owner chose, the shell frees whatever was made and + // retries ONCE at the native canvas (`fallback`); only a refused native window is fatal. On a + // desktop the request is the desktop's own size, not a setting, so there is no retry there. #[cfg(feature = "hostsim")] - let (wx, wy, ww_req, wh_req) = { - let (w, h) = plan_desktop_window(desktop_ask, Density::UNIT); - (WINDOWPOS_CENTERED, WINDOWPOS_CENTERED, w, h) - }; + let placement = Placement::Desktop; #[cfg(not(feature = "hostsim"))] - let (wx, wy, ww_req, wh_req) = { - let (w, h) = requested_drawable(&session).unwrap_or((SCR_W, SCR_H)); - (0, 0, w, h) + let placement = { + let size = requested_drawable(&session).unwrap_or((SCR_W, SCR_H)); + Placement::Panel { size, fallback: window_fallback(size) } }; // The title is furniture a television never draws (no window manager, no decoration) and // the first thing a desktop shows, so the two builds spell it differently: the device keeps @@ -1307,42 +791,18 @@ pub(crate) unsafe fn construct( #[cfg(not(feature = "hostsim"))] let title = c"plxnative"; // A frame dump's drawable is exactly the window's size in points: it is the one desktop window - // that does not ask for ALLOW_HIGHDPI (0x2000), so its window is the 1920x1080 points of the - // canonical Linux host on a Retina display too, and `fit_window_to_density` finds nothing to - // correct. (Absent from every shipping build.) + // that does not ask for ALLOW_HIGHDPI, so its window is the 1920x1080 points of the canonical + // Linux host on a Retina display too, and the shell's density fit finds nothing to correct. + // (Absent from every shipping build.) #[cfg(all(feature = "hostsim", feature = "devtriggers"))] - let window_flags = if crate::dev::framedump::requested() { SDL_WINDOW_FLAGS & !0x2000 } else { SDL_WINDOW_FLAGS }; + let high_dpi = !crate::dev::framedump::requested(); #[cfg(not(all(feature = "hostsim", feature = "devtriggers")))] - let window_flags = SDL_WINDOW_FLAGS; - // **A stored size the set will not give must never brick launch.** If the window or its GL - // context is refused at a smaller size the owner chose, free whatever was made and retry ONCE - // at the native canvas; only a refused native window is fatal. On a desktop the request is the - // desktop's own size, not a setting, so there is no retry there. - #[cfg(not(feature = "hostsim"))] - let mut fallback = window_fallback((ww_req, wh_req)); - #[cfg(feature = "hostsim")] - let mut fallback: Option<(c_int, c_int)> = None; - let (mut ww_try, mut wh_try) = (ww_req, wh_req); - let win = loop { - let win = SDL_CreateWindow(title.as_ptr(), wx, wy, ww_try, wh_try, window_flags); - if win.is_null() { - log(&format!("CreateWindow failed at {ww_try}x{wh_try}")); - } else { - let ctx = SDL_GL_CreateContext(win); - if !ctx.is_null() { - break win; - } - log(&format!("GL ctx failed at {ww_try}x{wh_try}")); - SDL_DestroyWindow(win); - } - let Some((w, h)) = fallback.take() else { return Err(Exit::refused(1)); }; - log(&format!("surface: retrying the window at the native {w}x{h}")); - (ww_try, wh_try) = (w, h); - }; - // Correct the size for the display's density now: `surface::probe` below reads the drawable once. - #[cfg(feature = "hostsim")] - fit_window_to_density(win, desktop_ask); - plx_base::surface::probe(win); + let high_dpi = true; + // The window and its GL context: created (with the retry above), corrected for the display's + // density, and its drawable probed (`surface::probe` reads it once, for good). The `Surface` it + // returns is the `App`'s for the rest of the process. + let surface = platform.shell.open(&mt, &OpenAsk { title, placement, high_dpi })?; + let win = surface.window(); // vsync on → the frame rate locks to the panel refresh. `/tmp/plxnative-novsync` uncaps it so // `fps=` reports the true GPU render rate. WSLg's X11/GLX swap accepts interval 1 without // blocking, so the software budget in `run` follows the same switch. @@ -1353,7 +813,7 @@ pub(crate) unsafe fn construct( #[cfg(not(all(feature = "hostsim", feature = "devtriggers")))] let dumping = false; let vsync_enabled = !dumping && (controlled || !crate::dev::scenarios::novsync_armed()); - SDL_GL_SetSwapInterval(if vsync_enabled { 1 } else { 0 }); + surface.set_swap_interval(if vsync_enabled { 1 } else { 0 }); #[cfg(all(feature = "hostsim", target_os = "linux"))] let wslg_frame_pacing = vsync_enabled && std::env::var_os("WSL_DISTRO_NAME").is_some() @@ -1393,12 +853,13 @@ pub(crate) unsafe fn construct( // …and the same handshake for the ROOT press: `tv::home::go_home`'s fallback leg minimizes // this window, and the window is created here, a long way from where BACK is decided. platform.shell.bind_window(win); - let wflags = SDL_GetWindowFlags(win); + let keyboard = plx_shell_sdl::text::keyboard_probe(win); log(&format!( - "keyboard: support={} active={} focus={} winflags=0x{wflags:x}", - SDL_HasScreenKeyboardSupport(), - SDL_IsTextInputActive(), - i32::from(wflags & SDL_WINDOW_INPUT_FOCUS != 0) + "keyboard: support={} active={} focus={} winflags=0x{:x}", + keyboard.support, + keyboard.active, + i32::from(keyboard.wflags & SDL_WINDOW_INPUT_FOCUS != 0), + keyboard.wflags )); platform.shell.grab_surface(win); @@ -2191,7 +1652,7 @@ pub(crate) unsafe fn construct( reread: Default::default(), ev, remote, - win, + surface, #[cfg(all(feature = "hostsim", target_os = "linux"))] wslg_frame_pacing, t0, diff --git a/rust-modules/src/app/deeplink.rs b/rust-modules/src/app/deeplink.rs index 6a1843bef9..d1810bf159 100644 --- a/rust-modules/src/app/deeplink.rs +++ b/rust-modules/src/app/deeplink.rs @@ -13,7 +13,7 @@ //! where Resume would. Anything else is `open`. //! - Unknown keys are ignored. No `plex` object at all is an ordinary launch. //! - A launch while the app runs carries the link too, where LG's SDL lets the app read relaunch -//! payloads (`app::boot::tap_relaunch_payloads`, webOS 7.4 on); the page then replaces wherever +//! payloads (`system::tap_relaunch_payloads`, webOS 7.4 on); the page then replaces wherever //! the app was. Elsewhere (webOS 4.x to 6.x) only a cold launch does, and a caller closes the app first //! (`com.webos.applicationManager/closeByAppId`), then launches. //! diff --git a/rust-modules/src/app/events.rs b/rust-modules/src/app/events.rs index 949ceec4cc..d6db179e44 100644 --- a/rust-modules/src/app/events.rs +++ b/rust-modules/src/app/events.rs @@ -1,6 +1,7 @@ -//! SDL event decoding and the remote-FIFO token synthesis — the raw-offset reads of LG's shifted -//! `SDL_KeyboardEvent`, the synthetic key/pointer/wheel events, and `dispatch_remote_token`. -//! Moved out of `app.rs` verbatim in phase 1a (a pure move; `pub(crate)` widening only). +//! What the loop reads of SDL's events, and the remote-FIFO token synthesis: the `HostEvent` a decoded +//! SDL event becomes, the `KeyPress` constructor, the token parser and `dispatch_remote_token`. The bytes +//! themselves (the raw-offset reads of LG's shifted `SDL_KeyboardEvent`, the synthetic key, pointer and +//! wheel events) are `plx_shell_sdl`'s, re-exported below. //! //! The one decode that yields a platform-neutral value is [`decode_host_event`]: SDL's quit, //! application-lifecycle, key, text, pointer and wheel events become a [`HostEvent`], which the loop @@ -23,99 +24,39 @@ pub(crate) fn text_inputs(text: &str, panel: bool, at: plx_machine::machine::Tic events } -#[inline] -pub(crate) fn rd_u32(ev: &[u8], off: usize) -> u32 { - u32::from_ne_bytes([ev[off], ev[off + 1], ev[off + 2], ev[off + 3]]) -} +// What SDL's bytes are, and how they are written back, is the stock-SDL shell's (`plx_shell_sdl`): the +// raw-offset readers and both layouts of the key, pointer, wheel and text events, the lifecycle codes +// the tape is written in, and the synthetic events pushed onto SDL's queue. The application keeps what +// needs its own vocabulary: the `HostEvent` the loop consumes, the `KeyPress` constructor, the desktop's +// key stand-in, and the token parser. Re-exported here so the `remote_synth_*` names every call site +// (the loop, the FIFO, the replay driver, the cursor-swap click) already uses stay what they are. +pub(crate) use plx_shell_sdl::event::{is_input_event, rd_u32, Decoded, Lifecycle, PointerEdge}; +pub(crate) use plx_shell_sdl::inject::{ + synth_key as remote_synth_key, synth_key_edge as remote_synth_key_edge, + synth_key_repeat as remote_synth_key_repeat, synth_lifecycle as remote_synth_lifecycle, + synth_pointer as remote_synth_pointer, synth_ptr as remote_synth_ptr, synth_wheel as remote_synth_wheel, +}; +// The byte writers are the loop tests' (they write the bytes a platform would deliver), and the two +// readers are the hostsim wheel test's (the stock layout's float). +#[cfg(all(test, feature = "hostsim"))] +pub(crate) use plx_shell_sdl::event::{rd_f32, rd_i32}; +#[cfg(test)] +pub(crate) use plx_shell_sdl::inject::{encode_key, encode_key_repeat, encode_pointer}; -/// A keyboard event's `(state, wcode, sym)`, decoded from the raw event bytes. -/// -/// **The two SDLs disagree about this struct, and nothing warns you.** LG's fork writes -/// `state` (u32) at +16, the webOS keycode at +20 and the SDL sym at +24. Stock SDL2 — -/// what the host simulator links — has `SDL_KeyboardEvent { type, timestamp, windowID, -/// state:u8@12, repeat:u8@13, pad, pad, keysym{ scancode:u32@16, sym:i32@20, … } }`, so -/// every field the app reads is at a different offset and there is no webOS keycode at all. -/// Reading the fork's offsets out of a stock event yields the window id as a keystate and -/// a scancode as a sym — plausible-looking garbage rather than a crash. -/// -/// `cfg!` rather than `#[cfg]` deliberately: both arms stay compiled on both platforms, so -/// the one nobody is currently building cannot rot. This is the single site that knows the -/// layout — `rd_u32`'s callers elsewhere read pointer events, whose offsets already agree. -/// -/// **The `wcode` this returns is LG's SCANCODE**, which is worth saying because the name suggests -/// otherwise. Every field measured off the dev set is the SDL scancode of the key beside it — -/// backspace 42, Clear 156, ◀/▶ 80/79, OK 40 — so the fork's shift puts an ordinary -/// `SDL_Keysym { scancode, sym }` at +20/+24 rather than inventing a webOS keycode namespace. That -/// is why the codes above SDL's own range (450 play, 482 back, 505 exit) carry no sym at all: they -/// are LG-private scancodes the keymap has no keycode for. `docs/remote-keys.md` has the account. +/// The wcode a key press is read as: the one its bytes carried, else the desktop's stand-in for it. /// -/// # The simulator's carrier moved, because the old one was silently DEAD -/// -/// A synthetic press from the remote FIFO has to get its wcode across `SDL_PushEvent`, and on the -/// host that queue is not SDL2's: macOS `libSDL2` is **sdl2-compat forwarding into SDL3**, so every -/// pushed event is converted out and back. Measured 2026-08-23 by dumping the polled bytes of a -/// press whose every spare field carried a distinct value: -/// -/// | field | offset | survives | -/// |------------------------------|--------|----------| -/// | `windowID` | +8 | yes | -/// | `padding2` / `padding3` | +14/15 | no | -/// | `keysym.scancode` | +16 | **no** — comes back 0 | -/// | `keysym.mod` | +24 | yes | -/// | `keysym.unused` | +28 | **no** — comes back 1 | -/// -/// It used to be `unused`, so **every wcode-ONLY token was dead**: `play`, `pause`, `stop`, `ff`, -/// `rew`, `playpause`, `exit`, `chup`, `chdown` all decoded as wcode 1 and did nothing at all, and -/// `tests/keytable.json` recorded three of them as `moved: false` — which reads as "that key does -/// nothing on that screen" and actually meant the press never arrived. An instrument silent by -/// construction: prove it can see the thing before reading its silence. -/// -/// `scancode` would have been the honest home (it is what a wcode IS) and it is the one field the -/// compat layer recomputes. So a synthetic press carries the value in `mod` and a MARKER in -/// `windowID` ([`SYNTH_WINDOW`]) — two fields, because the value alone cannot say whether it is -/// one: a real press puts its modifier bitmask in `mod`, so `mod != 0` means "shift is down" at -/// least as often as it means "injected". The marker restores the priority the `unused` field used -/// to express — **injected first, the desktop stand-in only as a fallback** — which is load-bearing -/// and not a preference: `host_wcode(8)` is BACK, while `remote_token_key`'s `backspace` token is -/// `(8, 42)`, so asking the stand-in first turns the panel's delete key into a navigation. -/// Clobbering `windowID` is safe here and nowhere else: this arm is `hostsim`-only, the simulator -/// has one window, and nothing in the event loop reads that field. +/// The shell reports `None` only for a stock-SDL press that carries no injected wcode (the television's +/// layout always has one), and the stand-in is the only way a physical Mac keyboard reaches a key the +/// remote has and a keyboard does not (space = PAUSE). **Injected first, the stand-in only as a +/// fallback** is load-bearing and not a preference: `host_wcode(8)` is BACK, while the `backspace` token +/// is `(8, 42)`, so asking the stand-in first turns the panel's delete key into a navigation +/// (`plx_shell_sdl::event::decode_key` has the measurement behind the carrier). It lives here and not in +/// the shell because `host_wcode` is a `ui` table the shell may not name. #[inline] -pub(crate) fn decode_key(ev: &[u8]) -> (u32, u32, u32) { - if cfg!(feature = "hostsim") { - let pressed = *ev.get(12).unwrap_or(&0) as u32; - let repeat = *ev.get(13).unwrap_or(&0) as u32; - let sym = rd_u32(ev, 20); - // Rebuild the fork's packed state byte-for-byte: low byte pressed(1)/released(0), - // bit 0x100 auto-repeat. Everything downstream tests exactly those two. - let state = pressed | if repeat != 0 { 0x100 } else { 0 }; - let injected = if rd_u32(ev, 8) == SYNTH_WINDOW { - u32::from(u16::from_ne_bytes([ev[24], ev[25]])) - } else { - 0 // a real desktop press: `mod` there is the modifier bitmask, not a wcode - }; - // The stand-in is the only way a physical Mac keyboard reaches a key the remote has and a - // keyboard does not (space = PAUSE), and it applies to real presses alone. - let wcode = if injected != 0 { - injected - } else { - host_wcode(sym) - }; - (state, wcode, sym) - } else { - (rd_u32(ev, 16), rd_u32(ev, 20), rd_u32(ev, 24)) - } +fn wcode_of(carried: Option, sym: u32) -> u32 { + carried.unwrap_or_else(|| host_wcode(sym)) } -/// The `windowID` a SYNTHETIC key event carries on the host, marking it as one — see [`decode_key`] -/// for why the wcode needs a marker beside it rather than standing on its own. Any value no real -/// window can have; SDL numbers windows from 1. -/// -/// Defined unconditionally, like both halves of [`decode_key`]: the arm that uses it is behind -/// `cfg!` rather than `#[cfg]`, precisely so the configuration nobody is currently building cannot -/// rot. -pub(crate) const SYNTH_WINDOW: u32 = 0x504c_584b; // "PLXK" - /// The Magic Remote button a desktop keyboard stands in for, or 0. /// /// Only the keys with NO sym equivalent need this. Navigation and OK/BACK already work on a @@ -133,13 +74,6 @@ pub(crate) fn host_wcode(sym: u32) -> u32 { } } -/// SDL's application events (`SDL_APP_*`), the four the loop acts on: the compositor taking the -/// screen (WILL and DID enter background) and giving it back (WILL and DID enter foreground). -const SDL_APP_WILLENTERBACKGROUND: u32 = 0x103; -const SDL_APP_DIDENTERBACKGROUND: u32 = 0x104; -const SDL_APP_WILLENTERFOREGROUND: u32 = 0x105; -const SDL_APP_DIDENTERFOREGROUND: u32 = 0x106; - /// What the platform tells the loop: a key press, a text commit, the pointer, the wheel, the window /// leaving or returning to the screen, and the host asking the application to end. App-private, like /// [`Shell`](super::platform::Shell): no platform reaches it by a type of its own until the @@ -167,9 +101,9 @@ pub(crate) enum HostEvent { /// One commit from the platform's text input (the television's own keyboard): the decoded /// string, possibly empty (SDL delivers a commit for the IME's own bookkeeping too, and the /// loop ignores an empty one as it always has). The platform's own text layout is decoded - /// before it gets here (`textinput::decode`, the one place that knows the offsets). + /// before it gets here (`plx_shell_sdl::text::decode`, the one place that knows the offsets). Text(String), - /// One pointer event, at authored 1920x1080 coordinates ([`ptr_xy`]: the window's pixels + /// One pointer event, at authored 1920x1080 coordinates (`plx_shell_sdl::event::ptr_xy`: the window's pixels /// converted exactly once, the identity while the drawable is the canvas). `edge` is what it did: /// moved, went down or came up. It is the event TYPE alone, for any button, as the loop has always /// read it. The plan's `buttons` and `shown` members are not carried, because today's SDL events @@ -180,21 +114,10 @@ pub(crate) enum HostEvent { /// One tick of the wheel: its vertical count in the signed whole ticks the loop reads (a /// fractional trackpad tick that rounds to nothing is `0`, which the loop records and then /// ignores, as it always has). Decoded from whichever offset this host carries it at - /// ([`decode_wheel_dy`]). + /// (`plx_shell_sdl::event::decode_wheel_dy`). Wheel { dy: i32 }, } -/// What a [`HostEvent::Pointer`] did. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum PointerEdge { - /// `SDL_MOUSEMOTION`. - Move, - /// `SDL_MOUSEBUTTONDOWN`, any button. - Down, - /// `SDL_MOUSEBUTTONUP`, any button. - Up, -} - impl HostEvent { /// Is this the viewer's INPUT (a key, text, pointer or wheel event), as opposed to the window's /// (a lifecycle edge, quit)? The loop's activity bookkeeping asks it: input keeps a release-health @@ -264,11 +187,12 @@ impl KeyPress { Some(KeyPress { action, edge, raw }) } - /// The press an SDL key event is: the raw pair as `decode_key` reads it, its action, and the - /// edge the fork's packed `state` names (low byte 1 is down, bit 0x100 is the auto-repeat; the - /// same reading `bridge::key_input` makes of it). A key-up never carries the repeat bit here. - pub(crate) fn from_sdl(ev: &[u8]) -> Option { - let (state, wcode, sym) = decode_key(ev); + /// The press a decoded SDL key edge is: the raw pair (the carried wcode, else the desktop stand-in, + /// [`wcode_of`]), its action, and the edge the fork's packed `state` names (low byte 1 is down, bit + /// 0x100 is the auto-repeat; the same reading `bridge::key_input` makes of it). A key-up never + /// carries the repeat bit here. + fn from_decoded(state: u32, wcode: Option, sym: u32) -> Option { + let wcode = wcode_of(wcode, sym); let edge = if (state & 0xff) != 1 { Edge::Up } else if state & 0x100 != 0 { @@ -306,137 +230,27 @@ impl KeyPress { } } -/// One edge of the window's visibility. Both background edges park the tree (the second finds -/// nothing left to park); WILL foreground un-parks the tree, and DID foreground alone reacquires the -/// window and restores playback. A platform that sends only DID background is enough on its own -/// (`WindowActivity`). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Lifecycle { - WillBackground, - DidBackground, - WillForeground, - DidForeground, -} - -impl Lifecycle { - /// The SDL event type this edge arrives as, and so the code the SDL-coded readers take: the - /// recorder's tape (`enc_lifecycle`, whose recorded codes ARE the tape format), the window gate - /// and telemetry's crash steps and session. The inverse of [`decode_host_event`]'s table; - /// `host_event_tests` pins the four pairs. - pub(crate) const fn sdl_code(self) -> u32 { - match self { - Lifecycle::WillBackground => SDL_APP_WILLENTERBACKGROUND, - Lifecycle::DidBackground => SDL_APP_DIDENTERBACKGROUND, - Lifecycle::WillForeground => SDL_APP_WILLENTERFOREGROUND, - Lifecycle::DidForeground => SDL_APP_DIDENTERFOREGROUND, - } - } -} - -/// An SDL event decoded into a [`HostEvent`]: `SDL_QUIT`, the four application lifecycle types, a -/// key edge (`SDL_KEYDOWN`/`SDL_KEYUP`, through [`decode_key`], so both layouts), a text commit -/// (`SDL_TEXTINPUT`, through `textinput::decode`), a pointer event (motion, button down and button up, -/// through [`ptr_xy`]) and a wheel tick (through [`decode_wheel_dy`]). `None` for everything else, -/// which the loop reads raw (the IME's pre-edit, and the SDL events nothing acts on). Beside -/// [`decode_key`], the other place that knows SDL's event bytes. +/// An SDL event decoded into a [`HostEvent`]: the shell's decode of the bytes (both layouts of every +/// event, `plx_shell_sdl::event::decode`) mapped onto the vocabulary the loop reads. `None` for +/// everything the shell leaves raw (the IME's pre-edit, and the SDL events nothing acts on), which the +/// loop reads raw. #[inline] pub(crate) fn decode_host_event(ev: &[u8]) -> Option { - Some(match rd_u32(ev, 0) { - SDL_QUIT => HostEvent::Quit, - SDL_KEYDOWN | SDL_KEYUP => HostEvent::Key(KeyPress::from_sdl(ev)?), - SDL_TEXTINPUT => HostEvent::Text(crate::textinput::decode(ev)), - SDL_MOUSEMOTION => pointer_event(ev, PointerEdge::Move), - SDL_MOUSEBUTTONDOWN => pointer_event(ev, PointerEdge::Down), - SDL_MOUSEBUTTONUP => pointer_event(ev, PointerEdge::Up), - SDL_MOUSEWHEEL => HostEvent::Wheel { dy: decode_wheel_dy(ev) }, - SDL_APP_WILLENTERBACKGROUND => HostEvent::Lifecycle(Lifecycle::WillBackground), - SDL_APP_DIDENTERBACKGROUND => HostEvent::Lifecycle(Lifecycle::DidBackground), - SDL_APP_WILLENTERFOREGROUND => HostEvent::Lifecycle(Lifecycle::WillForeground), - SDL_APP_DIDENTERFOREGROUND => HostEvent::Lifecycle(Lifecycle::DidForeground), - _ => return None, - }) -} - -/// A pointer event's position and edge. The coordinates are read at +20 and +24 in both layouts (the -/// pointer offsets agree, [`ptr_xy`]), and the button at +16 and its state at +17 are not read: the -/// edge is the event type, for any button, as the loop has always taken it. -#[inline] -fn pointer_event(ev: &[u8], edge: PointerEdge) -> HostEvent { - let (x, y) = ptr_xy(ev); - HostEvent::Pointer { x, y, edge } -} - -/// A wheel event's vertical tick count, in the signed whole ticks the loop reads. -/// -/// **The host reads a DIFFERENT offset, and this one is not the LG-fork -/// shift `decode_key` documents — it is macOS `libSDL2` again being -/// sdl2-compat forwarding into SDL3.** `SDL_MouseWheelEvent` on real SDL2 -/// (what the television runs) carries a plain `Sint32 y` at +20, which is -/// what production code always read. Measured 2026-09-02 by dumping the -/// polled bytes of an injected -40 tick on this host: `+20` came back 0, and -/// -40.0 arrived instead as the FLOAT `preciseY` field at `+32` — SDL2's own -/// struct gained that field in 2.0.18 for fractional trackpad scroll, and -/// sdl2-compat's round trip apparently only forwards it, leaving the legacy -/// integer field zeroed for both a genuine trackpad tick and anything -/// `SDL_PushEvent`d in this shape (item 13's `wheel:` FIFO token hit -/// this the first time anything synthesized a wheel event at all — nothing -/// needed one before). `cfg!`, not `#[cfg]`, so both arms keep compiling. -#[inline] -fn decode_wheel_dy(ev: &[u8]) -> i32 { - if cfg!(feature = "hostsim") { - rd_f32(ev, 32).round() as i32 - } else { - rd_i32(ev, 20) - } -} - -/// The bytes a synthetic key event needs, in whichever layout [`decode_key`] reads. -/// -/// **The inverse of `decode_key`, and the pair is only correct together.** They already shipped -/// disagreeing once: the simulator accepted every FIFO token and never moved, because this end -/// wrote LG's fork layout while the reading end had been taught stock SDL2's. Nothing in the -/// compiler couples them, so `key_bytes_round_trip` below is what does. -/// -/// Pure, and separate from the `SDL_PushEvent` that consumes it, precisely so that test can run on -/// the host — `make check` links no SDL. -pub(crate) fn encode_key(sym: c_uint, wcode: c_uint, down: bool) -> [u8; 128] { - let mut ev = [0u8; 128]; - ev[0..4].copy_from_slice(&if down { SDL_KEYDOWN } else { SDL_KEYUP }.to_ne_bytes()); - if cfg!(feature = "hostsim") { - ev[12] = u8::from(down); // state - ev[13] = 0; // repeat - ev[20..24].copy_from_slice(&sym.to_ne_bytes()); - // The wcode rides `SDL_Keysym.mod` (event offset +24, a `Uint16`), under a marker in - // `windowID` that says this press is synthetic at all. Several tokens carry ONLY a wcode - // (`pause` is sym 0, wcode 72), so deriving it from the sym is not an option. - // `decode_key`'s doc has the measurement behind both fields — the short version is that of - // the spare places to put a value, these two are the ones sdl2-compat does not discard. - ev[8..12].copy_from_slice(&SYNTH_WINDOW.to_ne_bytes()); - ev[24..26].copy_from_slice(&(wcode as u16).to_ne_bytes()); - } else { - ev[16..20].copy_from_slice(&if down { 1u32 } else { 0 }.to_ne_bytes()); // state - ev[20..24].copy_from_slice(&wcode.to_ne_bytes()); - ev[24..28].copy_from_slice(&sym.to_ne_bytes()); - } - ev + host_event(plx_shell_sdl::event::decode(ev)?) } -/// The bytes a synthetic HARDWARE AUTO-REPEAT edge carries — `encode_key`'s down edge with the -/// 0x101 shape (`state & 0x100 != 0`) the loop's repeat arm requires, in whichever layout -/// `decode_key` reads. `encode_key` itself must never produce this (`key_bytes_round_trip` pins -/// that a synthetic EDGE "must never look like auto-repeat"), so it is a second, deliberately -/// separate function rather than a third argument threaded through the first — item 13's -/// `holdrep:` FIFO token is the only caller, and it exists so a script can exercise the -/// `Edge::Repeat` a screen receives without a real remote's own repeat cadence. -pub(crate) fn encode_key_repeat(sym: c_uint, wcode: c_uint) -> [u8; 128] { - let mut ev = encode_key(sym, wcode, true); - if cfg!(feature = "hostsim") { - ev[13] = 1; // the `repeat` byte `decode_key`'s hostsim arm folds into `state & 0x100` - } else { - let state = rd_u32(&ev, 16) | 0x100; - ev[16..20].copy_from_slice(&state.to_ne_bytes()); - } - ev +/// One decoded SDL event as a [`HostEvent`]. The only place a [`Decoded`] becomes the application's own +/// type, so the next platform's events arrive through a sibling of this function and not through SDL's +/// bytes (`docs/platform-ports.md`, Target shape 8). +fn host_event(decoded: Decoded) -> Option { + Some(match decoded { + Decoded::Quit => HostEvent::Quit, + Decoded::Key { state, wcode, sym } => HostEvent::Key(KeyPress::from_decoded(state, wcode, sym)?), + Decoded::Text(text) => HostEvent::Text(text), + Decoded::Pointer { x, y, edge } => HostEvent::Pointer { x, y, edge }, + Decoded::Wheel { dy } => HostEvent::Wheel { dy }, + Decoded::Lifecycle(edge) => HostEvent::Lifecycle(edge), + }) } /// **One native key edge as the loop hands it to the tree**, for the effect-level guards (W5b): the @@ -454,25 +268,6 @@ pub(crate) fn native_key_input(sym: c_uint, wcode: c_uint, down: bool, at: plx_m (press, super::bridge::key_input(sym, wcode, press.state(), at, plx_machine::machine::Source::Sdl)) } -#[inline] -/// An SDL pointer event's position, converted from window pixels to the authored 1920x1080 canvas. -/// -/// THE one place event coordinates enter the UI, so the conversion cannot be forgotten at a new -/// call site — there are nine, and patching them individually is how the tenth ends up wrong. -/// `surface::to_logical` is the identity while the drawable is 1920x1080, which it is 1:1 unless -/// a webOS 1-3 owner picks a smaller Interface resolution (or the debug drawable trigger asks for one). -pub(crate) fn ptr_xy(ev: &[u8]) -> (f32, f32) { - plx_base::surface::to_logical(rd_i32(ev, 20) as f32, rd_i32(ev, 24) as f32) -} - -pub(crate) fn rd_i32(ev: &[u8], off: usize) -> i32 { - i32::from_ne_bytes([ev[off], ev[off + 1], ev[off + 2], ev[off + 3]]) -} - -pub(crate) fn rd_f32(ev: &[u8], off: usize) -> f32 { - f32::from_ne_bytes([ev[off], ev[off + 1], ev[off + 2], ev[off + 3]]) -} - /// Map a remote-control token (from the `crate::remote` FIFO) to the `(sym, wcode)` a /// real Magic-Remote press would carry — the pair the ONE key handler already matches /// (see `ui::consts`). Returns None for an unknown token. Kept deliberately small: the @@ -598,57 +393,6 @@ fn remote_token_pointer(tok: &str) -> Option<(RemotePointer, i32, i32)> { y.parse::().ok()?.clamp(0, plx_base::surface::LOGICAL_H as i32 - 1))) } -/// SDL pointer bytes shared by clicks, held-pointer FIFO edges and recorded-event replay. -/// The inverse of `ptr_xy`: convert authored coordinates exactly once, including window scaling -/// and letterboxing. Replay may carry a real off-canvas motion, so only the token parser clamps. -/// ABI: SDL's `SDL_events.h` (stock and the NDK's) mouse-event declarations put four -/// Uint32 fields before button@16/state@17 and Sint32 x@20/y@24. ARM32 NDK syntax-only -/// `offsetof` assertions verified these offsets; see `docs/testing-player-pointer.md`. -fn encode_pointer(et: u32, x: i32, y: i32) -> [u8; 128] { - let mut ev = [0u8; 128]; - let (px, py) = plx_base::surface::to_physical(x as f32, y as f32); - ev[0..4].copy_from_slice(&et.to_ne_bytes()); - ev[20..24].copy_from_slice(&(px.round() as i32).to_ne_bytes()); - ev[24..28].copy_from_slice(&(py.round() as i32).to_ne_bytes()); - if matches!(et, SDL_MOUSEBUTTONDOWN | SDL_MOUSEBUTTONUP) { - ev[16] = 1; // SDL_BUTTON_LEFT - ev[17] = u8::from(et == SDL_MOUSEBUTTONDOWN); - } - ev -} - -/// Synthesize a Magic-Remote pointer click at authored 1920x1080 coords (the browser -/// remote's click-on-the-stream): two motion events, then button down+up. The first -/// motion is a >=120px jitter so the accumulated pointer distance defeats the -/// D-pad-mode pointer gate (`Pointer::mot_accum < 120` swallows small motions after D-pad use); -/// the second lands on the target. The LG SDL fork's mouse events carry x@20 / y@24 -/// (i32) — the only fields the handlers read. -/// -/// The browser still sends clicks only: forwarding hover moved app focus on every pass of the -/// mouse over the streamed picture. A driver can explicitly send `pm:`/`pd:`/`pu:` instead to -/// separate HUD reveal from a press or to hold a drag across frames. Those edges add no jitter. -pub(crate) fn remote_synth_ptr(x: i32, y: i32) { - let jx = if x >= 200 { x - 200 } else { x + 200 }; - remote_synth_pointer(SDL_MOUSEMOTION, jx, y); - remote_synth_pointer(SDL_MOUSEMOTION, x, y); - remote_synth_pointer(SDL_MOUSEBUTTONDOWN, x, y); - remote_synth_pointer(SDL_MOUSEBUTTONUP, x, y); -} - -/// ONE pointer event in authored coordinates, shared by the FIFO and replay. Unlike `ck:`, -/// these primitives add no motion or release: `pd:` stays held until a separate `pu:` arrives. -pub(crate) fn remote_synth_pointer(et: u32, x: i32, y: i32) { - let ev = encode_pointer(et, x, y); - unsafe { SDL_PushEvent(ev.as_ptr() as *const c_void) }; -} - -/// One app lifecycle event (`0x103`–`0x106`), as the compositor would send it — the replay -/// driver's re-injection of a recorded background/foreground edge. -pub(crate) fn remote_synth_lifecycle(code: u32) { - let mut ev = [0u8; 128]; - ev[0..4].copy_from_slice(&code.to_ne_bytes()); - unsafe { SDL_PushEvent(ev.as_ptr() as *const c_void) }; -} /// A remote token that acts DIRECTLY rather than by pushing SDL events — the recorder writes /// these as `token` records, and the replay driver re-dispatches them. It is one of four fates: @@ -669,66 +413,6 @@ pub(crate) fn token_is_direct(tok: &str) -> bool { || tok.starts_with("txt:") } -/// Synthesize a full remote-key press (key-down then key-up) and push both onto SDL's -/// own event queue, so the existing poll loop consumes them as if they came off the -/// wayland input path. The LG SDL fork's `SDL_KeyboardEvent` carries state@16 / -/// wcode@20 / sym@24 (native-endian; the TV is LE), and the handler reads press vs -/// release from `state & 0xff` — so the down carries state=1, the up state=0. Both -/// are required: a grid-card OK arms on down and *commits on release*. -pub(crate) fn remote_synth_key(sym: c_uint, wcode: c_uint) { - remote_synth_key_edge(sym, wcode, true); - remote_synth_key_edge(sym, wcode, false); -} - -/// ONE edge of a remote key press. Split out for the `okdown`/`okup` FIFO tokens, because a -/// **press-and-hold** is only expressible as two tokens with real time between them: the item menu -/// opens on `press::is_long`, which measures the interval between the down and the up. The paired -/// `remote_synth_key` above is this called twice back to back (a tap). -pub(crate) fn remote_synth_key_edge(sym: c_uint, wcode: c_uint, down: bool) { - let ev = encode_key(sym, wcode, down); - unsafe { SDL_PushEvent(ev.as_ptr() as *const c_void) }; -} - -/// ONE hardware auto-repeat edge — item 13's `holdrep:` FIFO token, which lets a script -/// exercise a held key's `Edge::Repeat` (the Settings family's paced focus walk, the player -/// scrubber's continuous scrub) without a real remote's own repeat cadence. Only recognised as a -/// repeat by the loop's key arm when `App::down_sym` already equals `sym` — i.e. after a -/// `holddown:` and before its matching `holdup:`, the same split `okdown`/`okup` -/// already uses for a press-and-hold. -pub(crate) fn remote_synth_key_repeat(sym: c_uint, wcode: c_uint) { - let ev = encode_key_repeat(sym, wcode); - unsafe { SDL_PushEvent(ev.as_ptr() as *const c_void) }; -} - -/// Synthesize one Magic-Remote scroll-wheel tick — item 13's `wheel:` FIFO token, so a script -/// can drive the wheel with no mouse in the room. Encoded in the plain, real-SDL2 shape -/// (`Sint32 y` at `+20`) unconditionally: it is the READING side that has to branch by platform -/// now, not this one — see [`decode_wheel_dy`] on why `+20` decodes to 0 on this host and -/// where the value actually lands after `SDL_PushEvent` round-trips it. -pub(crate) fn remote_synth_wheel(dy: i32) { - let mut ev = [0u8; 128]; - ev[0..4].copy_from_slice(&SDL_MOUSEWHEEL.to_ne_bytes()); - ev[20..24].copy_from_slice(&dy.to_ne_bytes()); - unsafe { SDL_PushEvent(ev.as_ptr() as *const c_void) }; -} - -/// Is this SDL event type INPUT — a key, text, pointer or wheel event — as opposed to a lifecycle, -/// window or quit event? The one classification `Dispatcher::input_scope` rests on: input under -/// an open modal is the modal's, a lifecycle event is the app's and may change the page beneath. -pub(crate) fn is_input_event(et: u32) -> bool { - matches!( - et, - SDL_KEYDOWN - | SDL_KEYUP - | SDL_TEXTINPUT - | SDL_TEXTEDITING - | SDL_MOUSEMOTION - | SDL_MOUSEBUTTONDOWN - | SDL_MOUSEBUTTONUP - | SDL_MOUSEWHEEL - ) -} - #[cfg(test)] mod input_event_tests { use super::*; @@ -747,22 +431,6 @@ mod input_event_tests { assert_eq!(remote_token_pointer("pointer:1,2"), None); } - #[test] - fn pointer_bytes_round_trip_through_the_common_coordinate_decoder() { - let _serial = plx_base::testlock::serial(); - for et in [SDL_MOUSEMOTION, SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP] { - for (x, y) in [(0, 0), (1400, 870), (1919, 1079), (-200, 400)] { - let ev = encode_pointer(et, x, y); - assert_eq!(rd_u32(&ev, 0), et); - assert_eq!(ptr_xy(&ev), (x as f32, y as f32)); - if et != SDL_MOUSEMOTION { - assert_eq!(ev[16], 1, "the left button survives SDL's event queue"); - assert_eq!(ev[17], u8::from(et == SDL_MOUSEBUTTONDOWN)); - } - } - } - } - #[cfg(feature = "devtriggers")] #[test] fn hang_probes_are_direct_recorder_tokens() { @@ -800,27 +468,6 @@ mod input_event_tests { // a by-id input is recorded as an input at its tap, never as a direct recorder token assert!(!token_is_direct("focus:home.row.2") && !token_is_direct("press:home.row.2")); } - - /// The boundary `Dispatcher::input_scope` rests on: every input kind is in, and the - /// lifecycle events (background/foreground, `0x103`–`0x106`), window events and quit are out. - #[test] - fn input_events_are_the_modals_and_lifecycle_events_are_the_apps() { - for et in [ - SDL_KEYDOWN, - SDL_KEYUP, - SDL_TEXTINPUT, - SDL_TEXTEDITING, - SDL_MOUSEMOTION, - SDL_MOUSEBUTTONDOWN, - SDL_MOUSEBUTTONUP, - SDL_MOUSEWHEEL, - ] { - assert!(is_input_event(et), "{et:#x} is input"); - } - for et in [SDL_QUIT, 0x101, 0x103, 0x104, 0x105, 0x106, 0x200] { - assert!(!is_input_event(et), "{et:#x} is the app's, not a modal's"); - } - } } /// Dispatch one synthetic-input token. Shared by the SSH-only development FIFO and Lab Control's @@ -939,9 +586,18 @@ pub(crate) fn dispatch_remote_token(tok: &str, ps: &plx_media::route::PlaybackSe #[cfg(test)] mod key_layout_tests { - use super::{decode_key, encode_key, encode_key_repeat}; + use super::{encode_key, encode_key_repeat, wcode_of}; use plx_ui::consts::{SDLK_DOWN, SDLK_RETURN, WCODE_BACK, WCODE_PAUSE}; + /// What the loop reads a key's bytes as: the shell's decode with this application's desktop + /// stand-in applied where the bytes carry no wcode, the way `KeyPress::from_decoded` reads it. + /// The shell's own tests grade the byte layout; these grade the pair that reaches the loop, + /// stand-in priority included. + fn decode_key(ev: &[u8]) -> (u32, u32, u32) { + let (state, wcode, sym) = plx_shell_sdl::event::decode_key(ev); + (state, wcode_of(wcode, sym), sym) + } + /// `encode_key` and `decode_key` must agree, in whichever layout this build compiled. /// /// This is the regression test for a bug that shipped: the two ends disagreed about diff --git a/rust-modules/src/app/exit.rs b/rust-modules/src/app/exit.rs index a66d6f7f63..f0ff5bf38a 100644 --- a/rust-modules/src/app/exit.rs +++ b/rust-modules/src/app/exit.rs @@ -29,8 +29,8 @@ //! [`release_of`] that ends with `SDL_Quit()` (`NativeExit::Clean`), `Retained` is the arm that logs //! "SDL_Quit skipped" because a native worker is still inside firmware //! (`NativeExit::WorkerInFirmware`) and, for a refusal, "nothing was torn down". The executable -//! ignores it; a hosted entry maps `Retained` to `clean = 0`. Until the shell crate lands, `SDL_Quit` -//! IS the release of the window and the GL context, so `Complete` already means both. +//! ignores it; a hosted entry maps `Retained` to `clean = 0`. `Complete` means `Surface::quit` ran; +//! for the SDL shell that is `SDL_Quit`, which releases the window and the GL context. //! //! # The host doorway //! diff --git a/rust-modules/src/app/mod.rs b/rust-modules/src/app/mod.rs index 7210ad9e3d..657912679a 100644 --- a/rust-modules/src/app/mod.rs +++ b/rust-modules/src/app/mod.rs @@ -1,6 +1,7 @@ -//! run_application — the Rust app core (was the body of src/main.c). Owns SDL init, the -//! event loop, input decode, the per-frame tick, draw orchestration, app lifecycle, -//! the buffer-feed pump orchestration, and the dev triggers. The C boot shim +//! run_application — the Rust app core (was the body of src/main.c). Drives SDL's bring-up through the +//! platform's `Shell` (the SDL work is `plx_shell_sdl`'s), the event loop, the `HostEvent` mapping, +//! the per-frame tick, draw orchestration, app lifecycle, the buffer-feed pump orchestration, and +//! the dev triggers. The C boot shim //! (main.c) sets up the log and fallback crash tracer, calls the Rust image-marker and native-spool //! entries when required, then calls `plex_run` (port.rs), which hands over to `run_application` //! and, when it returns its `Exit` (`exit.rs`), ends the process. The desktop executable @@ -19,7 +20,6 @@ use std::os::raw::{c_char, c_int, c_uint, c_void}; use std::sync::atomic::Ordering::Relaxed; // ---- constants (SDL 2.0.4 + GLES2 + app) ---- -const SDL_INIT_VIDEO: u32 = 0x20; /// Appended to every heartbeat on a simulator build, and empty on a television. /// /// The heartbeat is the app's perf surface: `tests/run.py --fps` grades `loop=` and `fps=` from it, @@ -33,61 +33,16 @@ const SIM_TAG: &str = if cfg!(feature = "hostsim") { "" }; -/// OPENGL | FULLSCREEN on the television, which owns the whole panel. -/// -/// The desktop asks for OPENGL | ALLOW_HIGHDPI — no fullscreen grab (hostile on a laptop) and -/// **not RESIZABLE**: `surface::probe` reads the drawable once, at boot, so a dragged edge would -/// leave the viewport describing a window that no longer exists, and the interface would sit in a -/// 1920x1080-shaped corner of the new one with every pointer hit landing somewhere else. The window -/// opens at an exact divisor of the canvas instead — see `boot::plan_desktop_window`. -/// -/// ALLOW_HIGHDPI is what makes that divisor land on a **1:1 surface** on the Mac people actually -/// have: without it a Retina display gives a drawable equal to the window in POINTS, which the -/// compositor then doubles, so the whole interface is an upscale of a half-size render. With it, -/// `boot::fit_window_to_density` measures the pixels per point once the window exists and sizes -/// it in points for the drawable it should give: 960x540 points for a 1920x1080 drawable on a 2x -/// display, so `surface::scale() == 1.0`, the same 1:1 texel contract the television gets. -const SDL_WINDOW_FLAGS: u32 = if cfg!(feature = "hostsim") { - 0x2 | 0x2000 -} else { - 0x2 | 0x1 -}; -/// `SDL_WINDOW_INPUT_FOCUS`. Note it is NOT among the flags requested above — no window flag can -/// ask for it; SDL sets it when the compositor gives this surface the keyboard. Read, never asked -/// for, and read by exactly one thing: `crate::textinput`, whose panel it silently gates. -pub(crate) const SDL_WINDOW_INPUT_FOCUS: u32 = 0x200; const GL_COLOR_BUFFER_BIT: c_uint = 0x0000_4000; const GL_RENDERER: c_uint = 0x1F01; const GL_VERSION: c_uint = 0x1F02; -// SDL_GLattr enum -const A_RED: c_int = 0; -const A_GREEN: c_int = 1; -const A_BLUE: c_int = 2; -const A_ALPHA: c_int = 3; -const A_BUFFER_SIZE: c_int = 4; -const A_DEPTH: c_int = 6; -const A_STENCIL: c_int = 7; -const A_CTX_MAJOR: c_int = 17; -const A_CTX_MINOR: c_int = 18; -const A_CTX_PROFILE_MASK: c_int = 21; -const CTX_PROFILE_ES: c_int = 0x0004; -/// `SDL_GL_CONTEXT_PROFILE_CORE` — the simulator's only option on macOS. See the context request. -const CTX_PROFILE_CORE: c_int = 0x0001; -// event types -const SDL_QUIT: u32 = 0x100; -const SDL_KEYDOWN: u32 = 0x300; -const SDL_KEYUP: u32 = 0x301; -const SDL_MOUSEMOTION: u32 = 0x400; -const SDL_MOUSEBUTTONDOWN: u32 = 0x401; -const SDL_MOUSEBUTTONUP: u32 = 0x402; -const SDL_MOUSEWHEEL: u32 = 0x403; -/// The IME's in-progress COMPOSITION. Not acted on — the search field shows what has been -/// committed, so a preedit would put characters on screen the query does not contain — but LOGGED, -/// because the panel's word prediction is a replace and this is where its delete half would arrive -/// if it arrives at all. See the `"edit"` arm in the event ladder. -const SDL_TEXTEDITING: u32 = 0x302; -/// Text COMMITTED by the system keyboard — `crate::textinput`. -pub(crate) const SDL_TEXTINPUT: u32 = 0x303; +// SDL's event-type codes the ladder and the loop tests read, and the one window flag `textinput` reads, +// are the stock-SDL shell's (`plx_shell_sdl`); they are re-exported here so every `use super::*` chain +// below keeps resolving them by the names it always has. +pub(crate) use plx_shell_sdl::event::{ + SDL_KEYDOWN, SDL_KEYUP, SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP, SDL_MOUSEMOTION, SDL_TEXTEDITING, SDL_TEXTINPUT, +}; +pub(crate) use plx_shell_sdl::window::SDL_WINDOW_INPUT_FOCUS; // keysyms, the OK/BACK predicates and `classify` — the key VOCABULARY the ladder below dispatches // on — live in ui::consts (the single keycode home) use plx_ui::consts::{ @@ -95,24 +50,14 @@ use plx_ui::consts::{ WCODE_POINTER_HIDDEN, }; // The window we ASK SDL for. `surface::probe` then reads back what we actually got. +// Both are read only by the television's window request (`boot.rs`): the desktop's own sizing is +// `plx_shell_sdl`'s, so a hostsim build has no reader of either and they share one gate. +#[cfg(any(not(feature = "hostsim"), test))] const SCR_W: c_int = plx_base::surface::LOGICAL_W as c_int; +#[cfg(any(not(feature = "hostsim"), test))] const SCR_H: c_int = plx_base::surface::LOGICAL_H as c_int; pub(crate) const COLS: c_int = 10; -// Desktop-only window management. Apart for the mirror-image reason: a television owns the whole -// panel and never asks how big a display is, so on that build these would be dead code — which -// `[workspace.lints.rust] warnings = "deny"` makes a build failure, not a warning. -#[cfg(feature = "hostsim")] -extern "C" { - /// `SDL_GetDisplayUsableBounds` — the display minus the menu bar and the Dock, which is what - /// a window may actually occupy. The out parameter is an `SDL_Rect`: exactly four `c_int`. - fn SDL_GetDisplayUsableBounds(display: c_int, rect: *mut c_int) -> c_int; - /// `SDL_SetWindowSize` / `SDL_SetWindowPosition` — `app::boot::fit_window_to_density` re-sizes - /// and re-centres the window once the display's pixel density has been measured from it. - fn SDL_SetWindowSize(win: *mut c_void, w: c_int, h: c_int); - fn SDL_SetWindowPosition(win: *mut c_void, x: c_int, y: c_int); -} - // Phase 1a of the UI restructure split this file: everything above `run_application` moved into // the submodules below as a PURE move (`pub(crate)` widening only), glob-imported here so the // loop body reads exactly as before. `run_application` itself is phase 1b. @@ -156,59 +101,6 @@ use self::input::*; use self::content::*; extern "C" { - fn SDL_SetMainReady(); - fn SDL_SetHint(name: *const c_char, value: *const c_char) -> c_int; - fn SDL_Init(flags: u32) -> c_int; - fn SDL_GetCurrentVideoDriver() -> *const c_char; - fn SDL_GL_SetAttribute(attr: c_int, value: c_int) -> c_int; - fn SDL_CreateWindow( - title: *const c_char, - x: c_int, - y: c_int, - w: c_int, - h: c_int, - flags: u32, - ) -> *mut c_void; - fn SDL_DestroyWindow(win: *mut c_void); - fn SDL_GL_CreateContext(win: *mut c_void) -> *mut c_void; - fn SDL_GL_SetSwapInterval(interval: c_int) -> c_int; - fn SDL_Delay(ms: u32); - fn SDL_PollEvent(event: *mut c_void) -> c_int; - fn SDL_PushEvent(event: *const c_void) -> c_int; - fn SDL_GL_SwapWindow(win: *mut c_void); - fn SDL_Quit(); - // The system on-screen keyboard. A PLAIN link, not `dynlib!`, and the rule in `dynlib.rs` is - // why: that module is for libraries whose SONAME moves, and this is stock public SDL2 API — - // `tools/fwcompat.py --lib libSDL2-2.0.so.0 --grep TextInput` finds the whole family exported - // by all 14 firmware inventories, so there is nothing here for a runtime bind to tolerate. - // - // `pub(crate)` on these five alone because `crate::textinput` owns this seam and is the only - // caller; the declarations stay here with the rest of SDL rather than being duplicated into a - // second `extern` block, where a signature could drift from this one unnoticed. - // - // The `allow(dead_code)` below is a consequence of that ownership: under `cfg(test)` the only - // caller swaps itself for `textinput::host_test_sdl`'s stubs, so these three lose their last - // use in the TEST build alone and warn there. The allow is narrower than it looks — a real - // orphan would be silent in every configuration, and these are live on device. - #[allow(dead_code)] - pub(crate) fn SDL_StartTextInput(); - #[allow(dead_code)] - pub(crate) fn SDL_StopTextInput(); - pub(crate) fn SDL_IsTextInputActive() -> c_int; - pub(crate) fn SDL_HasScreenKeyboardSupport() -> c_int; - /// LG's `WebOSIsScreenKeyboardShown`, the fourth of the four hooks its Wayland driver installs. - /// Exported by all 14 inventories, and **it does not answer the question its name asks** on this - /// firmware — `textinput`'s note has the measurement and what replaced it. Declared, unused, and - /// kept so the next person finds the finding before they find the symbol. - #[allow(dead_code)] - pub(crate) fn SDL_IsScreenKeyboardShown(w: *mut c_void) -> c_int; - pub(crate) fn SDL_GetWindowFlags(w: *mut c_void) -> u32; - /// Turn the DRIVER's own tracing on for one category. LG's `WebOSShowScreenKeyboard` / - /// `Hide` / `TextModelLeave` / `TextModelInputPanelState` all log through SDL at - /// `SDL_LOG_CATEGORY_INPUT`, which is silent at the default priority — so this is how the - /// keyboard's real lifecycle becomes readable without patching SDL. - #[allow(dead_code)] // test build only — see the note above `SDL_StartTextInput` - pub(crate) fn SDL_LogSetPriority(category: c_int, priority: c_int); fn glGetString(name: c_uint) -> *const c_char; fn glViewport(x: c_int, y: c_int, w: c_int, h: c_int); fn glClear(mask: c_uint); @@ -346,10 +238,12 @@ pub(crate) struct App { /// The re-read of covered pages and of the visible one on resume, stepped once per loop /// iteration beside the view-state pumps (`app/reread.rs`). pub(crate) reread: reread::Reread, + /// The buffer [`platform::Surface::poll`] fills, one event at a time. ev: [u8; 128], remote: Option, - /// The SDL window (`SDL_CreateWindow`), for the swap. - win: *mut c_void, + /// The window and its GL context (`Shell::open`): the swap, the event poll, the raw handle the + /// shell's per-window calls take, and the process's SDL quit. Thread-affine, like the loop. + surface: Box, /// WSLg accepts swap interval 1 on X11/GLX without pacing the compositor. This boot-scoped /// flag enables the host-only software frame budget while leaving native Linux and macOS on /// their driver swap behavior. @@ -588,7 +482,7 @@ unsafe fn run_and_shutdown(app: &mut App) -> Exit { let failed = finish_recording(&mut app.rec, bridge.landgate()) || bridge.controlled_failure().is_some(); app.glass.sources.borrow_mut().clear(); - let release = run::shutdown(&mut app.player.session, &mut app.adapters.player); + let release = run::shutdown(&mut app.player.session, &mut app.adapters.player, &*app.surface); // The crash-channel guard is the one `Drop` that persists something (it closes the capture // backend and removes its database), so it runs here explicitly: nothing drops the `App`. drop(app.telemetry_guard.take()); @@ -678,7 +572,8 @@ pub(crate) fn run_application(platform: &'static platform::Platform, pms_host: * // the origin an `EntryId` on the mounted player screen, so the same questions are asked of a // real container, beside `playback::enter_player`/`exit_player` — including two the description // could not reach: the spot the page comes back at, and an origin that is really gone. -// * `key_layout_tests` — beside `events::decode_key`/`encode_key`, whose byte offsets it pins. +// * `key_layout_tests` — beside `events`' `encode_key`, round-tripped through `plx_shell_sdl::event::decode_key`, +// whose byte offsets it pins. // * `route_tests` — split in two, each half beside its subject: the direct-screen server rule is // `boot::resolve_direct_server`'s, and the profile chip's alphabet is `ScreenArg::chrome`'s, in // `screens::registry`. diff --git a/rust-modules/src/app/platform.rs b/rust-modules/src/app/platform.rs index cb89b04963..7ff3228b10 100644 --- a/rust-modules/src/app/platform.rs +++ b/rust-modules/src/app/platform.rs @@ -7,10 +7,11 @@ //! accessors (identity, the secure store, Home and the toast, the legacy webOS media verbs). //! `run_application` installs it into `tv` once, and nothing else in the app reads it. //! - `shell`: the window, the bus and the pointer's visibility, [`Shell`]. Its consumers are boot -//! (`app::boot` brings the window up with the platform it was handed), the loop (`app::run` drives -//! it every frame, through `App::platform`) and the bridge, which holds the shell for the -//! dispatcher's two opaque-region hooks and lends it to the pointer's own callers (`input`, -//! `playback`), which hide and show the Magic Remote's pointer through it. +//! (`app::boot` brings the window up with the platform it was handed: `init`, then `open`, which +//! returns the [`Surface`] the `App` owns from then on), the loop (`app::run` drives it every +//! frame, through `App::platform`, and presents and polls through the surface) and the bridge, which +//! holds the shell for the dispatcher's two opaque-region hooks and lends it to the pointer's own +//! callers (`input`, `playback`), which hide and show the Magic Remote's pointer through it. //! - `diag`: the six frame probes, [`FrameProbe`], read by the loop. The renderer's clear hook takes //! plain functions, so the platform's entry installs it (`gfx::install_clear_probe`). //! - `media`: [`MediaBoot`], the platform's two boot-time playback steps. `early_init` runs once before @@ -19,10 +20,11 @@ //! platform composed through [`publish_composition`], the one function that does, so the set of //! installed drivers and the resolver the planner reads cannot disagree. //! -//! `Shell`, `FrameProbe` and `Platform` are app-private on purpose: no type a platform's shell has +//! `Shell`, `Surface`, `FrameProbe` and `Platform` are app-private on purpose: no type a platform's shell has //! to match leaves the application crate until the platform contract is settled. The webOS value is //! built by `port.rs`; `ci/check-deps.sh`'s `frame` gate pins the call text of the three //! privileged calls (`pump_bus`, `opaque_route`, `clear_opaque_region`) to `app/run.rs`. +use super::Exit; use plx_base::task::MainThread; use plx_media::player::adapter::PlayerAdapter; use plx_media::route::uri_preflight::ResolvePort; @@ -30,11 +32,30 @@ use plx_media::route::PlaybackSession; use plx_os::tv::Services; use std::os::raw::c_void; +/// What a platform's boot asks of SDL, as plain data: [`InitHooks`] (the two steps a platform runs +/// around `SDL_Init`), and [`OpenAsk`] with its [`Placement`] (the window's title, place and size). The +/// shell crate's own types, re-exported rather than copied: they hold no SDL type, and W7a, which +/// publishes `Shell` and `Surface`, is where a platform-neutral spelling of them is decided. +pub(crate) use plx_shell_sdl::{InitHooks, OpenAsk, Placement}; + /// The platform's window, bus and pointer, as the application drives them: the SDL window and its /// surface, the opaque-region hint, the platform bus pump, and the visibility of the Magic Remote's /// pointer. Every call runs on the loop thread, and every hook is required: a platform with nothing /// to do states a no-op, as the desktop and the test-only host platform do. +/// +/// `init` and `open` are the two steps that bring the surface up, and they are two because the +/// application reads the stored session between them (the window size is a setting): SDL and the GL +/// request first, the session read, then the window. That is the order boot has always had, and +/// `app::boot` pins it. A platform whose surface is not SDL's states its own pair; every SDL one is the +/// shell crate's (`plx_shell_sdl`), reached through [`sdl_init`] and [`sdl_open`]. pub(crate) trait Shell: Sync { + /// Bring the platform's windowing up and ask for the GL context, once, FIRST: before the stored + /// session is read and before [`open`](Shell::open). A refusal ends the boot with that `Exit`. + fn init(&self, mt: &MainThread) -> Result<(), Exit>; + /// Open the window and its GL context at `ask`, make the context current on this thread and + /// probe the drawable it gave. The [`Surface`] it returns is the application's for the rest of the + /// process. A refusal ends the boot with that `Exit`. + fn open(&self, mt: &MainThread, ask: &OpenAsk) -> Result, Exit>; /// Hand the platform the SDL window, once, at boot: the window is created deep inside boot and /// the platform needs it a long way from there (`textinput::bind`'s shape and its reason). fn bind_window(&self, win: *mut c_void); @@ -66,6 +87,82 @@ pub(crate) trait Shell: Sync { fn hide_is_cursor_swap(&self) -> bool; } +/// The window the application presents to and reads events from, owned by `App` for the rest of the +/// process. App-private and thread-affine (not `Sync`) like [`Shell`], and for the same reason: no +/// type a platform has to match leaves the application crate until the platform contract is settled +/// (`docs/platform-ports.md`, Target shapes 1 and 8, which W7a publishes as `host`). +/// +/// `window` is the raw handle the [`Shell`]'s per-window calls still take (`bind_window`, +/// `grab_surface`, and `textinput`'s focus read), so every call site the `frame` gate pins stays where +/// it is; W7a folds those into this trait. `poll` is SDL-shaped bytes until the platform's own event +/// sink replaces it. There is no destructor: the `App` is leaked at exit and a worker may still hold +/// the handle, so the end is the explicit, decided [`quit`](Surface::quit). +pub(crate) trait Surface { + /// The raw window handle, null for a surface that has none (the rig's). + fn window(&self) -> *mut c_void; + /// Present the frame. The compositor commit of the opaque-region request just made is this call's. + fn swap(&self); + /// 1 locks the frame rate to the panel's refresh, 0 uncaps it; the application computes which. + fn set_swap_interval(&self, interval: i32); + /// Take the next event off the platform's queue into `ev`; `false` when there is none. + fn poll(&self, ev: &mut [u8; 128]) -> bool; + /// End the platform's windowing for the process. + /// + /// # Safety + /// After the loop's last use of it, on the loop thread; nothing may touch the platform's + /// windowing afterwards. The caller decides WHEN (`run::quits_sdl`): a worker still inside + /// firmware means the display must not be torn down under it. + unsafe fn quit(&self); +} + +/// SDL's window is a [`Surface`] by delegation: the one SDL implementation, for the television and a +/// desktop alike. The trait is local, so the orphan rule has nothing to say. +impl Surface for plx_shell_sdl::Window { + fn window(&self) -> *mut c_void { + self.raw() + } + fn swap(&self) { + plx_shell_sdl::Window::swap(self) + } + fn set_swap_interval(&self, interval: i32) { + plx_shell_sdl::Window::set_swap_interval(self, interval) + } + fn poll(&self, ev: &mut [u8; 128]) -> bool { + plx_shell_sdl::event::poll(ev) + } + unsafe fn quit(&self) { + plx_shell_sdl::init::quit() + } +} + +/// [`Shell::init`] for an SDL platform: SDL up with the platform's two steps around `SDL_Init`, then the +/// GL context request. `SDL_Init` refused ends the boot (`Exit::refused(1)`, the status it always had). +/// +/// # Safety +/// `hooks` must be sound to call on the SDL main thread (`mt` is the proof of the thread) at the two +/// points `plx_shell_sdl::init::init` calls them. +pub(crate) unsafe fn sdl_init(mt: &MainThread, hooks: InitHooks) -> Result<(), Exit> { + plx_shell_sdl::init::init(mt, hooks).map_err(|_| Exit::refused(1))?; + plx_shell_sdl::init::request_gl(mt); + Ok(()) +} + +/// [`Shell::open`] for an SDL platform: the window and its GL context. Refused at the native size, the +/// boot ends with `Exit::refused(1)`, the status it always had. +pub(crate) fn sdl_open(mt: &MainThread, ask: &OpenAsk) -> Result, Exit> { + plx_shell_sdl::Window::open(mt, ask) + .map(|window| Box::new(window) as Box) + .map_err(|_| Exit::refused(1)) +} + +/// A surface with no window, for the shells of a process that owns none: a host test, and the loop's +/// rig. Its swap is `SDL_GL_SwapWindow(NULL)` and its poll is SDL's real process-global queue, which is +/// what the rig's null handle and the tests that push events have always had. Test builds only. +#[cfg(test)] +pub(crate) fn detached_surface() -> Box { + Box::new(plx_shell_sdl::Window::DETACHED) +} + /// The dev frame probe (`/tmp/plxnative-framecb`): the platform's presentation-callback clock, read /// by the loop and by the renderer's clear hook. Unarmed, every call is a latched flag read. pub(crate) trait FrameProbe: Sync { @@ -169,6 +266,12 @@ struct HostShell; #[cfg(test)] impl Shell for HostShell { + fn init(&self, _mt: &MainThread) -> Result<(), Exit> { + Ok(()) + } + fn open(&self, _mt: &MainThread, _ask: &OpenAsk) -> Result, Exit> { + Ok(detached_surface()) + } fn bind_window(&self, _win: *mut c_void) {} fn grab_surface(&self, _win: *mut c_void) {} fn release_surface(&self) -> bool { @@ -212,6 +315,12 @@ pub(crate) struct SwapShell { #[cfg(test)] impl Shell for SwapShell { + fn init(&self, _mt: &MainThread) -> Result<(), Exit> { + Ok(()) + } + fn open(&self, _mt: &MainThread, _ask: &OpenAsk) -> Result, Exit> { + Ok(detached_surface()) + } fn bind_window(&self, _win: *mut c_void) {} fn grab_surface(&self, _win: *mut c_void) {} fn release_surface(&self) -> bool { @@ -287,6 +396,17 @@ mod tests { "the services are the host-test services (`tv`'s own tests pin each answer)" ); + // SAFETY: a host test owns the one thread it runs the shell's bring-up on. + let mt = unsafe { MainThread::assume() }; + assert_eq!(s.init(&mt), Ok(()), "there is no windowing to bring up"); + let ask = OpenAsk { + title: c"PlxNative", + placement: Placement::Panel { size: (1920, 1080), fallback: None }, + high_dpi: false, + }; + let surface = s.open(&mt, &ask).expect("a process with no platform opens a windowless surface"); + assert!(surface.window().is_null(), "and the surface it hands back has no window"); + let window = std::ptr::null_mut(); s.bind_window(window); s.grab_surface(window); @@ -307,8 +427,7 @@ mod tests { p.acquired(); assert_eq!(p.fields(), "", "an unarmed probe has nothing to log"); - // SAFETY: a host test owns the one thread it runs the media boot on. - let mt = unsafe { MainThread::assume() }; + // The same thread, the same proof: the media boot runs on it too. (media.early_init)(&mt); let mut adapter = PlayerAdapter::new(mt); let composed = (media.compose)(&mut adapter, false); @@ -349,4 +468,37 @@ mod tests { "another platform's counts are its own"); assert!(!other.shell.release_surface(), "the rest of the shell answers as the host-test one does"); } + + /// **The SDL calls the application still declares are the two that stay.** Everything SDL-shaped + /// that is the stock shell's (the window, the GL context, the queue, the text-input panel) is + /// `plx_shell_sdl`'s; what remains is `system.rs`'s `SDL_GetWindowWMInfo` handshake (the television's + /// SDL writes a larger `SDL_SysWMinfo` than the headers declare, so the buffer and the version query + /// are LG's and stay verbatim) and `clock.rs`'s `SDL_GetTicks`, the `ticks` gate's one door. A third + /// declaration here is a second SDL seam beside the shell crate's. Reads the sources, like + /// `port.rs`'s tests, because no host test can see a declaration. + #[test] + fn the_application_declares_no_sdl_function_but_the_two_that_stay() { + fn walk(dir: &std::path::Path, src: &std::path::Path, hits: &mut Vec) { + for entry in std::fs::read_dir(dir).expect("read a source directory") { + let path = entry.expect("a directory entry").path(); + if path.is_dir() { + walk(&path, src, hits); + } else if path.extension().is_some_and(|ext| ext == "rs") { + let rel = path.strip_prefix(src).expect("under src").to_string_lossy().replace('\\', "/"); + if rel == "system.rs" || rel == "app/clock.rs" { + continue; + } + let text = std::fs::read_to_string(&path).expect("read a source file"); + // Split with `concat!`, so this file's own text is never what it matches. + if text.contains(concat!("fn ", "SDL_")) { + hits.push(rel); + } + } + } + } + let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut hits = Vec::new(); + walk(&src, &src, &mut hits); + assert!(hits.is_empty(), "an SDL function is declared outside `system.rs` and `app/clock.rs`: {hits:?}"); + } } diff --git a/rust-modules/src/app/run.rs b/rust-modules/src/app/run.rs index dbd88d74d4..2ef8d7fb06 100644 --- a/rust-modules/src/app/run.rs +++ b/rust-modules/src/app/run.rs @@ -975,7 +975,7 @@ unsafe fn present_and_swap( // dev (`/tmp/plxnative-framecb`): this frame's compositor callback, requested before // the swap that commits it. One latched bool unarmed. app.platform.diag.request(); - SDL_GL_SwapWindow(app.win); + app.surface.swap(); } app.window_activity.presented(fr.player); // dev diagnostic, OFF unless `/tmp/plxnative-eglage` was present at boot: re-ask EGL for @@ -1036,7 +1036,7 @@ unsafe fn present_and_swap( // Device and macOS presented frames block in swap; WSLg/X11 presented frames use the // software budget above. A skipped frame reaches neither path, so sleep here to keep a // settled screen from becoming a CPU spinner. - SDL_Delay(plx_machine::motion::report::IDLE_POLL_MS); + plx_shell_sdl::init::delay_ms(plx_machine::motion::report::IDLE_POLL_MS); } } @@ -1068,7 +1068,7 @@ pub(crate) unsafe fn ingest(app: &mut App, fr: &mut Frame) { } unsafe fn drain_sdl(app: &mut App, fr: &mut Frame) { - while SDL_PollEvent(app.ev.as_mut_ptr() as *mut c_void) != 0 { + while app.surface.poll(&mut app.ev) { ingest_sdl_event(app, fr); } } @@ -1207,7 +1207,7 @@ unsafe fn ingest_host_event(app: &mut App, fr: &mut Frame, event: HostEvent, // Only its DID foreground reacquires native handles. Recorded notifications // below never reacquire them, revoke grants or resume a native player. match event { - HostEvent::Lifecycle(Lifecycle::DidForeground) => restore_window(app.win), + HostEvent::Lifecycle(Lifecycle::DidForeground) => restore_window(app.surface.window()), HostEvent::Quit | HostEvent::Lifecycle(Lifecycle::WillBackground | Lifecycle::DidBackground) => { app.rec.refuse("live window exit interrupted controlled replay"); @@ -1378,7 +1378,7 @@ unsafe fn host_foreground(app: &mut App, edge: Lifecycle, playing: bool, // The television may have been away long enough for every page to be stale. app.reread.resume(); // Reacquire only on DID foreground, before playback restoration and rendering. - restore_window(app.win); + restore_window(app.surface.window()); app.note_presentation_damage(plx_machine::present::Provenance::Lifecycle); // A decoder-release park is claimed by this edge like any other park. app.decoder_parked = false; @@ -3394,7 +3394,7 @@ pub(crate) unsafe fn draw(app: &mut App, fr: &mut Frame) -> (i32, i32, i32, i32) }; plx_gfx::gfx::draw_number( *fps_shown, - SCR_W as f32 - 70.0, + plx_base::surface::LOGICAL_W - 70.0, 64.0, 46.0, fps_col.as_ptr(), @@ -3810,11 +3810,13 @@ pub(crate) fn quits_sdl(native_exit: plx_media::player::NativeExit) -> bool { /// Teardown after the loop: abandon the pending report, stop the active backend, wait for the stop /// scrobble, close the capture stream and the poster workers, quit SDL (unless a worker is still -/// in firmware). Answers what it released: the caller (`app::run_and_shutdown`) returns it in the -/// `Exit`, and the executable entry then ends the process with `_exit`. +/// in firmware: `surface.quit()` is the platform's, and WHETHER it runs is this function's). Answers +/// what it released: the caller (`app::run_and_shutdown`) returns it in the `Exit`, and the executable +/// entry then ends the process with `_exit`. pub(crate) unsafe fn shutdown( ps: &mut plx_media::route::PlaybackSession, pa: &mut plx_media::player::adapter::PlayerAdapter, + surface: &dyn super::platform::Surface, ) -> Release { ps.finish_metric_request(plx_media::player::attempt_metrics::RequestOutcome::Cancelled); pa.sync_request_metrics(ps); @@ -3839,7 +3841,7 @@ pub(crate) unsafe fn shutdown( // anywhere above leaves its state for the next boot to classify as crashed or abnormal. plx_telemetry::telemetry::session::shutdown(); if quits_sdl(native_exit) { - SDL_Quit(); + surface.quit(); } else { log("shutdown: a native worker is still inside firmware; SDL_Quit skipped, exiting without unwinding"); } @@ -4115,7 +4117,7 @@ pub(in crate::app) mod lifecycle_regression_tests { reread: Default::default(), ev: [0; 128], remote: Default::default(), - win: Default::default(), + surface: crate::app::platform::detached_surface(), #[cfg(target_os = "linux")] wslg_frame_pacing: false, t0: Default::default(), @@ -5293,6 +5295,96 @@ pub(in crate::app) mod lifecycle_regression_tests { } } + // ---- W6: the loop's other calls on the platform's shell ------------------------------------- + // + // Three call sites reach `Shell` from the loop outside the key and pointer arms the tests above + // count, and none of them had a test that would notice the call going missing: the idle pointer + // over the video (`playback_tick`), the hand-back of Back's hidden pointer on backgrounding + // (`host_background`), and a controlled pointer input's wake (`controlled_key_input`). Each is + // counted on a `SwapShell`, the platform's shell as the loop holds it. + + /// **An idle pointer over the video is hidden through the platform's shell**, once, after more + /// than three seconds without motion on a mounted player: not at three seconds, not again on the + /// next frame, and not while a button is held. + #[test] + fn an_idle_pointer_over_the_video_is_hidden_through_the_platforms_shell_after_three_seconds() { + use std::sync::atomic::Ordering::Relaxed; + fn tick(app: &mut App, now: u32) { + let mut fr = Frame::begin(&app.player.session, app.runtime.metadata_view()); + fr.now = now; + unsafe { playback_tick(app, &mut fr) }; + } + let _serial = plx_base::testlock::serial(); + let (platform, shell) = crate::app::platform::SwapShell::platform(); + clock::set_replay(100); + let mut app = app_on(platform); + super::super::bridge::show_page(&mut app.pages, AppArg::Player); + frame(&mut app, 0); + assert!(matches!(app.route(), AppArg::Player), "premise: the player is mounted"); + app.ptr.last_motion = 1_000; + tick(&mut app, 4_000); + assert_eq!((shell.hides.load(Relaxed), app.ptr.cur_hidden), (0, false), "three seconds is not more than three seconds"); + app.ptr.button_down = true; + tick(&mut app, 4_001); + assert_eq!((shell.hides.load(Relaxed), app.ptr.cur_hidden), (0, false), "a held button keeps the pointer"); + app.ptr.button_down = false; + tick(&mut app, 4_001); + assert_eq!((shell.hides.load(Relaxed), app.ptr.cur_hidden), (1, true), "more than three seconds idle hides it, through the shell"); + tick(&mut app, 9_000); + assert_eq!(shell.hides.load(Relaxed), 1, "...once"); + } + + /// **Backgrounding hands back the pointer Back hid, through the platform's shell**: the OS took + /// the screen, so the cursor Back's hold made transparent is shown again (nothing else would + /// until a motion), whether the edge arrives as SDL's bytes or as the host's `Lifecycle`. + #[test] + fn backgrounding_hands_back_the_pointer_back_hid_through_the_platforms_shell() { + use plx_machine::machine::{InstanceId, MachineId}; + use plx_screens::registry::BackCursorChange; + use std::sync::atomic::Ordering::Relaxed; + let _serial = plx_base::testlock::serial(); + for hosted in [false, true] { + let (platform, shell) = crate::app::platform::SwapShell::platform(); + let mut app = app_on(platform); + let mut fr = Frame::begin(&app.player.session, app.runtime.metadata_view()); + let target = (MachineId::Instance(InstanceId(1)), 7); + app.ptr.sync_back_cursor(app.platform.shell, Some(target), Some((target, BackCursorChange::Hide))); + assert!(app.ptr.back_cursor_active() && app.ptr.cur_hidden, "premise: Back holds a hidden pointer"); + assert_eq!((shell.hides.load(Relaxed), shell.shows.load(Relaxed)), (1, 0), "premise: it hid it through the shell"); + deliver(&mut app, &mut fr, hosted, HostEvent::Lifecycle(Lifecycle::WillBackground)); + assert!(!app.ptr.back_cursor_active() && !app.ptr.cur_hidden, "backgrounding ends Back's hold (hosted {hosted})"); + assert_eq!(shell.shows.load(Relaxed), 1, "...and shows the pointer again, through the shell (hosted {hosted})"); + } + } + + /// **A controlled pointer input wakes a hidden pointer through the platform's shell**, as the + /// SDL pointer path does: a recorded or scripted pointer, click or drag is the viewer moving the + /// pointer, so the pointer the D-pad hid comes back, once (`controlled_key_input`). + #[test] + fn a_controlled_pointer_input_shows_a_hidden_pointer_through_the_platforms_shell() { + use plx_machine::machine::{InputEvent, InputKind, Source, Tick}; + use std::sync::atomic::Ordering::Relaxed; + let _serial = plx_base::testlock::serial(); + let kinds = [ + InputKind::::Pointer { x: 400.0, y: 300.0, hit: None }, + InputKind::Click { x: 400.0, y: 300.0, hit: None }, + InputKind::Drag { x: 400.0, y: 300.0, hit: None }, + ]; + for kind in kinds { + let (platform, shell) = crate::app::platform::SwapShell::platform(); + let mut app = app_on(platform); + app.ptr.cur_hidden = true; + let event = InputEvent { at: Tick { ms: 500, dt_us: 0 }, source: Source::Sdl, kind }; + unsafe { controlled_key_input(&mut app, event) }; + assert_eq!(shell.shows.load(Relaxed), 1, "the controlled pointer input shows the hidden pointer, through the shell"); + assert!(!app.ptr.cur_hidden && app.ptr.last_motion == 500); + let again = InputEvent { at: Tick { ms: 516, dt_us: 0 }, source: Source::Sdl, + kind: InputKind::Pointer { x: 410.0, y: 300.0, hit: None } }; + unsafe { controlled_key_input(&mut app, again) }; + assert_eq!(shell.shows.load(Relaxed), 1, "...once"); + } + } + /// **The tape is the same whichever way a pointer event or a wheel tick arrives**, and it is /// today's: one `pointer`, `click` or `release` row per event at its authored position, and the /// wheel's `wheel` row (its count in `y`) at the debounce's pace, before the zero-tick return. @@ -5383,8 +5475,8 @@ pub(in crate::app) mod lifecycle_regression_tests { let (mut app, mut fr) = settings_app(); clock::set_replay(1_000); remote_synth_wheel(-2); - let polled = unsafe { SDL_PollEvent(app.ev.as_mut_ptr() as *mut c_void) }; - assert_eq!(polled, 1, "SDL handed the pushed wheel event back"); + let polled = plx_shell_sdl::event::poll(&mut app.ev); + assert!(polled, "SDL handed the pushed wheel event back"); let precise = rd_f32(&app.ev, 32); assert!(rd_i32(&app.ev, 20) == -2 || precise == -2.0, "premise: the tick survived SDL's round trip in one field"); unsafe { ingest_sdl_event(&mut app, &mut fr) }; @@ -5836,18 +5928,9 @@ pub(in crate::app) mod lifecycle_regression_tests { assert!(recording.frames.iter().all(|frame| frame.inputs.is_empty()), "a read-back is not recorded"); } - /// Only SDL's event subsystem, for the tests that poll SDL (a by-id token drains it first): no - /// window, renderer, boot or device. Quits when dropped. - struct SdlEvents; - impl SdlEvents { - fn init() -> Self { - assert_eq!(unsafe { SDL_Init(0x4000) }, 0); - Self - } - } - impl Drop for SdlEvents { - fn drop(&mut self) { unsafe { SDL_Quit(); } } - } + // Only SDL's event subsystem, for the tests that poll SDL (a by-id token drains it first): no + // window, renderer, boot or device. Quits when dropped (`plx_shell_sdl::testing`). + use plx_shell_sdl::testing::EventsOnly as SdlEvents; fn by_id_tags(inputs: &[plx_machine::machine::InputEvent]) -> Vec { use plx_machine::machine::InputKind; @@ -6086,12 +6169,7 @@ pub(in crate::app) mod lifecycle_regression_tests { fn hang_probe_dispatch_preserves_key_order() { let _serial = plx_base::testlock::serial(); // Only SDL's event subsystem: no window, renderer, boot or device. - assert_eq!(unsafe { SDL_Init(0x4000) }, 0); - struct Events; - impl Drop for Events { - fn drop(&mut self) { unsafe { SDL_Quit(); } } - } - let _events = Events; + let _events = plx_shell_sdl::testing::EventsOnly::init(); for fifo in [true, false] { let mut app = app(); super::super::bridge::show_page(&mut app.pages, @@ -6208,12 +6286,7 @@ pub(in crate::app) mod lifecycle_regression_tests { const ADDRESS: &str = "https://example.com/hud.plxhud"; let _serial = plx_base::testlock::serial(); // SDL's event subsystem only: no window, renderer, native playback or device. - assert_eq!(unsafe { SDL_Init(0x4000) }, 0); - struct Events; - impl Drop for Events { - fn drop(&mut self) { unsafe { SDL_Quit(); } } - } - let _events = Events; + let _events = plx_shell_sdl::testing::EventsOnly::init(); // Three doors: the FIFO's token, the television's keyboard as the SDL bytes the drain decodes, // and the same commit as the `HostEvent::Text` a platform with no SDL hands the loop (W5b). for (fifo, hosted) in [(true, false), (false, false), (false, true)] { @@ -6266,12 +6339,7 @@ pub(in crate::app) mod lifecycle_regression_tests { } let _serial = plx_base::testlock::serial(); // SDL's event subsystem only: no window, renderer, native playback or device. - assert_eq!(unsafe { SDL_Init(0x4000) }, 0); - struct Events; - impl Drop for Events { - fn drop(&mut self) { unsafe { SDL_Quit(); } } - } - let _events = Events; + let _events = plx_shell_sdl::testing::EventsOnly::init(); let dir = HudDir::new("close-then-text"); let (mut app, mut fr, mut now) = hud_address_field_up(&dir.0, dial); @@ -6300,12 +6368,7 @@ pub(in crate::app) mod lifecycle_regression_tests { use plx_machine::machine::{Edge, InputKind, Key}; let _serial = plx_base::testlock::serial(); // SDL's event subsystem only: no window, renderer, native playback or device. - assert_eq!(unsafe { SDL_Init(0x4000) }, 0); - struct Events; - impl Drop for Events { - fn drop(&mut self) { unsafe { SDL_Quit(); } } - } - let _events = Events; + let _events = plx_shell_sdl::testing::EventsOnly::init(); let mut app = app(); super::super::bridge::show_page(&mut app.pages, AppArg::Player); frame(&mut app, 0); @@ -12762,7 +12825,8 @@ mod straighten_wiring_tests { let compositor = at("composite_plane_under();\n }"); let dump = at("crate::dev::framedump::after_draw("); let shot = at("crate::shot::maybe_capture("); - let swap = at("SDL_GL_SwapWindow(app.win);"); + let swap = at("app.surface.swap();"); + assert_eq!(src.matches("app.surface.swap();").count(), 1, "one swap closes the frame"); assert!(begin < draw, "the ledger opens before the frame draws"); assert!(draw < capture && capture < pass, "the capture stream reads before the pass"); assert!(pass < compositor, "the simulator's compositor runs after the pass it models"); diff --git a/rust-modules/src/platform_desktop.rs b/rust-modules/src/platform_desktop.rs index 33d7aaa591..10e0e16d56 100644 --- a/rust-modules/src/platform_desktop.rs +++ b/rust-modules/src/platform_desktop.rs @@ -14,8 +14,10 @@ //! - the video sink is the Feed backend's host sink (`HOST_SINK`) when the build has one, else the //! refusing `NoSink`. //! -//! The shell and the frame probe are plain no-ops: SDL owns the window and its event loop, there is -//! no compositor to hint, no bus to pump and no remote pointer to hide. The secure store is +//! The shell's hooks and the frame probe are plain no-ops, bar the two that bring SDL up and open its +//! window (`init` and `open`, the shell crate's, with nothing around `SDL_Init`): SDL owns the window +//! and its event loop, there is no compositor to hint, no bus to pump and no remote pointer to hide. +//! The secure store is //! `SecureHooks::NONE`: nothing seals, so a session is the 0600 plaintext file the session layer //! writes itself, which the simulator's harnesses plant and read. //! The storage group is `StorageHooks::NONE`: there is no storage helper, so the account's records @@ -27,7 +29,8 @@ //! made one of them reachable would fail to link for want of libwayland, glib or luna-service2, on //! a Mac and on Linux alike. `simulators.yml` links the shapes the simulator ships in to guard that //! until the platform crates split (`docs/platform-ports.md`, W7). -use crate::app::platform::{Composition, FrameProbe, MediaBoot, Platform, Shell}; +use crate::app::platform::{sdl_init, sdl_open, Composition, FrameProbe, InitHooks, MediaBoot, OpenAsk, Platform, Shell, Surface}; +use crate::app::Exit; use plx_os::devcaps::dv::{self, DvCapability, DvProbe, ProbeSource}; use plx_os::tv::toast::{Identity, Outcome, Sent}; use plx_os::tv::{IdentityHooks, LegacyWebosMedia, SecureHooks, Services, StorageHooks, SystemHooks}; @@ -98,12 +101,20 @@ fn deliver_toast(_message: &str, identity: Identity) -> Sent { Sent { reply: None, outcome: Outcome::NoBus } } -/// The desktop shell: SDL owns the window and its event loop, so nothing is bound, grabbed, hinted -/// or pumped, and no surface is ever held. The pointer is a mouse the application does not hide, so -/// hiding and showing it do nothing, and a click is always a real one (the hide is not a cursor swap). +/// The desktop shell: SDL owns the window and its event loop (`init` and `open` are the shell crate's, +/// with no hook around `SDL_Init`), so nothing is bound, grabbed, hinted or pumped, and no surface is +/// ever held. The pointer is a mouse the application does not hide, so hiding and showing it do +/// nothing, and a click is always a real one (the hide is not a cursor swap). struct DesktopShell; impl Shell for DesktopShell { + fn init(&self, mt: &plx_base::task::MainThread) -> Result<(), Exit> { + // SAFETY: `InitHooks::NONE` calls nothing. + unsafe { sdl_init(mt, InitHooks::NONE) } + } + fn open(&self, mt: &plx_base::task::MainThread, ask: &OpenAsk) -> Result, Exit> { + sdl_open(mt, ask) + } fn bind_window(&self, _win: *mut c_void) {} fn grab_surface(&self, _win: *mut c_void) {} fn release_surface(&self) -> bool { diff --git a/rust-modules/src/port.rs b/rust-modules/src/port.rs index 8ce5310957..bef2c7fbe7 100644 --- a/rust-modules/src/port.rs +++ b/rust-modules/src/port.rs @@ -7,7 +7,9 @@ //! platform (`platform_desktop`), which never names this module, so a desktop build compiles the //! television's code and the linker drops it. use crate::app::adapters::backends; -use crate::app::platform::{FrameProbe, MediaBoot, Platform, Shell}; +use crate::app::platform::{sdl_init, sdl_open, FrameProbe, InitHooks, MediaBoot, OpenAsk, Platform, Shell, Surface}; +use crate::app::Exit; +use plx_base::task::MainThread; use std::os::raw::{c_char, c_int, c_void}; #[cfg(all(not(test), feature = "play-feed"))] @@ -53,10 +55,28 @@ static SERVICES: plx_os::tv::Services = plx_os::tv::Services { /// The webOS shell: the SDL window's Wayland surface, the opaque-region hint, the LS2 bus pump and the /// Magic Remote's pointer. The bodies stay in `crate::system` (and `webos::bind_window`); this is the -/// table over them. +/// table over them. SDL itself, and the window it opens, are the shell crate's (`plx_shell_sdl`), which +/// this platform brings up with LG's two boot hooks around `SDL_Init`. struct WebosShell; impl Shell for WebosShell { + fn init(&self, mt: &MainThread) -> Result<(), Exit> { + // SAFETY: both hooks are LG's SDL boot steps (`crate::system`), run on the SDL main thread `mt` + // proves, at the two points `plx_shell_sdl::init::init` calls them: the cursor hint before + // `SDL_Init`, which reads it, and the relaunch tap after, once LG's SDL has filled its slot. + unsafe { + sdl_init( + mt, + InitHooks { + before: crate::system::webos3_cursor_sleep_hint, + after: crate::system::tap_relaunch_payloads, + }, + ) + } + } + fn open(&self, mt: &MainThread, ask: &OpenAsk) -> Result, Exit> { + sdl_open(mt, ask) + } fn bind_window(&self, win: *mut c_void) { plx_os::webos::bind_window(win); } @@ -183,6 +203,41 @@ mod tests { assert_eq!(SERVICES.secure.mode, plx_os::tv::secure::StoreMode::Durable); } + /// **The two LG hooks are the webOS shell's `init`, handed in the order SDL needs.** The shell crate + /// pins the order inside `plx_shell_sdl::init::init` (`before`, then `SDL_Init`, then `after`) and + /// cannot name the hooks; this pins that the webOS shell hands exactly them, the cursor hint as the + /// step BEFORE (SDL reads it in `SDL_Init`, so a hint set after does nothing) and the relaunch tap as + /// the step AFTER (LG's SDL fills the slot it wraps inside `SDL_Init`), once each, and that nothing + /// else in this file names them. Reads the source, like the tests below, because no host test can + /// run LG's SDL. + #[test] + fn the_webos_shell_binds_the_cursor_hint_before_and_the_relaunch_tap_after_sdl_init() { + // The needles are split with `concat!` so this test's own text, which `include_str!` reads too, + // can never be what they match. + let source = include_str!("port.rs"); + let init = source + .split_once(concat!("impl Shell for ", "WebosShell {")) + .expect("the webOS shell") + .1 + .split_once(" fn init(") + .expect("its init") + .1 + .split_once("\n }\n") + .expect("the end of its init") + .0; + let before = concat!("before: crate::system::", "webos3_cursor_sleep_hint,"); + let after = concat!("after: crate::system::", "tap_relaunch_payloads,"); + assert_eq!(init.matches(before).count(), 1, "the cursor hint is `init`'s `before`"); + assert_eq!(init.matches(after).count(), 1, "the relaunch tap is `init`'s `after`"); + assert!(init.find(before) < init.find(after), "`before` is stated first, as it runs first"); + for hook in [ + concat!("crate::system::", "webos3_cursor_sleep_hint"), + concat!("crate::system::", "tap_relaunch_payloads"), + ] { + assert_eq!(source.matches(hook).count(), 1, "{hook} is named by `WebosShell::init` and nowhere else"); + } + } + /// Every `.rs` file under the application crate's `src`, as text. fn crate_sources() -> Vec { fn walk(dir: &std::path::Path, out: &mut Vec) { diff --git a/rust-modules/src/system.rs b/rust-modules/src/system.rs index 48854b2031..c7fbd42b72 100644 --- a/rust-modules/src/system.rs +++ b/rust-modules/src/system.rs @@ -7,7 +7,7 @@ use std::os::raw::{c_int, c_uint, c_void}; const SDL_GL_ALPHA_SIZE: c_int = 3; // SDL_GLattr: RED=0,GREEN=1,BLUE=2,ALPHA=3 -/// `SDL_GL_DEPTH_SIZE` / `SDL_GL_STENCIL_SIZE` — same enum, 6 and 7. `app.rs` asks for zero of +/// `SDL_GL_DEPTH_SIZE` / `SDL_GL_STENCIL_SIZE` — same enum, 6 and 7. `plx_shell_sdl::init` asks for zero of /// both; these read back what the driver actually granted, which is the only thing that settles it. const SDL_GL_DEPTH_SIZE: c_int = 6; const SDL_GL_STENCIL_SIZE: c_int = 7; @@ -142,7 +142,7 @@ pub(crate) fn sys_grab_wayland(winp: *mut c_void) { // television's ES2 context, the only one this runs on, both are legal. glGetIntegerv(GL_DEPTH_BITS, &mut dbits); glGetIntegerv(GL_STENCIL_BITS, &mut sbits); - // `depth=`/`stencil=` are here to be READ: `app.rs` asks for zero of each because nothing + // `depth=`/`stencil=` are here to be READ: `plx_shell_sdl::init` asks for zero of each because nothing // in this renderer uses them, and on a tiler a granted depth buffer is a per-frame // write-back of 1920x1080x2 bytes nobody consumes. A non-zero here means the driver // refused and the saving is not real. @@ -918,6 +918,154 @@ fn cursor_door() -> CursorDoor { }) } +// ---- The LG SDL's boot hooks (moved from `app::boot`, W6) ------------------------------------------- +// +// The two steps a webOS platform runs around `SDL_Init`, which the shell crate (`plx_shell_sdl::init`) +// calls in the order it pins: [`webos3_cursor_sleep_hint`] before it and [`tap_relaunch_payloads`] after +// it. They name LG's SDL fork (its `SDL_webOSCursorVisibility`, its `HELPER_HLunaServiceMessage` slot), +// so they are the webOS platform's and not the stock-SDL shell's; `WebosShell::init` (`port.rs`) is the +// only caller. They compile in every build, a desktop one included, where nothing calls them and the +// linker drops them, like the rest of this file. + +/// **webOS 3.x: shorten LG's own idle hide from about five minutes to five seconds.** Without +/// LG's extension, LG's SDL hides its pointer by itself after `SDL_WEBOS_CURSOR_SLEEP_TIME` of +/// stillness, and its default is about five minutes (timed on a 3.9.3 set, issue #642), where +/// every other app on that television hides it within seconds. Measured on the same set: the value +/// is milliseconds, `5000` hides a still pointer after about five seconds, and a deliberate +/// movement brings it back. Set only where `SDL_webOSCursorVisibility` is absent, so webOS 4+ +/// keeps its SDL's own behaviour. Must run before `SDL_Init`, which reads the hint. +pub(crate) unsafe fn webos3_cursor_sleep_hint() { + if let Some(ms) = cursor_sleep_hint(self_sym("SDL_webOSCursorVisibility").is_some()) { + plx_shell_sdl::set_hint(c"SDL_WEBOS_CURSOR_SLEEP_TIME", ms); + log("cursor: SDL_WEBOS_CURSOR_SLEEP_TIME=5000 (no SDL_webOS* in this SDL)"); + } +} + +/// The idle-hide time to ask SDL for, in milliseconds as a string; `None` where LG's extension is +/// present and its SDL keeps its own behaviour. +fn cursor_sleep_hint(has_lg_extension: bool) -> Option<&'static std::ffi::CStr> { + (!has_lg_extension).then_some(c"5000") +} + +/// **A warm launch's parameters, read where LG's SDL reads its `registerApp` replies.** SAM sends a +/// relaunch's parameters only to the `registerApp` subscriber, which is LG's SDL; its handler +/// (`callback_RegistNativeApp`) raises the window and never reads `parameters`. It fetches every +/// reply's payload through `HELPER_HLunaServiceMessage`, an exported pointer slot that +/// `LoadWEBOSBASELibrary` fills from `libhelpers.so.2` inside `SDL_Init` and that the handler +/// reloads on every call. Wrapping that slot hands a relaunch payload to `tv::launch` and returns +/// it unchanged, so SDL still raises the window. No new Luna registration: SAM refuses the app's +/// own (`tv::launch`). The firmware inventories have the slot from webOS 7.4 on; where it is missing +/// or empty (webOS 4.x to 6.x), nothing changes and callers keep closing the app first. +/// The tap installs only when the slot holds the address `libhelpers.so.2` (already mapped, +/// `RTLD_NOLOAD`) exports as `HLunaServiceMessage` ([`slot_holds`]); any other value is left alone. +pub(crate) unsafe fn tap_relaunch_payloads() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let Some(slot) = self_sym("HELPER_HLunaServiceMessage") else { + log("relaunch tap: no HELPER_HLunaServiceMessage in this SDL"); + return; + }; + // An atomic reference to a misaligned address is undefined behaviour: refuse a symbol that is + // not a word-aligned slot before forming it. + if !slot_aligned(slot as usize) { + log("relaunch tap: slot misaligned \u{2014} not installed"); + return; + } + // SDL's Luna thread may read the slot while it is replaced: store it atomically, after the + // function it forwards to is published. + let slot = &*(slot as *const AtomicUsize); + let wrapped = wrapped_message as *const () as usize; + let current = slot.load(Ordering::Acquire); + if current == 0 || current == wrapped { + log(if current == 0 { "relaunch tap: HELPER_HLunaServiceMessage is empty" } + else { "relaunch tap: already installed" }); + return; + } + // The slot is only ours to wrap while it holds libhelpers' own `HLunaServiceMessage`: another + // value (a different SDL build, a slot of some other type) would be called as a function + // pointer it is not. + let expected = plx_base::dynlib::Handle::open_loaded(&["libhelpers.so.2"]) + .and_then(|(h, _)| h.sym("HLunaServiceMessage")) + .filter(|p| !p.is_null()) + .map(|p| p as usize); + if !slot_holds(current, expected) { + log("relaunch tap: slot does not hold libhelpers' HLunaServiceMessage \u{2014} not installed"); + return; + } + REAL_MESSAGE.store(current, Ordering::Release); + MAIN_THREAD.store(libc::pthread_self() as usize, Ordering::Relaxed); + slot.store(wrapped, Ordering::Release); + log("relaunch tap: installed"); +} + +/// Does the SDL slot hold exactly the function `libhelpers.so.2` exports as `HLunaServiceMessage`? +/// The Thumb bit is compared as `dlsym` and the slot both carry it. `expected` is `None` when +/// libhelpers is not mapped or lacks the symbol, and then nothing holds. +fn slot_holds(current: usize, expected: Option) -> bool { + expected == Some(current) +} + +/// Is `addr` aligned for the `AtomicUsize` the slot is read and written as? +fn slot_aligned(addr: usize) -> bool { + addr % core::mem::align_of::() == 0 +} + +type LunaMessageFn = unsafe extern "C" fn(*mut std::ffi::c_void) -> *const std::ffi::c_char; +static REAL_MESSAGE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static MAIN_THREAD: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// SDL's payload read, passed through. Every Luna reply SDL subscribed to comes through here, so +/// anything that is not a relaunch costs one substring scan and nothing else. +unsafe extern "C" fn wrapped_message(msg: *mut std::ffi::c_void) -> *const std::ffi::c_char { + let real = REAL_MESSAGE.load(std::sync::atomic::Ordering::Acquire); + if real == 0 { + return std::ptr::null(); + } + let real: LunaMessageFn = std::mem::transmute(real); + let p = real(msg); + if !p.is_null() { + let payload = std::ffi::CStr::from_ptr(p).to_string_lossy(); + if payload.contains("\"relaunch\"") { + let main = libc::pthread_self() as usize == MAIN_THREAD.load(std::sync::atomic::Ordering::Relaxed); + log(&format!("relaunch tap: {} bytes on the {} thread, parameters={}", + payload.len(), if main { "main" } else { "other" }, payload.contains("\"parameters\""))); + plx_os::tv::launch::offer(&payload); + } + } + p +} + +#[cfg(test)] +mod relaunch_tap_tests { + use super::slot_holds; + + #[test] + fn relaunch_slot_must_hold_libhelpers() { + assert!(slot_holds(0x1000, Some(0x1000)), "the slot holds libhelpers' function"); + assert!(!slot_holds(0x1000, Some(0x1001)), "a different value, even by the Thumb bit"); + assert!(!slot_holds(0x1000, None), "libhelpers is not mapped or lacks the symbol"); + assert!(!slot_holds(0, None)); + } + + #[test] + fn the_slot_must_be_word_aligned() { + use super::slot_aligned; + let word = core::mem::align_of::(); + assert!(slot_aligned(0x1000) && slot_aligned(word)); + assert!(!slot_aligned(0x1000 + 1) && !slot_aligned(word + word / 2)); + } +} + +#[cfg(test)] +mod cursor_sleep_hint_tests { + use super::*; + + #[test] + fn the_idle_hide_hint_is_asked_for_only_where_lgs_extension_is_absent() { + assert_eq!(cursor_sleep_hint(false), Some(c"5000")); + assert_eq!(cursor_sleep_hint(true), None); + } +} + #[cfg(test)] mod wayland_tests { use super::*; diff --git a/rust-modules/src/textinput.rs b/rust-modules/src/textinput.rs index 20b4f58fff..1354f37947 100644 --- a/rust-modules/src/textinput.rs +++ b/rust-modules/src/textinput.rs @@ -12,11 +12,11 @@ //! `Wayland_CreateDevice` writes four real hooks into `SDL_VideoDevice` //! (`WebOSHasScreenKeyboardSupport`, `Show`, `Hide`, `IsShown`), `SDL_StartTextInput` dispatches to //! the second, and `WebOSShowScreenKeyboard` is a complete `text_model` IME client. Typed text -//! comes back as an ordinary `SDL_TEXTINPUT` event, so `app.rs`'s existing `SDL_PollEvent` loop -//! already sees it. moonlight-tv 1.5.8 shipped exactly this against the TV's own SDL. +//! comes back as an ordinary `SDL_TEXTINPUT` event, so the existing `SDL_PollEvent` loop +//! (`plx_shell_sdl::event`) already sees it. moonlight-tv 1.5.8 shipped exactly this against the TV's own SDL. //! -//! Linking is the plain `extern "C"` case, not `dynlib!`: all 14 firmware images in -//! `tools/fwcompat.py`'s inventories export the whole `SDL_*TextInput*` family. That says nothing +//! Linking is the plain `extern "C"` case (declared in `plx_shell_sdl`'s `sys.rs`), not `dynlib!`: all 14 +//! firmware images in `tools/fwcompat.py`'s inventories export the whole `SDL_*TextInput*` family. That says nothing //! about whether the PANEL rises, though — those are stock public API in every SDL2 build — so //! [`available`] probes at runtime rather than assuming. //! @@ -26,8 +26,10 @@ //! starts at **+16**, not the `+12` that stock SDL 2.0.4's `SDL_events.h` declares. That //! header lies about this build; the NDK sysroot's fork copy is the proof. //! Under `hostsim` the offset really is `+12` — desktop SDL2 is stock — so this is a `cfg`, and -//! a single hard-coded number ships garbage on one of the two platforms. [`TEXT_OFF`] is that -//! `cfg`; `decode_text_at` takes the offset as an argument so `make check` grades both. +//! a single hard-coded number ships garbage on one of the two platforms. `plx_shell_sdl::text::TEXT_OFF` +//! is that `cfg`, and the decoder next to it takes the offset as an argument so `make check` grades +//! both: the byte layout is the shell crate's, and [`decode`] and [`encode_event`] are re-exported +//! from it. //! 2. **`SDL_WINDOW_INPUT_FOCUS` is a precondition.** `SDL_StartTextInput` shows the panel only //! `if (SDL_GetKeyboardFocus())` — the window carrying `0x200` — and our window is created //! `OPENGL | FULLSCREEN` with neither `SHOWN` nor a focus flag. If it is clear, SDL still @@ -58,7 +60,7 @@ //! libSDL3**, and SDL3's text event carries a `char *text` POINTER where SDL2's carries an inline //! `char text[32]`; the compat layer dereferences it while converting the pushed event. Keys and //! pointer clicks survive the same trip only because every field they use is a scalar. So -//! `app.rs`'s `txt:` token drives [`on_event`] directly, and what it proves stops one step short +//! the application's `txt:` token drives [`on_event`] directly, and what it proves stops one step short //! of `SDL_PollEvent`'s own delivery. //! //! Two dead ends, so nobody spends a day on them again: the Luna route (only four @@ -84,58 +86,17 @@ #![allow(dead_code)] use crate::app::SDL_WINDOW_INPUT_FOCUS; -#[cfg(not(test))] -use crate::app::{ - SDL_GetWindowFlags, SDL_HasScreenKeyboardSupport, SDL_StartTextInput, SDL_StopTextInput, -}; -#[cfg(test)] -use host_test_sdl::{ - SDL_GetWindowFlags, SDL_HasScreenKeyboardSupport, SDL_StartTextInput, SDL_StopTextInput, -}; - -/// The four SDL entry points this module calls, stubbed for the HOST TEST BINARY only. -/// -/// `cargo test --lib` links a Mach-O binary against no SDL at all, and unlike every other SDL user -/// in this crate these calls are reachable from ordinary `pub(crate)` functions that a test can -/// touch — `available()` and `start()` are one `screens::search::SearchScreen` call away. An unguarded reference is -/// therefore an undefined symbol at LINK time, which does not fail one test: it stops the whole -/// suite building, exactly as `ff.rs`'s `#[link]` directives used to before that module moved to -/// `dlopen`. SDL is a real link on the device, so the seam here is a `cfg` rather than a `dlopen`. -/// -/// **Only `test` is stubbed.** `hostsim` links desktop SDL2 and takes the real arm — which is the -/// whole point, since the simulator is where the decode path can actually be exercised by typing. -// the stubs carry SDL's own C names ON PURPOSE — `use`d unqualified by the arms below, so the call -// sites read identically in both builds and a signature drift shows up as a type error there -#[allow(non_snake_case)] -#[cfg(test)] -mod host_test_sdl { - use std::os::raw::{c_int, c_void}; - /// No window, so no focus bit — which makes [`super::has_focus`] answer `Some(false)` under - /// test, the same answer a real television gives when the panel cannot rise. - pub(super) unsafe fn SDL_GetWindowFlags(_w: *mut c_void) -> u32 { - 0 - } - /// No panel on the host, matching what the simulator's own boot probe reports (`support=0`). - pub(super) unsafe fn SDL_HasScreenKeyboardSupport() -> c_int { - 0 - } - pub(super) unsafe fn SDL_StartTextInput() {} - pub(super) unsafe fn SDL_StopTextInput() {} -} use plx_base::eventlog::log; -use std::os::raw::{c_int, c_void}; +use std::os::raw::c_void; use std::ptr::{addr_of, addr_of_mut}; -/// `SDL_TEXTINPUTEVENT_TEXT_SIZE` — `char text[32]`, inline in the event rather than a pointer. -/// Both headers agree on the size; they disagree only about where it starts (trap 1). -const TEXT_CAP: usize = 32; - -/// Where that array begins in the raw event bytes. **Trap 1**, and the only number in this file -/// that is wrong on the platform you are not currently building. -/// -/// `cfg!` and not `#[cfg]`, matching `app::decode_key`: both arms stay compiled on both platforms, -/// so the one nobody is building cannot rot into a compile error nobody sees for a month. -const TEXT_OFF: usize = if cfg!(feature = "hostsim") { 12 } else { 16 }; +// What the panel IS (the SDL calls that raise and dismiss it, the focus flag, the driver's own log +// priority) and what an `SDL_TEXTINPUT` event looks like in bytes (LG's fork and stock SDL put the +// text at different offsets, and decoding and encoding are only ever correct as a pair) are the +// stock-SDL shell's: `plx_shell_sdl::text`, which stubs the four SDL calls for a host TEST binary +// (its `test-support` feature, enabled for this crate's tests) exactly as this module did. What +// stays here is the state machine around them and the queue. +pub(crate) use plx_shell_sdl::text::{decode, encode_event}; /// How many un-drained commits to hold before dropping the oldest. /// @@ -181,37 +142,7 @@ static mut WIN: *mut c_void = std::ptr::null_mut(); /// started yet. So [`start`] re-reads it at the one moment it decides anything. pub(crate) fn bind(win: *mut c_void) { unsafe { *addr_of_mut!(WIN) = win }; - trace_driver(); -} - -/// `SDL_LOG_CATEGORY_INPUT` / `SDL_LOG_PRIORITY_DEBUG`, from `SDL_log.h`. -const SDL_LOG_CATEGORY_INPUT: c_int = 3; -const SDL_LOG_PRIORITY_DEBUG: c_int = 2; - -/// Ask LG's SDL to narrate its own keyboard lifecycle into stderr -/// (`/tmp/plxnative-stderr.log`). -/// -/// The driver already logs `[WebOSShowScreenKeyboard] called`, `... called text_model_activate`, -/// `[TextModelLeave] called`, `[TextModelInputPanelState] called - state: %d` and -/// `[WebOSHideScreenKeyboard] called` — at `INPUT`/`DEBUG`, which is below the default priority, -/// so none of it prints. One call makes the whole sequence readable without patching SDL. -/// -/// It is here for a specific open question, not as general noise. Disassembly says the panel -/// cannot be REOPENED because `text_model.leave` NULLs the model *before* calling -/// `SDL_StopTextInput`, so `WebOSHideScreenKeyboard` early-returns and `text_model_deactivate` is -/// never sent — after which the compositor ignores every later `activate`. The decisive -/// observation is whether `[TextModelLeave] called` appears BEFORE our own `stop()`: if it does, -/// the compositor dismissed the panel and that path ran; if it does not, our dismissal sent the -/// deactivate and something else is wrong. One is a five-line mitigation, the other is not. -/// -/// Cheap and permanent: a handful of lines per keyboard session, on a log that is already the -/// primary debugging surface, on a path a user reaches only by opening a text field: Search's, -/// or Settings > Player HUD's "Install from address". -fn trace_driver() { - #[cfg(not(test))] - unsafe { - crate::app::SDL_LogSetPriority(SDL_LOG_CATEGORY_INPUT, SDL_LOG_PRIORITY_DEBUG); - } + plx_shell_sdl::text::trace_driver(); } /// `SDL_GetWindowFlags & SDL_WINDOW_INPUT_FOCUS`, or `None` before [`bind`]. @@ -221,14 +152,14 @@ fn has_focus() -> Option { if win.is_null() { return None; } - Some(SDL_GetWindowFlags(win) & SDL_WINDOW_INPUT_FOCUS != 0) + Some(plx_shell_sdl::text::window_flags(win) & SDL_WINDOW_INPUT_FOCUS != 0) } } /// Does this build/firmware claim a system keyboard? Probed, never assumed — see the module doc. /// A `false` here means the field can still be typed into by other means but no panel will rise. pub(crate) fn available() -> bool { - unsafe { SDL_HasScreenKeyboardSupport() != 0 } + plx_shell_sdl::text::has_screen_keyboard() } /// Raise the keyboard. Idempotent: calling it while the panel is already up is not an error, and @@ -262,7 +193,7 @@ pub(crate) fn start() { None => "?".into(), // bind() was never called — a boot-order bug, not a TV fact } )); - SDL_StartTextInput(); + plx_shell_sdl::text::start_input(); } } @@ -283,7 +214,7 @@ pub(crate) fn stop() { // panel simply never returns — which looks exactly like the driver's own reopen wedge and // is not it. With both transitions logged, one log answers which of the two you have. log("keyboard: stop"); - SDL_StopTextInput(); + plx_shell_sdl::text::stop_input(); } } @@ -352,13 +283,6 @@ pub(crate) fn pending() -> usize { PENDING.with(|pending| pending.borrow().len()) } -/// What [`on_event`] would read out of these bytes, at THIS platform's offset. Exposed so a -/// caller can log the decode without duplicating the choice of offset — which is the one thing in -/// this file that must never be written down twice. -pub(crate) fn decode(ev: &[u8]) -> String { - decode_text_at(ev, TEXT_OFF) -} - /// One `SDL_TEXTINPUT` event, straight off the wire: [`decode`], then [`queue`]. Called by the /// `txt:` remote token (`app/events.rs`), which has the bytes [`encode_event`] built. The event /// loop gets its text already decoded (`HostEvent::Text`) and calls [`queue`] itself. @@ -384,128 +308,11 @@ pub(crate) fn queue(s: String) { }); } -/// The bytes an `SDL_TEXTINPUT` event carries for `text`, in whichever layout [`decode_text_at`] -/// reads — the inverse of it, and, like `app::encode_key`/`app::decode_key`, the pair is only ever -/// correct together. Nothing in the compiler couples them; `encode_decode_round_trips` does. -/// -/// It exists so this seam can be DRIVEN, by `app.rs`'s `txt:` remote token. A real -/// `SDL_TEXTINPUT` needs a human at a keyboard — no trigger raises the panel, and typing into the -/// simulator means somebody physically typing — so without it nothing automated could ever put a -/// character in the search field, on either platform. -/// -/// The bytes are a faithful event in THIS platform's layout, and `txt:` hands them to -/// [`on_event`] rather than to `SDL_PushEvent`: pushing a synthetic `SDL_TEXTINPUT` segfaults -/// inside the Mac's SDL, for the reason recorded at that call site and in the dead ends above. -pub(crate) fn encode_event(text: &str) -> [u8; 128] { - let mut ev = [0u8; 128]; - ev[0..4].copy_from_slice(&crate::app::SDL_TEXTINPUT.to_ne_bytes()); - // `text[32]` holds at most 31 bytes plus its terminator — and the cut must land on a CHAR - // BOUNDARY. Slicing a codepoint in half would make the decoder answer U+FFFD for text that - // was perfectly valid when it was written, which reads as a decoder bug and is not one. - let mut n = text.len().min(TEXT_CAP - 1); - while n > 0 && !text.is_char_boundary(n) { - n -= 1; - } - ev[TEXT_OFF..TEXT_OFF + n].copy_from_slice(&text.as_bytes()[..n]); - ev -} - -/// The committed text in a raw `SDL_TEXTINPUT` event whose `text[]` begins at `off`. -/// -/// Pure, and offset-parameterised rather than reading [`TEXT_OFF`] itself, so `make check` can -/// grade BOTH platforms' layouts on a host that only ever builds one of them — the same reason -/// `app::decode_key` and `app::encode_key` are pure and tested as a pair. -/// -/// Every failure mode here is a byte string somebody else chose: the panel's own IME writes this -/// field, and the app cannot afford a panic inside the SDL event loop (see `remote.rs`, where -/// exactly that class took the app down). So a short buffer, a missing NUL and invalid UTF-8 are -/// all answers, not faults. -fn decode_text_at(ev: &[u8], off: usize) -> String { - // `min(ev.len())` before the slice, not after: `text[32]` is the LAST field of the event, so a - // truncated or short buffer is the ordinary case at the end of the struct, not a malformed one. - let end = off.saturating_add(TEXT_CAP).min(ev.len()); - let Some(field) = ev.get(off..end) else { - return String::new(); // off past the end — `get` refuses the inverted range rather than panicking - }; - // NUL-terminated INSIDE a fixed array: the terminator is the length, and everything after it - // is whatever the last, longer commit left behind. - let n = field.iter().position(|&b| b == 0).unwrap_or(field.len()); - // The two edges of a codepoint the fixed array may have CUT — see `drop_cut_tail`. The tail - // rule is conditional on the array being FULL (`n == TEXT_CAP`), which is the signature of a - // cut; the head rule is unconditional, because no UTF-8 string may begin with a continuation - // byte under any circumstances. Deliberately NOT `n == field.len()`, which is also true when - // the CALLER's buffer ran out before `text[32]` did — a short buffer is the reader's limit, - // not the panel's, and there is nothing to say the panel cut anything at all. - let text = drop_orphan_head(&field[..n]); - let text = if n == TEXT_CAP { - drop_cut_tail(text) - } else { - text - }; - // Lossy, never `from_utf8`: a single bad byte would otherwise discard the whole commit — and - // an IME that emits one is a keystroke the user typed, not an attack. - String::from_utf8_lossy(text).into_owned() -} - -/// Drop a trailing UTF-8 sequence that is well-formed so far but CUT SHORT by the end of the -/// buffer. Everything else — a lone continuation byte, an overlong or out-of-range lead, a -/// surrogate — is left for `from_utf8_lossy` to answer with U+FFFD, because a replacement character -/// is the only visible signal that something arrived broken and it must not be swallowed. -/// -/// **This is LG checklist row #16** (`docs/lg-self-checklist.md` §2), which asks that the character -/// which arrives be the character that was pressed. `text[32]` is a fixed array, so a commit that -/// fills it is cut at a BYTE, and that cut lands mid-codepoint for any query that is not pure -/// ASCII. Decoded lossily, the surviving half becomes a `` the user never typed, in their search -/// field — exactly the substitution the row is about. Nothing can recover the character (its other -/// half is not in this event), so the honest answer is the text that WAS whole. -/// -/// **The classification is `std`'s, not ours.** `Utf8Error::error_len() == None` is precisely -/// "valid so far, ended mid-sequence", and `valid_up_to()` is where to cut — where a hand-rolled -/// lead-byte width table accepts `0xC0`, `0xF5..=0xF7` and surrogate pairs as merely "incomplete" -/// and deletes real corruption without a trace. Only the LAST sequence is offered to it (walk back -/// at most four bytes to the first non-continuation byte; no sequence is longer), so an interior -/// error earlier in the commit cannot suppress the tail rule. -/// -/// **Belt-and-braces for a case this project has not settled.** Stock SDL2 fills `text[32]` with -/// `SDL_utf8strlcpy`, which truncates on a character boundary and always terminates — so on stock -/// SDL this branch is unreachable, and `encode_event` cuts on a boundary too, which is why nothing -/// the simulator or the `txt:` token can drive reaches it either. Whether **LG's fork** does the -/// same is a question for the television's own `libSDL2`, not for a header or another client: -/// `.agents/skills/decompile-tv-lib/` is how the `+16 inputSource` offset above was settled, and it -/// is how this would be. Until then the branch costs one comparison and cannot make a correct -/// commit wrong. -fn drop_cut_tail(b: &[u8]) -> &[u8] { - for back in 1..=b.len().min(4) { - let i = b.len() - back; - if b[i] & 0xC0 == 0x80 { - continue; // a continuation byte — the sequence it belongs to starts further back - } - return match std::str::from_utf8(&b[i..]) { - Err(e) if e.error_len().is_none() => &b[..i], - _ => b, - }; - } - b // nothing but continuation bytes: garbage, and `from_utf8_lossy`'s to answer -} - -/// The other edge of the same cut: drop a leading run of continuation bytes. -/// -/// If the panel really does split a codepoint at `text[32]`, the half [`drop_cut_tail`] discards -/// arrives at the START of the NEXT commit — orphaned, with its lead byte in the event before it. -/// Left alone those bytes are one U+FFFD each, which is the row-#16 substitution again, one -/// character later; dropping the head is what makes the rule whole rather than one-sided. -/// -/// Unconditional, and safe to be: **no UTF-8 string may begin with a continuation byte**, so this -/// can only ever remove bytes that were already unreadable — never a character the user typed. -fn drop_orphan_head(b: &[u8]) -> &[u8] { - let n = b.iter().take_while(|&&c| c & 0xC0 == 0x80).count(); - &b[n..] -} - // --------------------------------------------------------------------------------------- #[cfg(test)] mod tests { use super::*; + use plx_shell_sdl::text::TEXT_OFF; use std::sync::Mutex; /// `STARTED` is a module singleton (and `PENDING` is per thread, but these tests drive both @@ -515,7 +322,7 @@ mod tests { static BUF: Mutex<()> = Mutex::new(()); /// A synthetic event in one platform's layout: type at +0, the text at `off`, NUL-terminated - /// if it fits. `[u8; 128]` because that is what `app.rs` polls into. + /// if it fits. `[u8; 128]` because that is what `plx_shell_sdl::event::poll` reads into. fn ev_with(off: usize, text: &[u8]) -> [u8; 128] { let mut ev = [0u8; 128]; ev[0..4].copy_from_slice(&0x303u32.to_ne_bytes()); // SDL_TEXTINPUT @@ -523,257 +330,6 @@ mod tests { ev } - /// **The trap this whole file is shaped around.** LG's fork inserts `Uint32 inputSource` at - /// +12, so the text is at +16 on the television and at +12 on a desktop. A single hard-coded - /// offset does not fail loudly on the wrong platform — it reads four bytes of `windowID` (or - /// of the text's own head) and commits plausible garbage into the search field. - #[test] - fn the_text_decodes_at_both_platforms_offsets() { - assert_eq!(decode_text_at(&ev_with(16, b"webos"), 16), "webos"); - assert_eq!(decode_text_at(&ev_with(12, b"desktop"), 12), "desktop"); - // …and reading one layout with the other's offset is exactly the silent corruption above: - // at +16 a stock event is four bytes into the text, and at +12 a fork event is inside - // `inputSource`, which is zero — an empty commit. - assert_eq!(decode_text_at(&ev_with(12, b"desktop"), 16), "top"); - assert_eq!(decode_text_at(&ev_with(16, b"webos"), 12), ""); - } - - /// The ordinary case: a short string in a fixed 32-byte array, terminated by NUL. Everything - /// after the terminator is the tail of some LONGER earlier commit, and must not be returned. - #[test] - fn a_nul_terminates_the_string_inside_the_fixed_array() { - let mut ev = ev_with(16, b"ab\0cdefghijklmnop"); - ev[16 + 31] = b'!'; // …up to and including the last byte of text[32] - assert_eq!(decode_text_at(&ev, 16), "ab"); - } - - /// A commit that fills `text[32]` completely has NO terminator — the array is the length. A - /// decoder that insists on finding a NUL reads past the field into `SDL_Event`'s padding. - #[test] - fn a_full_32_byte_commit_has_no_terminator() { - let text = [b'x'; TEXT_CAP]; - let ev = ev_with(16, &text); - assert_eq!(decode_text_at(&ev, 16), "x".repeat(TEXT_CAP)); - } - - /// Invalid UTF-8 must not panic. This runs inside the SDL event loop, where a panic unwinds - /// out of `plex_run` and takes the app with it — `remote.rs` lost the app exactly this way to - /// a multi-byte whitespace. The bytes come from the television's own IME, so "that cannot - /// happen" is not a thing this file gets to assume. - #[test] - fn invalid_utf8_is_replaced_rather_than_panicking() { - let s = decode_text_at(&ev_with(16, b"a\xffb"), 16); - assert_eq!(s, "a\u{fffd}b"); - // A bad byte in the MIDDLE keeps its replacement whatever surrounds it — it is neither - // edge of a cut, so neither trim rule can claim it. (A LEADING continuation byte is the - // orphan case and IS dropped; `a_commit_orphaned_from_its_lead_byte_is_dropped_rather_ - // than_replaced` owns that, and `\x80` alone belongs to it rather than here.) - assert_eq!(decode_text_at(&ev_with(16, b"x\x80y"), 16), "x\u{fffd}y"); - assert_eq!(decode_text_at(&ev_with(16, b"x\xc0y"), 16), "x\u{fffd}y"); - } - - /// **Row #16: a codepoint the fixed array CUT must not arrive as a character nobody typed.** - /// `text[32]` has no room for the tail of a sequence that starts at its last byte, so a lossy - /// decode puts a `` in the user's query — the exact substitution the checklist row is about. - /// The whole prefix is kept; only the half codepoint goes. - #[test] - fn a_codepoint_cut_by_the_end_of_the_field_is_dropped_not_replaced() { - // Each width of lead byte, cut at every point that leaves it incomplete. - for (lead, whole) in [(0xc3u8, "é"), (0xe5, "千"), (0xf0, "🎬")] { - let need = whole.len(); - for kept in 1..need { - let mut raw = vec![b'y'; TEXT_CAP - kept]; - raw.extend_from_slice(&whole.as_bytes()[..kept]); - assert_eq!(raw.len(), TEXT_CAP); - let got = decode_text_at(&ev_with(16, &raw), 16); - assert_eq!( - got, - "y".repeat(TEXT_CAP - kept), - "lead {lead:#x}, {kept} of {need} bytes" - ); - assert!( - !got.contains('\u{fffd}'), - "a cut must not invent a character" - ); - } - // …and the same codepoint that FITS is untouched, which is what proves the rule cuts - // only what was actually truncated. - let mut raw = vec![b'y'; TEXT_CAP - need]; - raw.extend_from_slice(whole.as_bytes()); - assert_eq!( - decode_text_at(&ev_with(16, &raw), 16), - format!("{}{whole}", "y".repeat(TEXT_CAP - need)) - ); - } - } - - /// A TERMINATED commit is as long as the panel meant it to be, so a malformed tail inside one - /// is genuine garbage and keeps the defensive replacement — the cut rule must not swallow it. - /// Neither may a SHORT BUFFER be read as a cut: that is the caller's limit, not the panel's. - #[test] - fn a_bad_tail_before_a_terminator_still_replaces_rather_than_vanishing() { - // `ab` + a bare 3-byte lead + NUL: nothing cut this, the byte is simply wrong. - assert_eq!(decode_text_at(&ev_with(16, b"ab\xe5\0"), 16), "ab\u{fffd}"); - // …and a buffer that ends mid-codepoint is the READER running out, so the tail rule stays - // off and the bad byte is still reported. - assert_eq!( - decode_text_at(&ev_with(16, "é".as_bytes())[..17], 16), - "\u{fffd}" - ); - } - - /// **A byte no cut could have produced keeps its replacement.** The rule is "valid so far, - /// ended mid-sequence" and nothing looser — a hand-rolled lead-byte width table calls all of - /// these merely incomplete and deletes them, which turns real corruption from the panel's IME - /// into a silent shortening with no signal at all. `std::str::from_utf8` draws the line. - #[test] - fn corruption_that_is_not_a_cut_is_reported_rather_than_deleted() { - for (name, tail) in [ - ("overlong lead", &[0xC0u8][..]), - ("out-of-range lead", &[0xF5][..]), - ("never-a-lead byte", &[0xFF][..]), - ("surrogate half", &[0xED, 0xA0][..]), - ] { - let mut raw = vec![b'y'; TEXT_CAP - tail.len()]; - raw.extend_from_slice(tail); - let got = decode_text_at(&ev_with(16, &raw), 16); - assert!( - got.contains('\u{fffd}'), - "{name} must survive as a replacement, got {got:?}" - ); - } - } - - /// The other edge of the same cut: a commit ORPHANED from its lead byte — the remainder of a - /// codepoint the previous event was cut inside — must not arrive as one U+FFFD per byte, which - /// is the row-#16 substitution again, one character later. - #[test] - fn a_commit_orphaned_from_its_lead_byte_is_dropped_rather_than_replaced() { - // "🎬" is F0 9F 8E AC; cut after F0, the next commit opens with its three tail bytes. - assert_eq!( - decode_text_at(&ev_with(16, b"\x9f\x8e\xacstar"), 16), - "star" - ); - // …and a commit that is nothing BUT an orphaned remainder yields nothing, rather than one - // replacement character per byte. - assert_eq!(decode_text_at(&ev_with(16, b"\x80"), 16), ""); - // …and a commit that legitimately STARTS with a multi-byte character is untouched. - assert_eq!( - decode_text_at(&ev_with(16, "🎬star".as_bytes()), 16), - "🎬star" - ); - } - - /// **Capital and small letters transfer as themselves.** The panel's Shift/Caps is resolved on - /// the television — it commits the CASED character — so the app's whole obligation is to carry - /// the bytes through without touching them, and this is what proves it does. (A decoder that - /// normalised case would be invisible until someone searched for a title that differs only by - /// it.) Deliberately cites no checklist row number: `docs/lg-self-checklist.md` records no such - /// row, and a number this repo cannot corroborate does not belong in a permanent comment. - #[test] - fn letter_case_transfers_exactly_as_the_panel_committed_it() { - for s in [ - "A", "a", "Wallace", "WALLACE", "wallace", "WaLlAcE", "Ç", "ç", "Ä", "ä", - ] { - assert_eq!(decode_text_at(&ev_with(16, s.as_bytes()), 16), s); - assert_eq!(decode_text_at(&encode_event(s), TEXT_OFF), s); - } - } - - /// **Row #16, its own worked example.** The checklist names the full-width `\` (U+FF3C) and - /// asks that it not arrive as a backslash — the substitution a keyboard stack makes when it - /// folds full-width forms to ASCII, and the one a byte-oriented decoder makes when it reads one - /// of the three bytes of a full-width form on its own. - /// - /// The `lookalike` column is not a second assertion (the equality above already implies it); - /// it is the table saying what each row is FOR, so the next reader can tell a deliberate pair - /// from an arbitrary one. The rest are the characters a VKB commonly substitutes or a layer - /// below eats — the shell and URL metacharacters, and the quote pair a keyboard "smartens". - #[test] - fn a_full_width_character_is_not_folded_to_its_ascii_lookalike() { - for (typed, _lookalike) in [ - ("\", "\\"), // U+FF3C FULLWIDTH REVERSE SOLIDUS — the row's own example - ("¥", "\\"), // U+FFE5, the same key on a JP panel, and the same wrong answer - ("/", "/"), - (":", ":"), - (" ", " "), // U+3000 IDEOGRAPHIC SPACE - ("“", "\""), - ("’", "'"), - ("-", "-"), - ] { - let got = decode_text_at(&ev_with(16, typed.as_bytes()), 16); - assert_eq!( - got, typed, - "the character pressed must be the character that arrives" - ); - assert_eq!(decode_text_at(&encode_event(typed), TEXT_OFF), typed); - } - // The ASCII originals still arrive as themselves — nothing here rewrites in either - // direction. `\` is the one the row calls out, and the rest are what a URL layer or a - // shell would eat if anything on the path were not byte-transparent. - for s in [ - "\\", "/", "&", "%", "+", "#", "?", "=", "\"", "'", "<", ">", " ", "\t", - ] { - assert_eq!(decode_text_at(&ev_with(16, s.as_bytes()), 16), s); - } - } - - /// A buffer that ends before (or inside) the text field is an answer, not a fault. `SDL_Event` - /// is a union and nothing guarantees a caller polled into 128 bytes. - #[test] - fn a_short_buffer_yields_an_empty_string() { - assert_eq!(decode_text_at(&[0u8; 8], 16), ""); - assert_eq!(decode_text_at(&[], 16), ""); - // Ending mid-field returns the part that IS there, rather than nothing. - let ev = ev_with(16, b"abcdef"); - assert_eq!(decode_text_at(&ev[..19], 16), "abc"); - } - - /// Multi-byte UTF-8 survives intact — the field is bytes, not characters, and a European or - /// CJK query is the normal case for a media library. - #[test] - fn multibyte_text_round_trips() { - assert_eq!( - decode_text_at(&ev_with(16, "Amélie".as_bytes()), 16), - "Amélie" - ); - assert_eq!( - decode_text_at(&ev_with(16, "千と千尋".as_bytes()), 16), - "千と千尋" - ); - } - - /// The encoder writes what the decoder reads, on whichever platform this is — the pair that - /// nothing but this test couples. `app.rs` already lost the simulator's whole remote FIFO to - /// exactly this: `encode_key` wrote LG's layout while `decode_key` had been taught stock - /// SDL2's, so every token was accepted and nothing moved. - #[test] - fn encode_decode_round_trips() { - for s in ["a", "wallace", "Amélie", "千と千尋", "star wars"] { - assert_eq!(decode_text_at(&encode_event(s), TEXT_OFF), s); - } - } - - /// Over-long text is cut to fit `text[32]`, and the cut lands on a CHAR BOUNDARY — a codepoint - /// sliced in half would come back as U+FFFD and look like a decoder fault. - #[test] - fn an_over_long_commit_is_cut_on_a_char_boundary() { - let long = "x".repeat(100); - assert_eq!( - decode_text_at(&encode_event(&long), TEXT_OFF), - "x".repeat(TEXT_CAP - 1) - ); - // 16 CJK codepoints = 48 bytes: the 31-byte limit falls mid-codepoint, so the cut must - // back up to 30 bytes (10 characters) rather than emit a replacement character. - let cjk = "千".repeat(16); - let got = decode_text_at(&encode_event(&cjk), TEXT_OFF); - assert_eq!(got, "千".repeat(10)); - assert!( - !got.contains('\u{fffd}'), - "the cut must not split a codepoint" - ); - } - /// Commits queue in order and `drain` takes them exactly once — the caller appends them to the /// query, so a duplicate is a doubled character and a lost one is a dropped keystroke. #[test] diff --git a/rust-modules/ui/src/consts.rs b/rust-modules/ui/src/consts.rs index fe4d104344..69a25e4a3d 100644 --- a/rust-modules/ui/src/consts.rs +++ b/rust-modules/ui/src/consts.rs @@ -315,9 +315,9 @@ pub enum Key { /// After the directions the order is the ladder's own — pointer, OK, PAUSE, PLAY, STOP, BACK. The /// two alternate D-pad codes are resolved up here beside the plain ones rather than down where the /// scrub arm tests them, so a pair carrying one of those AND a transport code resolves as the -/// direction rather than as the transport key. Both fields describe ONE press — `app.rs`'s -/// `decode_key` reads them off a single event and its `remote_token_key` builds each synthetic -/// pair from a single token — so a pair naming two DIFFERENT keys is not a shape either path is +/// direction rather than as the transport key. Both fields describe ONE press — the shell's +/// `plx_shell_sdl::event::decode_key` reads them off a single event and the application's `remote_token_key` builds each +/// synthetic pair from a single token — so a pair naming two DIFFERENT keys is not a shape either path is /// built to carry; the order above settles it rather than leaving it to whichever test came first. pub fn classify(sym: c_uint, wcode: c_uint) -> Key { match sym { @@ -464,7 +464,7 @@ pub fn page_dir(sym: c_uint, wcode: c_uint) -> Option { /// number buttons ([`pin_digit`], which owns that behaviour). /// /// **The `sym` field ONLY, and that is a deliberate divergence from [`pin_digit`], which also reads -/// the range out of `wcode`.** `wcode` is a SCANCODE (`app.rs::decode_key`), and 48–57 there are +/// the range out of `wcode`.** `wcode` is a SCANCODE (`plx_shell_sdl::event::decode_key`), and 48–57 there are /// not digits at all: they are `]` `\` `#` `;` `'` `` ` `` `,` `.` `/` and CapsLock. The digits' /// scancodes are 30–39 — which is exactly why 33/34 turned out to be `4` and `5` a few dozen lines /// up. Mirroring [`pin_digit`] would put the retired mis-reading straight back into the gate this diff --git a/tools/build-bench.py b/tools/build-bench.py index 6a0cbd9cfc..098c53f227 100755 --- a/tools/build-bench.py +++ b/tools/build-bench.py @@ -59,7 +59,7 @@ leaf-inc `leaf` with CARGO_INCREMENTAL=1 in rust-modules/target-fast (the `make test-fast` tree). hub-inc `hub`, incremental. The two -inc rows are skipped with a note when target-fast is absent, unless `--cold` (which builds it, untimed, first). - tests the default-feature unit suite (`cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_owp`, run through + tests the default-feature unit suite (`cargo test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_net -p plx_ui -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_playback_contract -p plx_play_uri -p plx_play_feed -p plx_media_codecs -p plx_appkit -p plx_screens -p plx_shell_sdl -p plx_owp`, run through tools/cargo-test-parallel.py exactly as the Makefile's recipes do) on a warm tree; the `test result:` counts of every crate are summed. arm the ARM staticlib line (`cargo rustc ... --crate-type staticlib`) after touching lib.rs, @@ -161,7 +161,7 @@ # The cargo subcommand skeletons the Makefile's recipes use. Everything else (toolchain, dirs, # feature flags, RUSTFLAGS) comes from `make -s print-bench-config`. ci/test_build_bench.py compares # these to the recipes in the Makefile. -HOST_TEST_ARGS = ("test", "--lib", "-p", "plxnative-modules", "-p", "plx_base", "-p", "plx_machine", "-p", "plx_os", "-p", "plx_gfx", "-p", "plx_net", "-p", "plx_ui", "-p", "plx_plex", "-p", "plx_telemetry", "-p", "plx_data", "-p", "plx_session", "-p", "plx_media", "-p", "plx_playback_contract", "-p", "plx_play_uri", "-p", "plx_play_feed", "-p", "plx_media_codecs", "-p", "plx_appkit", "-p", "plx_screens", "-p", "plx_owp") +HOST_TEST_ARGS = ("test", "--lib", "-p", "plxnative-modules", "-p", "plx_base", "-p", "plx_machine", "-p", "plx_os", "-p", "plx_gfx", "-p", "plx_net", "-p", "plx_ui", "-p", "plx_plex", "-p", "plx_telemetry", "-p", "plx_data", "-p", "plx_session", "-p", "plx_media", "-p", "plx_playback_contract", "-p", "plx_play_uri", "-p", "plx_play_feed", "-p", "plx_media_codecs", "-p", "plx_appkit", "-p", "plx_screens", "-p", "plx_shell_sdl", "-p", "plx_owp") HOST_TEST_BUILD_ARGS = HOST_TEST_ARGS + ("--no-run", "--message-format=json") ARM_ARGS_HEAD = ("rustc",) # then the Makefile's ARM_PROFILE_FLAG (`--release` / `--profile tvdev`) ARM_ARGS_TARGET = ("--target",) # then the target triple diff --git a/tools/screenshots.py b/tools/screenshots.py index fffc7609a7..9da8e22fbd 100755 --- a/tools/screenshots.py +++ b/tools/screenshots.py @@ -251,7 +251,7 @@ def png_size(png): def fit_capture(png, w, h): """The capture at exactly `w`x`h` (the canvas times the scene's render scale), which `output_spec`'s crops assume. The simulator writes its DRAWABLE, which it now sizes to the canvas on any display density - (`app::boot::plan_desktop_window`), so a capture arrives at exactly `w`x`h` and passes through untouched. + (`plx_shell_sdl::window::plan_desktop_window`), so a capture arrives at exactly `w`x`h` and passes through untouched. A binary from before that had a drawable 2x the window on a HiDPI display (a Retina Mac): 3840x2160 for the 1920x1080 canvas, whose top-left quadrant a canvas-sized crop then cut, a Library that looked zoomed 2x. That is what this still guards: a whole multiple is downscaled (Lanczos, bit-exact); anything else is refused.""" From 7ceb6f76f6740bb47619212d55b9ca9621efbab8 Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Sat, 21 Nov 2026 01:33:28 +0300 Subject: [PATCH 22/26] With no playback driver composed, Detail disables what plays and every composition is tested through the planner (#1494) Step W6c of the platform plan (discussion #1460). Tests prove that each playback composition a platform can publish plays an ordinary title or refuses it with a typed reason, through the real planner: URI only, a source the driver declines, no driver (a typed refusal before any PMS decision or encoder request) and both drivers (a qualified URI original before the Feed original, on the URI tie-break of Target shape 6d). `media/src/route/ decision_composition_tests.rs` uses the contract's `FakeUriDriver`; `src/app/run_uri_boot_tests.rs` boots the real product driver over the lifecycle rig. No planner change was needed. When a platform composes no playback driver, which only the Tizen emulator MVP (W9) will, the screens say so instead of failing on a press. webOS composes both drivers and the desktop composes Feed, so neither draws or behaves differently. - `ScreenInputs.backends` is the set the session was told at boot, filled by `bridge.rs` in `publish_player_presentation`. A cold or controlled host keeps the default, Feed; `can_play()` is true when either driver is present. - Detail's Play, Restart and Trailer (`HeroCtl::starts_playback`) draw the shared disabled idiom (`Button::enabled(false)`, and a new `CircleButton::enabled` that follows `Button` and `TransportButton`), own no focus stop, and do nothing on a press. The facts line's play-mode clause shows one word, "Playback unavailable" (`browse.detail.no_playback`, in all twelve languages), through the existing `Bit::Word` path. - Detail never leaves a focus the page chose on a control that writes to the account (the Watchlist disc and the watched toggle, `HeroCtl::writes_account`). With no driver, a fresh open marks its focus as the page's own (`DetailScreen::provisional`, after the screens guide's "a seat nobody chose follows the head"), and while it is, `reconcile` answers `default_elem`: the row's first stop that writes nothing, else the first section below the row, seated through the engine's own `Focusable::seat`. The item landing, a later landing, a restore waiting on a season and a restore that retires all re-seat by that rule. The claim ends when the viewer moves, presses OK on a landed page, or holds to open a menu. A restore that names the control the viewer left keeps it, and the write controls stay reachable by travel. With a driver composed, Play stays the default and nothing changes. - The Version list's rows are disabled `FormSection` rows with one note giving the reason; OK on one does nothing and BACK closes the panel. `AppMsg::PlayVersion` asks for no play. - The hero trailer preview is refused when no Feed is composed, through the preview machine's existing refusal path (`Fact::RefusedDirect`, `Settle::Refused`), before any metadata, PlayQueue, decision or encoder request, with no standing verdict, no Error read-out and no failure report. `Preview` gains no variant: it describes how the server delivers an item, and "this build has no driver" is a platform fact. Every existing fixture renders as before (`make check-replay`: SAME=4 REFUSED_EXPECTED=8 unexpected=0). Other Play entry points (the card item menu, Continue Watching on OK, episode rows, Extras) rely on the planner's typed refusal and draw nothing new. --- locales/be/browse.json | 1 + locales/ca/browse.json | 1 + locales/de/browse.json | 1 + locales/en/browse.json | 4 + locales/es/browse.json | 1 + locales/fr/browse.json | 1 + locales/hu/browse.json | 1 + locales/it/browse.json | 1 + locales/nl/browse.json | 1 + locales/pl/browse.json | 1 + locales/pt/browse.json | 1 + locales/ru/browse.json | 1 + rust-modules/appkit/src/version_list.rs | 58 +- .../src/route/decision_composition_tests.rs | 273 ++++++ .../media/src/route/decision_version_tests.rs | 3 + rust-modules/media/src/route/mod.rs | 3 + rust-modules/screens/src/CLAUDE.md | 11 +- .../screens/src/detail/geometry_tests.rs | 1 + rust-modules/screens/src/detail/hero.rs | 211 +++- .../src/detail/hero_watchlist_tests.rs | 10 +- .../screens/src/detail/identity_tests.rs | 2 +- rust-modules/screens/src/detail/mod.rs | 202 +++- .../screens/src/detail/no_driver_tests.rs | 901 ++++++++++++++++++ rust-modules/screens/src/detail/tests.rs | 64 +- rust-modules/screens/src/inputs.rs | 17 +- rust-modules/screens/src/item_menu.rs | 2 +- rust-modules/screens/src/registry.rs | 4 +- rust-modules/screens/src/versions_panel.rs | 69 +- rust-modules/src/app/bridge.rs | 32 +- rust-modules/src/app/content.rs | 107 ++- rust-modules/src/app/detail_panel_tests.rs | 49 +- rust-modules/src/app/run_uri_boot_tests.rs | 198 ++++ rust-modules/ui/src/focus.rs | 6 +- rust-modules/ui/src/widgets.rs | 30 +- .../ui/src/widgets_control_face_tests.rs | 27 + 35 files changed, 2161 insertions(+), 134 deletions(-) create mode 100644 rust-modules/media/src/route/decision_composition_tests.rs create mode 100644 rust-modules/screens/src/detail/no_driver_tests.rs diff --git a/locales/be/browse.json b/locales/be/browse.json index 2c4e00c527..c656f94c1b 100644 --- a/locales/be/browse.json +++ b/locales/be/browse.json @@ -51,6 +51,7 @@ "browse.detail.converts": "Канвертуецца на серверы", "browse.detail.direct_play": "Прамое прайграванне", "browse.detail.direct_stream": "Прамы паток", + "browse.detail.no_playback": "Прайграванне недаступнае", "browse.detail.original_audio_converted": "Арыгінал · гук канвертаваны", "browse.detail.hardware_needs": "апаратнае канвертаванне патрабуе", "browse.detail.tonemap_needs": "танальная кампрэсія патрабуе", diff --git a/locales/ca/browse.json b/locales/ca/browse.json index 8dcf71776b..cef69551d2 100644 --- a/locales/ca/browse.json +++ b/locales/ca/browse.json @@ -51,6 +51,7 @@ "browse.detail.converts": "Es converteix al servidor", "browse.detail.direct_play": "Reproducció directa", "browse.detail.direct_stream": "Transmissió directa", + "browse.detail.no_playback": "Reproducció no disponible", "browse.detail.original_audio_converted": "Original · àudio convertit", "browse.detail.hardware_needs": "la conversió per maquinari requereix", "browse.detail.tonemap_needs": "el mapatge de tons requereix", diff --git a/locales/de/browse.json b/locales/de/browse.json index ea39af0e7c..d969bf4903 100644 --- a/locales/de/browse.json +++ b/locales/de/browse.json @@ -51,6 +51,7 @@ "browse.detail.converts": "Wird auf dem Server konvertiert", "browse.detail.direct_play": "Direktwiedergabe", "browse.detail.direct_stream": "Direkt-Stream", + "browse.detail.no_playback": "Wiedergabe nicht verfügbar", "browse.detail.original_audio_converted": "Original · Audio konvertiert", "browse.detail.hardware_needs": "Hardware-Konvertierung erfordert", "browse.detail.tonemap_needs": "Tone-Mapping erfordert", diff --git a/locales/en/browse.json b/locales/en/browse.json index a3f59728ed..f95cf2d19f 100644 --- a/locales/en/browse.json +++ b/locales/en/browse.json @@ -207,6 +207,10 @@ "value": "Direct Stream", "description": "browse detail direct_stream" }, + "browse.detail.no_playback": { + "value": "Playback unavailable", + "description": "Detail-page play-mode clause beside the disabled Play pill when this device composes no playback driver at all." + }, "browse.detail.original_audio_converted": { "value": "Original · audio converted", "description": "Detail-page playback label when the picture is copied untouched and only the audio of the track that will play is converted by the server." diff --git a/locales/es/browse.json b/locales/es/browse.json index 393d996b77..1d267a33e0 100644 --- a/locales/es/browse.json +++ b/locales/es/browse.json @@ -51,6 +51,7 @@ "browse.detail.converts": "Se convierte en el servidor", "browse.detail.direct_play": "Reproducción directa", "browse.detail.direct_stream": "Transmisión directa", + "browse.detail.no_playback": "Reproducción no disponible", "browse.detail.original_audio_converted": "Original · audio convertido", "browse.detail.hardware_needs": "la conversión por hardware requiere", "browse.detail.tonemap_needs": "el mapeo de tonos requiere", diff --git a/locales/fr/browse.json b/locales/fr/browse.json index c4cfffa7cf..2ea63b76fc 100644 --- a/locales/fr/browse.json +++ b/locales/fr/browse.json @@ -51,6 +51,7 @@ "browse.detail.converts": "Converti sur le serveur", "browse.detail.direct_play": "Lecture directe", "browse.detail.direct_stream": "Flux direct", + "browse.detail.no_playback": "Lecture indisponible", "browse.detail.original_audio_converted": "Original · audio converti", "browse.detail.hardware_needs": "conversion matérielle requise", "browse.detail.tonemap_needs": "mappage tonal requis", diff --git a/locales/hu/browse.json b/locales/hu/browse.json index 7c2e96d453..92787931dd 100644 --- a/locales/hu/browse.json +++ b/locales/hu/browse.json @@ -51,6 +51,7 @@ "browse.detail.converts": "Konvertálás a szerveren", "browse.detail.direct_play": "Közvetlen lejátszás", "browse.detail.direct_stream": "Közvetlen stream", + "browse.detail.no_playback": "A lejátszás nem érhető el", "browse.detail.original_audio_converted": "Eredeti · konvertált hang", "browse.detail.hardware_needs": "a hardveres konvertáláshoz szükséges:", "browse.detail.tonemap_needs": "a tónusleképezéshez szükséges:", diff --git a/locales/it/browse.json b/locales/it/browse.json index ef726532ed..5f6ab67c82 100644 --- a/locales/it/browse.json +++ b/locales/it/browse.json @@ -51,6 +51,7 @@ "browse.detail.converts": "Conversione sul server", "browse.detail.direct_play": "Direct Play", "browse.detail.direct_stream": "Streaming diretto", + "browse.detail.no_playback": "Riproduzione non disponibile", "browse.detail.original_audio_converted": "Originale · audio convertito", "browse.detail.hardware_needs": "la conversione hardware richiede", "browse.detail.tonemap_needs": "il tone mapping richiede", diff --git a/locales/nl/browse.json b/locales/nl/browse.json index ac9200d87f..cfd78d0245 100644 --- a/locales/nl/browse.json +++ b/locales/nl/browse.json @@ -51,6 +51,7 @@ "browse.detail.converts": "Wordt op server geconverteerd", "browse.detail.direct_play": "Direct Play", "browse.detail.direct_stream": "Direct Stream", + "browse.detail.no_playback": "Afspelen niet beschikbaar", "browse.detail.original_audio_converted": "Origineel · audio geconverteerd", "browse.detail.hardware_needs": "hardwareconversie vereist", "browse.detail.tonemap_needs": "tone-mapping vereist", diff --git a/locales/pl/browse.json b/locales/pl/browse.json index 309acf87a2..ae2f43ab5b 100644 --- a/locales/pl/browse.json +++ b/locales/pl/browse.json @@ -51,6 +51,7 @@ "browse.detail.converts": "Konwersja na serwerze", "browse.detail.direct_play": "Direct Play", "browse.detail.direct_stream": "Direct Stream", + "browse.detail.no_playback": "Odtwarzanie niedostępne", "browse.detail.original_audio_converted": "Oryginalna · konwersja dźwięku", "browse.detail.hardware_needs": "wymagania konwersji sprzętowej", "browse.detail.tonemap_needs": "wymagania mapowania tonów", diff --git a/locales/pt/browse.json b/locales/pt/browse.json index 0190951aa9..22fbb3ae0f 100644 --- a/locales/pt/browse.json +++ b/locales/pt/browse.json @@ -51,6 +51,7 @@ "browse.detail.converts": "Convertido no servidor", "browse.detail.direct_play": "Reprodução direta", "browse.detail.direct_stream": "Transmissão direta", + "browse.detail.no_playback": "Reprodução indisponível", "browse.detail.original_audio_converted": "Original · áudio convertido", "browse.detail.hardware_needs": "requisitos de conversão por hardware", "browse.detail.tonemap_needs": "requisitos de mapeamento de tons", diff --git a/locales/ru/browse.json b/locales/ru/browse.json index 2a4ee2cb33..22e4215742 100644 --- a/locales/ru/browse.json +++ b/locales/ru/browse.json @@ -51,6 +51,7 @@ "browse.detail.converts": "Преобразуется на сервере", "browse.detail.direct_play": "Прямое воспроизведение", "browse.detail.direct_stream": "Прямая передача", + "browse.detail.no_playback": "Воспроизведение недоступно", "browse.detail.original_audio_converted": "Видео без изменений · аудио преобразовано", "browse.detail.hardware_needs": "требования к аппаратному преобразованию", "browse.detail.tonemap_needs": "требования к тональному отображению", diff --git a/rust-modules/appkit/src/version_list.rs b/rust-modules/appkit/src/version_list.rs index daf7842b00..b0584cb681 100644 --- a/rust-modules/appkit/src/version_list.rs +++ b/rust-modules/appkit/src/version_list.rs @@ -15,11 +15,17 @@ pub fn title() -> &'static str { } /// **The list as one section**, in the server's order: row `n` is `versions[n]`, identified by -/// `id(n)` and reporting `act(&versions[n])`. Every row is a button that plays. +/// `id(n)` and reporting `act(&versions[n])`. Every row is a button that plays, unless +/// `unavailable` gives the reason nothing can (a platform that composed no playback driver): every +/// row is then disabled (`FormSection::disabled`, which makes it answer no press) and the reason is +/// said once, as the note under the rows (`FormSection::note`, the shared line for a reason that +/// belongs to the rows above it: it wraps, where a per-row value would not fit beside a version's +/// label and detail). pub fn section( versions: &[MediaVersion], id: impl Fn(u16) -> Id, act: impl Fn(&MediaVersion) -> A, + unavailable: Option<&str>, ) -> FormSection { let mut sec = FormSection::new(title()); for (n, (v, (label, detail))) in versions.iter().zip(labels(versions)).enumerate() { @@ -27,9 +33,12 @@ pub fn section( if !detail.is_empty() { row = row.detail(detail); } - sec = sec.item(id(n as u16), RowKind::Button, act(v), row); + sec = sec.item(id(n as u16), RowKind::Button, act(v), row).disabled(unavailable.is_some()); + } + match unavailable { + Some(why) => sec.note(why), + None => sec, } - sec } /// What each version's row says: `"25.2 Mbps · 4K"`, over the facts that DIFFER between the @@ -133,14 +142,43 @@ mod tests { let mut out = Vec::new(); for language in SHIPPED { let _guard = language_on_this_thread_for_test(language); - let mut form: FormTable = FormTable::new(plx_ui::table_screen::BAND_BASE); - form.set(Form::new().section(section(&sample(), Pos, |v| v.id)), None); - form.table.compact = false; - let tag = format!("{} versions", language.tag()); - out.extend(form.table.menu_cap_failure(&measure, &tag)); - out.extend(form.table.app_fit_failures(plx_ui::table::MENU_MAX_W, &tag)); - out.extend(form.table.app_fit_failures_hugged(&tag)); + // Both states: the rows that play, and the rows a platform with no driver disables + // under the one note that says why. + for unavailable in [None, Some(plx_os::i18n::msg::browse_detail_no_playback())] { + let mut form: FormTable = FormTable::new(plx_ui::table_screen::BAND_BASE); + form.set(Form::new().section(section(&sample(), Pos, |v| v.id, unavailable)), None); + form.table.compact = false; + let tag = format!("{} versions{}", language.tag(), if unavailable.is_some() { " (no playback)" } else { "" }); + out.extend(form.table.menu_cap_failure(&measure, &tag)); + out.extend(form.table.app_fit_failures(plx_ui::table::MENU_MAX_W, &tag)); + out.extend(form.table.app_fit_failures_hugged(&tag)); + } } plx_ui::table::assert_no_fit_failures(&out); } + + /// With a reason every row is disabled and answers no press, and the reason is said once, as the + /// note under them; a list with none is the buttons that play and no note. + #[test] + fn an_unavailable_list_is_disabled_rows_that_press_nothing() { + let _g = plx_os::i18n::language_on_this_thread_for_test(plx_os::i18n::Preference::En); + let why = plx_os::i18n::msg::browse_detail_no_playback(); + for (unavailable, disabled) in [(None, false), (Some(why), true)] { + let mut form: FormTable = FormTable::new(plx_ui::table_screen::BAND_BASE); + form.set(Form::new().section(section(&sample(), Pos, |v| v.id, unavailable)), None); + let rows: Vec<_> = form.table.sections.iter().flat_map(|s| s.rows.iter()).collect(); + let versions: Vec<_> = rows.iter().filter(|row| !row.is_note()).collect(); + let notes: Vec<_> = rows.iter().filter(|row| row.is_note()).collect(); + assert_eq!(versions.len(), 2); + for (i, row) in versions.iter().enumerate() { + assert_eq!(row.disabled, disabled, "row {i}"); + assert_eq!(row.value, None, "row {i}: the reason is not repeated per row"); + } + assert_eq!(notes.iter().map(|row| row.label.as_str()).collect::>(), + unavailable.into_iter().collect::>(), "the one note says why"); + for i in 0..2 { + assert_eq!(form.activate(i).is_some(), !disabled, "row {i}: a disabled row answers no press"); + } + } + } } diff --git a/rust-modules/media/src/route/decision_composition_tests.rs b/rust-modules/media/src/route/decision_composition_tests.rs new file mode 100644 index 0000000000..6f2fc3ef01 --- /dev/null +++ b/rust-modules/media/src/route/decision_composition_tests.rs @@ -0,0 +1,273 @@ +//! **An ordinary title through the REAL planner, for each composition a platform can supply** +//! (platform plan W6c): a URI driver and no Feed, a source that driver declines, no driver at all, +//! and both drivers. Every case but (c)'s planner half drives `request_play` -> the resolve worker -> +//! `pump_play` over a loopback PMS ((c) reads the plan's own decline fields from `build_stream` +//! directly, and lands its refusal through `pump_play` in its second test), with the session told what the adapter's installed drivers form +//! (`PlayerAdapter::composed_backends`) and the resolver a composition publishes, exactly as the +//! app's `publish_composition` tells it. The URI driver is the contract's `FakeUriDriver`, which +//! carries no display binding of any platform, and it certifies itself: the resolver's evidence is +//! the driver's own capabilities and display, the viewer's experimental setting stays Off. + +use super::*; +#[allow(unused_imports)] +use super::test_support::*; +use crate::route::uri_preflight::{OriginalQualifier, OriginalRequest, PmsRequest, PmsVerdict, + ProductEvidence, ResolvePort, Verdict, SOURCE_VERDICT_TTL}; +use plx_playback_contract::test_support::{FakeUriDriver, FakeUriHandle}; +use plx_playback_contract::uri::UriDriver; +use plx_playback_contract::{BackendKind, BackendSet, Capabilities}; +use std::sync::{Arc, Mutex}; + +/// An h264/aac Matroska file with a duration: what Standard direct-plays, and so what any +/// qualifier may carry as an original. +const ORDINARY_TITLE: &[u8] = br#"{"MediaContainer":{"Metadata":[{"ratingKey":"rk-v","type":"movie","duration":600000,"Media":[ + {"id":3086,"duration":450000,"bitrate":2372,"width":1920,"height":1080,"videoCodec":"h264","audioCodec":"aac","container":"mkv", + "Part":[{"id":3134,"duration":450000,"key":"/library/parts/3134/1/file.mkv","container":"mkv","Stream":[ + {"id":31341,"streamType":1,"codec":"h264","index":0}, + {"id":31342,"streamType":2,"codec":"aac","channels":2,"index":1,"languageCode":"eng","default":true,"selected":true}]}]}]}]}}"#; + +/// What a Tizen-like driver's composition would supply: no viewer opt-in is asked for, the driver +/// is the platform's only path and says what it plays. An original Standard would direct-play is a +/// URL carrier; a PMS conversion is certified only when `pms` is armed. It records the opt-in each +/// request carried. +struct SelfCertified { + pms: Option>>>, + opt_in_seen: Arc>>, +} + +impl OriginalQualifier for SelfCertified { + fn qualify(&self, _: &plx_base::task::OffFrame, request: OriginalRequest) -> Verdict { + self.opt_in_seen.lock().unwrap().push(request.uri_opt_in); + if let Some(gap) = request.standard.first_gap() { return Verdict::Unknown(gap); } + let url = request.source_url.clone(); + Verdict::Known(crate::route::uri_preflight::KnownSource::url_carrier( + &request, url, SOURCE_VERDICT_TTL)) + } + + fn qualify_pms(&self, off: &plx_base::task::OffFrame, request: PmsRequest) -> PmsVerdict { + match &self.pms { + Some(seen) => OriginalQualifier::qualify_pms(&QualifiedPms(seen.clone()), off, request), + None => PmsVerdict::Unknown, + } + } +} + +const URI_CAPS: Capabilities = Capabilities { progressive_uri: true, hls_uri: false, + packet_feed: false, pause: true, seek: true, audio_track: true, subtitle_track: true, + audio_off: false, subtitle_off: false }; + +/// A URI-only composition as a platform's `compose` builds it: the driver seated on a fresh +/// adapter, the resolver whose evidence is that driver's own display and capabilities (the driver +/// certifies itself), and the session told the set the adapter forms. +struct Composed { + adapter: crate::player::adapter::PlayerAdapter, + handle: FakeUriHandle, + opt_in_seen: Arc>>, +} + +fn compose_uri_only(ps: &mut PlaybackSession, pms: Option>>>) + -> Composed { + let mut adapter = crate::player::adapter::PlayerAdapter::new(unsafe { + plx_base::task::MainThread::assume() }); + let (driver, handle) = FakeUriDriver::new(URI_CAPS); + let evidence = ProductEvidence { display: driver.display(), callable: URI_CAPS, + certified: URI_CAPS }; + assert!(adapter.install_uri_driver(Box::new(driver)).is_ok()); + let opt_in_seen = Arc::new(Mutex::new(Vec::new())); + ps.install_uri_preflight_port(ResolvePort::new(evidence, + Arc::new(SelfCertified { pms, opt_in_seen: opt_in_seen.clone() }))); + ps.install_backends(adapter.composed_backends()); + Composed { adapter, handle, opt_in_seen } +} + +fn play_ordinary(ps: &mut PlaybackSession, meta: &mut plx_data::stores::metadata::MetadataStore, + sid: plx_plex::plex::ServerId, vcodec: &str, acodec: &str) -> Option { + assert!(request_play(ps, meta, plx_os::devcaps::caps(), sid, + "rk-v", "/library/parts/3134/1/file.mkv", vcodec, acodec, "Film", "", None, "")); + assert!(wait_resolve_workers_for_test(std::time::Duration::from_secs(15))); + pump_play(ps, meta) +} + +/// (a) URI only, the experimental setting Off, the driver certifying itself: an ordinary title +/// resolves to a URI original, the adapter takes the offer and the Start reaches the driver. +#[test] +fn a_uri_only_composition_plays_an_ordinary_title_with_the_experimental_setting_off() { + let mut ps = crate::route::PlaybackSession::IDLE; + let _g = fresh_registry(&mut ps); + assert!(plx_net::net::global_init()); + assert_eq!(uri_engine(), plx_plex::plex::session::UriEngine::Off, "the viewer opted into nothing"); + let mut composed = compose_uri_only(&mut ps, None); + assert_eq!(ps.backends(), BackendSet::URI, "no Feed driver is composed"); + let (port, done, server) = versions_pms_with(ORDINARY_TITLE, MDE_DIRECTPLAY); + let sid = plx_plex::plex::register_for_test("uri-only", "127.0.0.1", port, "token", "uri-only-client"); + let mut meta = plx_data::stores::metadata::MetadataStore::default(); + let start = play_ordinary(&mut ps, &mut meta, sid, "h264", "aac").expect("the title resolves"); + let offer = start.uri_offer.expect("an ordinary title resolves to a URI offer"); + assert_eq!(offer.offer_id(), crate::route::backend_policy::OfferId::URI_ORIGINAL); + assert_eq!(*composed.opt_in_seen.lock().unwrap(), [false], + "the qualifier was asked once, and the viewer's opt-in was not part of the answer"); + assert!(composed.adapter.offer_qualified_uri(&mut ps, offer).is_ok()); + assert!(matches!(ps.backend_offer(), crate::route::backend_policy::Selection::Open(choice) + if choice.backend == BackendKind::Uri)); + let started = crate::player::start_playback_tracked(&mut ps, &mut composed.adapter); + assert!(matches!(started, crate::player::BufferfeedStartOutcome::Launched(_)), "{started:?}"); + assert!(composed.handle.dispatched().iter().any(|(_, _, op)| + matches!(op, plx_playback_contract::Operation::Start { .. })), + "the Start reached the URI driver: {:?}", composed.handle.dispatched()); + done.send(()).unwrap(); + let requests = server.join().unwrap(); + assert!(!requests.iter().any(|line| line.contains("/decision?") || line.contains("/transcode/")), + "no Feed decision or encoder: {requests:?}"); + scrobble_stop(&mut ps, None, None); + drain_scrobble(); + plx_plex::plex::reset_servers_for_test(); +} + +/// (b, the refusal) A source the URI driver's qualifier declines (DTS audio the set cannot play +/// natively, so Standard would not direct-play it), in a URI-only composition whose qualifier +/// certifies no PMS conversion: the planner today returns the typed `NoQualifiedBackend` refusal +/// and names the PMS decline. It does not fall to a Feed that is not there. +#[test] +fn a_source_the_only_driver_declines_is_a_typed_refusal_when_no_conversion_is_certified() { + let mut ps = crate::route::PlaybackSession::IDLE; + let _g = fresh_registry(&mut ps); + assert!(plx_net::net::global_init()); + let composed = compose_uri_only(&mut ps, None); + let (port, done, server) = versions_pms_with(URI_DTS, MDE_PMS_OUTPUT); + let sid = plx_plex::plex::register_for_test("declined", "127.0.0.1", port, "token", "declined-client"); + let mut meta = plx_data::stores::metadata::MetadataStore::default(); + assert!(play_ordinary(&mut ps, &mut meta, sid, "h264", "dca").is_none()); + assert_eq!(ps.play_verdict, Some(PlayVerdict::NoQualifiedBackend)); + assert_eq!(ps.pms_decline(), + Some(crate::route::uri_preflight::PmsDecline::UnknownCertificate)); + assert_eq!(composed.opt_in_seen.lock().unwrap().len(), 1, "the driver was asked about the original"); + done.send(()).unwrap(); + let _ = server.join().unwrap(); + scrobble_stop(&mut ps, None, None); + drain_scrobble(); + plx_plex::plex::reset_servers_for_test(); +} + +/// (b, the conversion) The same declined original, where the driver's qualifier DOES certify the +/// server's converted output: the planner offers the `URI_PMS_*` recipe, not the original. +#[test] +fn a_source_the_only_driver_declines_becomes_a_uri_pms_conversion_when_one_is_certified() { + let mut ps = crate::route::PlaybackSession::IDLE; + let _g = fresh_registry(&mut ps); + assert!(plx_net::net::global_init()); + let seen = Arc::new(Mutex::new(Vec::new())); + let _composed = compose_uri_only(&mut ps, Some(seen.clone())); + let (port, done, server) = versions_pms_with(URI_DTS, MDE_PMS_OUTPUT); + let sid = plx_plex::plex::register_for_test("converted", "127.0.0.1", port, "token", "converted-client"); + let mut meta = plx_data::stores::metadata::MetadataStore::default(); + let start = play_ordinary(&mut ps, &mut meta, sid, "h264", "dca").expect("the conversion starts"); + let offer = start.uri_offer.expect("the converted output is offered to the URI driver"); + use crate::route::backend_policy::OfferId; + assert!(matches!(offer.offer_id(), OfferId::URI_PMS_REMUX | OfferId::URI_PMS_ENCODE), + "{:?}", offer.offer_id()); + assert_eq!(seen.lock().unwrap().len(), 1, "the converted output was qualified once"); + scrobble_stop(&mut ps, None, None); + drain_scrobble(); + done.send(()).unwrap(); + let _ = server.join().unwrap(); + plx_plex::plex::reset_servers_for_test(); +} + +/// (c) Zero drivers: the set the adapter forms is `NONE`, no resolver is published, and the +/// planner refuses an ordinary title with the typed verdict before any PMS decision or encoder +/// request (the PlayQueue request precedes the refusal, `plan.rs`'s `NoQualifiedBackend`). +#[test] +fn a_composition_with_no_driver_refuses_an_ordinary_title_with_a_typed_verdict() { + let mut ps = crate::route::PlaybackSession::IDLE; + let _g = fresh_registry(&mut ps); + assert!(plx_net::net::global_init()); + let adapter = crate::player::adapter::PlayerAdapter::new(unsafe { + plx_base::task::MainThread::assume() }); + ps.install_uri_preflight_port(Option::::None); + ps.install_backends(adapter.composed_backends()); + assert_eq!(ps.backends(), BackendSet::NONE, "a bare adapter composes nothing"); + let (port, done, server) = versions_pms_with(ORDINARY_TITLE, MDE_DIRECTPLAY); + let sid = plx_plex::plex::register_for_test("none", "127.0.0.1", port, "token", "none-client"); + let env = ResolveEnv::snapshot(&ps, + plx_data::stores::metadata::MetadataStore::default().view(), sid, "rk-v"); + let plan = build_stream(&plx_base::task::OffFrame::for_test(), "rk-v", + "/library/parts/3134/1/file.mkv", "h264", "aac", &env); + done.send(()).unwrap(); + let requests = server.join().unwrap(); + assert_eq!(plan.verdict, Some(PlayVerdict::NoQualifiedBackend)); + assert_eq!(plan.uri_decline, Some(crate::route::uri_preflight::UriDecline::NoPort), + "no resolver, so no URI original was even asked about"); + assert!(plan.url.is_empty() && plan.sess.is_empty() && plan.uri_original.is_none()); + assert!(!requests.iter().any(|line| line.contains("/decision?") || line.contains("/transcode/")), + "no Feed work for a platform with no Feed: {requests:?}"); + plx_plex::plex::reset_servers_for_test(); +} + +/// (c, through the landing) The same refusal reaches the session as its play verdict, which is what +/// the player's read-out reads. +#[test] +fn a_composition_with_no_driver_lands_the_refusal_on_the_session() { + let mut ps = crate::route::PlaybackSession::IDLE; + let _g = fresh_registry(&mut ps); + assert!(plx_net::net::global_init()); + ps.install_uri_preflight_port(Option::::None); + ps.install_backends(BackendSet::NONE); + let (port, done, server) = versions_pms_with(ORDINARY_TITLE, MDE_DIRECTPLAY); + let sid = plx_plex::plex::register_for_test("none-landing", "127.0.0.1", port, "token", "none-landing-client"); + let mut meta = plx_data::stores::metadata::MetadataStore::default(); + assert!(play_ordinary(&mut ps, &mut meta, sid, "h264", "aac").is_none()); + assert_eq!(ps.play_verdict, Some(PlayVerdict::NoQualifiedBackend)); + done.send(()).unwrap(); + let _ = server.join().unwrap(); + plx_plex::plex::reset_servers_for_test(); +} + +/// (d) Two drivers composed (Target shape 6d): the planner's choice between them is today's +/// `Offer::rank`. A URI original that the resolver qualifies precedes the Feed's own original (both +/// are the original handoff, and the URI tie-break wins); where the resolver declines, Feed's +/// original plays and no URI offer exists. +#[test] +fn with_both_drivers_a_qualified_uri_original_precedes_the_feed_original() { + use crate::route::backend_policy::{OfferId, Qualification, Selection}; + for (certified, expect) in [(true, BackendKind::Uri), (false, BackendKind::Feed)] { + let mut ps = crate::route::PlaybackSession::IDLE; + let _g = fresh_registry(&mut ps); + assert!(plx_net::net::global_init()); + let seen = Arc::new(Mutex::new(Vec::new())); + // The resolver answers for the URI driver; the session carries both backends. + let _composed = compose_uri_only(&mut ps, None); + if !certified { + ps.install_uri_preflight_port(ResolvePort::new( + ProductEvidence { display: plx_playback_contract::uri::DisplayEvidence::ready("fake"), + callable: URI_CAPS, certified: URI_CAPS }, + Arc::new(SelfCertified { pms: None, opt_in_seen: seen.clone() }))); + } + ps.install_backends(BackendSet::BOTH); + let (port, done, server) = versions_pms_with( + if certified { ORDINARY_TITLE } else { URI_DTS }, + if certified { MDE_DIRECTPLAY } else { MDE_TRANSCODE_VIDEO }); + let sid = plx_plex::plex::register_for_test("both", "127.0.0.1", port, "token", "both-client"); + let mut meta = plx_data::stores::metadata::MetadataStore::default(); + let acodec = if certified { "aac" } else { "dca" }; + let start = play_ordinary(&mut ps, &mut meta, sid, "h264", acodec); + match start.and_then(|s| s.uri_offer) { + Some(offer) => { + assert!(certified); + ps.qualify_backend_offer(BackendKind::Uri, offer.offer_id(), Qualification::Qualified); + // The Feed driver could carry the same original too: both are candidates, and + // the rank (the URI tie-break) alone chooses. + assert!(ps.qualify_resolved_feed_offer(OfferId::FEED_ORIGINAL, + CandidatePurpose::NewCandidate)); + } + None => assert!(!certified, "a certified original must reach the planner as an offer"), + } + assert!(matches!(ps.backend_offer(), Selection::Open(choice) + if choice.backend == expect && (certified == (choice.id == OfferId::URI_ORIGINAL))), + "{:?}", ps.backend_offer()); + scrobble_stop(&mut ps, None, None); + drain_scrobble(); + done.send(()).unwrap(); + let _ = server.join().unwrap(); + plx_plex::plex::reset_servers_for_test(); + } +} diff --git a/rust-modules/media/src/route/decision_version_tests.rs b/rust-modules/media/src/route/decision_version_tests.rs index 0f0c396210..6905a9a984 100644 --- a/rust-modules/media/src/route/decision_version_tests.rs +++ b/rust-modules/media/src/route/decision_version_tests.rs @@ -1290,3 +1290,6 @@ fn the_published_resolver_is_readable_and_an_absence_clears_it() { ps.install_uri_preflight_port(Option::::None); assert!(ps.uri_preflight_port().is_none(), "an absence clears it"); } + +#[path = "decision_composition_tests.rs"] +mod composition_tests; diff --git a/rust-modules/media/src/route/mod.rs b/rust-modules/media/src/route/mod.rs index 25116c6c3e..78712ec62d 100644 --- a/rust-modules/media/src/route/mod.rs +++ b/rust-modules/media/src/route/mod.rs @@ -22,6 +22,9 @@ mod prefs; mod track_memory; pub use decision::*; +/// The playback backends a composition supplies, for the layers (screens) that read the set the +/// session was told and may not name the contract crate. +pub use plx_playback_contract::BackendSet; pub use flight::{ discard_stale_flight_landing, engineless_flight_outstanding, flight_is_current, flight_outstanding, recovery_flight_offset_ns, recovery_flight_outstanding, resume_flight_outstanding, retire_superseded_encoder, take_ready_flight, take_ready_recovery_flight, ReadyFlight, RecoveryLanding, RecoveryVerdict, SeekVerdict, diff --git a/rust-modules/screens/src/CLAUDE.md b/rust-modules/screens/src/CLAUDE.md index c05373dbca..f3674d1597 100644 --- a/rust-modules/screens/src/CLAUDE.md +++ b/rust-modules/screens/src/CLAUDE.md @@ -99,7 +99,16 @@ that mixes async content with a live cursor: block that lands late). A restore is only what the reader chose: the engine remembers the page's own seats too, so the page keeps their provenance (`LibraryScreen::placed`). Home already has this shape (the hero seats when its action row arrives, while focus is still on the strip); Search seats its field, which never arrives async, - and Person and Detail keep no self-seat for a landing to strand. + and Person keeps no self-seat for a landing to strand. Detail keeps none while a playback driver + is composed (Play is its first seat and the landing does not move it); with none composed its + first seat, before the item lands, is the watched toggle, which writes to the account once the + item is there. The page owns that seat the way the Library owns its grid's + (`DetailScreen::provisional`, set by a fresh open's `Enter`): every frame's `reconcile` answers + `DetailScreen::default_elem` until the viewer moves focus (a key that moves it, the pointer) or + presses OK on a landed page. The item's landing, a later Also available landing and a restore that + waits on a season or retires all move the seat by that one rule, so account safety never depends on + a restore firing in the landing frame. A key that moves nothing, and an OK before the item lands, + leave it the page's. - **The grid absorbs an index landing, the page shifts its scroll.** The Library's grid is a `cards::Grid` in `ScrollMode::External`: when the focused element's index changes with no `FocusMoved` (an insert or reorder before it) the grid moves its pop with the element and diff --git a/rust-modules/screens/src/detail/geometry_tests.rs b/rust-modules/screens/src/detail/geometry_tests.rs index 39bfdf871c..2d6fb4bbef 100644 --- a/rust-modules/screens/src/detail/geometry_tests.rs +++ b/rust-modules/screens/src/detail/geometry_tests.rs @@ -111,6 +111,7 @@ fn bare(sid: ServerId, rk: &str) -> DetailScreen { preview_had_picture: false, trailer_ctl: super::trailer::Transport::IDLE, restore_intent: None, + provisional: false, teardown_cleared: false, withdrawn: false, refresh: DetailRefreshPhase::None, diff --git a/rust-modules/screens/src/detail/hero.rs b/rust-modules/screens/src/detail/hero.rs index b5c3f6d84f..5353b56144 100644 --- a/rust-modules/screens/src/detail/hero.rs +++ b/rust-modules/screens/src/detail/hero.rs @@ -167,6 +167,25 @@ impl HeroCtl { pub fn is_watch(self) -> bool { matches!(self, HeroCtl::MarkWatched | HeroCtl::MarkUnwatched) } + /// Does pressing this control start a playback? Play and Restart play the item, Trailer plays + /// its extra. A platform that composed no playback driver ([`Stops::no_playback`]) can start + /// none of them, so none owns a focus stop there. The Play Version disc is not one: it only + /// opens the list, whose own rows are disabled in that state (`versions_panel`). + pub const fn starts_playback(self) -> bool { + matches!(self, HeroCtl::Play | HeroCtl::Restart | HeroCtl::Trailer) + } + /// Does pressing this control WRITE to the household's account? The bookmark disc adds or + /// removes the title on the plex.tv Watchlist, and the watched toggle in either face marks it + /// watched or unwatched on the server. The rest play, navigate or open a menu or panel. The page + /// never seats ITSELF on one of these once its item is there ([`default_stop`]): a reflex OK on a + /// page that has just appeared must not change the record. Travel still reaches them, and focus + /// the viewer put on one stays. Before the item lands, the one seat on a write control (the + /// watched toggle of a page with no driver) presses nothing (`activate_hero`) and is the page's + /// own seat, which every frame moves to `DetailScreen::default_elem` until the viewer moves focus + /// (`DetailScreen::provisional`). + pub const fn writes_account(self) -> bool { + matches!(self, HeroCtl::Watchlist | HeroCtl::MarkWatched | HeroCtl::MarkUnwatched) + } /// **The control's accessibility word** (`detail.hero.`): one static word per variant, never /// derived from the label, which changes with the item (Play wears "Resume" mid-title: both are /// `play`) and the language. The watched toggle's two faces are two words, for what pressing each does. @@ -265,11 +284,30 @@ pub fn hero_ctls(set: HeroSet) -> ([HeroCtl; MAX_CTLS], usize) { (v, n) } -/// Whether `ctl` may hold — or be enumerated as holding — focus right now, given whether -/// full-trailer mode owns the screen. The ONE predicate [`visible_ctls`] (group extent) and -/// `DetailScreen::reconcile`/`valid` (focus legitimacy) all gate on, so the row cannot offer a -/// control the mode has taken away — the exact class of bug this predicate replaced (two -/// independent "what's visible" checks that had silently drifted apart). +/// The two facts that decide which of the row's controls own a focus stop, read where the row is +/// enumerated (never stored: a screen keeps no copy of either). +#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] +pub struct Stops { + /// Full-trailer mode owns the screen (`DetailScreen::full_trailer`). + pub full_trailer: bool, + /// The platform composed no playback driver at all (`ScreenInputs::can_play` is false). + pub no_playback: bool, +} + +impl Stops { + /// The row of a platform that can play, with only full-trailer mode deciding: what the row was + /// before a platform could compose no driver. + pub const fn trailer(full_trailer: bool) -> Self { + Self { full_trailer, no_playback: false } + } +} + +/// Whether `ctl` may hold — or be enumerated as holding — focus right now, given [`Stops`]. The +/// ONE predicate [`visible_ctls`] (group extent), the travel, the seat and the fallback +/// (`DetailScreen::neighbour`/`seat`/`reconcile`), `valid` (focus legitimacy) and the pointer's +/// stops all gate on, so the row cannot offer a control the state has taken away — the exact class +/// of bug this predicate replaced (two independent "what's visible" checks that had silently +/// drifted apart). /// /// **Play survives as the ANCHOR, not as a reachable control.** Full-trailer mode fades the whole /// row out together (`DetailScreen::draw_buttons` draws every control from [`hero_ctls`] @@ -279,30 +317,40 @@ pub fn hero_ctls(set: HeroSet) -> ([HeroCtl; MAX_CTLS], usize) { /// EMPTY hero group would push it into the sections below, scrolling the page out from under a /// trailer nobody asked to leave. Keys never reach the row anyway: the mode answers them itself, /// before the engine. -pub fn focusable(ctl: HeroCtl, full_trailer: bool) -> bool { - !full_trailer || ctl == HeroCtl::Play +/// +/// **A disabled control owns no focus stop** (`plx_ui::focus::next_enabled_index`; the player HUD's +/// disabled discs): with no playback driver composed, the controls that start playback +/// ([`HeroCtl::starts_playback`]) are drawn disabled and the focus travels only between the +/// controls that can act. The shared button draws no focused face for a disabled control, so a stop +/// on one would leave focus visibly nowhere. Where the page rests when nothing says where is a +/// separate rule ([`default_stop`]): the page never seats itself on a control that writes to the +/// account once its item is there. +pub fn focusable(ctl: HeroCtl, stops: Stops) -> bool { + if stops.full_trailer { + return ctl == HeroCtl::Play; + } + !(stops.no_playback && ctl.starts_playback()) } -/// [`hero_ctls`], filtered through [`focusable`] for full-trailer mode's FOCUS/hit-testing extent -/// only — the transient UI state where the row narrows to its Play anchor alone and everything -/// else (Restart/Trailer/Alt/the watch toggle) stops being reachable the instant `full_trailer()` -/// flips. **This is not what gets drawn.** `DetailScreen::draw_buttons` draws every control -/// [`hero_ctls`] returns, full_trailer or not, so the row fades out together with the rest of the +/// [`hero_ctls`], filtered through [`focusable`] for the FOCUS/hit-testing extent only: in +/// full-trailer mode the row narrows to its Play anchor alone, and with no playback driver it +/// drops the controls that play. **This is not what gets drawn.** `DetailScreen::draw_buttons` +/// draws every control [`hero_ctls`] returns, so the row fades out together with the rest of the /// chrome instead of four pills hard-cutting a frame ahead of the one that fades (2026-09-17 -/// fix — a control losing its focus must not also lose its paint on the same frame). Deliberately -/// NOT a flag on [`HeroSet`]: that struct describes what the ITEM offers, not a screen's transient -/// presentation mode. Every call site that enumerates the row for focus/hit-testing extent must go -/// through this rather than `hero_ctls` directly, or the two can disagree about which controls -/// exist right now. -pub fn visible_ctls(set: HeroSet, full_trailer: bool) -> ([HeroCtl; MAX_CTLS], usize) { +/// fix — a control losing its focus must not also lose its paint on the same frame), and a +/// disabled Play is still drawn, as disabled. Deliberately NOT a flag on [`HeroSet`]: that struct +/// describes what the ITEM offers, not a screen's transient presentation mode or the platform. +/// Every call site that enumerates the row for focus/hit-testing extent must go through this +/// rather than `hero_ctls` directly, or the two can disagree about which controls exist right now. +/// +/// The result is a SUBSET in drawn order, not a prefix: its positions are not drawn indices. A +/// control's drawn index is [`index_of`] over [`hero_ctls`]. +pub fn visible_ctls(set: HeroSet, stops: Stops) -> ([HeroCtl; MAX_CTLS], usize) { let (all, n) = hero_ctls(set); - if !full_trailer { - return (all, n); - } let mut v = [HeroCtl::Play; MAX_CTLS]; let mut count = 0; for &c in &all[..n] { - if focusable(c, full_trailer) { + if focusable(c, stops) { v[count] = c; count += 1; } @@ -310,7 +358,52 @@ pub fn visible_ctls(set: HeroSet, full_trailer: bool) -> ([HeroCtl; MAX_CTLS], u (v, count) } -/// The control at index `i` in `set`, or `None` for an index the set does not have. +/// The row's first stop: Play with a playback driver composed (it is always first), the first +/// control that can act without one. A press UP into the row from a section below seats on +/// [`default_stop`] and reaches for this one only when every stop writes (a movie with no driver: +/// the bookmark and the watched toggle), so the write controls stay reachable by travel; it is +/// also the last resort of [`DetailScreen::default_elem`](super::DetailScreen). The row always +/// has a stop (the watched toggle is unconditional and plays nothing, and Play anchors +/// full-trailer mode), so the answer needs no `Option`; were that ever false it is the array's +/// own fill, Play. +pub fn first_stop(set: HeroSet, stops: Stops) -> HeroCtl { + visible_ctls(set, stops).0[0] +} + +/// The row's stop the page opens on when nothing says which: its first stop that does not write to +/// the account ([`HeroCtl::writes_account`]). That is Play with a playback driver composed, and +/// without one Go to Show, More, the versions control or Also available, whichever the row has. +/// `None` when every stop the row has writes (a movie with no driver: the bookmark and the watched +/// toggle), which sends the page's default below the row (`DetailScreen::default_elem`). +pub fn default_stop(set: HeroSet, stops: Stops) -> Option { + let (v, n) = visible_ctls(set, stops); + v[..n].iter().copied().find(|ctl| !ctl.writes_account()) +} + +/// The row's stop on drawn index `col` (a restored spot's column), or `None` when that column is +/// past the row or names a control the row does not stop on right now (a platform that cannot play +/// has no stop on Play). A restore that names a stop keeps it, whatever it does: it is where the +/// viewer left their own focus. One that does not resolves by the default rule ([`default_stop`]), +/// not onto the nearest stop, which would be a write as often as not. +pub fn stop_at(set: HeroSet, stops: Stops, col: usize) -> Option { + let (v, n) = hero_ctls(set); + (col < n && focusable(v[col], stops)).then(|| v[col]) +} + +/// The drawn indices of the row's first and last stop, for the group's extent: the row's +/// controls are placed by drawn index, so a stop's place is `hero_btn_rect_at` of its +/// [`index_of`], never of its position among the stops. +pub fn stop_span(set: HeroSet, stops: Stops) -> Option<(usize, usize)> { + let (v, n) = hero_ctls(set); + let mut stops_at = (0..n).filter(|&i| focusable(v[i], stops)); + let first = stops_at.next()?; + Some((first, stops_at.last().unwrap_or(first))) +} + +/// The control at index `i` in `set`, or `None` for an index the set does not have. The pages +/// resolve a column through [`stop_at`] (a column may name a control that is not a stop); this +/// is the plain inverse of [`index_of`] the tests pin the row's identities with. +#[cfg(test)] pub fn ctl_at(set: HeroSet, i: usize) -> Option { let (v, n) = hero_ctls(set); (i < n).then(|| v[i]) @@ -662,7 +755,10 @@ enum Bit { const FACTS_BITS: usize = 8; -fn play_mode_bits(d: &Detail, after: bool) -> ([Bit; FACTS_BITS], usize) { +fn play_mode_bits(d: &Detail, playable: bool, after: bool) -> ([Bit; FACTS_BITS], usize) { + if !playable { + return no_playback_bits(after); + } match plx_media::route::detail_playback_preview(d) { Some((plx_media::route::Preview::DirectPlay | plx_media::route::Preview::Remux, _)) => ([Bit::Air(0.0); FACTS_BITS], 0), Some((preview, file)) => play_mode_bits_for(preview, file.hdr, item_subscription(d), after), @@ -670,6 +766,20 @@ fn play_mode_bits(d: &Detail, after: bool) -> ([Bit; FACTS_BITS], usize) { } } +/// The play-mode clause of a device that composes no playback driver: the one reason word, in the +/// facts line's own ink, in the place the preview clause takes. Nothing about the item's route is read, +/// since no route can start. +fn no_playback_bits(after: bool) -> ([Bit; FACTS_BITS], usize) { + let mut bits = [Bit::Air(0.0); FACTS_BITS]; + let mut n = 0; + if after { + bits[n] = Bit::Sep; + n += 1; + } + bits[n] = Bit::Word(plx_os::i18n::msg::browse_detail_no_playback_c(), plx_ui::detail_layout::FACTS_INK, 0); + (bits, n + 1) +} + /// [`play_mode_bits`] once the item's route has been read: the line's play-mode clause, behind a /// separator of its own when something already stands in front of it (`after`). fn play_mode_bits_for( @@ -758,20 +868,21 @@ fn bits_flow( flow.end() - x } -fn play_mode_w(d: &Detail, after: bool, measure: &dyn plx_machine::machine::Measure) -> f32 { - let (bits, n) = play_mode_bits(d, after); +fn play_mode_w(d: &Detail, playable: bool, after: bool, measure: &dyn plx_machine::machine::Measure) -> f32 { + let (bits, n) = play_mode_bits(d, playable, after); bits_flow(&bits[..n], 0.0, measure, |_, _| {}) } fn draw_play_mode( p: Painter, d: &Detail, + playable: bool, x: f32, y: f32, after: bool, measure: &dyn plx_machine::machine::Measure, ) -> f32 { - let (bits, n) = play_mode_bits(d, after); + let (bits, n) = play_mode_bits(d, playable, after); paint_bits(p, &bits[..n], x, y, measure) } @@ -864,12 +975,12 @@ fn facts_flow( } /// Draw the facts line at `y`; the width it draws from the margin. -pub fn draw_facts(p: Painter, d: &Detail, y: f32, measure: &dyn plx_machine::machine::Measure) -> f32 { +pub fn draw_facts(p: Painter, d: &Detail, playable: bool, y: f32, measure: &dyn plx_machine::machine::Measure) -> f32 { let (date, extent) = hero_facts(d); let extent = extent.as_deref().unwrap_or(""); let credit = plx_ui::fmt::shared_by(&d.source()).unwrap_or_default(); let column = Rect::new(plx_ui::consts::MARGIN_X, y, FACTS_R - plx_ui::consts::MARGIN_X, theme::hero::FACTS_H); - if play_mode_w(d, false, measure) == 0.0 { + if play_mode_w(d, playable, false, measure) == 0.0 { let resumes = hero_resume_ns(d) > 0; return plx_ui::widgets::hero_facts(p, column, &date, extent, resumes, &credit, measure); } @@ -878,7 +989,7 @@ pub fn draw_facts(p: Painter, d: &Detail, y: f32, measure: &dyn plx_machine::mac &[date.as_str(), if fit.extent { extent } else { "" }], if fit.credit { &credit } else { "" }, |text, _, size, _| measure.width_str(text, size, false), - |_, after| play_mode_w(d, after, measure), + |_, after| play_mode_w(d, playable, after, measure), ) }; let fit = facts_fit( @@ -888,7 +999,7 @@ pub fn draw_facts(p: Painter, d: &Detail, y: f32, measure: &dyn plx_machine::mac ); let elided; let date = if fit.elide { - let budget = (column.w - play_mode_w(d, true, measure)).max(0.0); + let budget = (column.w - play_mode_w(d, playable, true, measure)).max(0.0); elided = plx_gfx::text::elide_by(&date, budget, false, |t| { measure.width_str(t, theme::size::CAPTION, false) }); @@ -915,7 +1026,7 @@ pub fn draw_facts(p: Painter, d: &Detail, y: f32, measure: &dyn plx_machine::mac }) .unwrap_or(0.0) }, - |dx, after| draw_play_mode(p, d, plx_ui::consts::MARGIN_X + dx, y, after, measure), + |dx, after| draw_play_mode(p, d, playable, plx_ui::consts::MARGIN_X + dx, y, after, measure), ) } @@ -1020,12 +1131,12 @@ mod tests { for alt in [false, true] { for trailer in [false, true] { let s = set_full(restart, alt, mark, trailer); - let (v, n) = visible_ctls(s, true); + let (v, n) = visible_ctls(s, Stops::trailer(true)); assert_eq!(n, 1, "set={s:?}"); assert_eq!(v[0], HeroCtl::Play, "set={s:?}"); // And the non-full-trailer path must be byte-identical to `hero_ctls` — // `visible_ctls` is a strict narrowing, never a second row model. - assert_eq!(visible_ctls(s, false), hero_ctls(s), "set={s:?}"); + assert_eq!(visible_ctls(s, Stops::trailer(false)), hero_ctls(s), "set={s:?}"); // Drawing does not narrow with `visible_ctls` — `draw_buttons` iterates // `hero_ctls` directly — so drawing always sees strictly more than // full-trailer mode makes focusable/pointer-reachable: the watch toggle @@ -2193,4 +2304,36 @@ mod tests { } } } + + /// W6c: with no playback driver composed the play-mode clause is the one reason word (after a + /// separator when something precedes it) and never the item's preview; with a driver it is + /// today's clause, which an item with no route preview leaves empty. + #[test] + fn no_playback_replaces_the_play_mode_clause_with_one_reason_word() { + let d = Detail::default(); + let measure = plx_ui::fixture::FixtureMeasure; + assert_eq!(play_mode_w(&d, true, false, &measure), 0.0, "today: nothing to say for this item"); + assert!(play_mode_w(&d, false, false, &measure) > 0.0, "no driver: the reason is drawn"); + let (bits, n) = play_mode_bits(&d, false, false); + assert_eq!(n, 1); + assert!(matches!(bits[0], Bit::Word(word, ink, 0) + if word == plx_os::i18n::msg::browse_detail_no_playback_c() + && ink == plx_ui::detail_layout::FACTS_INK), "one word in the facts line's own ink"); + let (after, n) = play_mode_bits(&d, false, true); + assert!(n == 2 && matches!(after[0], Bit::Sep) && matches!(after[1], Bit::Word(..))); + } + + /// W6c: a host that never says (the default inputs) is a platform with a driver. + #[test] + fn inputs_that_set_no_backends_mean_a_playable_platform() { + use crate::registry::ScreenInputs; + use plx_media::route::BackendSet; + assert!(ScreenInputs::default().can_play()); + for (set, can) in [(BackendSet::FEED, true), (BackendSet::URI, true), (BackendSet::BOTH, true), + (BackendSet::NONE, false)] { + assert_eq!(ScreenInputs { backends: set, ..Default::default() }.can_play(), can); + } + assert!(!ScreenInputs::default().same_facts(&ScreenInputs { backends: BackendSet::NONE, ..Default::default() }), + "the set is a screen-visible fact, so a change of it presents"); + } } diff --git a/rust-modules/screens/src/detail/hero_watchlist_tests.rs b/rust-modules/screens/src/detail/hero_watchlist_tests.rs index 8bb7ff4741..927ae7d1e2 100644 --- a/rust-modules/screens/src/detail/hero_watchlist_tests.rs +++ b/rust-modules/screens/src/detail/hero_watchlist_tests.rs @@ -82,11 +82,11 @@ fn the_elem_id_is_fresh_in_the_hero_range_and_round_trips() { #[test] fn full_trailer_mode_drops_the_disc_from_the_focus_extent() { for s in sets() { - let (v, n) = visible_ctls(s, true); + let (v, n) = visible_ctls(s, Stops::trailer(true)); assert_eq!((v[0], n), (HeroCtl::Play, 1), "{s:?}"); - assert!(!focusable(HeroCtl::Watchlist, true)); - assert!(focusable(HeroCtl::Watchlist, false)); - assert_eq!(visible_ctls(s, false).1, hero_ctls(s).1); + assert!(!focusable(HeroCtl::Watchlist, Stops::trailer(true))); + assert!(focusable(HeroCtl::Watchlist, Stops::trailer(false))); + assert_eq!(visible_ctls(s, Stops::trailer(false)).1, hero_ctls(s).1); } } @@ -131,6 +131,6 @@ fn an_item_without_a_watchlist_guid_has_no_disc() { assert!(!v[..n].contains(&HeroCtl::Watchlist), "{s:?}"); assert_eq!(v[0], HeroCtl::Play); assert_eq!(index_of(s, HeroCtl::Watchlist), None); - assert!(!visible_ctls(s, false).0[..visible_ctls(s, false).1].contains(&HeroCtl::Watchlist)); + assert!(!visible_ctls(s, Stops::trailer(false)).0[..visible_ctls(s, Stops::trailer(false)).1].contains(&HeroCtl::Watchlist)); } } diff --git a/rust-modules/screens/src/detail/identity_tests.rs b/rust-modules/screens/src/detail/identity_tests.rs index b0625ef4d4..d01aa541a5 100644 --- a/rust-modules/screens/src/detail/identity_tests.rs +++ b/rust-modules/screens/src/detail/identity_tests.rs @@ -82,7 +82,7 @@ fn body(entry: EntryId, rk: &str) -> DetailScreen { preview_started_for: None, preview_had_picture: false, trailer_ctl: super::trailer::Transport::IDLE, - restore_intent: None, teardown_cleared: false, withdrawn: false, scroll: Spring::at(0.0), + restore_intent: None, provisional: false, teardown_cleared: false, withdrawn: false, scroll: Spring::at(0.0), refresh: DetailRefreshPhase::None, refresh_gen: 0, scroll_target: 0.0, free: false, episode_free: false, episode_scroll: Spring::at(0.0), tab_scroll: Spring::at(0.0), diff --git a/rust-modules/screens/src/detail/mod.rs b/rust-modules/screens/src/detail/mod.rs index 12be47fa25..260e0eff33 100644 --- a/rust-modules/screens/src/detail/mod.rs +++ b/rust-modules/screens/src/detail/mod.rs @@ -256,6 +256,20 @@ pub struct DetailScreen { /// for the same (sid, rk) that predates this promotion's own admission. refresh_gen: u32, restore_intent: Option, + /// The page, not the viewer, placed the current focus: a fresh open with no playback driver + /// composed seats itself before its item has landed, on the watched toggle (the row's only stop + /// until then), which writes to the account the moment the item is there. While this holds, + /// every frame's `reconcile` answers the page's default ([`Self::default_elem`]), so that seat + /// follows the head wherever the landing puts it (the item, a later Also available landing) and + /// never waits on a restore to fire. It ends with the viewer's own act: a move a direction key + /// or the pointer makes, an OK on a landed page, or a hold that opens a menu (a hold that opens + /// nothing, a key that moves nothing and an OK before the item lands leave the seat the page's). + /// `LibraryScreen::provisional` follows the head the same way for the Library's first seat but + /// ends on ANY key-down, pointer or wheel, so its ending is not this one. Never set with a + /// driver composed, where Play is the default from the first frame and the page keeps no + /// self-seat. Not hashed, not in [`SHAPE`]: a `SHAPE` bump would invalidate every detail + /// fixture, and a fixture's page has a driver. + provisional: bool, /// This page has already sent its addressed `ClearItem` to the Metadata store. §3.4's /// `pop_sequence` delivers `WillLeave(ForGood)` AND `Unmount` to the same body, and both land /// in the teardown arm below, so without the latch one teardown would send two. The command is @@ -575,6 +589,7 @@ impl DetailScreen { refresh: DetailRefreshPhase::None, refresh_gen: 0, restore_intent: None, + provisional: false, teardown_cleared: false, withdrawn: false, scroll: Spring::at(0.0), @@ -1389,8 +1404,13 @@ impl DetailScreen { self.engine_key(related::elem(Self::related_nearest(d, position))?) } - fn restore_focus(&self, meta: plx_data::metadata::MetadataView<'_>) -> Option { + /// Where a restore puts focus. A restored hero spot keeps the control it names while the row + /// still stops on it (the viewer's own position, a write control included); a column that is no + /// longer a stop, and a section the item no longer has, take the page's default + /// ([`Self::default_elem`]). Full-trailer mode is not read here, it is `reconcile`'s own first check. + fn restore_focus(&self, cx: &Cx<'_, H>) -> Option { if self.return_pending { return None; } + let meta = ::metadata(cx); let intent = self.restore_intent.as_ref()?; let d = self.detail(meta)?; if season::restore_step( @@ -1407,7 +1427,11 @@ impl DetailScreen { 0 => { let set = self.hero_set(meta); let (_, n) = hero::hero_ctls(set); - hero::ctl_at(set, clamp(intent.spot.col, n)).map(hero::HeroCtl::elem) + let stops = hero::Stops { full_trailer: false, no_playback: self.stops(cx).no_playback }; + match hero::stop_at(set, stops, clamp(intent.spot.col, n)) { + Some(ctl) => Some(ctl.elem()), + None => return Some(self.default_elem(cx)), + } } 1 if !d.seasons.is_empty() => season::elem(d.cur_season.min(d.seasons.len() - 1)), 2 if !d.episodes.is_empty() => { @@ -1444,10 +1468,39 @@ impl DetailScreen { about::CARD_ELEM }, ), - _ => Some(hero::ELEM_PLAY), + _ => return Some(self.default_elem(cx)), }?; self.engine_key(local) } + + /// **Where focus lands when nothing says where** (a page's first seat, a focus that lost its + /// place, a restore whose control is no longer a stop): the row's first stop that does not + /// write to the account ([`hero::default_stop`]: Play with a driver composed, else Go to Show, + /// More, the versions control or Also available). A row of writes only (a movie with no playback + /// driver: the bookmark and the watched toggle) has none, so the page opens on the first section + /// below the row, which that group's own `seat` picks, exactly as the engine would have seated + /// it from the group's head. A page whose item has not landed has no section below; its row + /// stops on the watched toggle alone, which presses nothing until the item is there + /// (`activate_hero`), and the toggle is the last resort ([`hero::first_stop`]). That seat is + /// the page's own ([`Self::provisional`]): `reconcile` answers this same rule every frame until + /// the viewer moves focus, so the landing, a later Also available landing and a restore that + /// waits or retires all leave the toggle without any one of them having to fire, and a reflex OK + /// on a page that has just appeared never writes to someone's account. + fn default_elem(&self, cx: &Cx<'_, H>) -> u32 { + let stops = self.stops(cx); + let set = self.hero_set(::metadata(cx)); + if let Some(ctl) = hero::default_stop(set, stops) { + return ctl.elem(); + } + let mut groups = Vec::new(); + Focusable::::groups(self, cx, &mut groups); + // `sections` lists a section only while it has stops, so every group below the row has some + // today; `len > 0` is each group's own word that the engine can seat on it. + match groups.iter().find(|g| g.id != hero::HERO_GROUP && g.len > 0) { + Some(below) => Focusable::::seat(self, below.id, plx_ui::focus::head_of(below.extent), cx).elem, + None => hero::first_stop(set, stops).elem(), + } + } } impl Focusable for DetailScreen { @@ -1462,9 +1515,14 @@ impl Focusable f self.disc_unfurl.map(|s| s.pos), self.named_episode(meta), ); - let (_, hero_n) = hero::visible_ctls(set, self.full_trailer()); + let stops = self.stops(cx); + let (_, hero_n) = hero::visible_ctls(set, stops); let hero_y = self.hero_chain(measure, meta).btn_y; - let hero_last = hero::hero_btn_rect_at(set, hero_n.saturating_sub(1), hero_y, widths); + // The extent spans the row's stops, which are placed by DRAWN index: with no driver the + // head (Play) is not one, so neither its index nor its place is the extent's. + let (hero_first, hero_last) = hero::stop_span(set, stops).unwrap_or((0, 0)); + let hero_first = hero::hero_btn_rect_at(set, hero_first, hero_y, widths); + let hero_last = hero::hero_btn_rect_at(set, hero_last, hero_y, widths); out.push(GroupSpec { id: hero::HERO_GROUP, kind: GroupKind::Row { wrap: false }, @@ -1477,9 +1535,9 @@ impl Focusable f EdgeRule::Stop, ], extent: Rect::new( - plx_ui::consts::MARGIN_X, + hero_first.x, hero_y - self.scroll_target, - hero_last.x + hero_last.w - plx_ui::consts::MARGIN_X, + hero_last.x + hero_last.w - hero_first.x, hero::CD, ), len: hero_n, @@ -1626,12 +1684,13 @@ impl Focusable f fn group_of(&self, key: &u32, cx: &Cx<'_, H>) -> Option { let meta = H::metadata(cx); let located = self.locate(*key, meta)?; - self.valid(located, meta).then(|| located.group()) + self.valid(located, meta, self.stops(cx)).then(|| located.group()) } fn neighbour(&self, key: FocusKey, dir: Dir, cx: &Cx<'_, H>) -> Step { let meta = H::metadata(cx); - let Some(located) = self.locate(key.elem, meta).filter(|l| self.valid(*l, meta)) else { + let stops = self.stops(cx); + let Some(located) = self.locate(key.elem, meta).filter(|l| self.valid(*l, meta, stops)) else { return Step::Edge; }; let moved = match located { @@ -1641,9 +1700,12 @@ impl Focusable f return Step::Edge; }; let (controls, n) = hero::hero_ctls(set); + // The neighbour is the next control that owns a stop, skipping a disabled one + // (`next_enabled_index`: the shared linear-group rule), never merely the next drawn. + let step = |forward| plx_ui::focus::next_enabled_index(i, n, forward, |j| hero::focusable(controls[j], stops)); match dir { - Dir::Left if i > 0 => Some(controls[i - 1].elem()), - Dir::Right if i + 1 < n => Some(controls[i + 1].elem()), + Dir::Left => step(false).map(|j| controls[j].elem()), + Dir::Right => step(true).map(|j| controls[j].elem()), _ => None, } } @@ -1698,7 +1760,7 @@ impl Focusable f fn place(&self, key: &u32, cx: &Cx<'_, H>, at: At) -> Option { let meta = H::metadata(cx); let measure = cx.measure; - let located = self.locate(*key, meta).filter(|l| self.valid(*l, meta))?; + let located = self.locate(*key, meta).filter(|l| self.valid(*l, meta, self.stops(cx)))?; let d = self.detail(meta); let vertical = if at == At::Drawn { self.scroll.pos @@ -1821,7 +1883,7 @@ impl Focusable f // return-pending focus land on a control the row no longer offers. if self.full_trailer() { if let Some(Located::Hero(ctl)) = self.locate(want.elem, meta) { - if !hero::focusable(ctl, true) { + if !hero::focusable(ctl, hero::Stops::trailer(true)) { return FocusKey { entry: want.entry, elem: hero::HeroCtl::Play.elem(), @@ -1838,6 +1900,14 @@ impl Focusable f if self.return_pending && self.detail(meta).is_none() && hero::HeroCtl::of_elem(want.elem).is_some() { return want; } + // A focus the page itself placed (`provisional`) is the page's default wherever the item + // stands: the landing, a later Also available landing and a restore that waits on a season + // or retires all move it by this one rule, so nothing below has to fire for focus to leave + // the watched toggle. Only the viewer's own act ends it (the `FocusMoved`, `PressHold` and + // `activate` arms), or a return (`Enter(Restored)`). + if self.provisional { + return FocusKey { entry: want.entry, elem: self.default_elem(cx) }; + } let known = self.keys.iter().any(|key| key.elem == want.elem); // `self.refresh != None` is the page's OWN outstanding server obligation, and it belongs // beside the store's answer rather than behind it. The store's `Some(true)` only reports a @@ -1867,7 +1937,8 @@ impl Focusable f } } } - if let Some(elem) = self.restore_focus(meta) { + let stops = self.stops(cx); + if let Some(elem) = self.restore_focus(cx) { return FocusKey { entry: want.entry, elem, @@ -1878,7 +1949,7 @@ impl Focusable f // itself here just because the ITEM's facts still offer it. `hero::focusable` is the same // predicate `visible_ctls` and `valid` gate on, so this cannot silently drift from either. if let Some(Located::Hero(ctl)) = self.locate(want.elem, meta) { - if hero::focusable(ctl, self.full_trailer()) { + if hero::focusable(ctl, stops) { let set = self.hero_set(meta); if hero::index_of(set, ctl).is_some() { return want; @@ -1894,7 +1965,7 @@ impl Focusable f } if self .locate(want.elem, meta) - .is_some_and(|located| self.valid(located, meta)) + .is_some_and(|located| self.valid(located, meta, stops)) { return want; } @@ -1906,9 +1977,10 @@ impl Focusable f if let Some(elem) = self.shelf_recovery(want.elem, meta) { return FocusKey { entry: want.entry, elem }; } + // Nothing else holds: the page's default, which is Play unless no driver is composed. FocusKey { entry: want.entry, - elem: hero::HeroCtl::Play.elem(), + elem: self.default_elem(cx), } } @@ -1917,8 +1989,20 @@ impl Focusable f let meta = H::metadata(cx); let d = self.detail(meta); let from_i = from.index.unwrap_or(0) as usize; + let (set, stops) = (self.hero_set(meta), self.stops(cx)); + // The row's stop a press UP into it seats on, and where a section's key that cannot be + // resolved falls back to: the default stop, else (a row of writes only) its first stop. + let first_stop = hero::default_stop(set, stops).unwrap_or_else(|| hero::first_stop(set, stops)).elem(); let elem = if group == hero::HERO_GROUP { - hero::HeroCtl::Play.elem() + // The page's FIRST seat (nothing of this page focused yet: the container's + // `FirstInGroup`) is its default, which may sit below the row; a viewer already on the + // page who presses UP into the row chose it, so it seats on a stop of the row even when + // every stop writes (the write controls stay reachable by travel). + if cx.focus.current.is_some_and(|key| key.entry == self.entry) { + first_stop + } else { + return FocusKey { entry: self.entry, elem: self.default_elem(cx) }; + } } else if group == season::SEASON_GROUP { // Land on the SELECTED season, not whichever tab happens to be geometrically nearest // `from`: `Placed` carries no source group, so this fires from every entry into the @@ -1977,7 +2061,7 @@ impl Focusable f entry: self.entry, elem: Self::locate_local(elem, self.tracks_available(meta)) .and_then(|located| self.key_of(located)) - .unwrap_or(hero::ELEM_PLAY), + .unwrap_or(first_stop), } } @@ -1993,7 +2077,7 @@ impl Focusable f /// a menu) has none. fn a11y(&self, key: &u32, cx: &Cx<'_, H>) -> Option> { let meta = H::metadata(cx); - let located = self.locate(*key, meta).filter(|l| self.valid(*l, meta))?; + let located = self.locate(*key, meta).filter(|l| self.valid(*l, meta, self.stops(cx)))?; let d = self.detail(meta); let named = |section: &'static str| A11yPath::new().name(section); // the text is the page's own words as the data layer published them: cloned, since the @@ -2041,7 +2125,7 @@ impl Focusable f fn a11y_elems(&self, g: GroupId, cx: &Cx<'_, H>, out: &mut Vec) { let meta = H::metadata(cx); if g == hero::HERO_GROUP { - let (ctls, n) = hero::visible_ctls(self.hero_set(meta), self.full_trailer()); + let (ctls, n) = hero::visible_ctls(self.hero_set(meta), self.stops(cx)); out.extend(ctls[..n].iter().map(|ctl| ctl.elem())); return; } @@ -2112,14 +2196,15 @@ impl Focusable f } impl DetailScreen { - fn valid(&self, located: Located, meta: plx_data::metadata::MetadataView<'_>) -> bool { + fn valid(&self, located: Located, meta: plx_data::metadata::MetadataView<'_>, stops: hero::Stops) -> bool { let d = self.detail(meta); match located { // A control other than Play is never valid while full-trailer mode has narrowed the - // row to its anchor — `hero::focusable` is the same predicate `reconcile` and + // row to its anchor, and a control that plays is never valid while no driver is + // composed — `hero::focusable` is the same predicate `reconcile` and // `hero::visible_ctls` gate on. Located::Hero(c) => { - hero::focusable(c, self.full_trailer()) && hero::index_of(self.hero_set(meta), c).is_some() + hero::focusable(c, stops) && hero::index_of(self.hero_set(meta), c).is_some() } Located::Season(i) => d.is_some_and(|d| i < d.seasons.len()), Located::Episode(i, _) => d.is_some_and(|d| d.episodes.get(i).is_some()), @@ -2240,6 +2325,14 @@ impl Machine for // resumes from what the stop committed, not from the `viewOffset` the page // opened with. let fresh_open = matches!(kind, Enter::Fresh { .. }); + // The page is seated before its item lands (the item is requested right here). With + // no playback driver that first seat is the watched toggle, the row's only stop + // until the item is there, and it must not stay there: it writes the moment the item + // lands. The seat is the page's, not the viewer's, until the viewer moves focus + // (`provisional`): `reconcile` answers the page's default every frame it holds, + // whatever the restore a navigation arrives with does or does not do. A return + // (`Restored`) is the viewer's own place and ends it. + self.provisional = fresh_open && !H::screen_inputs(cx).can_play(); let request = refresh == DetailRefreshPhase::Deferred || refresh == DetailRefreshPhase::Requested && request_status.is_none() || refresh == DetailRefreshPhase::None @@ -2291,6 +2384,9 @@ impl Machine for if matches!(by, By::Dir | By::Pointer | By::Script) { self.return_pending = false; self.restore_intent = None; + // The viewer moved focus (a key that moved it, the pointer): it is theirs now, + // and no landing takes it from them. A key that moves nothing never gets here. + self.provisional = false; } // A hover moves focus, never the page: the pointer scrolls by the screen's edges // (and a click by what it clicked, `Input`'s `Click` arm). @@ -2343,6 +2439,7 @@ impl Machine for ) }); if supported { + self.provisional = false; self.content(fx, ContentReq::ItemMenu); fx.invalidate(Provenance::Input); Handled::Yes @@ -2523,7 +2620,11 @@ impl Machine for // The *Play Version* surface committed a row: this page plays that version as its // Play pill would. ScreenEvent::App(AppMsg::PlayVersion(media)) => { - self.play_hero(false, Some(*media), fx, H::metadata(cx)); + // The panel's rows are disabled with no driver composed (`versions_panel`) and send + // nothing; a message that arrives anyway starts nothing. + if H::screen_inputs(cx).can_play() { + self.play_hero(false, Some(*media), fx, H::metadata(cx)); + } Handled::Yes } // Dismissed: the page under this surface has just been entered again, and it decided @@ -2635,8 +2736,9 @@ impl DetailScreen { } } - fn restore_target_matches(&self, located: Located, meta: plx_data::metadata::MetadataView<'_>) -> bool { - self.restore_focus(meta).and_then(|elem| self.locate(elem, meta)) == Some(located) + fn restore_target_matches(&self, located: Located, cx: &Cx<'_, H>) -> bool { + let meta = ::metadata(cx); + self.restore_focus(cx).and_then(|elem| self.locate(elem, meta)) == Some(located) } } @@ -3034,7 +3136,7 @@ impl DetailScreen { ); } if let Some(d) = d { - hero::draw_facts(chrome, d, chain.facts_y, cx.measure); + hero::draw_facts(chrome, d, H::screen_inputs(cx).can_play(), chain.facts_y, cx.measure); hero::draw_people(chrome, d, chain.btn_y, measure); } // Full-trailer mode takes the action row with the rest of the page: the viewer asked for @@ -3190,6 +3292,10 @@ impl DetailScreen { // fades every button through `chrome`'s `preview_chrome` alpha (`draw_hero`), and cutting // four of the five pills here a frame early defeats that fade before it can be seen. let (controls, n) = hero::hero_ctls(set); + // Drawing never narrows with full-trailer mode (the row fades with the chrome), but a + // control that plays is drawn disabled while no driver is composed: the same predicate that + // takes its focus stop away (`hero::focusable`), so the two cannot disagree. + let drawn = hero::Stops { full_trailer: false, no_playback: !H::screen_inputs(cx).can_play() }; let row = hero::hero_row_rect(set, y, widths); let row = [row.x, row.y - self.scroll.pos, row.w, row.h]; let picture = plx_media::player::preview::view().picture; @@ -3221,6 +3327,9 @@ impl DetailScreen { rect, ) .icon(plx_ui::icons::Icon::Play) + // No playback driver composed: the shared button's own disabled look. The reason + // is the facts line's clause (`hero::draw_facts`). + .enabled(hero::focusable(ctl, drawn)) .focus_mix(fill) .palette(palette) .ground(ground) @@ -3251,6 +3360,7 @@ impl DetailScreen { let mut button = CircleButton::new(c"".as_ptr()) .icon(icon) .frame(rect) + .enabled(hero::focusable(ctl, drawn)) .focus_mix(fill) .palette(palette) .ground(ground) @@ -3319,8 +3429,10 @@ impl DetailScreen { // Stop is a hit-testable rect, so registering Play's here would let a magic-remote click // land on a pill nobody can see and start the FEATURE from a screen showing only a // trailer. Skip the whole hero group rather than filtering by `valid()`/`focusable`, so - // hover and click both go away together. - if !self.full_trailer() { + // hover and click both go away together. A control that plays, with no driver composed, is + // not `valid()` either, so `place` below yields it no rect and it registers no stop: + // hovering a disabled pill never parks focus on it, nor does a click reach it. + if !self.stops(f.cx).full_trailer { let (controls, n) = hero::hero_ctls(set); elems.extend(controls[..n].iter().map(|c| (c.elem(), Activate::Press))); } @@ -4074,7 +4186,7 @@ impl DetailScreen { || watchlist_moving; if !meta.detail_loading() && !meta.season_loading() - && focused.is_some_and(|located| self.return_pending && !self.return_waiting(meta) || self.restore_target_matches(located, meta)) + && focused.is_some_and(|located| self.return_pending && !self.return_waiting(meta) || self.restore_target_matches(located, cx)) { self.restore_intent = None; self.return_pending = false; @@ -4336,10 +4448,13 @@ impl DetailScreen { ); } - /// Is full-trailer mode (UP-promoted, trailer picture up) running right now? The one - /// predicate every site that enumerates or resolves hero focus must agree on — `groups` (via - /// [`hero::visible_ctls`]) for the row's extent, `reconcile`/`valid` for what is FOCUSABLE, - /// `record_stops` for what is pointer-reachable, and the input arm for who owns the keys. + /// Is full-trailer mode (UP-promoted, trailer picture up) running right now? One of the TWO + /// facts that decide which hero controls own a focus stop ([`Self::stops`] pairs it with + /// `ScreenInputs::can_play`; [`hero::focusable`] reads both): every site that enumerates or + /// resolves hero focus reads them together, never this alone — `groups` (via + /// [`hero::stop_span`]) for the row's extent, `reconcile`/`valid` for what is FOCUSABLE, + /// `record_stops` for what is pointer-reachable. This alone is the input arm's fact, for who + /// owns the keys. /// `draw_buttons` deliberately does NOT gate on this: it draws every hero control regardless /// and lets the eased `preview_chrome` alpha (set from this same predicate in `preview_tick`) /// fade the row, so a control losing focus does not also lose its paint on the same frame. @@ -4351,6 +4466,13 @@ impl DetailScreen { self.preview_promoted && plx_media::player::preview::view().picture } + /// What decides which hero controls own a focus stop right now ([`hero::Stops`]): the mode + /// above and whether the platform composed any playback driver. Read from `cx` where the row is + /// enumerated, never kept on the page. + fn stops(&self, cx: &Cx<'_, H>) -> hero::Stops { + hero::Stops { full_trailer: self.full_trailer(), no_playback: !H::screen_inputs(cx).can_play() } + } + /// Un-promotes full-trailer mode if it was active — shared by the BACK and DOWN key arms and /// by the mode's own key ladder ([`Self::trailer_act`]), so the collapse itself has exactly one /// body. Returns whether it fired, so a caller can decide whether to also consume the key. @@ -4520,6 +4642,12 @@ impl DetailScreen { fn activate(&mut self, elem: u32, cx: &Cx<'_, H>, fx: &mut Effects<'_, H>) { let meta = H::metadata(cx); + // An OK on a landed page is the viewer's act on the focus it holds. One before the item is + // there presses nothing (`activate_hero`) and must not end the page's claim on the seat: the + // landing would then leave focus on a toggle the next OK writes with. + if self.detail(meta).is_some() { + self.provisional = false; + } let local = self.locate(elem, meta).and_then(Located::local_key).unwrap_or(elem); match self.locate(elem, meta) { Some(Located::Hero(ctl)) => self.activate_hero(ctl, cx, fx, meta), @@ -4614,6 +4742,10 @@ impl DetailScreen { meta: plx_data::metadata::MetadataView<'_>, ) { let measure = cx.measure; + // Play, Restart and Trailer start a playback; with no driver composed they are drawn + // disabled, own no focus stop (`hero::focusable`), and a press that reaches them anyway (a + // by-id press, a stale click) does nothing. + if ctl.starts_playback() && !H::screen_inputs(cx).can_play() { return; } match ctl { hero::HeroCtl::Play => { self.play_hero(false, None, fx, meta); diff --git a/rust-modules/screens/src/detail/no_driver_tests.rs b/rust-modules/screens/src/detail/no_driver_tests.rs new file mode 100644 index 0000000000..062250bc24 --- /dev/null +++ b/rust-modules/screens/src/detail/no_driver_tests.rs @@ -0,0 +1,901 @@ +//! A platform that composed no playback driver (W6c): the Detail controls that play are drawn +//! disabled and own no focus stop, so focus travels between the controls that can act, and a press +//! that reaches a disabled one anyway does nothing. A page whose item is there never opens on a +//! control that writes to the account (the bookmark, the watched toggle): its default is the first +//! stop that does not, or, for a row of writes only, the first section below the row, and a restore +//! that names a control the viewer was on keeps it. A page seated before its item lands has only the +//! watched toggle, which presses nothing until the item is there; that seat is the PAGE's, not the +//! viewer's (`DetailScreen::provisional`), so every frame moves it to the page's default until the +//! viewer moves focus or presses OK on a landed page, whatever a restore does meanwhile. With a driver +//! composed every one of these is exactly what it was. +//! +//! The shared rule these pin is `focus.rs`'s "a disabled item owns no focus stop" +//! (`next_enabled_index`; the player HUD's disabled discs): the shared button draws no focused face +//! while disabled, so a stop on one would leave a page that opens with nothing visibly focused. + +use super::*; +use plx_machine::machine::{FocusTarget, InputOwner}; +use plx_ui::focus::{FocusEngine, Outcome}; + +/// TEST ONLY: the host publishes a platform with no playback driver while this is alive. +struct NoDriver; +impl NoDriver { + fn set(on: bool) -> Self { + NO_DRIVER.with(|flag| flag.set(on)); + NoDriver + } +} +impl Drop for NoDriver { + fn drop(&mut self) { + NO_DRIVER.with(|flag| flag.set(false)); + } +} + +const OWNER: InputOwner = InputOwner::Entry(EntryId(7)); + +fn key(elem: u32) -> FocusKey { + FocusKey { entry: EntryId(7), elem } +} + +/// A movie with a resume point, a Watchlist guid and a trailer: its row is +/// `[Play, Watchlist, Restart, Mark watched]`, so Restart sits BETWEEN two controls that can act and +/// a skip over it is observable. +fn resumable(sid: ServerId) -> Detail { + Detail { + sid, rk: "movie".into(), kind: "movie".into(), part: "/library/parts/1/file.mkv".into(), + guid: "plex://movie/5d776b1d96b655001f2a9c3e".into(), resume_ms: 30_000, dur_ms: 120_000, + extras: vec![trailer_extra()], ..Default::default() + } +} + +/// The control the page's focus lands on when it is entered the way the container mints it +/// (`FirstInGroup(hero)`), or, given a `restored` key, reconciled from it. +fn enter(screen: &DetailScreen, restored: Option>) -> u32 { + let measure = plx_ui::fixture::FixtureMeasure; + let mut engine = FocusEngine::new(); + match engine.enter::(OWNER, screen, FocusTarget::FirstInGroup(hero::HERO_GROUP), restored, &cx(&measure, None)) { + Outcome::Moved { to, .. } => to.elem, + other => panic!("an entry moves focus onto something: {other:?}"), + } +} + +/// Which hero control `elem` is, if it is one. +fn ctl_of(elem: u32) -> Option { + hero::HeroCtl::of_elem(elem) +} + +#[test] +fn only_the_controls_that_play_lose_their_stop_and_the_row_is_never_empty() { + for ctl in [hero::HeroCtl::Play, hero::HeroCtl::Restart, hero::HeroCtl::Trailer] { + assert!(ctl.starts_playback(), "{ctl:?}"); + } + for ctl in [hero::HeroCtl::Alt, hero::HeroCtl::MarkWatched, hero::HeroCtl::MarkUnwatched, hero::HeroCtl::Watchlist, + hero::HeroCtl::GoToShow, hero::HeroCtl::Version, hero::HeroCtl::More] { + assert!(!ctl.starts_playback(), "{ctl:?} opens, marks or navigates; it does not play"); + } + // The controls that WRITE to the account: the bookmark and the watched toggle in both faces. + for ctl in [hero::HeroCtl::Play, hero::HeroCtl::Restart, hero::HeroCtl::Trailer, hero::HeroCtl::Alt, + hero::HeroCtl::GoToShow, hero::HeroCtl::Version, hero::HeroCtl::More] { + assert!(!ctl.writes_account(), "{ctl:?} plays, navigates or opens a menu; it writes nothing"); + } + for ctl in [hero::HeroCtl::Watchlist, hero::HeroCtl::MarkWatched, hero::HeroCtl::MarkUnwatched] { + assert!(ctl.writes_account(), "{ctl:?} changes the household's record"); + } + for mark in [PosterMark::None, PosterMark::InProgress, PosterMark::Watched] { + for bits in 0..64u32 { + let set = hero::HeroSet { + watchlist: bits & 1 != 0, go_show: bits & 2 != 0, version: bits & 4 != 0, restart: bits & 8 != 0, + trailer: bits & 16 != 0, alt: bits & 32 != 0, more: bits & 3 == 0, mark, + }; + let (all, drawn) = hero::hero_ctls(set); + for stops in [hero::Stops::default(), hero::Stops { no_playback: true, ..Default::default() }] { + let (visible, n) = hero::visible_ctls(set, stops); + assert!(n >= 1, "{set:?} {stops:?}: the watched toggle plays nothing, so the row is never empty"); + assert!(visible[..n].iter().all(|c| hero::focusable(*c, stops))); + assert_eq!(hero::first_stop(set, stops), visible[0], "{set:?} {stops:?}"); + let want: Vec<_> = all[..drawn].iter().copied().filter(|c| !(stops.no_playback && c.starts_playback())).collect(); + assert_eq!(&visible[..n], &want[..], "{set:?} {stops:?}: a subset of the drawn row, in drawn order"); + let (first, last) = hero::stop_span(set, stops).expect("a stop"); + assert_eq!((all[first], all[last]), (visible[0], visible[n - 1]), "{set:?} {stops:?}"); + // A column the row stops on is that control, any other (a control the row does not + // stop on, or past the row) is none: a restore then takes the page's default. + for col in 0..drawn + 2 { + let at = hero::stop_at(set, stops, col); + assert_eq!(at, (col < drawn && hero::focusable(all[col], stops)).then(|| all[col]), + "{set:?} {stops:?}: column {col}"); + } + // The default stop is the first stop that does not write: Play with a driver, and + // without one the first of Go to Show, More, Version, Also available the row has, + // or none at all when every stop the row has writes. + let default = hero::default_stop(set, stops); + assert_eq!(default, visible[..n].iter().copied().find(|c| !c.writes_account()), "{set:?} {stops:?}"); + assert!(default.map_or(true, |c| hero::focusable(c, stops) && !c.writes_account()), "{set:?} {stops:?}"); + if !stops.no_playback { + assert_eq!(default, Some(hero::HeroCtl::Play), "{set:?} {stops:?}: with a driver Play stays the default"); + } + if stops.no_playback && !(set.go_show || set.more || set.version || set.alt) { + assert_eq!(default, None, "{set:?}: a row of writes only has no default stop of its own"); + } + } + // Full-trailer mode is Play alone, whatever the platform composed. + for no_playback in [false, true] { + let stops = hero::Stops { full_trailer: true, no_playback }; + assert_eq!(hero::visible_ctls(set, stops).1, 1); + assert_eq!(hero::first_stop(set, stops), hero::HeroCtl::Play); + assert_eq!(hero::default_stop(set, stops), Some(hero::HeroCtl::Play)); + } + } + } +} + +/// With a driver the focus group is what it always was: every drawn control is a stop and the extent +/// runs from the margin to the end of the last one. With none it spans the stops only. +#[test] +fn the_hero_group_spans_the_controls_that_own_a_stop() { + let sid = ServerId::UNSET; + let measure = plx_ui::fixture::FixtureMeasure; + for no_driver in [false, true] { + let guard = install(resumable(sid)); + let _driver = NoDriver::set(no_driver); + let screen = bare(&guard, sid, "movie"); + let meta = test_store().view(); + let set = screen.hero_set(meta); + assert_eq!(hero::hero_ctls(set).1, 4, "Play, Watchlist, Restart, Mark watched"); + let mut groups = Vec::new(); + Focusable::::groups(&screen, &cx(&measure, None), &mut groups); + let spec = groups.iter().find(|g| g.id == hero::HERO_GROUP).expect("the hero group"); + let widths = hero::hero_widths(&measure, set, set.restart, screen.disc_unfurl.map(|s| s.pos), screen.named_episode(meta)); + let y = screen.hero_chain(&measure, meta).btn_y; + let rect = |i| hero::hero_btn_rect_at(set, i, y, widths); + let (len, first) = if no_driver { (2, 1) } else { (4, 0) }; + let (head, tail) = (rect(first), rect(3)); + assert_eq!(spec.len, len, "no_driver={no_driver}"); + assert_eq!(spec.extent, Rect::new(head.x, y - screen.scroll_target, tail.x + tail.w - head.x, hero::CD), "no_driver={no_driver}"); + if !no_driver { + // The row as it stood before a platform could compose nothing: from the margin. + assert_eq!(spec.extent.x, plx_ui::consts::MARGIN_X); + } + let mut listed = Vec::new(); + Focusable::::a11y_elems(&screen, hero::HERO_GROUP, &cx(&measure, None), &mut listed); + assert_eq!(listed.len(), len, "the ids the harness can name are the stops the group counts"); + clear(); + } +} + +/// The engine key of the first card of the Extras shelf: `resumable`'s item has one (its trailer), +/// so it is the first section below its row. +fn first_extra(screen: &DetailScreen) -> u32 { + screen.engine_key(extras::elem(0).expect("an extras card")).expect("the card has a key") +} + +/// The page opens on Play with a driver. With none its row is the bookmark and the watched toggle, +/// both of which WRITE to the account, so a reflex OK on a page that has just appeared must not land +/// on either: it opens on the first section below the row, seated by that group's own `seat`. +#[test] +fn focus_opens_on_the_first_control_that_can_act() { + let sid = ServerId::UNSET; + for no_driver in [false, true] { + let guard = install(resumable(sid)); + let _driver = NoDriver::set(no_driver); + let screen = bare(&guard, sid, "movie"); + let first = if no_driver { first_extra(&screen) } else { hero::ELEM_PLAY }; + // A page minted fresh seats by the group's own policy... + assert_eq!(enter(&screen, None), first, "no_driver={no_driver}"); + // ...and one restored onto Play (a remembered cursor, the old default) reconciles to the + // same place, not to a pill that draws no focus. + assert_eq!(enter(&screen, Some(key(hero::ELEM_PLAY))), first, "no_driver={no_driver}"); + // Restart is a stop only while a driver can play: without one a focus left on it falls back + // to the same default. + assert_eq!(enter(&screen, Some(key(hero::ELEM_RESTART))), if no_driver { first } else { hero::ELEM_RESTART }, + "no_driver={no_driver}"); + // ...but a restore onto the very control the viewer left keeps it, a write control included: + // that is their own position. + if no_driver { + for own in [hero::ELEM_WATCHLIST, hero::ELEM_MARK_WATCHED] { + assert_eq!(enter(&screen, Some(key(own))), own, "no_driver={no_driver}: the viewer's own focus stays"); + } + } + clear(); + } +} + +/// A movie with nothing below its row but the About card: the default is that card, not a write +/// control and not nothing. +#[test] +fn a_movie_whose_only_stops_write_opens_on_the_first_section_below_the_row() { + let sid = ServerId::UNSET; + let guard = install(Detail { + sid, rk: "movie".into(), kind: "movie".into(), part: "/library/parts/1/file.mkv".into(), + guid: "plex://movie/5d776b1d96b655001f2a9c3e".into(), ..Default::default() + }); + let screen = bare(&guard, sid, "movie"); + let meta = test_store().view(); + { + let _driver = NoDriver::set(true); + let set = screen.hero_set(meta); + let stops = hero::Stops { full_trailer: false, no_playback: true }; + let (row, n) = hero::visible_ctls(set, stops); + assert_eq!(&row[..n], &[hero::HeroCtl::Watchlist, hero::HeroCtl::MarkWatched], "premise: every stop of the row writes"); + assert_eq!(hero::default_stop(set, stops), None); + let landed = enter(&screen, None); + assert!(matches!(screen.locate(landed, meta), Some(Located::About(0))), "the first section below the row"); + assert!(ctl_of(landed).is_none(), "and not a control of the row"); + } + // With a driver nothing changes: Play. + let _driver = NoDriver::set(false); + assert_eq!(enter(&screen, None), hero::ELEM_PLAY); + clear(); +} + +/// A row that has a stop which neither plays nor writes opens on it (Go to Show, More, Play Version, +/// Also available), ahead of the writes that sit before it in the row; UP into the row from below +/// seats there as well. +#[test] +fn a_row_with_a_stop_that_does_not_write_opens_on_it() { + let sid = ServerId::UNSET; + let episode = Detail { + sid, rk: "ep".into(), kind: "episode".into(), part: "/library/parts/1/file.mkv".into(), + show_rk: "show".into(), season: 1, ..Default::default() + }; + for (what, item, lands) in [ + ("a movie with two versions", versioned("movie", 2), hero::ELEM_VERSION), + ("an episode", episode, hero::ELEM_GO_TO_SHOW), + ] { + let guard = install(item); + let _driver = NoDriver::set(true); + let screen = bare(&guard, sid, if what == "an episode" { "ep" } else { "leaf" }); + let set = screen.hero_set(test_store().view()); + let stops = hero::Stops { full_trailer: false, no_playback: true }; + let (row, n) = hero::visible_ctls(set, stops); + assert!(row[..n].iter().any(|ctl| ctl.writes_account()), "{what}: premise: the row has a write control too"); + assert_eq!(enter(&screen, None), lands, "{what}"); + assert_eq!(enter(&screen, Some(key(hero::ELEM_PLAY))), lands, "{what}: a restore onto Play resolves the same way"); + // UP into the row from the section below seats there as well. + let about = screen.engine_key(about::CARD_ELEM).expect("the About card has a key"); + let mut engine = FocusEngine::new(); + engine.set(OWNER, key(about), Some(about::ABOUT_GROUP), By::Restore); + assert_eq!(moved_to(collection_move(&screen, &mut engine, Dir::Up), "UP into the row"), lands, "{what}"); + clear(); + } +} + +/// A page with no item yet offers Play and the watch disc. With no driver the watch disc is the +/// row's only stop and there is no section below to seat on, so the page opens on it: a control that +/// writes, but one that presses nothing until the item is there (`activate_hero`), and not one focus +/// stays on once it is (`a_page_seated_before_its_item_lands_leaves_the_write_control_when_it_does`). +#[test] +fn a_page_whose_item_has_not_landed_opens_on_the_watch_disc_with_no_driver() { + let sid = ServerId::UNSET; + for (no_driver, first) in [(false, hero::ELEM_PLAY), (true, hero::ELEM_MARK_WATCHED)] { + let guard = install(Detail { sid, rk: "other".into(), ..Default::default() }); + let _driver = NoDriver::set(no_driver); + let mut screen = bare(&guard, sid, "movie"); + assert!(screen.detail(test_store().view()).is_none(), "the page's own item is not loaded"); + assert_eq!(enter(&screen, None), first, "no_driver={no_driver}"); + let (_, effects) = step(&mut screen, &ScreenEvent::Activate(hero::ELEM_MARK_WATCHED), Some(first)); + assert!(!effects.iter().any(|e| matches!(e.fx, Fx::App(AppFx::Store(StoreId::ViewState, _)))), + "no_driver={no_driver}: OK on the watch disc before the item is there writes nothing"); + clear(); + } +} + +/// **The real order: the page is seated BEFORE its item lands** (the item is requested on every fresh +/// open). With no driver the first seat can only be the watched toggle, the row's one stop until the +/// item is there, and it must not stay there once the toggle is live. The seat is the page's own +/// (`provisional`), so the landing moves it to the page's default whether the navigation seeded a +/// restore (`DetailSeed`) or not, instead of leaving focus on a write control. +#[test] +fn a_page_seated_before_its_item_lands_leaves_the_write_control_when_it_does() { + let sid = ServerId::UNSET; + let measure = plx_ui::fixture::FixtureMeasure; + // with a restore armed by the mount (a navigation's seed), and with none (a fresh open without one) + for (no_driver, seeded) in [(true, true), (true, false), (false, true), (false, false)] { + let guard = install(Detail { sid, rk: "other".into(), ..Default::default() }); + let _driver = NoDriver::set(no_driver); + let mut screen = bare(&guard, sid, "movie"); + if seeded { + screen.restore(&Spot::default(), test_store().view()); + } + step(&mut screen, &ScreenEvent::Enter(plx_ui::screen::Enter::Fresh { + focus: FocusTarget::FirstInGroup(hero::HERO_GROUP), + }), None); + assert_eq!(screen.restore_intent.is_some(), seeded, "no_driver={no_driver} seeded={seeded}: Enter arms no restore of its own"); + let mut engine = FocusEngine::new(); + let first = if no_driver { hero::ELEM_MARK_WATCHED } else { hero::ELEM_PLAY }; + match engine.enter::(OWNER, &screen, FocusTarget::FirstInGroup(hero::HERO_GROUP), None, &cx(&measure, None)) { + Outcome::Moved { to, .. } => assert_eq!(to.elem, first, "no_driver={no_driver}: before the item lands"), + other => panic!("an entry moves focus onto something: {other:?}"), + } + // The item lands, and the engine's reconcile runs after the landing, as `Dispatcher` does. + plx_data::metadata::set_current_for_test(test_store().state_mut(), Some(resumable(sid))); + step(&mut screen, &ScreenEvent::StoreChanged(StoreId::Metadata.ord(), 1), Some(first)); + let landed = Cx { focus: engine.read(OWNER), ..cx(&measure, None) }; + let after = match engine.reconcile::(OWNER, &screen, &landed) { + Outcome::Moved { to, .. } => to.elem, + Outcome::Nothing => first, + other => panic!("{other:?}"), + }; + let want = if no_driver { first_extra(&screen) } else { hero::ELEM_PLAY }; + assert_eq!(after, want, "no_driver={no_driver} seeded={seeded}: where focus stands once the item is there"); + clear(); + } +} + +/// `Enter` makes the seat the page's own only for the page it is about: a FRESH open with no driver, +/// whatever its item (a page whose item is there can still see a later landing change its default). +/// With a driver Play is the default from the first frame and the page keeps no self-seat, and a Back +/// return brings the viewer's own place, which ends the claim a fresh open had made. A body nothing +/// has entered yet (one rebuilt for a return, between its mount and its `Enter`, while the engine +/// still holds the viewer's cursor on the entry) claims nothing. +#[test] +fn enter_makes_the_seat_the_pages_own_only_for_a_fresh_open_with_no_driver() { + use plx_ui::screen::Enter; + let sid = ServerId::UNSET; + let fresh = Enter::Fresh { focus: FocusTarget::FirstInGroup(hero::HERO_GROUP) }; + let built = DetailScreen::new(EntryId(7), sid, "movie".into(), plx_data::pms::HubsSnapshot::empty_for_test().view()); + assert!(!built.provisional, "a body nothing has entered claims no seat"); + // (what, no driver, item landed, the enters in order, the page's own seat after them) + for (what, no_driver, landed, enters, own) in [ + ("a fresh open before its item lands", true, false, vec![fresh], true), + ("a fresh open whose item is already there", true, true, vec![fresh], true), + ("a fresh open with a driver composed", false, false, vec![fresh], false), + ("a return after a fresh open", true, false, vec![fresh, Enter::Restored], false), + ("a restored enter", true, false, vec![Enter::Restored], false), + ] { + let guard = install(if landed { resumable(sid) } else { Detail { sid, rk: "other".into(), ..Default::default() } }); + let _driver = NoDriver::set(no_driver); + let mut screen = bare(&guard, sid, "movie"); + for enter in enters { + step(&mut screen, &ScreenEvent::Enter(enter), None); + } + assert_eq!(screen.provisional, own, "{what}"); + clear(); + } +} + +/// Focus only ever lands on a control of the row that draws a focused face. The shared button draws +/// none while disabled (`widgets::Button::face_now`), which is why a disabled control owns no stop. +#[test] +fn the_control_focus_lands_on_draws_a_focused_face_and_a_disabled_one_never_would() { + let sid = ServerId::UNSET; + let measure = plx_ui::fixture::FixtureMeasure; + // What the row draws once control `focus`'s lift spring has settled (`ctl_pop` is what `Tick` + // steps); `None` is the row at rest. + let drawn = |screen: &mut DetailScreen, focus: Option| { + for _ in 0..120 { + screen.ctl_pop.step(focus, 0.05); + } + plx_ui::draw_census::capture_inks(|| screen.draw_buttons(plx_ui::Painter::recording(), &cx(&measure, None), 600.0, 1.0)) + }; + for no_driver in [false, true] { + let guard = install(resumable(sid)); + let _driver = NoDriver::set(no_driver); + let mut screen = bare(&guard, sid, "movie"); + let set = screen.hero_set(test_store().view()); + let at_rest = drawn(&mut screen, None); + // Every control the row owns a stop on draws a focused face: a focus that travels onto one + // is never invisible. (With a driver the page opens on Play; without one it opens below the + // row, and the row's own stops are reached by travel.) + let (row, n) = hero::visible_ctls(set, hero::Stops { full_trailer: false, no_playback: no_driver }); + for &stop in &row[..n] { + let index = hero::index_of(set, stop).expect("in the row"); + assert_ne!(drawn(&mut screen, Some(index)), at_rest, "no_driver={no_driver}: {stop:?} draws a focused face"); + } + if no_driver { + for ctl in [hero::HeroCtl::Play, hero::HeroCtl::Restart] { + let index = hero::index_of(set, ctl).expect("in the row"); + assert_eq!(drawn(&mut screen, Some(index)), at_rest, + "{ctl:?} is drawn disabled: focused or not it draws the same, which is why it owns no stop"); + } + } + clear(); + } +} + +#[test] +fn focus_travels_between_the_controls_that_can_act_and_never_onto_one_that_cannot() { + let sid = ServerId::UNSET; + // (driver composed, the row's stops in order) + for (no_driver, stops) in [ + (false, vec![hero::ELEM_PLAY, hero::ELEM_WATCHLIST, hero::ELEM_RESTART, hero::ELEM_MARK_WATCHED]), + (true, vec![hero::ELEM_WATCHLIST, hero::ELEM_MARK_WATCHED]), + ] { + let guard = install(resumable(sid)); + let _driver = NoDriver::set(no_driver); + let screen = bare(&guard, sid, "movie"); + let mut engine = FocusEngine::new(); + engine.set(OWNER, key(stops[0]), Some(hero::HERO_GROUP), By::Restore); + for pair in stops.windows(2) { + assert_eq!(moved_to(collection_move(&screen, &mut engine, Dir::Right), "RIGHT along the row"), pair[1], + "no_driver={no_driver}: RIGHT from {:?}", pair[0]); + } + assert!(matches!(collection_move(&screen, &mut engine, Dir::Right), Outcome::Nothing), "the row ends"); + for pair in stops.windows(2).rev() { + assert_eq!(moved_to(collection_move(&screen, &mut engine, Dir::Left), "LEFT along the row"), pair[0], + "no_driver={no_driver}: LEFT from {:?}", pair[1]); + } + assert!(matches!(collection_move(&screen, &mut engine, Dir::Left), Outcome::Nothing), + "no_driver={no_driver}: LEFT of the first stop is the row's edge, not a disabled pill"); + // Whatever key is pressed from whatever stop, focus never lands on a control that plays. + for from in &stops { + for dir in [Dir::Left, Dir::Right, Dir::Up, Dir::Down] { + engine.set(OWNER, key(*from), Some(hero::HERO_GROUP), By::Restore); + if let Outcome::Moved { to, .. } = collection_move(&screen, &mut engine, dir) { + assert!(!no_driver || !ctl_of(to.elem).is_some_and(hero::HeroCtl::starts_playback), + "no_driver={no_driver}: {dir:?} from {from} reached a control that plays"); + } + } + } + clear(); + } +} + +/// Coming back UP into the row from the section below seats on a stop of the row, never on a +/// disabled Play, and on the first one even when it writes (here every stop does): the viewer chose +/// the row, and the write controls stay reachable by travel. The engine's `Seat::First` is +/// `DetailScreen::seat`. +#[test] +fn up_into_the_row_seats_on_its_first_stop() { + let sid = ServerId::UNSET; + for (no_driver, first) in [(false, hero::ELEM_PLAY), (true, hero::ELEM_WATCHLIST)] { + let mut d = resumable(sid); + // No Extras shelf (the trailer) between the row and Related: UP from Related is the row. + d.extras.clear(); + d.related = vec![Default::default(), Default::default()]; + let guard = install(d); + let _driver = NoDriver::set(no_driver); + let screen = bare(&guard, sid, "movie"); + let related = screen.engine_key(related::elem(0).unwrap()).unwrap(); + let mut engine = FocusEngine::new(); + engine.set(OWNER, key(related), Some(related::RELATED_GROUP), By::Restore); + let up = moved_to(collection_move(&screen, &mut engine, Dir::Up), "UP out of the first section"); + assert_eq!(up, first, "no_driver={no_driver}"); + clear(); + } +} + +/// A page that opened below its row (a movie with no driver) still reaches the row's write controls +/// by travel: UP seats on the first, RIGHT reaches the next, and DOWN leaves the row again. The page's +/// FIRST seat is the default below the row even when focus is still on another page's key, while an +/// UP from a focus already on this page is the viewer's own choice of the row. +#[test] +fn the_write_controls_stay_reachable_by_travel_from_a_page_that_opened_below_them() { + let sid = ServerId::UNSET; + let measure = plx_ui::fixture::FixtureMeasure; + let guard = install(resumable(sid)); + let _driver = NoDriver::set(true); + let screen = bare(&guard, sid, "movie"); + // The container's fresh enter, while the scope still reads the page that was left (another entry). + let mut elsewhere = cx(&measure, None); + elsewhere.focus.current = Some(FocusKey { entry: EntryId(9), elem: hero::ELEM_PLAY }); + let mut engine = FocusEngine::new(); + let landed = match engine.enter::(OWNER, &screen, FocusTarget::FirstInGroup(hero::HERO_GROUP), None, &elsewhere) { + Outcome::Moved { to, .. } => to.elem, + other => panic!("an entry moves focus onto something: {other:?}"), + }; + assert_eq!(landed, first_extra(&screen), "another entry's focus is not this page's: it opens by default"); + assert_eq!(moved_to(collection_move(&screen, &mut engine, Dir::Up), "UP into the row"), hero::ELEM_WATCHLIST); + assert_eq!(moved_to(collection_move(&screen, &mut engine, Dir::Right), "RIGHT along the row"), hero::ELEM_MARK_WATCHED); + assert_eq!(moved_to(collection_move(&screen, &mut engine, Dir::Down), "DOWN out of the row"), first_extra(&screen)); + clear(); +} + +/// A restored spot names a column of the drawn row. A column the row still stops on keeps that +/// control (the viewer's own position, a write control included); one that is no longer a stop +/// (Play and Restart with no driver) resolves by the page's default rule, not onto the nearest stop, +/// which would be a write: here, below the row. +#[test] +fn a_restored_hero_spot_keeps_the_control_it_names_and_otherwise_takes_the_default() { + let sid = ServerId::UNSET; + let measure = plx_ui::fixture::FixtureMeasure; + // columns: 0 Play, 1 Watchlist, 2 Restart, 3 Mark watched; `None` is the default below the row + for (no_driver, col, lands) in [ + (false, 0, Some(hero::ELEM_PLAY)), (false, 2, Some(hero::ELEM_RESTART)), + (true, 0, None), (true, 1, Some(hero::ELEM_WATCHLIST)), (true, 2, None), + (true, 3, Some(hero::ELEM_MARK_WATCHED)), + ] { + let guard = install(resumable(sid)); + let _driver = NoDriver::set(no_driver); + let mut screen = bare(&guard, sid, "movie"); + screen.restore(&Spot { section: 0, col, ..Default::default() }, test_store().view()); + let got = Focusable::::reconcile(&screen, key(hero::ELEM_PLAY), &cx(&measure, None)); + assert_eq!(got.elem, lands.unwrap_or_else(|| first_extra(&screen)), "no_driver={no_driver}: column {col}"); + clear(); + } +} + +/// A spot saved on a section the item no longer has (no related shelf here) falls back to the page's +/// default: Play when a driver can play, else below the row. +#[test] +fn a_restore_whose_section_is_gone_falls_back_to_the_default() { + let sid = ServerId::UNSET; + let measure = plx_ui::fixture::FixtureMeasure; + for no_driver in [false, true] { + let guard = install(resumable(sid)); + let _driver = NoDriver::set(no_driver); + let mut screen = bare(&guard, sid, "movie"); + screen.restore(&Spot { section: 3, col: 2, ..Default::default() }, test_store().view()); + let got = Focusable::::reconcile(&screen, key(hero::ELEM_MARK_WATCHED), &cx(&measure, None)); + let first = if no_driver { first_extra(&screen) } else { hero::ELEM_PLAY }; + assert_eq!(got.elem, first, "no_driver={no_driver}"); + clear(); + } +} + +/// A restore retires once focus sits on the place it resolves to: with no driver that is the default +/// below the row, not the Play the spot named, so the page does not keep re-seating a focus that +/// already landed. Focus on any other place of the page leaves it armed. +#[test] +fn a_restore_retires_once_focus_is_on_the_place_the_page_resolves_it_to() { + let sid = ServerId::UNSET; + for no_driver in [false, true] { + let guard = install(resumable(sid)); + let _driver = NoDriver::set(no_driver); + let mut screen = bare(&guard, sid, "movie"); + // `step` takes the page's own (local) elem and keys it itself. + let lands = if no_driver { extras::elem(0).expect("an extras card") } else { hero::ELEM_PLAY }; + screen.restore(&Spot { section: 0, col: 0, ..Default::default() }, test_store().view()); + assert!(screen.restore_intent.is_some(), "premise: the restore is armed"); + // Focus on any other place of the page (the bookmark disc is a stop either way) is not where + // the restore resolves to: it stays armed and keeps seating. + step(&mut screen, &ScreenEvent::Tick(plx_machine::machine::Tick { ms: 16, dt_us: 16_667 }), Some(hero::ELEM_WATCHLIST)); + assert!(screen.restore_intent.is_some(), "no_driver={no_driver}: focus on the bookmark is not the restore's target"); + step(&mut screen, &ScreenEvent::Tick(plx_machine::machine::Tick { ms: 16, dt_us: 16_667 }), Some(lands)); + assert!(screen.restore_intent.is_none(), "no_driver={no_driver}: focus is on {lands}, the restore's target"); + clear(); + } +} + +/// The pointer reaches only what owns a stop: hovering a disabled pill must not park focus on it. +#[test] +fn the_pointer_registers_no_stop_on_a_control_that_cannot_act() { + let sid = ServerId::UNSET; + let measure = plx_ui::fixture::FixtureMeasure; + for no_driver in [false, true] { + let guard = install(resumable(sid)); + let _driver = NoDriver::set(no_driver); + let mut screen = bare(&guard, sid, "movie"); + let stops = drawn_stops(&mut screen, &cx(&measure, None)); + let has = |elem: u32| stops.iter().any(|stop| stop.key.elem == elem); + assert!(has(hero::ELEM_WATCHLIST) && has(hero::ELEM_MARK_WATCHED), "no_driver={no_driver}"); + assert_eq!((has(hero::ELEM_PLAY), has(hero::ELEM_RESTART)), (!no_driver, !no_driver), "no_driver={no_driver}"); + clear(); + } +} + +/// Play, Restart, Trailer and a Play Version pick start a playback with a driver and do nothing +/// without one; a control that does not play still acts. +#[test] +fn every_control_that_plays_is_inert_with_no_driver_and_unchanged_with_one() { + let sid = ServerId::UNSET; + for no_driver in [false, true] { + let guard = install(resumable(sid)); + let _driver = NoDriver::set(no_driver); + let mut screen = bare(&guard, sid, "movie"); + for (name, event, focus) in [ + ("Play", ScreenEvent::Activate(hero::ELEM_PLAY), hero::ELEM_PLAY), + ("Restart", ScreenEvent::Activate(hero::ELEM_RESTART), hero::ELEM_RESTART), + ("Trailer", ScreenEvent::Activate(hero::ELEM_TRAILER), hero::ELEM_TRAILER), + ("Play Version", ScreenEvent::App(AppMsg::PlayVersion(plx_plex::plex::MediaId(7))), hero::ELEM_VERSION), + ] { + let (_, effects) = step(&mut screen, &event, Some(focus)); + assert_eq!(play_item(&effects).is_some(), !no_driver, "{name}, no_driver={no_driver}"); + } + // The watched toggle plays nothing and still writes. + let (_, effects) = step(&mut screen, &ScreenEvent::Activate(hero::ELEM_MARK_WATCHED), Some(hero::ELEM_MARK_WATCHED)); + assert!(effects.iter().any(|e| matches!(e.fx, Fx::App(AppFx::Store(StoreId::ViewState, _)))), + "Mark watched still acts, no_driver={no_driver}"); + clear(); + } +} + +/// A version pick plays THAT version with a driver (it is `Some(media)` on the intent, not the +/// default one), so the inertness above is the guard and not a pick that never played. +#[test] +fn a_version_pick_plays_that_version_when_a_driver_is_composed() { + let sid = ServerId::UNSET; + let guard = install(resumable(sid)); + let mut screen = bare(&guard, sid, "movie"); + let (_, effects) = step(&mut screen, &ScreenEvent::App(AppMsg::PlayVersion(plx_plex::plex::MediaId(7))), None); + let (play, _) = play_item(&effects).expect("a version pick plays"); + assert!(matches!(play, PlayIntent::Item { version: Some(plx_plex::plex::MediaId(7)), .. }), "the pick names its version"); + clear(); +} + +/// A page running the way `Dispatcher` runs it: `Enter` reaches the screen and the engine then seats +/// the entry; after every landing the engine's `reconcile` runs, the move it makes comes back to the +/// screen as `FocusMoved`, and the screen ticks (`dispatch.rs`, step 6). A test that calls `reconcile` +/// by hand and never feeds the move back cannot see a `FocusMoved` arm that takes the page's own move +/// for the viewer's. +struct Running { + screen: DetailScreen, + engine: FocusEngine, + /// Every move the engine reported, as `(where, by)`. + moves: Vec<(u32, By)>, + ms: u32, +} + +impl Running { + /// Opened the way a navigation opens a fresh page. + fn open(screen: DetailScreen) -> Self { + let mut run = Running { screen, engine: FocusEngine::new(), moves: Vec::new(), ms: 0 }; + let fresh = plx_ui::screen::Enter::Fresh { focus: FocusTarget::FirstInGroup(hero::HERO_GROUP) }; + step(&mut run.screen, &ScreenEvent::Enter(fresh), None); + let measure = plx_ui::fixture::FixtureMeasure; + let outcome = run.engine.enter::(OWNER, &run.screen, FocusTarget::FirstInGroup(hero::HERO_GROUP), None, &cx(&measure, None)); + run.deliver(outcome); + run + } + + fn deliver(&mut self, outcome: Outcome) { + if let Outcome::Moved { from, to, by } = outcome { + self.moves.push((to.elem, by)); + step(&mut self.screen, &ScreenEvent::FocusMoved { from, to, by }, Some(to.elem)); + } + } + + fn focus(&self) -> u32 { + self.engine.read(OWNER).current.expect("the page holds focus").elem + } + + /// One frame: the engine reconciles, the move is delivered back, the page ticks. + fn frame(&mut self) { + let measure = plx_ui::fixture::FixtureMeasure; + let landed = Cx { focus: self.engine.read(OWNER), ..cx(&measure, None) }; + let outcome = self.engine.reconcile::(OWNER, &self.screen, &landed); + self.deliver(outcome); + self.ms += 16; + let at = self.focus(); + step(&mut self.screen, &ScreenEvent::Tick(plx_machine::machine::Tick { ms: self.ms, dt_us: 16_667 }), Some(at)); + } + + fn frames(&mut self, n: usize) { + for _ in 0..n { + self.frame(); + } + } + + /// The store publishes `d` as the page's item. + fn land(&mut self, d: Detail) { + plx_data::metadata::set_current_for_test(test_store().state_mut(), Some(d)); + self.changed(); + } + + /// The Metadata store raised its notice. + fn changed(&mut self) { + let at = self.focus(); + step(&mut self.screen, &ScreenEvent::StoreChanged(StoreId::Metadata.ord(), 1), Some(at)); + } + + /// A direction key the viewer presses: the screen sees it, then the engine moves focus if it can. + fn press(&mut self, key: Key) { + let event = ScreenEvent::Input(InputEvent { + at: Default::default(), + source: plx_machine::machine::Source::Script, + kind: InputKind::Key { key, sym: 0, wcode: 0, edge: Edge::Down, at_edge: false }, + }); + let at = self.focus(); + step(&mut self.screen, &event, Some(at)); + let measure = plx_ui::fixture::FixtureMeasure; + let context = Cx { focus: self.engine.read(OWNER), ..cx(&measure, None) }; + let mut links = Vec::new(); + Screen::::links(&self.screen, &mut links); + let outcome = self.engine.move_dir(OWNER, &self.screen, &links, Dir::of_key(key).expect("a direction"), &context); + self.deliver(outcome); + } + + /// OK on the focused control, as a press that commits delivers it. + fn ok(&mut self) -> Vec> { + let at = self.focus(); + step(&mut self.screen, &ScreenEvent::Activate(at), Some(at)).1 + } +} + +fn is_write(elem: u32) -> bool { + ctl_of(elem).is_some_and(hero::HeroCtl::writes_account) +} + +fn writes_viewstate(effects: &[plx_machine::machine::Stamped]) -> bool { + effects.iter().any(|e| matches!(e.fx, Fx::App(AppFx::Store(StoreId::ViewState, _)))) +} + +/// **Account safety does not depend on a restore firing in the landing frame.** A show opened from an +/// episode's Go to Show arrives with a restore that names a season (`Spot { season }`, `open_detail`). +/// The show opens on its on-deck season, so while the named one loads the restore WAITS and answers +/// nothing, and when the named season is not the show's it RETIRES without ever answering; either way +/// the page was seated, before its item landed, on the watched toggle, which is live the moment the +/// item is there. The page's own seat follows the page's default instead of waiting on the restore. +#[test] +fn a_show_opened_with_a_season_restore_never_rests_on_the_write_control_while_it_loads() { + let sid = ServerId::UNSET; + for (what, season, loading) in [ + ("a season the show has, which is not the on-deck one, still loading", 2, true), + ("a season the show does not have", 9, false), + ] { + let guard = install(Detail { sid, rk: "other".into(), ..Default::default() }); + let _driver = NoDriver::set(true); + let mut screen = bare(&guard, sid, "show"); + // What `open_detail` seeds an episode's Go to Show with. + screen.restore(&Spot { season: Some(season), ..Default::default() }, test_store().view()); + let mut run = Running::open(screen); + assert_eq!(run.focus(), hero::ELEM_MARK_WATCHED, "{what}: premise: seated before the item lands, on the toggle"); + run.land(detail(sid, "show")); + plx_data::metadata::set_season_loading_for_test(test_store().adapter_ref(), loading); + run.frames(6); + let at = run.focus(); + assert!(!is_write(at), "{what}: focus is on a control that writes: {at}"); + assert!(matches!(run.screen.locate(at, test_store().view()), Some(Located::Season(0))), "{what}: the page's default is the season strip's selected tab"); + assert!(!writes_viewstate(&run.ok()), "{what}: a reflex OK writes nothing"); + plx_data::metadata::set_season_loading_for_test(test_store().adapter_ref(), false); + clear(); + } +} + +/// **A direction key that moves nothing is not the viewer's choice of the seat.** Before the item +/// lands the row's only stop is the toggle, so a key moves focus nowhere, yet it cancels the restore +/// (`Input`); and an OK before the item lands presses nothing. Neither may leave focus on the toggle +/// when it goes live. +#[test] +fn a_key_or_an_ok_before_the_item_lands_leaves_the_page_free_to_move_off_the_toggle() { + let sid = ServerId::UNSET; + for (what, seeded, key, ok) in [ + ("a seeded page, DOWN", true, Some(Key::Down), false), + ("an unseeded page, DOWN", false, Some(Key::Down), false), + ("a seeded page, LEFT", true, Some(Key::Left), false), + ("a seeded page, OK", true, None, true), + ("an unseeded page, OK", false, None, true), + ] { + let guard = install(Detail { sid, rk: "other".into(), ..Default::default() }); + let _driver = NoDriver::set(true); + let mut screen = bare(&guard, sid, "movie"); + if seeded { + screen.restore(&Spot::default(), test_store().view()); + } + let mut run = Running::open(screen); + assert_eq!(run.focus(), hero::ELEM_MARK_WATCHED, "{what}: premise"); + if let Some(key) = key { + run.press(key); + } + if ok { + assert!(!writes_viewstate(&run.ok()), "{what}: OK before the item lands writes nothing"); + } + assert_eq!(run.focus(), hero::ELEM_MARK_WATCHED, "{what}: premise: nothing moved focus"); + run.land(resumable(sid)); + run.frames(6); + assert_eq!(run.focus(), first_extra(&run.screen), "{what}: the landing took focus off the toggle"); + assert!(!writes_viewstate(&run.ok()), "{what}: the OK after the landing writes nothing either"); + clear(); + } +} + +/// A movie, with no playback driver, whose item has landed with only write controls in its row (so +/// the page seats below the row) and whose second source has not: `(guard, own server, the other)`. +/// The second source lands with [`alt_lands`]. +fn movie_awaiting_its_second_source() -> (plx_base::testlock::Serial, ServerId, ServerId, NoDriver) { + let guard = install(Detail { sid: ServerId::UNSET, rk: "other".into(), ..Default::default() }); + plx_plex::plex::reset_servers_for_test(); + let sid = plx_plex::plex::register_for_test("w6c-alt-own", "127.0.0.1", 1, "t", "c1"); + let other = plx_plex::plex::register_for_test("w6c-alt-other", "127.0.0.1", 2, "t", "c2"); + let driver = NoDriver::set(true); + plx_data::metadata::set_current_for_test(test_store().state_mut(), Some(resumable(sid))); + (guard, sid, other, driver) +} + +/// *Also available* lands (`request_alt_sources`): the row gains a control that does not write, which +/// is the page's default from then on. +fn alt_lands(run: &mut Running, sid: ServerId, other: ServerId) { + test_store().run_with_keys(plx_data::stores::metadata::MetadataCmd::AltInstall { + sid, + rk: "movie".into(), + copies: vec![ + plx_data::metadata::AltCopy { sid, rk: "movie".into(), ..Default::default() }, + plx_data::metadata::AltCopy { sid: other, rk: "movie-copy".into(), ..Default::default() }, + ], + }, &plx_data::pms::registry_keys_for_test()); + run.changed(); + assert!(run.screen.hero_set(test_store().view()).alt, "premise: the second source landed"); +} + +/// **A seat nobody chose follows the head** (`screens/src/CLAUDE.md`). A movie whose first landing has +/// only write controls seats below the row; a later landing (*Also available*, `request_alt_sources`) +/// gives the row a stop that does not write, which is the page's default, and focus the viewer never +/// moved goes there. +#[test] +fn a_later_landing_that_changes_the_default_moves_a_seat_the_viewer_never_chose() { + let (guard, sid, other, _driver) = movie_awaiting_its_second_source(); + let screen = bare(&guard, sid, "movie"); + let mut run = Running::open(screen); + run.frames(3); + let below = first_extra(&run.screen); + assert_eq!(run.focus(), below, "premise: the first landing has only writes in its row, so the page seats below it"); + alt_lands(&mut run, sid, other); + run.frames(6); + assert_eq!(run.focus(), hero::ELEM_ALT, "the seat nobody chose follows the head onto the control that can act"); + let settled = run.moves.len(); + run.frames(10); + assert_eq!(run.moves.len(), settled, "and it stays there: no frame moves it again"); + clear(); + plx_plex::plex::reset_servers_for_test(); +} + +/// **A focus the viewer placed is never moved by a landing.** The viewer's own move (a direction key +/// that moves: here DOWN and UP among the sections, then UP into the row, where the write controls +/// are reachable) ends the page's claim on the seat: the later landing that changes the default does +/// not take it from them. +#[test] +fn a_landing_never_moves_a_focus_the_viewer_placed() { + let (guard, sid, other, _driver) = movie_awaiting_its_second_source(); + let mut run = Running::open(bare(&guard, sid, "movie")); + run.frames(3); + // The page seated below the row (nothing in it acts without a driver); DOWN and back UP stay in + // the sections, the next UP crosses into the row, where every control writes. + for key in [Key::Down, Key::Up, Key::Up] { + run.press(key); + run.frames(3); + } + let chosen = run.focus(); + assert!(is_write(chosen), "premise: UP into an all-writes row seats on one of its write controls: {chosen}"); + alt_lands(&mut run, sid, other); + run.frames(10); + assert_eq!(run.focus(), chosen, "the later landing leaves the viewer's own focus where they put it"); + clear(); + plx_plex::plex::reset_servers_for_test(); +} + +/// **An OK on a landed page is the viewer's own act on the seat they hold**, so the later landing +/// leaves focus on it. (An OK before the item lands presses nothing and is not one: +/// `a_key_or_an_ok_before_the_item_lands_leaves_the_page_free_to_move_off_the_toggle`.) +#[test] +fn an_ok_on_a_landed_page_keeps_the_seat_it_pressed_on() { + let (guard, sid, other, _driver) = movie_awaiting_its_second_source(); + let mut run = Running::open(bare(&guard, sid, "movie")); + run.frames(3); + let below = first_extra(&run.screen); + assert_eq!(run.focus(), below, "premise: the page seated below the row"); + run.ok(); + alt_lands(&mut run, sid, other); + run.frames(10); + assert_eq!(run.focus(), below, "the later landing leaves the control the viewer pressed OK on"); + clear(); + plx_plex::plex::reset_servers_for_test(); +} + +/// **Only a move the viewer makes ends the page's claim on its seat.** A key that moved focus, the +/// pointer and a script are the viewer's; the engine's own seat and the reconcile that follows a +/// landing are the page's, and must not end it, or the first frame after the landing would. +#[test] +fn only_a_move_the_viewer_makes_ends_the_pages_claim_on_the_seat() { + use plx_ui::screen::Enter; + let sid = ServerId::UNSET; + let _driver = NoDriver::set(true); + for (by, the_viewers) in [(By::Dir, true), (By::Pointer, true), (By::Script, true), (By::Reconcile, false), (By::Restore, false)] { + let guard = install(Detail { sid, rk: "other".into(), ..Default::default() }); + let mut screen = bare(&guard, sid, "movie"); + step(&mut screen, &ScreenEvent::Enter(Enter::Fresh { focus: FocusTarget::FirstInGroup(hero::HERO_GROUP) }), None); + assert!(screen.provisional, "premise: a fresh open with no driver seats the page's own focus"); + let to = key(hero::ELEM_MARK_WATCHED); + step(&mut screen, &ScreenEvent::FocusMoved { from: None, to, by }, Some(to.elem)); + assert_eq!(screen.provisional, !the_viewers, "a move by {by:?}"); + clear(); + } +} + +/// **A hold is the viewer's own act**, when it opens something (a season, an episode's still, a +/// Related or Collection card): the page does not move focus out from under the menu it opened. A +/// hold that opens nothing (the watched toggle) is not one. +#[test] +fn a_hold_that_opens_a_menu_ends_the_pages_claim_and_one_that_opens_nothing_does_not() { + use plx_ui::screen::Enter; + let sid = ServerId::UNSET; + let _driver = NoDriver::set(true); + let hold = ScreenEvent::PressHold(plx_machine::machine::PressId(9)); + for (what, held, own) in [("a season tab", season::elem(0).unwrap(), false), ("the watched toggle", hero::ELEM_MARK_WATCHED, true)] { + let guard = install(detail(sid, "show")); + let mut screen = bare(&guard, sid, "show"); + step(&mut screen, &ScreenEvent::Enter(Enter::Fresh { focus: FocusTarget::FirstInGroup(hero::HERO_GROUP) }), None); + assert!(screen.provisional, "{what}: premise"); + step(&mut screen, &hold, Some(held)); + assert_eq!(screen.provisional, own, "{what}"); + clear(); + } +} diff --git a/rust-modules/screens/src/detail/tests.rs b/rust-modules/screens/src/detail/tests.rs index 3175449d14..ce5192a722 100644 --- a/rust-modules/screens/src/detail/tests.rs +++ b/rust-modules/screens/src/detail/tests.rs @@ -33,7 +33,14 @@ impl ScreenArg for TestArg { pub(super) struct TestHost; impl crate::registry::ScreenInputsLike for TestHost { - fn screen_inputs<'a>(_: &Cx<'a, Self>) -> &'a crate::registry::ScreenInputs { crate::registry::caption_fixture() } + fn screen_inputs<'a>(_: &Cx<'a, Self>) -> &'a crate::registry::ScreenInputs { + if NO_DRIVER.with(|flag| flag.get()) { crate::registry::no_driver_fixture() } else { crate::registry::caption_fixture() } + } +} + +thread_local! { + /// TEST ONLY: the host publishes a platform that composed no playback driver. + static NO_DRIVER: std::cell::Cell = const { std::cell::Cell::new(false) }; } impl crate::registry::PlayerLike for TestHost { @@ -173,6 +180,7 @@ pub(super) fn bare_held(sid: ServerId, rk: &str) -> DetailScreen { refresh: DetailRefreshPhase::None, refresh_gen: 0, restore_intent: None, + provisional: false, teardown_cleared: false, withdrawn: false, scroll: Spring::at(0.0), @@ -3356,7 +3364,7 @@ fn extras_sit_after_cast_and_crew_and_do_not_move_the_compact_title() { spot.section = 6; spot.col = 1; screen.restore(&spot, test_store().view()); - let key = screen.restore_focus(test_store().view()).expect("extras column restores"); + let key = screen.restore_focus(&cx(&plx_ui::fixture::FixtureMeasure, None)).expect("extras column restores"); assert!(matches!(screen.locate(key, test_store().view()), Some(Located::Extras(1)))); let movie = Detail { @@ -4741,10 +4749,10 @@ fn a_restore_onto_episode_700_waits_for_its_page_and_then_seats_it() { seek: Default::default(), }); screen.sync_keys(test_store().view()); - assert_eq!(screen.restore_focus(test_store().view()), None, "episode 700's page has not landed"); + assert_eq!(screen.restore_focus(&cx(&plx_ui::fixture::FixtureMeasure, None)), None, "episode 700's page has not landed"); land_page(1000, 11); screen.sync_keys(test_store().view()); - assert_eq!(screen.restore_focus(test_store().view()), episode_key(&screen, 700, episodes::Row::Still)); + assert_eq!(screen.restore_focus(&cx(&plx_ui::fixture::FixtureMeasure, None)), episode_key(&screen, 700, episodes::Row::Still)); clear(); } @@ -5174,7 +5182,7 @@ fn a_non_plex_guid_has_no_bookmark_disc() { let set = screen.hero_set(test_store().view()); assert!(!set.watchlist); assert!(!hero::hero_ctls(set).0[..hero::hero_ctls(set).1].contains(&hero::HeroCtl::Watchlist)); - assert!(!hero::visible_ctls(set, false).0[..hero::visible_ctls(set, false).1].contains(&hero::HeroCtl::Watchlist)); + assert!(!hero::visible_ctls(set, hero::Stops::trailer(false)).0[..hero::visible_ctls(set, hero::Stops::trailer(false)).1].contains(&hero::HeroCtl::Watchlist)); assert_eq!(hero::index_of(set, hero::HeroCtl::Watchlist), None); let (_, fx) = step(&mut screen, &ScreenEvent::Activate(hero::ELEM_WATCHLIST), Some(hero::ELEM_WATCHLIST)); assert!(item_menu_acts(&fx).is_empty()); @@ -6103,3 +6111,49 @@ pub(crate) fn detail_conforms() -> plx_ui::a11y::Namespaces { #[path = "hero_shade_tests.rs"] mod hero_shade; + +#[path = "no_driver_tests.rs"] +mod no_driver; + +/// W6c: a platform that composes no playback driver leaves Detail's Play pill inert (it owns no focus +/// stop either: `no_driver`'s tests). The same press with a driver composed starts the play, so the +/// guard is the only difference. +#[test] +fn the_hero_play_is_inert_when_no_playback_driver_is_composed() { + let sid = ServerId::UNSET; + for (no_driver, plays) in [(false, true), (true, false)] { + let _guard = install(Detail { + sid, rk: "movie".into(), kind: "movie".into(), part: "/library/parts/1/file.mkv".into(), + ..Default::default() + }); + NO_DRIVER.with(|flag| flag.set(no_driver)); + let mut screen = bare(&_guard, sid, "movie"); + let (_, effects) = step(&mut screen, &ScreenEvent::Activate(hero::ELEM_PLAY), Some(hero::ELEM_PLAY)); + NO_DRIVER.with(|flag| flag.set(false)); + assert_eq!(play_item(&effects).is_some(), plays, "no_driver={no_driver}"); + clear(); + } +} + +/// W6c: the Play pill's label wears the shared button's disabled ink while no playback driver is +/// composed, and its ordinary ink otherwise: `Button::enabled`, not a screen-local look. +#[test] +fn the_play_pill_reads_disabled_when_no_playback_driver_is_composed() { + let sid = ServerId::UNSET; + let play_label = plx_os::i18n::msg::browse_detail_play(); + let mut inks = Vec::new(); + for no_driver in [false, true] { + let _guard = install(Detail { sid, rk: "movie".into(), kind: "movie".into(), ..Default::default() }); + NO_DRIVER.with(|flag| flag.set(no_driver)); + let screen = bare(&_guard, sid, "movie"); + let measure = plx_ui::fixture::FixtureMeasure; + let runs = plx_ui::draw_census::capture_runs(|| { + screen.draw_buttons(plx_ui::Painter::recording(), &cx(&measure, None), 600.0, 1.0) + }); + NO_DRIVER.with(|flag| flag.set(false)); + inks.push(runs.iter().find(|r| r.text == play_label).map(|r| r.ink)); + clear(); + } + assert_eq!(inks[1], Some(plx_ui::theme::INK_DISABLED), "no driver: the disabled ink"); + assert!(inks[0].is_some() && inks[0] != inks[1], "a driver composed: the ordinary ink"); +} diff --git a/rust-modules/screens/src/inputs.rs b/rust-modules/screens/src/inputs.rs index a35eb03f5a..1cd3f52e55 100644 --- a/rust-modules/screens/src/inputs.rs +++ b/rust-modules/screens/src/inputs.rs @@ -50,13 +50,17 @@ pub struct ScreenInputs { /// A host-local semantic revision, independent of server-roster changes. pub grant_generation: u64, pub resolution_offered: bool, + /// The playback backends the platform composed, as the session was told them at boot. A host + /// that never publishes the set (a cold or controlled one) keeps today's `FEED`, so nothing a + /// screen draws changes unless a live host says no driver is composed. + pub backends: plx_media::route::BackendSet, } impl Default for ScreenInputs { fn default() -> Self { Self { session: Arc::new(Session::default()), settled: false, visible_generation: 0, revision: 0, profile: Arc::new(CurrentProfile { user: None, generation: 0, stamp: String::new() }), current_server: ServerId::UNSET, servers: Default::default(), grants: Arc::new(GrantInputs::default()), - grant_generation: 0, resolution_offered: false, runtime_policy: RuntimePolicy::default(), preferences: None, + grant_generation: 0, resolution_offered: false, backends: plx_media::route::BackendSet::FEED, runtime_policy: RuntimePolicy::default(), preferences: None, install_language: Default::default(), running_language: Default::default(), player_presentation: Default::default() } } } @@ -81,6 +85,8 @@ impl ScreenInputs { plx_plex::plex::session::effective::(&self.session.prefs, own) } + /// Whether any playback driver is composed: with none, the Play control has nothing to start. + pub fn can_play(&self) -> bool { self.backends.uri || self.backends.feed } pub fn settled_session(&self) -> Option<&Arc> { self.settled.then_some(&self.session) } pub fn same_facts(&self, other: &Self) -> bool { self.runtime_policy == other.runtime_policy @@ -94,6 +100,7 @@ impl ScreenInputs { && self.current_server == other.current_server && self.servers == other.servers && self.resolution_offered == other.resolution_offered + && self.backends == other.backends && self.grant_generation == other.grant_generation && self.profile.generation == other.profile.generation && self.profile.stamp == other.profile.stamp @@ -135,6 +142,7 @@ pub(crate) fn capture_fixture() -> ScreenInputs { current_server: plx_plex::plex::current_server(), servers: Arc::new(servers), grant_generation: grant::revision(), resolution_offered: plx_os::tv::device::ui_resolution_offered(), runtime_policy: RuntimePolicy::default(), install_language: plx_os::i18n::saved_preference(), running_language: plx_os::i18n::current().preference(), player_presentation: Default::default(), + backends: plx_media::route::BackendSet::FEED, preferences: crate::registry::captions::TEST_UNDER_POSTERS.with(|cell| cell.get()).map(|setting| session::ProfilePrefs { under_posters: Some(setting), ..Default::default() }) } } @@ -149,6 +157,13 @@ pub(crate) fn caption_fixture() -> &'static ScreenInputs { })) } +/// The retained inputs of a live host whose platform composed no playback driver at all. +#[cfg(test)] +pub(crate) fn no_driver_fixture() -> &'static ScreenInputs { + static NONE: std::sync::OnceLock = std::sync::OnceLock::new(); + NONE.get_or_init(|| ScreenInputs { backends: plx_media::route::BackendSet::NONE, ..Default::default() }) +} + /// Immutable publications for legacy fixture contexts that outlive their helper call. /// Each capture is deliberately independent, like the fixtures' leaked catalog rows. #[cfg(test)] diff --git a/rust-modules/screens/src/item_menu.rs b/rust-modules/screens/src/item_menu.rs index 1dd20f90d6..dfbad27774 100644 --- a/rust-modules/screens/src/item_menu.rs +++ b/rust-modules/screens/src/item_menu.rs @@ -633,7 +633,7 @@ fn build_versions(rk: &str, versions: &[MediaVersion]) -> ItemForm { Form::new().section(plx_appkit::version_list::section(versions, ItemRow::Version, |v| Action::PlayVersion { rk: rk.to_string(), media: v.id, - })) + }, None)) } /// Beside the card, never over it: to its RIGHT by default, flipped to its LEFT when that would run diff --git a/rust-modules/screens/src/registry.rs b/rust-modules/screens/src/registry.rs index 469d46c55e..871a5bf195 100644 --- a/rust-modules/screens/src/registry.rs +++ b/rust-modules/screens/src/registry.rs @@ -28,7 +28,7 @@ pub use crate::family::SettingsPage; pub use crate::family::InnerViews; pub use crate::inputs::{moved, GrantInputs, RuntimePolicy, ScreenInputs}; #[cfg(test)] -pub(crate) use crate::inputs::{capture_fixture, caption_fixture, empty_fixture, publication_fixture}; +pub(crate) use crate::inputs::{capture_fixture, caption_fixture, empty_fixture, no_driver_fixture, publication_fixture}; /// The stored Under posters setting as the ui caption policy: the shared door a screen outside /// Settings (the Library's Collections page) reads it through, so none names `crate::settings`. pub use crate::settings::caption_policy_of; @@ -2483,7 +2483,7 @@ where ), AppArg::VersionsPanel(arg) => { let versions = versions_page(H::metadata(cx), arg).map_or(&[][..], crate::detail::hero_versions); - Box::new(crate::versions_panel::VersionsPanelScreen::new(entry, arg.clone(), versions)) + Box::new(crate::versions_panel::VersionsPanelScreen::new(entry, arg.clone(), versions, H::screen_inputs(cx).can_play())) } AppArg::TracksPanel(arg) => Box::new( crate::tracks_panel::TracksPanelScreen::new(entry, *arg), diff --git a/rust-modules/screens/src/versions_panel.rs b/rust-modules/screens/src/versions_panel.rs index 0337fb281a..42dbb08318 100644 --- a/rust-modules/screens/src/versions_panel.rs +++ b/rust-modules/screens/src/versions_panel.rs @@ -82,11 +82,14 @@ pub struct VersionsPanelScreen { } impl VersionsPanelScreen { - pub fn new(entry: EntryId, arg: VersionsArg, versions: &[MediaVersion]) -> Self { + /// `can_play` is whether the platform composed any playback driver (`ScreenInputs::can_play`): + /// without one every row is disabled and says why, and presses nothing. + pub fn new(entry: EntryId, arg: VersionsArg, versions: &[MediaVersion], can_play: bool) -> Self { let mut form = FormTable::new(plx_ui::table_screen::BAND_BASE); // rows carry a sub-line: the track menu's size class form.table.compact = false; - form.set(Form::new().section(plx_appkit::version_list::section(versions, VersionRow, |v| v.id)), Some(&VersionRow(0))); + let unavailable = (!can_play).then(plx_os::i18n::msg::browse_detail_no_playback); + form.set(Form::new().section(plx_appkit::version_list::section(versions, VersionRow, |v| v.id, unavailable)), Some(&VersionRow(0))); Self { entry, arg, versions: versions.iter().map(|v| v.id).collect(), form } } @@ -101,9 +104,15 @@ impl VersionsPanelScreen { } /// Close, and report row `elem`'s version to the page. Takes the elem, not the cursor: a click - /// names the stop it hit (`AltSourcesScreen::commit`). + /// names the stop it hit (`AltSourcesScreen::commit`). OK on a DISABLED row (no playback driver + /// composed) does nothing and the panel stays up, as on every disabled row (`ui/CLAUDE.md`: "OK + /// does nothing"); BACK still closes it. fn commit(&mut self, elem: u32, fx: &mut Effects<'_, H>) { - let media = match self.form.index_of_key(RowKey(elem)).and_then(|i| self.form.activate(i)) { + let activation = self.form.index_of_key(RowKey(elem)).map(|i| self.form.activate(i)); + if matches!(activation, Some(None)) { + return; + } + let media = match activation.flatten() { Some(plx_ui::form::Activation::Action(media)) => Some(media), _ => None, }; @@ -379,6 +388,7 @@ pub(crate) mod tests { EntryId(3), VersionsArg { host: InstanceId(9), sid: ServerId::from_raw(1), rk: "42".into(), anchor }, &plx_appkit::version_list::sample(), + true, ) } @@ -471,4 +481,55 @@ pub(crate) mod tests { }); assert_eq!(played, Some(plx_appkit::version_list::sample()[1].id), "the host page is told which version"); } + + /// A platform that composed no playback driver opens the same list with every row disabled and the + /// one reason noted under them (`browse.detail.no_playback`, the Detail facts line's own word): OK + /// on a row does nothing, as on every disabled row (`ui/CLAUDE.md`), so the panel stays up and + /// nothing is asked of a driver that is not there, while BACK still closes it. + #[test] + fn with_no_playback_driver_every_row_is_disabled_and_reports_nothing() { + use plx_machine::machine::{InputEvent, Source, Tick}; + let _lang = plx_os::i18n::language_on_this_thread_for_test(plx_os::i18n::Preference::En); + let why = plx_os::i18n::msg::browse_detail_no_playback(); + let anchor = [500.0f32, 600.0, 64.0, 64.0].map(f32::to_bits); + let arg = VersionsArg { host: InstanceId(9), sid: ServerId::from_raw(1), rk: "42".into(), anchor }; + // What one event does to a panel: the effects it pushes. + let drive = |p: &mut VersionsPanelScreen, ev: ScreenEvent| { + let mut out = Vec::new(); + let mut present = plx_machine::present::Present::new(); + let mut fx: Effects<'_, HostFixture> = + Effects::new(&mut out, MachineId::Instance(InstanceId(4)), &mut present); + Machine::::step(p, &ev, &cx(), &mut fx); + out.into_iter().map(|e| e.fx).collect::>() + }; + let closes = |fx: &[Fx]| fx.iter().any(|f| matches!(f, Fx::Nav(NavOp::Dismiss(EntryId(3))))); + let reports = |fx: &[Fx]| fx.iter().any(|f| matches!(f, + Fx::Deliver(_, Delivery::Screen(ScreenEvent::App(AppMsg::PlayVersion(_)))))); + for (can_play, disabled) in [(true, false), (false, true)] { + let mut p = VersionsPanelScreen::new(EntryId(3), arg.clone(), &plx_appkit::version_list::sample(), can_play); + let rows: Vec<_> = p.form.table.sections.iter().flat_map(|s| s.rows.iter()).collect(); + let versions: Vec<_> = rows.iter().filter(|row| !row.is_note()).collect(); + let notes: Vec<_> = rows.iter().filter(|row| row.is_note()).collect(); + assert_eq!(versions.len(), 2); + for row in versions { + assert_eq!(row.disabled, disabled, "can_play={can_play}"); + } + assert_eq!(notes.iter().map(|row| row.label.as_str()).collect::>(), + disabled.then_some(why).into_iter().collect::>(), "can_play={can_play}: the one note says why"); + // OK, through the handler's own arm (`Activate`, what a click and the engine's OK deliver). + let ok = drive(&mut p, ScreenEvent::Activate(1)); + assert_eq!((closes(&ok), reports(&ok)), (!disabled, !disabled), + "can_play={can_play}: OK on a row closes the panel and reports it only while the row is enabled"); + if disabled { + assert!(ok.is_empty(), "OK on a disabled row does nothing at all, got {} effects", ok.len()); + } + // BACK closes the panel whichever state it is in, and reports nothing. + let back = drive(&mut p, ScreenEvent::Input(InputEvent { + at: Tick::default(), + source: Source::Script, + kind: InputKind::Key { key: Key::Back, sym: 0, wcode: 0, edge: Edge::Down, at_edge: false }, + })); + assert!(closes(&back) && !reports(&back), "can_play={can_play}: BACK closes the panel and plays nothing"); + } + } } diff --git a/rust-modules/src/app/bridge.rs b/rust-modules/src/app/bridge.rs index 203f7b0699..6d02a2d090 100644 --- a/rust-modules/src/app/bridge.rs +++ b/rust-modules/src/app/bridge.rs @@ -1662,8 +1662,12 @@ impl Bridge<'_> { // No Player replay domain exists: controlled owners retain explicit neutral/supplied facts. if !self.retained.live_screen_inputs { return false; } let next = super::player_presentation::capture(ps); - if self.retained.screen_inputs.player_presentation == next { return false; } + // The set the composition published: the screens read it to disable Play when none is composed. + let backends = ps.backends(); + if self.retained.screen_inputs.player_presentation == next + && self.retained.screen_inputs.backends == backends { return false; } self.retained.screen_inputs.player_presentation = next; + self.retained.screen_inputs.backends = backends; self.retained.screen_inputs.revision = self.retained.screen_inputs.revision.wrapping_add(1); true } @@ -6014,6 +6018,32 @@ mod screen_input_publication_tests { }); } + /// W6c: the set the session was told reaches the screens as `ScreenInputs.backends`, moves the + /// frame's revision when it changes, and a controlled host keeps the default (today's) set. + #[test] + fn the_composed_backend_set_reaches_the_screen_inputs() { + use plx_media::route::BackendSet; + let _serial = plx_base::testlock::serial(); + let mut owner = crate::app::runtime_owners::Harness::new(|| 0); + let mut bridge = owner.bridge(); + let mut ps = plx_media::route::PlaybackSession::IDLE; + // The presentation half reads process-wide diagnostics another test may have left, so the + // first publication settles it and only the set's own effects are asserted. + bridge.publish_player_presentation(&ps); + assert_eq!(bridge.retained.screen_inputs.backends, BackendSet::FEED, + "the session's default set is the inputs' default"); + let revision = bridge.retained.screen_inputs.revision; + ps.install_backends(BackendSet::NONE); + assert!(bridge.publish_player_presentation(&ps), "a platform with no driver is a visible change"); + assert_eq!(bridge.retained.screen_inputs.backends, BackendSet::NONE); + assert_ne!(bridge.retained.screen_inputs.revision, revision); + assert!(!bridge.publish_player_presentation(&ps), "an unchanged set presents nothing"); + bridge.retained.live_screen_inputs = false; + ps.install_backends(BackendSet::BOTH); + assert!(!bridge.publish_player_presentation(&ps), "a controlled host publishes nothing"); + assert_eq!(bridge.retained.screen_inputs.backends, BackendSet::NONE); + } + #[test] fn captured_preference_live_pick_moves_without_waiting_for_stored_session() { use plx_plex::plex::session::{self, DeckPress, DeckPressPref}; diff --git a/rust-modules/src/app/content.rs b/rust-modules/src/app/content.rs index e2057d4618..140397dd27 100644 --- a/rust-modules/src/app/content.rs +++ b/rust-modules/src/app/content.rs @@ -594,6 +594,74 @@ fn halt_screen_preview(app: &mut ScreenCommandApp<'_, '_>) { halt_preview_now(&mut app.player.session, &mut app.adapters.player); } +/// The item a hero preview is asked for, and the part it would open ([`ContentReq::PreviewStart`]). +#[cfg(feature = "play-feed")] +pub(crate) struct HeroPreviewAsk<'a> { + pub(crate) sid: plx_plex::plex::ServerId, + pub(crate) rk: &'a str, + pub(crate) part: &'a str, + pub(crate) vcodec: &'a str, + pub(crate) acodec: &'a str, + pub(crate) title: &'a str, +} + +/// How [`start_hero_preview`] ended. +#[cfg(feature = "play-feed")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum HeroPreview { + /// The item has no extra to preview; the preview machine remembers it. + NoExtra, + /// Nothing was started. A boot that composed no Feed is remembered (`Fact::RefusedDirect`), and + /// so is a standing refusal of the machine's own (`preview::blocked` answers from it), so the + /// page's dwell gate does not ask again; a busy machine and a refused admission remember + /// nothing, and the page asks again after its next dwell. + Refused, + /// The resolve is in flight and the asking page owns the preview. + Started, +} + +/// **`ContentReq::PreviewStart`, performed.** A hero preview is a Feed engine's: the resolve lands a +/// direct-play plan the Feed opens muted. A boot that composed no Feed (`BackendSet::feed` false) +/// has nothing to open it on, so the request is refused HERE, once, through the preview machine's +/// own fact for an item it cannot preview (`Fact::RefusedDirect`, the same one the build with no +/// Feed compiled in says): the page's dwell gate (`preview::blocked`) then stops asking, and no +/// resolve runs. Left to the planner, the refusal would land as a standing verdict +/// (`NoQualifiedBackend`), which `player::state()` reads as an Error and `report::tick_preview` +/// reports as a failed preview. +/// +/// A boot with only the URI driver is refused the same way, and the planner already refused it +/// (`pms_uri_possible` excludes a preview, and no display places a preview rectangle: +/// `DisplayEvidence::preview_rectangle` is false on every path). A display that did place one +/// would be the reason to revisit this gate. +#[cfg(feature = "play-feed")] +pub(crate) fn start_hero_preview( + session: &mut plx_media::route::PlaybackSession, + meta: &mut plx_data::stores::metadata::MetadataStore, + ask: &HeroPreviewAsk<'_>, + now: u32, +) -> HeroPreview { + use plx_media::player::preview; + if !session.backends().feed { + preview::note_refused_direct(ask.sid, ask.rk); + return HeroPreview::Refused; + } + if ask.part.is_empty() { + preview::note_no_extra(ask.sid, ask.rk); + return HeroPreview::NoExtra; + } + if !matches!(preview::request_start(ask.sid, ask.rk, now), preview::Start::Accepted) { + return HeroPreview::Refused; + } + if plx_media::route::request_preview(session, meta, super::playback::start_caps(), + ask.sid, ask.rk, ask.part, ask.vcodec, ask.acodec, ask.title) + { + HeroPreview::Started + } else { + preview::note_admission_refused(); + HeroPreview::Refused + } +} + fn content_command(app: &mut ScreenCommandApp<'_, '_>, source: MachineId, request: ContentReq, ret: ReturnState, now: u32, ) -> plx_machine::machine::AppCommandOutcome { @@ -645,37 +713,22 @@ fn content_command(app: &mut ScreenCommandApp<'_, '_>, source: MachineId, reques ContentReq::PreviewStart { sid, rk, part, vcodec, acodec, title } => { #[cfg(not(feature = "play-feed"))] { - let _ = (sid, rk, part, vcodec, acodec, title); - // Hero previews have no URI qualification. + let _ = (part, vcodec, acodec, title); + // Hero previews have no URI qualification. The refusal is the item's, said + // once through the preview machine's own fact (`Fact::RefusedDirect`), so the + // page's dwell gate (`preview::blocked`) stops asking: left unsaid, the hero + // would send this request again every `DWELL_S` for as long as it holds focus. + plx_media::player::preview::note_refused_direct(sid, &rk); return AppCommandOutcome::Refused; } #[cfg(feature = "play-feed")] + match start_hero_preview(&mut app.player.session, app.bridge.metadata_mut(), + &HeroPreviewAsk { sid, rk: &rk, part: &part, vcodec: &vcodec, acodec: &acodec, title: &title }, + now) { - if part.is_empty() { - plx_media::player::preview::note_no_extra(sid, &rk); - return AppCommandOutcome::Completed; - } - if !matches!( - plx_media::player::preview::request_start(sid, &rk, now), - plx_media::player::preview::Start::Accepted - ) { return AppCommandOutcome::Refused; } - let ok = plx_media::route::request_preview( - &mut app.player.session, - app.bridge.metadata_mut(), - super::playback::start_caps(), - sid, - &rk, - &part, - &vcodec, - &acodec, - &title, - ); - if ok { - PREVIEW_HOST.with(|h| h.set(Some(instance))); - } else { - plx_media::player::preview::note_admission_refused(); - return AppCommandOutcome::Refused; - } + HeroPreview::NoExtra => return AppCommandOutcome::Completed, + HeroPreview::Refused => return AppCommandOutcome::Refused, + HeroPreview::Started => PREVIEW_HOST.with(|h| h.set(Some(instance))), } } ContentReq::PreviewStop => halt_screen_preview(app), diff --git a/rust-modules/src/app/detail_panel_tests.rs b/rust-modules/src/app/detail_panel_tests.rs index d3b1cd1279..76f332d622 100644 --- a/rust-modules/src/app/detail_panel_tests.rs +++ b/rust-modules/src/app/detail_panel_tests.rs @@ -229,6 +229,8 @@ struct PickTap { last: Option, /// `(what was asked, who asked, how it ended)`, in the order the runner finished them. commands: Vec<(Asked, MachineId, plx_machine::machine::AppCommandOutcome)>, + /// How many times a panel reported a picked version (`AppMsg::PlayVersion`) to its page. + play_version_reported: usize, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -243,7 +245,10 @@ enum Asked { impl plx_ui::dispatch::Tap for PickTap { fn effect(&mut self, _: u64, stamped: &plx_machine::machine::Stamped) { - use plx_screens::registry::{AppFx, ContentArg, ContentReq, PlayIntent}; + use plx_screens::registry::{AppFx, AppMsg, ContentArg, ContentReq, PlayIntent}; + if let Fx::Deliver(_, plx_machine::machine::Delivery::Screen(plx_ui::screen::ScreenEvent::App(AppMsg::PlayVersion(_)))) = &stamped.fx { + self.play_version_reported += 1; + } if let Fx::App(app) = &stamped.fx { self.last = Some(match app { AppFx::Content(ContentReq::Play { play, .. }) => Asked::Play(match play { @@ -341,6 +346,48 @@ fn a_picked_version_plays_that_version_though_its_panel_is_still_closing() { assert!(matches!(w.d.top_arg(), Some(AppArg::Player)), "the pick entered the player"); } +/// **Play Version on a platform that composed no playback driver (W6c):** the panel's rows are the +/// shared disabled rows, so the pick presses nothing: no play is asked, the player is not entered +/// and the panel stays up (OK on a disabled row does nothing; BACK still closes it). The mount +/// reads the platform's fact (`ScreenInputs::can_play`), which the previous test, on the default +/// set, proves is not what stops it there. +#[test] +fn a_version_pick_asks_for_no_play_when_the_platform_composed_no_driver() { + let versions = plx_appkit::version_list::sample(); + let pick = versions[1].id; + let mut w = World::detail_page("play-version-no-driver", plx_data::metadata::Detail { + sid: plx_plex::plex::ServerId::UNSET, + rk: "movie".into(), + kind: "movie".into(), + title: "Movie".into(), + part: "/library/parts/movie".into(), + versions, + ..Default::default() + }); + w.bridge.bridge().retained.screen_inputs.backends = plx_media::route::BackendSet::NONE; + let host = page_instance(&w.d); + open_content_panel( + &mut w.d, + host, + Some((plx_plex::plex::ServerId::UNSET, "movie")), + plx_screens::registry::ContentPanel::Versions { anchor: [300.0f32, 800.0, 300.0, 60.0].map(f32::to_bits) }, + ); + w.frames(40); + assert_eq!(w.d.nav.modals.surfaces.len(), 1, "premise: the Play Version panel is up"); + let mut tap = PickTap::default(); + let mut t = w.frame; + let mut bridge = w.bridge.bridge(); + pick_key(&mut w.d, &mut bridge, &mut t, Key::Down, &mut tap); + pick_key(&mut w.d, &mut bridge, &mut t, Key::Ok, &mut tap); + assert_eq!(tap.play_version_reported, 0, "a disabled row reports nothing to the page: {}", tap.account()); + assert!(tap.ended(host, &Asked::Play(Some(pick))).is_empty(), "no play was asked: {}", tap.account()); + assert!(tap.commands.iter().all(|(asked, ..)| !matches!(asked, Asked::Play(_))), "{}", tap.account()); + assert!(!matches!(w.d.top_arg(), Some(AppArg::Player)), "the player was not entered"); + assert_eq!(w.d.nav.modals.surfaces.len(), 1, "OK on a disabled row left the panel up: {}", tap.account()); + pick_key(&mut w.d, &mut bridge, &mut t, Key::Back, &mut tap); + assert!(w.d.nav.modals.surfaces.is_empty(), "BACK closes the panel: {}", tap.account()); +} + /// The two-copy *Also available* rig of `a_detail_panel_parks_across_a_push_and_returns_with_the_same_instance`: /// the page on `m1` of server `here`, the picker up over it, its cursor on the first copy. struct AltRig { diff --git a/rust-modules/src/app/run_uri_boot_tests.rs b/rust-modules/src/app/run_uri_boot_tests.rs index 06c12a8227..542ea7c2a0 100644 --- a/rust-modules/src/app/run_uri_boot_tests.rs +++ b/rust-modules/src/app/run_uri_boot_tests.rs @@ -250,6 +250,204 @@ mod uri_boot_tests { request.contains("/decision?")), "qualified original bypassed Feed MDE"); } + // ---- W6c: the compositions a platform can supply, through the real boot publisher ---- + + /// A bare adapter in the rig, the way a platform that composes no Feed starts: nothing installed. + fn bare_adapter(rig: &mut Rig) { + rig.app.adapters.player = plx_media::player::adapter::PlayerAdapter::new(unsafe { plx_base::task::MainThread::assume() }); + } + + /// The URI product composed over the rig's fake bus and display, as `compose` returns it, and + /// published with the adapter's set by `publish_composition`. Certified for everyone, so no + /// viewer opt-in is part of the play. + fn compose_self_certified(rig: &mut Rig) -> &'static Bus { + plx_plex::plex::client_for(rig.sid).unwrap() + .set_link(plx_plex::plex::probe::Location::Local); + let bus: &'static Bus = Box::leak(Box::new(Bus::new())); + let display: &'static Display = Box::leak(Box::new(Display)); + let caps = Capabilities { progressive_uri: true, hls_uri: false, + packet_feed: false, pause: true, seek: true, audio_track: true, + subtitle_track: true, audio_off: false, subtitle_off: false }; + let product = UriProduct { binding: Binding::Exported { canvas: (1920, 1080) }, + callable: caps, certified: caps, qualifier: Arc::new(QualifiedOriginal) }; + assert!(crate::app::adapters::backends::install_and_publish_uri_product( + &mut rig.app.adapters.player, &mut rig.app.player.session, product, bus, display)); + bus + } + + /// URI only, no Feed driver anywhere: the set the session was told is URI alone, an ordinary + /// title resolves to a URI offer with the viewer's setting Off, and its Start is the driver's + /// native Load. No Feed decision is asked of the server. + #[test] + fn a_uri_only_boot_plays_an_ordinary_title_with_no_feed_driver() { + let _serial = plx_base::testlock::serial(); + let Some(mut rig) = Rig::serving(false) else { return }; + bare_adapter(&mut rig); + let bus = compose_self_certified(&mut rig); + assert_eq!(rig.app.player.session.backends(), plx_playback_contract::BackendSet::URI); + assert_eq!(rig.app.adapters.player.composed_backends(), plx_playback_contract::BackendSet::URI); + assert_eq!(plx_media::route::uri_engine(), plx_plex::plex::session::UriEngine::Off); + rig.request(); + let offer = resolve_pending(&mut rig).uri_offer.expect("the ordinary title is a URI offer"); + assert!(rig.app.adapters.player.offer_qualified_uri(&mut rig.app.player.session, offer).is_ok()); + let started = plx_media::player::start_playback_tracked( + &mut rig.app.player.session, &mut rig.app.adapters.player); + assert!(matches!(started, plx_media::player::BufferfeedStartOutcome::Launched(_))); + let at = rig.app.adapters.player.backend_tick(); + let _ = rig.app.adapters.player.backend_poll_session_at(&mut rig.app.player.session, at); + assert!(bus.load_payload().is_some(), "the Start became the driver's native Load"); + assert!(!rig.requests.lock().unwrap().iter().any(|request| request.contains("/decision?")), + "no Feed decision for a platform with no Feed"); + } + + /// Zero drivers (`Composition::default()` over a bare adapter): the boot publishes `NONE` and + /// no resolver, and an ordinary title is refused with the typed verdict instead of falling to + /// a Feed nothing installed. + #[test] + fn a_boot_that_composed_no_driver_refuses_an_ordinary_title() { + let _serial = plx_base::testlock::serial(); + let Some(mut rig) = Rig::serving(false) else { return }; + bare_adapter(&mut rig); + crate::app::platform::publish_composition(&mut rig.app.player.session, + &rig.app.adapters.player, crate::app::platform::Composition::default()); + assert_eq!(rig.app.player.session.backends(), plx_playback_contract::BackendSet::NONE); + assert!(rig.app.player.session.uri_preflight_port().is_none()); + rig.request(); + rig.release.send(()).unwrap(); + poll_until("the refusal did not land", || { + let _ = plx_media::route::pump_play(&mut rig.app.player.session, + rig.app.runtime.metadata_mut()); + plx_media::route::play_verdict(&rig.app.player.session).is_some() + }); + assert_eq!(plx_media::route::play_verdict(&rig.app.player.session).as_deref(), + Some(plx_os::i18n::msg::widgets_reason_open()), + "the typed NoQualifiedBackend verdict, worded by the catalog"); + assert!(!rig.requests.lock().unwrap().iter().any(|request| request.contains("/decision?"))); + } + + /// **A platform that composed no Feed has no hero trailer, and says so once, quietly.** The + /// Detail hero's dwell asks for a preview whenever focus rests on it and the item is not known + /// to refuse (`player::preview::blocked`). With no Feed composed the request is refused by + /// `start_hero_preview` through the preview machine's own fact (`Fact::RefusedDirect`), BEFORE + /// any server work: no PlayQueue request, no resolve, so no standing verdict for `player::state()` + /// to read as an Error (and for the failure report to tell as a failed preview), and the dwell + /// gate stops asking, so there is no retry every `DWELL_S`. Nothing reaches the route. + #[cfg(feature = "play-feed")] + #[test] + fn a_boot_that_composed_no_feed_refuses_the_hero_preview_once_and_quietly() { + use crate::app::content::{start_hero_preview, HeroPreview, HeroPreviewAsk}; + use plx_media::player::preview; + let _serial = plx_base::testlock::serial(); + let _preview = crate::app::bridge::test_support::PreviewReset; + let Some(mut rig) = Rig::serving(false) else { return }; + let mut t = product_transition(&mut rig.app); + settle(&mut rig.app, &mut t); + bare_adapter(&mut rig); + crate::app::platform::publish_composition(&mut rig.app.player.session, + &rig.app.adapters.player, crate::app::platform::Composition::default()); + assert_eq!(rig.app.player.session.backends(), plx_playback_contract::BackendSet::NONE); + preview::reset_for_test(); + preview::restore_trailer_autoplay(true); + let route = rig.app.route(); + // No driver at all, and a boot with only the URI driver: neither has a Feed to open a + // preview on, and no display places a preview rectangle for the URI one. + for (rk, set) in [("1", plx_playback_contract::BackendSet::NONE), + ("2", plx_playback_contract::BackendSet::URI)] + { + rig.app.player.session.install_backends(set); + let served = rig.requests.lock().unwrap().len(); + let ask = HeroPreviewAsk { sid: rig.sid, rk, part: "/library/parts/1/file.mkv", + vcodec: "h264", acodec: "aac", title: "First" }; + assert!(!preview::blocked(rig.sid, rk), "{set:?}: nothing is known about the item yet"); + assert_eq!(start_hero_preview(&mut rig.app.player.session, rig.app.runtime.metadata_mut(), + &ask, 0), HeroPreview::Refused, "{set:?}"); + assert!(preview::blocked(rig.sid, rk), + "{set:?}: the refusal is remembered, so the page's dwell gate stops asking: no retry loop"); + assert_eq!(preview::request_start(rig.sid, rk, 1), + preview::Start::Cached(preview::Fact::RefusedDirect), "{set:?}"); + assert_eq!(start_hero_preview(&mut rig.app.player.session, rig.app.runtime.metadata_mut(), + &ask, 2_000), HeroPreview::Refused, "{set:?}: a dwell that asks anyway is refused the same way"); + for _ in 0..5 { + let mut fr = Frame::begin(&rig.app.player.session, rig.app.runtime.metadata_view()); + fr.now = t; + unsafe { + playback_tick(&mut rig.app, &mut fr); + update(&mut rig.app, &mut fr); + } + std::thread::sleep(Duration::from_millis(5)); + } + // The rig's own background traffic (a `GET /` reachability probe) may reach the server + // meanwhile; the item's resolve (its metadata, a decision) is what must not. That no + // resolve was dispatched at all is `play_pending` below. + let asked: Vec = rig.requests.lock().unwrap()[served..].to_vec(); + assert!(!asked.iter().any(|request| request.contains("/library/metadata/") + || request.contains("playQueues") || request.contains("decision")), + "{set:?}: refused before any server work, yet the server was asked {asked:?}"); + assert!(!preview::occupies(), "{set:?}: the machine stays Idle"); + assert!(!plx_media::route::play_pending(), "{set:?}: no resolve was started"); + assert!(!plx_media::route::play_refused(&rig.app.player.session), + "{set:?}: no standing verdict, so no Error read-out and no failure report"); + assert!(!plx_media::route::is_preview(&rig.app.player.session), "{set:?}"); + assert_ne!(plx_media::player::state(&rig.app.player.session), + plx_media::player::PlaybackState::Error, + "{set:?}: a refused hero trailer is not a playback error"); + assert!(crate::app::bridge::player(&rig.app.pages).is_none(), "{set:?}: no player page"); + assert!(rig.app.route() == route, "{set:?}: the route did not move"); + } + } + + /// The control for the test above: the same request on a boot that composed a Feed starts the + /// resolve, which is what the gate must leave alone. + #[cfg(feature = "play-feed")] + #[test] + fn a_boot_that_composed_a_feed_starts_the_hero_preview() { + use crate::app::content::{start_hero_preview, HeroPreview, HeroPreviewAsk}; + use plx_media::player::preview; + let _serial = plx_base::testlock::serial(); + let _preview = crate::app::bridge::test_support::PreviewReset; + let Some(mut rig) = Rig::serving(false) else { return }; + let mut t = product_transition(&mut rig.app); + settle(&mut rig.app, &mut t); + assert!(rig.app.player.session.backends().feed, "premise: the rig composes the Feed"); + preview::reset_for_test(); + preview::restore_trailer_autoplay(true); + let ask = HeroPreviewAsk { sid: rig.sid, rk: "1", part: "/library/parts/1/file.mkv", + vcodec: "h264", acodec: "aac", title: "First" }; + assert_eq!(start_hero_preview(&mut rig.app.player.session, rig.app.runtime.metadata_mut(), + &ask, 0), HeroPreview::Started); + assert!(rig.entered.recv_timeout(Duration::from_secs(1)).is_ok(), "the resolve reached the server"); + assert!(preview::occupies(), "the preview machine holds the request"); + // The page's focus leaves the hero while the resolve is parked on the server (the halted + // preview's own test): the landing is discarded, so no Engine is left behind to tear down. + preview::halt(&mut rig.app.player.session, &mut rig.app.adapters.player); + rig.release.send(()).unwrap(); + poll_until("the halted preview's resolve never settled", || { + let mut fr = Frame::begin(&rig.app.player.session, rig.app.runtime.metadata_view()); + fr.now = t; + unsafe { + playback_tick(&mut rig.app, &mut fr); + update(&mut rig.app, &mut fr); + } + !plx_media::route::play_pending() + }); + } + + /// Two drivers (the rig's Feed and the product URI driver): the session holds both, and the + /// planner's choice for a title the URI driver qualifies is the URI original. + #[test] + fn a_boot_with_both_drivers_offers_the_qualified_uri_original_first() { + let _serial = plx_base::testlock::serial(); + let Some(mut rig) = Rig::serving(false) else { return }; + let _bus = compose_self_certified(&mut rig); + assert_eq!(rig.app.player.session.backends(), plx_playback_contract::BackendSet::BOTH); + rig.request(); + let offer = resolve_pending(&mut rig).uri_offer.expect("the URI original is offered"); + assert!(rig.app.adapters.player.offer_qualified_uri(&mut rig.app.player.session, offer).is_ok()); + assert!(matches!(rig.app.player.session.backend_offer(), + plx_media::route::backend_policy::Selection::Open(choice) + if choice.backend == BackendKind::Uri)); + } + /// The product the composition builds for a viewer who opted in to the URI engine, over the /// exported-window `Display`: the binding of a major the product's exported-window table, /// `EXPORTED_STRATA`, has not admitted (`Unbound`: the host has no handle and the major is not diff --git a/rust-modules/ui/src/focus.rs b/rust-modules/ui/src/focus.rs index 61fe26d55d..edd48d76e8 100644 --- a/rust-modules/ui/src/focus.rs +++ b/rust-modules/ui/src/focus.rs @@ -473,8 +473,10 @@ fn resolve_group(groups: &[GroupSpec], g: GroupId) -> Option<&GroupSpec> { } /// A source placement at a group's head (its top-left corner), for `Seat::First` and a fresh -/// enter with no source. -fn head_of(extent: Rect) -> Placed { +/// enter with no source. Public for a screen whose own default seat sits in ANOTHER group than the +/// one the container named (Detail's, below its action row): it asks that group's `seat` for the +/// same placement the engine would have given it. +pub fn head_of(extent: Rect) -> Placed { let r = Rect::new(extent.x, extent.y, 1.0, 1.0); Placed { rect: r, diff --git a/rust-modules/ui/src/widgets.rs b/rust-modules/ui/src/widgets.rs index ed72fc9909..8cb7962b76 100644 --- a/rust-modules/ui/src/widgets.rs +++ b/rust-modules/ui/src/widgets.rs @@ -3283,6 +3283,9 @@ pub struct CircleButton { pub frame: Rect, pub glyph: *const c_char, pub icon: Option, // vector glyph; overrides the text glyph when set + /// Whether the control can act: a disabled disc wears the disabled ink and never the focused + /// face, whatever order the builder ran in ([`CircleButton::enabled`]). + pub enabled: bool, pub focused: bool, /// Focus PROGRESS 0..1 when driven off a spring ([`CircleButton::focus_mix`]); `None` is the /// plain binary [`focused`](Self::focused). @@ -3310,6 +3313,7 @@ impl CircleButton { glyph, icon: None, fill: None, + enabled: true, focused: false, focus: None, style: ControlStyle::Accent, @@ -3358,6 +3362,15 @@ impl CircleButton { self.focused = f; self } + /// A disc that cannot act: the disabled ink ([`theme::INK_DISABLED`]), and never the focused + /// face whatever order the two are set in — [`Button::enabled`]'s and + /// [`TransportButton::enabled`]'s own rule, so a disabled disc reads the same on every row. + /// A disabled control owns no focus stop (`focus::next_enabled_index`), so the caller that + /// disables one also keeps focus off it. Defaults to enabled. + pub fn enabled(mut self, enabled: bool) -> Self { + self.enabled = enabled; + self + } /// Draw the focus fill at progress `t` (0..1) — normally [`CtlPop::focus`], the lift spring — /// instead of the binary [`focused`](Self::focused); see [`ControlStyle::face_at`]. pub fn focus_mix(mut self, t: f32) -> Self { @@ -3367,7 +3380,15 @@ impl CircleButton { } /// The face this disc draws now. fn face_now(&self) -> ControlFace { - self.style.face_at(self.focus.unwrap_or(f32::from(self.focused)), self.ground, self.palette) + let mut face = self.style.face_at( + if self.enabled { self.focus.unwrap_or(f32::from(self.focused)) } else { 0.0 }, + self.ground, + self.palette, + ); + if !self.enabled { + face.ink = theme::INK_DISABLED; + } + face } /// The [FOCUS POP](CTRL_FOCUS_SCALE), about the control's centre — normally /// [`CtlPop::scale`], which already folds the press dip in. `1.0` is the resting control, which @@ -3503,14 +3524,15 @@ impl View for CircleButton { // capsule, and `face_box`/`face_outline` pick that up from the shape rather than from a // flag — at rest both are no-ops on a circle. let plate = face_box(r); - if self.focused { + let focused = self.enabled && self.focused; + if focused { control_cast_at(p, plate, plate.h * 0.5, self.focus.unwrap_or(1.0)); } let glass = self.ground == ControlGround::Keyed && glass_capsule(p, plate, 1.0, self.glass, None); if !glass { - control_rim(p, plate, plate.h * 0.5, face.top, face.body, self.focused, self.ground); - } else if self.focused { + control_rim(p, plate, plate.h * 0.5, face.top, face.body, focused, self.ground); + } else if focused { let focus = self.focus.unwrap_or(1.0); let bright = self.style.face_at(1.0, self.ground, self.palette); control_rim(p.alpha(focus), plate, plate.h * 0.5, bright.top, bright.body, true, self.ground); diff --git a/rust-modules/ui/src/widgets_control_face_tests.rs b/rust-modules/ui/src/widgets_control_face_tests.rs index adccf7b9b3..8eec980b42 100644 --- a/rust-modules/ui/src/widgets_control_face_tests.rs +++ b/rust-modules/ui/src/widgets_control_face_tests.rs @@ -931,3 +931,30 @@ fn a_discs_glyph_keeps_one_raster_across_its_whole_pop() { assert!((side - rest_side * scale).abs() < 1e-3, "scale {scale}: the box follows the spring continuously"); } } + +/// **A disabled disc is drawn at rest, whichever way focus reaches it and in whatever order the +/// builder ran** ([`TransportButton::enabled`]'s and [`Button::enabled`]'s own rule): the idle face, +/// in the disabled ink. The Detail hero row's bookmark and watched toggle are discs, and a platform +/// that cannot act on one must never show it lit. `face_now` is the one place the focus (the binary +/// flag or a spring's progress) and the disabled rule meet. +#[test] +fn a_disabled_disc_wears_the_idle_face_in_the_disabled_ink_however_focus_reaches_it() { + let make = || CircleButton::new(c"".as_ptr()); + let face = |b: CircleButton| { + let f = b.face_now(); + (f.top, f.body, f.ink) + }; + let (rest, lit) = (face(make()), face(make().focused(true))); + assert_ne!((rest.0, rest.1), (lit.0, lit.1), "the focused face is distinguishable from the idle one"); + let disabled = face(make().enabled(false)); + assert_eq!((disabled.0, disabled.1), (rest.0, rest.1), "a disabled disc keeps the idle plate"); + assert_eq!(disabled.2, theme::INK_DISABLED, "and wears the disabled ink"); + for (how, b) in [ + ("flag, then disabled", make().focused(true).enabled(false)), + ("disabled, then flag", make().enabled(false).focused(true)), + ("spring, then disabled", make().focus_mix(1.0).enabled(false)), + ("disabled, then spring", make().enabled(false).focus_mix(1.0)), + ] { + assert_eq!(face(b), disabled, "{how}: still the idle face in the disabled ink"); + } +} From 0c9a64db82e696d1f7168398d3654323d2c03a3f Mon Sep 17 00:00:00 2001 From: Gleb Linnik Date: Sat, 21 Nov 2026 06:46:18 +0300 Subject: [PATCH 23/26] The platform interface is published through one module, host, with an EventSink for input (#1500) Step W7a of the platform plan (discussion #1460). The application crate publishes what a platform crate needs to build its `static Platform` and hand it over through one module, `plxnative_modules::host`; nothing else of the application is public to a television build. The television and the simulator behave as before: the SDL events take the same bytes through the same `poll`. `host` re-exports `Platform`, `Shell`, `Surface`, `EventSink`, `FrameProbe`, `MediaBoot`, `Composition`, `Exit` and `Release`, and the lower layers' vocabulary their signatures name (`Services`, `MainThread`, `Edge`, `Action`, `RawKey`, `Lifecycle`, `PointerEdge`, `OpenAsk`, `Placement`). Its one function is `run`, the application's entry. By the owner's amendment to Decision 3 (2026-11-21), the eight application-crate items are reachable only through `host`. A platform crate names the application's types through `host` alone, and takes the hook tables from `plx_os` and `PlayerAdapter` from `plx_media` directly. Input has a public face, `EventSink`. A platform reports its events through `Surface::deliver`, and the application converts them into its private `HostEvent` in one place, `HostQueue`. SDL's surface delivers nothing there, and `poll` is hidden, defaulted, and retires at W9 at the latest. `RawKey` moves to `plx_ui::consts` beside `Action`. `sdl_init` and `sdl_open` are left for W7b. Two source pins in `host.rs` hold the ruling. The crate root's `pub` items are `host` plus the simulator's doors, each confined to `hostsim` by an evaluated `cfg`. `host.rs` is the only `pub use` of the application. An integration test, `rust-modules/tests/host_interface.rs`, builds a `static Platform` from fakes outside the crate and boots it through `host::run` to the fake shell's refusal of the window. `make test-host-interface` runs it incrementally, and `check-cargo-unit-hostsim` runs it in `make check`. The ARM binary's DT_NEEDED and undefined dynamic symbols equal the base's. Non-incremental `make build-bench` rows are flat. --- .agents/agents/fw-compat-reviewer.md | 2 +- Makefile | 50 ++++- ci/module-layers.ini | 5 +- ci/test_arm_profile.py | 2 +- ci/test_ci_split.py | 6 +- ci/test_host_threads.py | 9 +- docs/agent-reference.md | 23 +- docs/module-layers.md | 8 +- docs/platform-ports.md | 113 +++++++--- rust-modules/shell-sdl/src/lib.rs | 9 +- rust-modules/src/app/events.rs | 139 ++++++++++-- rust-modules/src/app/exit.rs | 10 +- rust-modules/src/app/mod.rs | 4 +- rust-modules/src/app/platform.rs | 134 ++++++++++-- rust-modules/src/app/run.rs | 45 ++++ rust-modules/src/host.rs | 240 ++++++++++++++++++++ rust-modules/src/lib.rs | 5 + rust-modules/tests/host_interface.rs | 313 +++++++++++++++++++++++++++ rust-modules/ui/src/consts.rs | 15 ++ 19 files changed, 1032 insertions(+), 100 deletions(-) create mode 100644 rust-modules/src/host.rs create mode 100644 rust-modules/tests/host_interface.rs diff --git a/.agents/agents/fw-compat-reviewer.md b/.agents/agents/fw-compat-reviewer.md index 30f2bd3af1..408369885b 100644 --- a/.agents/agents/fw-compat-reviewer.md +++ b/.agents/agents/fw-compat-reviewer.md @@ -128,7 +128,7 @@ into `dynlib!` **trades link-time symbol checking away** for version tolerance a it where the version actually varies. If a diff moves a stable library there, push back and ask for the `--inventory` output that justifies it. The precedent for the other direction is `rust-modules/shell-sdl/src/sys.rs`: plain `extern "C"` (the `SDL_*TextInput*` calls among them), -justified in its module doc by all 14 inventories exporting the whole SDL2 family it names. +justified in its module doc by all 14 inventories exporting every name outside its `hostsim` block. ## WHAT `fwcompat.py` NEEDS BEFORE IT WILL ANSWER — settle this first, not at your third command diff --git a/Makefile b/Makefile index 53d3663235..1be2537493 100644 --- a/Makefile +++ b/Makefile @@ -581,8 +581,8 @@ ARM_PROFILE_FLAG = $(if $(filter release,$(ARM_PROFILE)),--release,--profile $(A # make RUST_TOOLCHAIN=nightly HOST_THREADS=8 test-fast # # A HOST_THREADS above 1 on a non-nightly toolchain is a hard error here rather than a cargo failure -# in the middle of a recipe. Which recipes: ONLY the host `cargo test` / `check-cargo-unit-*` builds, -# `test-fast`, `test-crate`, `test-hostsim` and `build-bench` carry `$(HOST_ENV)`. It is NOT exported, so the ARM +# in the middle of a recipe. Which recipes: the host `cargo test` builds and nothing else +# (`grep -n HOST_ENV Makefile` is the exact set; `ci/test_host_threads.py`'s `HOST_RECIPES` pins it). It is NOT exported, so the ARM # staticlib recipes (which set RUSTFLAGS themselves), the simulators' builds, clippy and the package # steps never see it (ci/test_host_threads.py pins both). 0 and 1 mean the serial front end. A # RUSTFLAGS the caller exported wins over it (cargo reads CARGO_BUILD_RUSTFLAGS last). @@ -854,8 +854,8 @@ RUST_CFG = features:$(RUST_FEATFLAGS)$(if $(filter-out release,$(ARM_PROFI # it from the recipe AND its prerequisites, never the name (`check-ass` is a test goal and stages the # host libass into `pkg/`). Two kinds qualify: # -# * HOST-ONLY goals: the unit-test loops, the fuzz runs and the lint pass (`test-hostsim`, `check-nodef`, -# `test-fast`, `test-crate`, `fuzz-hud`, `lint`, `build-bench`), the pieces of `check` that are plain host work +# * HOST-ONLY goals: the unit-test loops, the fuzz runs and the lint pass (`test-hostsim`, `test-host-interface`, +# `check-nodef`, `test-fast`, `test-crate`, `fuzz-hud`, `lint`, `build-bench`), the pieces of `check` that are plain host work # (`check-cargo-lint`, `check-cargo-unit-hostsim`, `check-localization`, `check-c-unit`, # `check-python-harness`), the notices tables, and the set-up and local tooling that writes outside # `pkg/` (a toolchain install, the disk-watch agent, the test media, the demo library, the @@ -880,7 +880,7 @@ RUST_CFG = features:$(RUST_FEATFLAGS)$(if $(filter-out release,$(ARM_PROFI # goal in the two kinds above resets nothing under a dry run, and every goal named as NOT here stays out # of the list. The list is ONE line on purpose (`grep '^SIDE_EFFECT_FREE' Makefile` is the exact set, # and several tests read it that way). -SIDE_EFFECT_FREE = $(QUERY_GOALS) release-guard lab-guard disk disk-preflight build-bench build-bench-quick test-hostsim check-nodef test-fast test-crate fuzz-hud lint check-cargo-lint check-cargo-unit-hostsim check-localization check-c-unit check-python-harness notices notices-verify setup-rust setup-env disk-watch disk-watch-uninstall fixtures fixtures-quick fixtures-pipeline demo-library sim-token sim-macos-token sim-clean sim-macos-clean kill run run-stream verify-deploy uninstall fetch-profile softfloat-probe tv-lock-require +SIDE_EFFECT_FREE = $(QUERY_GOALS) release-guard lab-guard disk disk-preflight build-bench build-bench-quick test-hostsim test-host-interface check-nodef test-fast test-crate fuzz-hud lint check-cargo-lint check-cargo-unit-hostsim check-localization check-c-unit check-python-harness notices notices-verify setup-rust setup-env disk-watch disk-watch-uninstall fixtures fixtures-quick fixtures-pipeline demo-library sim-token sim-macos-token sim-clean sim-macos-clean kill run run-stream verify-deploy uninstall fetch-profile softfloat-probe tv-lock-require PURE_QUERY := $(if $(MAKECMDGOALS),$(if $(filter-out $(SIDE_EFFECT_FREE),$(MAKECMDGOALS)),,yes),) # `PLAYBACK_BACKENDS=none` builds no television package. It is refused HERE, at parse time and before # the stamp reset below: a recipe-level refusal ran after that reset, so a mistyped @@ -1583,7 +1583,7 @@ test: deploy run # it is not the table's value for that dir's name (tools/disk-budget.py NEED_GIB). `ci/test_disk_preflight.py` # finds every target whose recipe runs cargo and fails when one is missing from this list. DISK_ENTRIES = check check-replay check-cargo-lint check-cargo-unit-default check-cargo-unit-hostsim lint \ - test-fast test-crate test-hostsim check-nodef check-ass check-ffmpeg sim-macos sim-linux screenshots-sim site-video-sim \ + test-fast test-crate test-hostsim test-host-interface check-nodef check-ass check-ffmpeg sim-macos sim-linux screenshots-sim site-video-sim \ $(RUST_LIB) pkg/plxnative-storage macapp macapp-zip build-bench build-bench-quick fuzz-hud $(DISK_ENTRIES): | disk-preflight @@ -1591,7 +1591,7 @@ $(DISK_ENTRIES): | disk-preflight DISK_TREE = $(if $(CARGO_TARGET_DIR),$(if $(filter /%,$(CARGO_TARGET_DIR)),$(CARGO_TARGET_DIR),$(CURDIR)/rust-modules/$(CARGO_TARGET_DIR)),$(CURDIR)/rust-modules/target) DISK_NEED = test-fast test-crate: DISK_TREE = $(CURDIR)/rust-modules/$(TEST_FAST_TDIR) -test-hostsim: DISK_TREE = $(CURDIR)/rust-modules/$(TEST_HOSTSIM_TDIR) +test-hostsim test-host-interface: DISK_TREE = $(CURDIR)/rust-modules/$(TEST_HOSTSIM_TDIR) # The fuzz tree (ASan + coverage, release with debuginfo, ten binaries): 3.1 GiB measured after a cold build # of the first eight; the ninth, `ws_frame`, adds 83 MiB, and the tenth, `owp_json`, 49 MiB with `plx_owp` # (measured on Linux x86_64). @@ -1646,9 +1646,10 @@ check: # best. A bare `cargo test` builds for the host triple, which is exactly what we want — and it is # also why this suite cannot cover anything that links the TV's own libraries: media-codecs/src/ffi.rs gates its four # `#[link]` directives out of cfg(test) so the crate's pure logic stays host-testable, and a test -# that actually calls into FFmpeg or GL fails to link by design. --lib keeps it to the crate's own -# `#[cfg(test)] mod tests` blocks (there are no integration tests in tests/ — that directory is the -# on-device Python harness, a different thing entirely). +# that actually calls into FFmpeg or GL fails to link by design. --lib keeps it to the crates' own +# `#[cfg(test)]` blocks. The one integration test, `rust-modules/tests/host_interface.rs`, needs `hostsim` +# and runs in `check-cargo-unit-hostsim` (and `make test-host-interface`), not here; the repo-root `tests/` +# is the on-device Python harness, a different thing entirely. # NB the suite APPENDS to `/tmp/plxnative-events.log` on the dev Mac, and deliberately cannot be # pointed elsewhere. Since 2026-08-15 enough of the tree logs its failures (stream, posters, img, # account, remote) that host tests exercising those paths write real lines. `PLXNATIVE_RUNTIME_DIR` @@ -1807,11 +1808,19 @@ check-cargo-unit-hostsim: @# was invisible to all 1398 default-feature tests because the seam it needs was not there. @# Cargo keys fingerprints by feature set, so the two configurations coexist in one target/ and @# this costs a few seconds warm rather than a rebuild. + @# The second cargo line is W7a's gate and a test executable of its own (`--lib` never builds an integration test): + @# `rust-modules/tests/host_interface.rs` uses the application crate's `host` module from outside the crate and boots + @# a fake platform to its shell's refusal. It needs `hostsim` and a throwaway runtime root, which this pass has; + @# `make test-host-interface` is the same line as an incremental loop. @set -e; d=$$(mktemp -d /tmp/plxnative-check.XXXXXX); trap 'rm -rf "'"$$d"'"' EXIT; \ cd rust-modules && PATH="$$HOME/.cargo/bin:$$PATH" PLXNATIVE_RUNTIME_DIR="$$d" \ $(TELEMETRY_ENV) \ $(HOST_ENV) \ - $(UNIT_RUN) -- cargo +$(RUST_TOOLCHAIN) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_play_feed -p plx_shell_sdl --features hostsim + $(UNIT_RUN) -- cargo +$(RUST_TOOLCHAIN) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_play_feed -p plx_shell_sdl --features hostsim; \ + PATH="$$HOME/.cargo/bin:$$PATH" PLXNATIVE_RUNTIME_DIR="$$d" \ + $(TELEMETRY_ENV) \ + $(HOST_ENV) \ + $(UNIT_RUN) -- cargo +$(RUST_TOOLCHAIN) test -p plxnative-modules --test host_interface --features hostsim # OPT-IN incremental inner loop: the default-feature unit suite (the same `cargo test --lib` as # `check-cargo-unit-default`, same throwaway runtime root and telemetry env) with @@ -1906,6 +1915,25 @@ test-hostsim: $(HOST_ENV) \ $(UNIT_RUN) --require-match $(if $(T),--filter '$(T)') -- cargo +$(RUST_TOOLCHAIN) test --lib $(addprefix -p ,$(HOSTSIM_PKGS)) --features hostsim +# `make test-host-interface` -- W7a's gate (docs/platform-ports.md, Target shape 8): the application crate's `host` +# module used from OUTSIDE the crate. `rust-modules/tests/host_interface.rs` is an integration test, a crate of its own +# that can name only the `pub` items of `plxnative_modules`. It builds a `static Platform` from a fake `Shell`, `Surface` +# and `FrameProbe` and boots it through `host::run` to the fake shell's refusal of the window (the boot cannot go +# further without a GL context). It needs `hostsim`: only there is the runtime root steerable, so the boot's logs land +# in the throwaway directory below. The incremental loop, in `rust-modules/$(TEST_HOSTSIM_TDIR)` beside `make test-hostsim` +# (same feature set, same tree); `make check` runs the same test non-incrementally in `check-cargo-unit-hostsim`. +# Refused under RELEASE=1 like `test-hostsim`. +.PHONY: test-host-interface +test-host-interface: + @$(if $(RELEASE),echo "make test-host-interface: refused under RELEASE=1 -- it runs the default-plus-hostsim feature set incrementally; RELEASE=1 is the shipping feature set (use make check-nodef for that)." >&2; exit 1,:) + @echo "test-host-interface: the host interface test of plxnative-modules in rust-modules/$(TEST_HOSTSIM_TDIR) -- see 'make disk'" + @set -e; d=$$(mktemp -d /tmp/plxnative-check.XXXXXX); trap 'rm -rf "'"$$d"'"' EXIT; \ + cd rust-modules && CARGO_INCREMENTAL=1 CARGO_TARGET_DIR=$(TEST_HOSTSIM_TDIR) \ + PATH="$$HOME/.cargo/bin:$$PATH" PLXNATIVE_RUNTIME_DIR="$$d" \ + $(TELEMETRY_ENV) \ + $(HOST_ENV) \ + $(UNIT_RUN) -- cargo +$(RUST_TOOLCHAIN) test -p plxnative-modules --test host_interface --features hostsim + # `make fuzz-hud [T=] [SECS=60]` -- the `cargo fuzz` package over every parser a HUD package or the # registry reaches (`fuzz/`: its own workspace, outside rust-modules, so nothing shipped names it). T is one # or more targets (`python3 tools/fuzz-hud.py list`), default all; SECS is the time per target, run one after diff --git a/ci/module-layers.ini b/ci/module-layers.ini index c515843672..469398249c 100644 --- a/ci/module-layers.ini +++ b/ci/module-layers.ini @@ -201,11 +201,12 @@ uses = base machine os gfx net plex telemetry ui data session media appkit play_ members = screens [app] -# The loop, its adapters and every dev/diagnostic surface; lib.rs's own items are the facade. +# The loop, its adapters and every dev/diagnostic surface; lib.rs's own items are the facade. `host` is the +# one doorway a platform crate names (re-exports of the construction interface, and `run`). uses = base machine os gfx net plex telemetry ui data session media appkit screens shell_sdl playback_contract play_uri play_feed media_codecs members = crate app dev lab capture remote focusprobe hud_cli hud_tools shot coldstart textinput system release_line port - platform_desktop + platform_desktop host [platform webos] # Not a layer: the modules that exist only because the target is webOS. Identity, capability and diff --git a/ci/test_arm_profile.py b/ci/test_arm_profile.py index b92b646a78..644dd6d5a7 100644 --- a/ci/test_arm_profile.py +++ b/ci/test_arm_profile.py @@ -110,7 +110,7 @@ def test_the_profile_is_part_of_the_stamp_only_when_it_is_not_release(self): # `check-cargo-unit-hostsim` and `check-python-harness` (tests/test_harness.py alone). `test-hostsim` # and `check-nodef` were the first two to be listed. `fuzz-hud` runs tools/fuzz-hud.py (a cargo tree # under rust-modules/ and files under fuzz/); it reads nothing the stamp guards. - "test-hostsim", "check-nodef", "test-fast", "test-crate", "fuzz-hud", "lint", "check-cargo-lint", "check-cargo-unit-hostsim", + "test-hostsim", "test-host-interface", "check-nodef", "test-fast", "test-crate", "fuzz-hud", "lint", "check-cargo-lint", "check-cargo-unit-hostsim", "check-localization", "check-c-unit", "check-python-harness", # the documentation tables "notices", "notices-verify", diff --git a/ci/test_ci_split.py b/ci/test_ci_split.py index 173fb1ebd0..113602ecf0 100644 --- a/ci/test_ci_split.py +++ b/ci/test_ci_split.py @@ -64,7 +64,11 @@ def rule(target): r"ci/test_no_host_staticlib\.py", r"ci/test_build_not_always_dirty\.py", ], - "check-cargo-unit-hostsim": [r"cargo \+\$\(RUST_TOOLCHAIN\) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_play_feed -p plx_shell_sdl --features hostsim"], + "check-cargo-unit-hostsim": [ + r"cargo \+\$\(RUST_TOOLCHAIN\) test --lib -p plxnative-modules -p plx_base -p plx_machine -p plx_os -p plx_gfx -p plx_plex -p plx_telemetry -p plx_data -p plx_session -p plx_media -p plx_play_feed -p plx_shell_sdl --features hostsim", + # W7a: the `host` module used from outside the crate (`make test-host-interface` is the same line) + r"cargo \+\$\(RUST_TOOLCHAIN\) test -p plxnative-modules --test host_interface --features hostsim", + ], } diff --git a/ci/test_host_threads.py b/ci/test_host_threads.py index 740ca0d7ed..406592be31 100644 --- a/ci/test_host_threads.py +++ b/ci/test_host_threads.py @@ -16,7 +16,7 @@ nightly toolchain: asking for more than one thread on the stable pin is a Makefile error that names the fix, rather than a cargo failure in the middle of a recipe; * the flag reaches exactly the host test recipes (`check-cargo-unit-default`, `-hostsim`, - `test-fast`, `test-crate`, `test-hostsim`, `build-bench`) when it is on, and NO recipe when it is off, so a CI + `test-fast`, `test-crate`, `test-hostsim`, `test-host-interface`, `build-bench`) when it is on, and NO recipe when it is off, so a CI recipe is the command it always was; * it is never exported and no ARM, simulator, clippy or package line, and no workflow, names it, so a release or simulator build cannot pick it up; @@ -39,7 +39,7 @@ "GITHUB_ACTIONS", "ARM_PROFILE", "HOST_THREADS") FLAG = "CARGO_BUILD_RUSTFLAGS" HOST_RECIPES = (("check-cargo-unit-default",), ("check-cargo-unit-hostsim",), ("test-fast",), - ("test-crate", "C=plx_base"), ("test-hostsim",), ("build-bench",)) + ("test-crate", "C=plx_base"), ("test-hostsim",), ("test-host-interface",), ("build-bench",)) def make(*args: str, env: dict[str, str] | None = None) -> str: @@ -109,7 +109,7 @@ def test_off_means_no_recipe_names_it(self): ("RELEASE", ["RELEASE=1"], None), ("stable", ["FLAVOR=stable"], None)): # those goals refuse RELEASE=1 outright goals = [goal for goal in HOST_RECIPES - if not (goal[0] in ("test-fast", "test-crate", "test-hostsim", "build-bench") and what in ("RELEASE",))] + if not (goal[0] in ("test-fast", "test-crate", "test-hostsim", "test-host-interface", "build-bench") and what in ("RELEASE",))] with self.subTest(f"{what}: {', '.join(goal[0] for goal in goals)}"): out = make("-n", *[word for goal in goals for word in goal], *args, env=env) self.assertNotIn(FLAG, out) @@ -125,7 +125,8 @@ def test_the_arm_and_simulator_recipes_never_name_it(self): self.assertNotIn(banned, line, f"Makefile:{lineno} puts the host flag on a non-host line") # ...and the lines that DO carry it are the host test recipes, nothing else. users = [l for l in text.splitlines() if "$(HOST_ENV)" in l and not l.lstrip().startswith("#")] - self.assertEqual(len(users), len(HOST_RECIPES), users) + # `check-cargo-unit-hostsim` carries it on two cargo lines (the `--lib` suite and W7a's `--test host_interface`). + self.assertEqual(len(users), len(HOST_RECIPES) + 1, users) def test_no_workflow_names_it(self): # Workflows and composite actions only: ci.yml's `paths` filter skips pushes that touch only diff --git a/docs/agent-reference.md b/docs/agent-reference.md index e66f458104..47802e7418 100644 --- a/docs/agent-reference.md +++ b/docs/agent-reference.md @@ -138,7 +138,7 @@ the pinned Sentry Native cross-build), and `sshpass` (Homebrew; deploy/run use y stack is mostly a chain, so cargo has little to run side by side and the front end (parse, type-check, borrow-check) is single-threaded per crate by default. `-Zthreads=N` (N = the core count, capped at 8) parallelises it for the host `cargo test` recipes (`check-cargo-unit-default`, - `check-cargo-unit-hostsim`, `test-fast`, `test-crate`, `test-hostsim`, `build-bench`) through + `check-cargo-unit-hostsim`, `test-fast`, `test-crate`, `test-hostsim`, `test-host-interface`, `build-bench`) through `CARGO_BUILD_RUSTFLAGS`. Measured 2026-10-05 on an M4 (10 cores) on nightly, `make build-bench` non-incremental edit-rebuilds, medians of 5: `plx_base` leaf 20.1 s to 17.8 s, `plx_ui` 10.7 to 7.8, `plx_screens` 8.3 to 5.7, app 4.8 to 2.9; the incremental `test-fast` loop is unchanged @@ -333,6 +333,25 @@ the pinned Sentry Native cross-build), and `sshpass` (Homebrew; deploy/run use y `CARGO_TARGET_DIR` at a `/tmp` directory: those trees were not in any checkout, so no tool counted or reclaimed them (28 of them, 45.6 GiB, were found in `/tmp` on 2026-10-19). Refused under `RELEASE=1`; `ci/test_managed_targets.py` pins that the target dir is inside the checkout. +- `make test-host-interface` — W7a's gate (`docs/platform-ports.md`, Target shape 8): the application crate's + `host` module (`rust-modules/src/host.rs`, the one path a platform crate names the application's types by) used from OUTSIDE the crate by + `rust-modules/tests/host_interface.rs`, an integration test and so a crate of its own. It builds a `static + Platform` from a fake `Shell`, `Surface` and `FrameProbe`, boots it through `host::run` (the real + `run_application`) and asserts that `init` ran before `open`, the `OpenAsk` the application made, and the fake's + refusal returned as the entry's `Exit`. The boot cannot go further: after `open` it makes real GL calls, and a fake + surface has no GL context (nothing stubs GL under `test-support`), so frames and the loop are graded by the + in-crate tests of `make test-hostsim`, not here. It needs `hostsim`, because only there does `PLXNATIVE_RUNTIME_DIR` + steer the runtime root, so the boot's event log and crash log land in the recipe's throwaway directory; the boot + replaces the process's panic hook (`install_panic_logger`, which wraps the previous hook and also writes the + event and crash logs), and only one test in the file boots, because the platform's services install once per + process. The file also holds a source scan that every path into the application crate starts + `plxnative_modules::host` (its own spelling only; the crate's surface is pinned by `host.rs`'s tests, which + `make test-crate C=plxnative_modules` runs). Same shape as `test-hostsim`: incremental in `rust-modules/target-hostsim`, through + `$(UNIT_RUN)` (a `--test` line is passed through), refused under `RELEASE=1`, in `SIDE_EFFECT_FREE` and + `DISK_ENTRIES`. `make check` runs the same test non-incrementally as the second cargo line of + `check-cargo-unit-hostsim` (`--lib` never builds an integration test), pinned in `ci/test_ci_split.py`'s `GATES`. + The file needs no `[[test]]` entry (cargo finds `rust-modules/tests/*.rs`), so the root manifest and the + `ci/proofs` certificates that hash it are unchanged. - `make fuzz-hud [T= ...] [SECS=60]` — the `cargo fuzz` package over every parser a HUD package or the registry reaches (`docs/hud-plugins.md`, threat model): `admit` (the whole admission path), `bundle_read`, `archive_read` (the 1.0 ZIP container), `svg_check` (the SVG gate in front of nanosvg), @@ -1263,7 +1282,7 @@ every thin back-edge with `file:line` (the work list for breaking it up); `--dot `abnormal`, like a freeze's; one made after backgrounding (the PLX-NATIVE-1P shape) finds no open session, because backgrounding already ended it `exited` (`telemetry::session`), so only the `error` event exists. -- `rust-modules/src/` — the app core (Rust): `app/` (`mod.rs` the `run_application` shim + `struct App`, `boot.rs` the bring-up, `run.rs` the frame loop and its phase functions, `events.rs`/`input.rs` the input decode and key ladders, `lifecycle.rs`, `playback.rs`, `content.rs`, `bridge.rs` the seam onto the container and the ONE navigation vocabulary, `words.rs` the heartbeat's `route=`/`overlay=` alphabet — `nav.rs` is gone with `enum Route` since restructure phase 12), `system.rs` (wayland), `rust-modules/shell-sdl/` (crate `plx_shell_sdl`: `SDL_Init`, the window, the GL swap, the event decode and the text-input calls, which `app/platform.rs`'s `Shell` opens as the app-private `Surface`), +- `rust-modules/src/` — the app core (Rust): `app/` (`mod.rs` the `run_application` shim + `struct App`, `boot.rs` the bring-up, `run.rs` the frame loop and its phase functions, `events.rs`/`input.rs` the input decode and key ladders, `lifecycle.rs`, `playback.rs`, `content.rs`, `bridge.rs` the seam onto the container and the ONE navigation vocabulary, `words.rs` the heartbeat's `route=`/`overlay=` alphabet — `nav.rs` is gone with `enum Route` since restructure phase 12), `system.rs` (wayland), `rust-modules/shell-sdl/` (crate `plx_shell_sdl`: `SDL_Init`, the window, the GL swap, the event decode and the text-input calls, which `app/platform.rs`'s `Shell` opens as the `Surface` the `App` owns (`Shell` and `Surface` are reachable from outside the crate only through `plxnative_modules::host`; `HostEvent` stays app-private)), and, in the media layer (`rust-modules/media/`, crate `plx_media`, which the application links), `player/` (buffer-feed engine + worker threads — **`rust-modules/media/src/player/CLAUDE.md` is the playback deep-dive; read it before touching playback**), `abr/` and `route/`, and `ff.rs`, which diff --git a/docs/module-layers.md b/docs/module-layers.md index 5091866d86..704e5e6ff1 100644 --- a/docs/module-layers.md +++ b/docs/module-layers.md @@ -136,7 +136,7 @@ base | media | `ff` (a facade over `play_feed`'s demuxer) `abr curlio player route speed_audio`; `aq` and `hls` moved to `play_feed` | 56k | 49% | | appkit | `appkit` (the player panels and the Sources row several screens draw) | 13k | 32% | | screens | `screens` | 54k | 28% | -| app | `crate app dev lab capture remote focusprobe shot coldstart textinput system release_line port` | 42k | 12% | +| app | `crate app dev lab capture remote focusprobe shot coldstart textinput system release_line port host` | 42k | 12% | "Prod lines" counts files that are not wholly `cfg(test)`, measured after L14. The last column is the share of all production lines in that layer plus every layer above it. Line counts stand in @@ -207,7 +207,7 @@ on the device, stock SDL2 under `hostsim`), the synthetic key, pointer, wheel an into the queue (a text event is built as bytes and handed to the decode, never pushed: pushing one crashes the Mac's SDL), and the text-input calls. The LG half does not move: the `SDL_SysWMinfo` buffer, the `wl_proxy_marshal` opaque region and the LS2 pump stay in `system.rs`, a member of `[platform webos]`, and a pin in the crate's `lib.rs` fails if the crate names the query that overruns it. The application reaches it through `app/platform.rs`, whose `Shell` opens a -`Surface` over the crate's `Window`; `Shell`, `Surface` and `HostEvent` stay application-private until W7a. +`Surface` over the crate's `Window`; `HostEvent` stays application-private, and `Shell` and `Surface` are reachable only through the application crate's `host` module (W7a). `ci/check-deps.sh` reads the whole crate for the same clock, statics and thread gates as every other layer, and not as one of the sans-IO areas: the shell is an IO crate by definition. @@ -347,8 +347,8 @@ proves the references are gone and nothing more; L15b is open. | **L15b** the OS-neutral port — **open** | — | An OS-neutral video sink with the ACB bind sequence behind it and the webOS facts the gate cannot see; the simulator became its own platform in W4. See below. | | **L15c** the platform value and the three contracts — **done** | — | Wave R (the rename that gave this page `os` and `[platform webos]`) landed as #1474; W2 landed (`tv::Port` became `tv::Services`, with four groups of hooks; the shell and the frame probes moved to `app::Platform`), and so did the three contracts, W3a to W3c: who may persist credentials (#1477), what evidence admits a URI player (#1478), who ends the process (#1479). See "L15c to L15h" below. | | **L15d** neutral types and the simulator as its own platform (L15b item 2) — **W3d and W4 landed** | — | W3d landed (the opaque `Backend` tag, `sandbox` to `native_video`, identity publishes a platform name and version, `device::Info` keeps its webOS fields in `WebosDetail`, and `devcaps` reads its files through the platform), and so did W4: `platform_desktop` (`rust-modules/src/platform_desktop.rs`, a second fence section, `[platform desktop]`) is the simulator's and the macOS app's own platform value, which `src/bin/sim.rs` enters through; the `hostsim` terms of the television's fence are gone, so the television's code is compiled into every build and the linker drops it from a desktop executable (`simulators.yml` links the macapp feature set to guard that until W7), and the stand-ins in `webos` and `keymanager` are test seams, compiled for tests and `test-support` (`docs/platform-ports.md`, W4). The desktop platform is the second implementation. | -| **L15e** events, the shell and composition — **W5a to W5c, W6 and W6b landed** | — | W5 (`HostEvent` with `Option`) landed in three PRs, lifecycle and quit (W5a, #1484), keys and text (W5b, #1487) and the pointer and wheel (W5c, #1492), and so did W6b (platform-supplied composition in two boot phases, #1489) and W6 (`plx_shell_sdl`, a `[shell_sdl]` layer: SDL's bring-up, the window, the swap, the event decode and the text-input calls moved out of the application behind its private `Shell` and `Surface`, and the LG half stays in `system.rs`). W6c (a URI-only and a two-driver composition play an ordinary title) is planned. | -| **L15f** extract the platform crates — **planned** | — | W7: a narrow public `host` module in the application crate, `rust-modules/platform-webos` and `platform-desktop` as crates above `app`, and the gate learning "a platform is a crate above `app`". After L15d, before L15g and L15h (the storage-authority part of W8a, #1488, #1490 and #1491, landed ahead of W7; the rest of W8 still follows W7). | +| **L15e** events, the shell and composition — **W5a to W5c, W6, W6b, W6c and W7a landed** | — | W5 (`HostEvent` with `Option`) landed in three PRs, lifecycle and quit (W5a, #1484), keys and text (W5b, #1487) and the pointer and wheel (W5c, #1492), and so did W6b (platform-supplied composition in two boot phases, #1489) and W6 (`plx_shell_sdl`, a `[shell_sdl]` layer: SDL's bring-up, the window, the swap, the event decode and the text-input calls moved out of the application behind its private `Shell` and `Surface`, and the LG half stays in `system.rs`). W6c (a URI-only and a two-driver composition play an ordinary title) landed (#1494), and W7a published the construction interface through `plxnative_modules::host` alone (`rust-modules/src/host.rs`, tested from outside the crate by `rust-modules/tests/host_interface.rs`, `make test-host-interface`). | +| **L15f** extract the platform crates — **planned** | — | W7b: `rust-modules/platform-webos` and `platform-desktop` as crates above `app`, over the narrow public `host` module W7a already published (the row above), and the gate learning "a platform is a crate above `app`". After L15d, before L15g and L15h (the storage-authority part of W8a, #1488, #1490 and #1491, landed ahead of W7; the rest of W8 still follows W7). | | **L15g** the webOS facts and the remaining `hostsim` (L15b item 3) — **W8a started** | — | W8a has begun: the platform states where the account's records live (`tv::Services.storage`, #1488), and telemetry's consent store (#1490) and plex's session persistence (#1491) follow it instead of the `target_arch = "arm"` fence. Still planned: the rest of W8a, one PR per directory (`os`, `src`, `base`, `storage` and `play-feed`; telemetry's nine `target_arch = "arm"` lines in `telemetry/src/telemetry/native.rs`, the Sentry Native crash capture, are not among them and no step owns them yet, the follow-up for Tizen ARM retail builds that #1490 names), sorting the `target_arch = "arm"` and `target_os = "linux"` sites into "is webOS" (a platform value or runner) and "is 32-bit ARM" or "is Linux" (stays); then W8b, the library name lists, `paths` and the packaging, and W8c, the `feature = "hostsim"` lines left in the tree (none of them in the fence now; `git grep -h 'feature = "hostsim"' -- '*.rs' | wc -l` counts them). | | **L15h** the OS-neutral Feed sink (L15b item 1) — **planned** | — | W11: `plx_acb` (an `[acb]` layer) takes the ACB plane owner and the URI media verbs out of `os`, the Feed-side ACB results become neutral, and the bind sequence moves behind a neutral sink. Needs the television. | diff --git a/docs/platform-ports.md b/docs/platform-ports.md index c236b7001c..2ce14a8792 100644 --- a/docs/platform-ports.md +++ b/docs/platform-ports.md @@ -894,17 +894,20 @@ There is no `default_backend` (review M8, critic M1): the backend set is derived `Shell` (the factory) opens the loop's `Surface`: `create_surface`, `make_current`, `swap`, `drawable_size`, `gl_proc_address`; `release`/`reacquire` around background; `video_hole(Option)`, which replaces `arm_opaque_region`, `opaque_route` and `clear_opaque_region`; `pump()`, which replaces `pump_bus`. The trait doc -states which thread runs each call (Target shape 7). `Shell`, `Surface` and `HostEvent` stay app-private until -H1 and H2 return (critic M5; H3, H4 and H5 returned on the emulator only, E6, E8, E10; Decision 3, A): code moves -now, but no type a Samsung shell must match leaves the app crate; Target shape 8 is the one narrow, public -construction interface. The dispatcher's rig hooks (`ui/src/dispatch.rs:728-730`) keep delegating through -`run::rig_*`. +states which thread runs each call (Target shape 7). `Shell`, `Surface` and `HostEvent` stayed app-private until +H1 and H2 return (critic M5; H3, H4 and H5 returned on the emulator only, E6, E8, E10; Decision 3, A). The owner then +ruled (2026-11-21, Decision 3 amended) that `Shell` and `Surface`, with the rest of the construction interface, +are reachable ONLY through `plxnative_modules::host` (Target shape 8), never as general `pub` items of the +application crate; `HostEvent` stays app-private, and a platform reports input through `EventSink`. W7a publishes +today's `Shell` (12 methods) and `Surface` (5, plus `deliver`) as they are; the fold toward the shape above (one +`Surface`, `video_hole`, `pump`) is W9's, which is the first change with a second implementation to fold toward. +The dispatcher's rig hooks (`ui/src/dispatch.rs:728-730`) keep delegating through `run::rig_*`. ### 2. Input and lifecycle: canonical actions (review M6, C8; critic F11) This replaces two earlier designs, "`HostEvent::Key` carries SDL keycodes plus LG scancodes" and critic M7's "map Ecore names to `remote_token_key` pairs". -- `HostEvent` (app-private, like `Shell`) has: +- `HostEvent` (app-private; `Shell` is published through `host` only, Target shape 8) has: - `Key { action: Option, edge: Edge, raw: Option }`, `Edge` being `Down | Repeat | Up` as in `InputKind::Key` (F33). `action` is `Option` because unbound keys flow today as raw pairs (`k:0,269` HOME, `app/events.rs:202-212`), the configurable lab trigger consumes pairs no `Action` names, and the recorder @@ -1177,23 +1180,52 @@ Ecore names to `remote_token_key` pairs". (`src/lib.rs:17`), so a sibling cannot name `app::Platform` or implement a crate-private `Shell`; and a `static PLATFORM` must be `Sync`, while window state is thread-affine (`MainThread` is `!Send + !Sync`, `base/src/task.rs:129`). -- The interface. One narrow public module, `plxnative_modules::host`, of re-exports only: `Platform`, `Services`, - `Shell`, `Surface`, `FrameProbe`, `MediaBoot`, `Composition`, `Exit`, `Release` and an `EventSink` trait. The - split is by thread: registration data (the `static PLATFORM`: function pointers and `&'static dyn` of `Sync` - types, `Shell` included as a factory) is `Sync` and shared; thread-affine state (window, GL context, the - Ecore handles) lives only in a `Surface` that `Shell::open(&self, &MainThread)` returns on the loop thread and - that the app owns inside `App`. The platform reports input through `EventSink` (`key(Option, - Option, Edge)`, `text`, `pointer`, `wheel`, `lifecycle`, `quit`, ...); the APP converts to its private - `HostEvent`, so the owner's decision that the event API stays private holds. `Action`, `RawKey` and `Edge` - are already public lower-layer types. -- Gate. Before extraction, a desktop-shaped root is compiled against `host` alone: an integration test +- The interface. One narrow public module, `plxnative_modules::host`: re-exports, and ONE function, `run(&'static + Platform, &CStr, u16) -> Exit`, which forwards to `run_application` (the single exception to "re-exports + only": the entry is `pub(crate)`, and a platform crate has nothing else to call). The re-exports are `Platform`, + `Services`, `Shell`, `Surface`, `FrameProbe`, `MediaBoot`, `Composition`, `Exit`, `Release` and an `EventSink` + trait, with the vocabulary their signatures use: `MainThread`, `OpenAsk`, `Placement`, `Lifecycle`, `PointerEdge`, + `Action`, `RawKey` and `Edge`. The eight application-crate items (`Platform`, `Shell`, `Surface`, `FrameProbe`, `MediaBoot`, + `Composition`, `Exit`, `Release`) are reachable ONLY through `host` (owner ruling, 2026-11-21; Decision 3, amended): + `Exit` and `Release` are `pub` inside the private `app`, and `Platform` and the traits are `pub` in a private + module, so no path outside `host` names them. `Services` is not one of the eight: it stays `plx_os::tv::Services`, + already a `pub` type of a lower crate, which `host` re-exports beside them. A platform crate names the APPLICATION + crate's types through `host` alone, but not everything it builds is the application's: a `Services` is built from + the hook tables of `plx_os::tv` (`IdentityHooks`, `SecureHooks`, `SystemHooks`, `StorageHooks`, `LegacyWebosMedia`, + `LocaleReply`) and `MediaBoot::compose` takes `plx_media::player::adapter::PlayerAdapter`, so a platform crate + depends on `plx_os` and `plx_media` directly, as well as on the application crate. `host` does not re-export them. + The split is by thread: registration data (the `static + PLATFORM`: function pointers and `&'static dyn` of `Sync` types, `Shell` included as a factory) is `Sync` and + shared; thread-affine state (window, GL context, the Ecore handles) lives only in a `Surface` that + `Shell::open(&self, &MainThread, &OpenAsk)` returns on the loop thread and that the app owns inside `App`. +- Events. The platform reports input through `EventSink` (`key(Option, Option, Edge) -> bool`, `text`, + `pointer`, `wheel`, `lifecycle`, `quit`); the APP converts to its private `HostEvent` (a private `HostQueue`, the + one place), so the owner's decision that the event API stays private holds. `Action`, `RawKey` and `Edge` are + lower-layer types: `RawKey` moved to `plx_ui::consts` beside `raw_pair` and `action_of` (a `pub(crate) use` keeps + the app's old path). `Surface::deliver(&self, &mut dyn EventSink)` is ADDITIVE, beside `Surface::poll`: `deliver` is + required, `poll` is defaulted to `false` and `#[doc(hidden)]`, and the loop's `drain_sdl` drains `poll` as before and + then calls `deliver` once. The SDL shells deliver nothing through the sink, so every SDL event still comes through + `poll` (a unit test pins both). `poll` is RETIRED once the SDL shells deliver through the sink, W9 at the latest. +- Gate. Before extraction, a platform is compiled against the application crate through `host` alone (and against + `plx_os` and `plx_media` for the hook tables and `PlayerAdapter` it names): an integration test (`rust-modules/tests/host_interface.rs`, a separate crate that can name only `pub` items) builds a - `static PLATFORM` with a fake `Shell` and boots it under `hostsim`. W7b extracts only after it passes. -- Runner (G8; F52). No target runs it today (every one is `cargo test --lib`; `rust-modules/tests/` does not - exist), so a test file alone would be a gate nobody runs. W7a adds (1) `make test-host-interface`: `cargo + `static PLATFORM` from a fake `Shell`, `Surface` and `FrameProbe` and boots it through the real `run_application` + (`host::run`) to the fake `Shell::open`'s refusal, under `hostsim` and a throwaway `PLXNATIVE_RUNTIME_DIR`. It + asserts `init` before `open`, the `OpenAsk` the application means to make, and the refusal returned as the entry's + `Exit`. It cannot run frames, and no fake `Surface` could take it further: after `open` the boot makes real GL calls + (`init_gl` links the renderer's programs), which need a current GL context, and nothing stubs GL under + `test-support`. The loop's fake-surface tests stay in the crate (`make test-hostsim`). The test's one source rule is + that every path into the application crate begins `plxnative_modules::host`; the lower-layer crates a platform + lists as its own dependencies (`plx_os`, `plx_media`) are fair to name, and it must, as above. That rule holds + only this file's own spelling. The crate's SURFACE is held by an in-crate source pin in `host.rs`'s tests (`make + test-crate C=plxnative_modules`): the crate root's `pub` items are `host` plus the `hostsim`-only simulator + doors (each confined to `hostsim`, or `test`, by its `cfg`), and `host.rs` is the only `pub use` whose tree names `app` (as `crate::app`, `super::app`, `self::app` or in a group), apart from the root's `hostsim`-only + `synthetic_home_initial`. W7b extracts only after it passes. +- Runner (G8; F52). As of `e9924f0f9` no target ran it (every one was `cargo test --lib`; `rust-modules/tests/` did not + exist), so a test file alone would have been a gate nobody ran. W7a added (1) `make test-host-interface`: `cargo test -p plxnative-modules --features hostsim --test host_interface`, incrementally in `target-hostsim` like - `make test-hostsim`, through `$(UNIT_RUN)` if it accepts `--test` (UNVERIFIED: F52) and as a plain `cargo test` - otherwise; it is a cargo-running target, so it joins `DISK_ENTRIES` (with its `DISK_TREE` line) or + `make test-hostsim`, through `$(UNIT_RUN)` (it accepts `--test`: it passes the cargo line through and requires one + executable per `-p`, which one integration test is); it is a cargo-running target, so it joins `DISK_ENTRIES` (with its `DISK_TREE` line) or `ci/test_disk_preflight.py` fails; and (2) the same invocation as a recipe line of `check-cargo-unit-hostsim`, the `host-unit-hostsim` CI job's target, so `make check` and CI run it, pinned in `ci/test_ci_split.py`'s `GATES`. @@ -1649,26 +1681,41 @@ W3d. Neutral types (L15b item 2 prerequisites; part of item 3). hidden W10 work critic M1 named, and they land here. ### W7 (N, accepted T). Extract the platform crates (W7a -> W7b) -- W7a: the interface of Target shape 8: `pub mod host` in `src/lib.rs`, `host_interface.rs`, a desktop-shaped root - compiled against it. W7b: `[platform webos]` becomes `rust-modules/platform-webos` and `[platform desktop]` +- W7a: the interface of Target shape 8: `pub mod host` in `src/lib.rs`, `host_interface.rs`, a fake platform compiled + against it and booted to its refusal. W7b: `[platform webos]` becomes `rust-modules/platform-webos` and `[platform desktop]` becomes `rust-modules/platform-desktop`. `RUST_LIB` (`Makefile:882`) archives `plx_platform_webos`; the gate learns "platform as crate above app". `tv/plane.rs` and `tv::uri` stay in the bottom layer until W11a. - Order: after W0, W4, W6, W6b, W6c and Wave R. W0's reading (the desktop counts as the second implementation) reverses `docs/module-layers.md:22-24`; the owner's yes is Decision 3, A. The owner's condition was H1-H4 from the emulator or a set: H3 and H4 returned on the emulator (E6, E8) and are recorded as answered on the emulator only; H1 and H2 are open (E9), recorded as open, and gate a retail set, not W7 (nor the emulator MVP of W9, - Decision 8). `HostEvent` and `Shell` stay app-private. + Decision 8). `HostEvent` stays app-private; `Shell` and `Surface` are reachable only through `host` (Decision 3, + amended 2026-11-21). - The Cargo mechanism of the PLATFORM axis lands here: the ARM recipe passes `RUST_FEATFLAGS` (`Makefile:1023-1024`), so each platform crate depends on the app with `default-features = false` and forwards - every app feature the Makefile passes (`rust-modules/Cargo.toml:78-82`), same defaults. -- Files: `src/lib.rs`, `rust-modules/tests/host_interface.rs`, `rust-modules/Cargo.toml`, the `Makefile` `RUST_LIB` + every app feature the Makefile passes (`rust-modules/Cargo.toml:78-82`), same defaults. W7b's platform crates + also depend on `plx_os` and `plx_media` directly: the hook tables of `Services` and `PlayerAdapter` are theirs, and + `host` does not re-export them (`rust-modules/tests/host_interface.rs` shows what a platform crate names). +- Files: `src/lib.rs`, `src/host.rs`, `rust-modules/tests/host_interface.rs`, `rust-modules/Cargo.toml`, the `Makefile` `RUST_LIB` and `cargo rustc` lines and (W7a, G8; F52) the new `test-host-interface` target with its `DISK_ENTRIES` entry and a line in `check-cargo-unit-hostsim`, `ci/test_ci_split.py` (its `GATES`), `ci/check-staticlib-artifact.py` (`CRATE`, F25), `ci/check-module-layers.py`, `ci/module-layers.ini`, `docs/module-layers.md`, `ci/build-budgets.json` (re-measure; no raise), and the bottom layer's `src/lib.rs` (drops `pub mod keymanager;` and `pub mod webos;`) with its `Cargo.toml`: both pinned, a reviewed certificate change (F25). -- Test: `make test-hostsim` and `make test-host-interface` (the integration test, run by no target today; `ci/ +- As landed (W7a): the interface, not the move. `src/host.rs` is the one public module of a television build (re-exports and `run`; a `hostsim` build keeps the simulator binary's own doors), the + eight application-crate items of the owner's ruling are reachable through it only (`Services` is `plx_os`'s own `pub` type, re-exported), and `rust-modules/tests/host_interface.rs` builds + a `static Platform` from fakes and boots it through `host::run` to the fake shell's refusal, with a source scan + that holds every mention of the application crate in that file to `plxnative_modules::host`; the crate's own + surface is held by a source pin in `host.rs`'s tests. A platform crate depends on `plx_os` and `plx_media` as well as + the application crate. The test has no `[[test]]` + entry (cargo discovers `tests/*.rs`), so no `Cargo.toml` and no `ci/proofs` certificate changed. `make + test-host-interface` is the incremental loop and `check-cargo-unit-hostsim` runs the same line, pinned in + `ci/test_ci_split.py` (`GATES`). `Surface::poll` and `Surface::deliver` coexist until W9 retires `poll`; the SDL + shells' `deliver` delivers nothing. `sdl_init` and `sdl_open` are not published: W7b decides what the two real + platform crates need of them. The W6 minors rode along (the reviewer note's inventory claim, and the SDL crate's + source-file pin reading only `*.rs` entries). +- Test: `make test-hostsim` and `make test-host-interface` (the integration test; run by both since W7a; `ci/ test_disk_preflight.py` and `ci/test_ci_split.py` pass with it); W7a changes the `Makefile`, so its PR carries a build-bench table as well as W7b's; `ARM_PROFILE=release` size within budget; every undefined symbol of the C objects (`main.c`, `crashtrace.c`, `sentry_context.c`, `starfish.c`, @@ -1831,8 +1878,18 @@ emulator runs E11 and E12); they are recorded below and the body follows them. - 2026-11-20, Decision 3 (W7 gate): A. W7 may start. H3 and H4 recorded as answered on the emulator only; H1 and H2 stay open and gate W9, not W7. `Shell` and `HostEvent` stay app-private. Read with Decision 8: the emulator MVP of W9 does not wait for H1 and H2 either. +- 2026-11-21, Decision 3 amended (owner): the EIGHT application-crate items `Platform`, `Shell`, `Surface`, + `FrameProbe`, `MediaBoot`, `Composition`, `Exit` and `Release` are reachable only through `plxnative_modules::host`, + never as general `pub` items of the application crate. `Services` is not one of the eight: it is + `plx_os::tv::Services`, already a `pub` type of a lower crate, which `host` re-exports beside them. A platform + crate names the application crate's types through `host` alone; the hook tables a `Services` is built from + (`plx_os::tv`) and `PlayerAdapter` (`plx_media`) come from their own crates, which it depends on directly. + `HostEvent` stays app-private, and `EventSink` is the public face of input (it too is + reachable only through `host`). This replaces "`Shell` and `HostEvent` stay app-private" above for `Shell` and + only `Shell`. - 2026-11-20, Decision 4 (order): A. The three contracts (W3a-c) first, then the rest, the Samsung-facing types - app-private. Cut into the waves of "Workstreams". + app-private (`Shell` and `Surface` are published through `host` only, by the 2026-11-21 amendment to Decision 3). + Cut into the waves of "Workstreams". - 2026-11-20, Decision 5 (probes): go. H5 was built on `samsung/hello-tpk` for the emulator and passed there (E10, `64c609a46`); the tester request on #1460 for H1, H2 and H6 is posted only with the owner's approval; the tester build with an on-screen diagnostics and key-code panel ran on the emulator (E11) and is the diff --git a/rust-modules/shell-sdl/src/lib.rs b/rust-modules/shell-sdl/src/lib.rs index 507abe9c38..ee0d734fbc 100644 --- a/rust-modules/shell-sdl/src/lib.rs +++ b/rust-modules/shell-sdl/src/lib.rs @@ -11,8 +11,8 @@ //! as two plain function pointers the television fills and a desktop leaves empty. //! //! The crate is a mounted module of the `shell_sdl` layer (`ci/module-layers.ini`), which may use -//! `base`, `machine` and `os`; the crate names `base` alone. The application's `Shell` and `Surface` traits and its `HostEvent` stay app-private -//! (`docs/platform-ports.md`, Target shapes 1 and 8); [`window::Window`] is the one SDL +//! `base`, `machine` and `os`; the crate names `base` alone. The application's `HostEvent` stays app-private, and its `Shell` and `Surface` traits are reachable only through +//! the application crate's `host` module (`docs/platform-ports.md`, Target shapes 1 and 8); [`window::Window`] is the one SDL //! implementation of that `Surface`, and [`event::Decoded`] is the neutral value the application maps //! onto its own event type. //! @@ -57,9 +57,12 @@ mod pins { #[test] fn every_source_file_is_scanned() { + // `*.rs` files and directories only: an editor's swap file or a `.DS_Store` is not source. let mut on_disk: Vec = std::fs::read_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/src")) .expect("the crate's src directory") - .map(|e| e.expect("a directory entry").file_name().to_string_lossy().into_owned()) + .map(|e| e.expect("a directory entry")) + .filter(|e| e.path().is_dir() || e.path().extension().is_some_and(|x| x == "rs")) + .map(|e| e.file_name().to_string_lossy().into_owned()) .collect(); on_disk.sort(); let mut listed: Vec<&str> = SOURCES.iter().map(|s| s.0).collect(); diff --git a/rust-modules/src/app/events.rs b/rust-modules/src/app/events.rs index d6db179e44..375428525f 100644 --- a/rust-modules/src/app/events.rs +++ b/rust-modules/src/app/events.rs @@ -10,6 +10,8 @@ use super::*; use plx_machine::machine::Edge; +// `RawKey` is `plx_ui::consts`' (a platform crate names it through `host`); this is the application's spelling. +pub(crate) use plx_ui::consts::RawKey; use plx_ui::consts::{action_of, raw_pair, Action}; /// Preserve one IME commit and its place among key events. Desktop text does not imply an @@ -75,9 +77,10 @@ pub(crate) fn host_wcode(sym: u32) -> u32 { } /// What the platform tells the loop: a key press, a text commit, the pointer, the wheel, the window -/// leaving or returning to the screen, and the host asking the application to end. App-private, like -/// [`Shell`](super::platform::Shell): no platform reaches it by a type of its own until the -/// platform contract is settled (`docs/platform-ports.md`, Target shape 2). +/// leaving or returning to the screen, and the host asking the application to end. App-private, unlike +/// [`Shell`](super::platform::Shell) and [`Surface`](super::platform::Surface), which `host` publishes: a +/// platform reports input through [`EventSink`](super::platform::EventSink) and the application converts it +/// to this type in [`HostQueue`] (`docs/platform-ports.md`, Target shapes 2 and 8). /// /// The SDL drain decodes SDL's events into it ([`decode_host_event`]) and the loop consumes it in /// ONE function (`run::ingest_host_event`), so a host that stops the application without SDL @@ -128,17 +131,6 @@ impl HostEvent { } } -/// The raw `(sym, wcode)` pair a key arrived as. Kept beside the [`Action`] because three things -/// still read it: a press with no action (an unsupported key flows on as exactly the pair it was), -/// the lab trigger key (named by `lab.json`, not by an action), and the recorder's tape, whose -/// format IS the pair. A platform with no SDL pair sends none, and the loop builds -/// [`raw_pair`] for its action. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct RawKey { - pub sym: c_uint, - pub wcode: c_uint, -} - /// One edge of one key, as a platform hands it to the loop: the canonical [`Action`] where the key /// has one, the [`Edge`], and the raw pair where the platform has one. /// @@ -253,6 +245,44 @@ fn host_event(decoded: Decoded) -> Option { }) } +/// What a platform's [`EventSink`](super::platform::EventSink) calls become: the [`HostEvent`]s the loop +/// ingests, in the order the platform made them. The one place a non-SDL platform's events become the +/// application's own type, beside [`host_event`] for SDL's (the two are the only constructors of a +/// [`HostEvent`], so the private event type has exactly two doors). A key goes through [`KeyPress::new`], +/// which refuses what is neither an action nor a pair, or an action and a pair that name two keys. +#[derive(Default)] +pub(crate) struct HostQueue(Vec); + +impl HostQueue { + /// The queued events, oldest first. + pub(crate) fn into_events(self) -> Vec { + self.0 + } +} + +impl super::platform::EventSink for HostQueue { + fn key(&mut self, action: Option, raw: Option, edge: Edge) -> bool { + let Some(press) = KeyPress::new(action, edge, raw) else { return false }; + self.0.push(HostEvent::Key(press)); + true + } + fn text(&mut self, text: &str) { + self.0.push(HostEvent::Text(text.to_owned())); + } + fn pointer(&mut self, x: f32, y: f32, edge: PointerEdge) { + self.0.push(HostEvent::Pointer { x, y, edge }); + } + fn wheel(&mut self, dy: i32) { + self.0.push(HostEvent::Wheel { dy }); + } + fn lifecycle(&mut self, edge: Lifecycle) { + self.0.push(HostEvent::Lifecycle(edge)); + } + fn quit(&mut self) { + self.0.push(HostEvent::Quit); + } +} + /// **One native key edge as the loop hands it to the tree**, for the effect-level guards (W5b): the /// SDL bytes a television or the simulator delivers for the pair `(sym, wcode)` (the literals a /// test writes down, never an `Action`'s `raw_pair`), decoded by [`decode_host_event`], and the @@ -1214,3 +1244,84 @@ mod key_event_tests { assert_eq!(text(b""), Some(HostEvent::Text(String::new()))); } } + +/// A platform's `EventSink` calls become the same `HostEvent`s the SDL decode makes of the same events +/// (the one conversion a non-SDL platform's input goes through), in the order they were made, and a key +/// the application cannot name is refused, not queued. +#[cfg(test)] +mod host_queue_tests { + use super::super::platform::EventSink; + use super::{decode_host_event, encode_key, Action, Edge, HostEvent, HostQueue, KeyPress, Lifecycle, PointerEdge, RawKey}; + use plx_ui::consts::raw_pair; + + fn event_of(code: u32) -> [u8; 128] { + let mut ev = [0u8; 128]; + ev[..4].copy_from_slice(&code.to_ne_bytes()); + ev + } + + #[test] + fn quit_and_the_lifecycle_edges_queue_what_the_sdl_decode_makes_of_their_events() { + let mut queue = HostQueue::default(); + queue.quit(); + queue.lifecycle(Lifecycle::WillBackground); + queue.lifecycle(Lifecycle::DidBackground); + queue.lifecycle(Lifecycle::WillForeground); + queue.lifecycle(Lifecycle::DidForeground); + let decoded: Vec = + [0x100, 0x103, 0x104, 0x105, 0x106].iter().map(|&code| decode_host_event(&event_of(code)).expect("decoded")).collect(); + assert_eq!(queue.into_events(), decoded); + } + + #[test] + fn a_raw_pair_with_or_without_its_action_queues_the_press_the_sdl_decode_makes_of_those_bytes() { + let (sym, wcode) = raw_pair(Action::Ok); + let pair = RawKey { sym, wcode }; + let Some(decoded) = decode_host_event(&encode_key(sym, wcode, true)) else { panic!("a key event") }; + let mut queue = HostQueue::default(); + assert!(queue.key(None, Some(pair), Edge::Down), "a pair alone is a press"); + assert!(queue.key(Some(Action::Ok), Some(pair), Edge::Down), "and so is the pair with the action it names"); + assert_eq!(queue.into_events(), vec![decoded.clone(), decoded]); + } + + #[test] + fn an_action_alone_queues_a_press_whose_pair_is_the_one_a_remote_sends() { + let mut queue = HostQueue::default(); + assert!(queue.key(Some(Action::Back), None, Edge::Up)); + let want = KeyPress::new(Some(Action::Back), Edge::Up, None).expect("Back names a key"); + let events = queue.into_events(); + assert_eq!(events, vec![HostEvent::Key(want)]); + let HostEvent::Key(press) = &events[0] else { panic!("a key") }; + assert_eq!(press.pair(), RawKey { sym: raw_pair(Action::Back).0, wcode: raw_pair(Action::Back).1 }); + } + + #[test] + fn a_key_the_application_cannot_name_is_refused_and_queues_nothing() { + let (sym, wcode) = raw_pair(Action::Ok); + let mut queue = HostQueue::default(); + assert!(!queue.key(None, None, Edge::Down), "neither an action nor a pair"); + assert!(!queue.key(Some(Action::Digit(10)), None, Edge::Down), "no pair spells Digit(10)"); + assert!(!queue.key(Some(Action::Back), Some(RawKey { sym, wcode }), Edge::Down), "an action and a pair of two keys"); + assert!(queue.into_events().is_empty()); + } + + #[test] + fn text_pointer_and_wheel_queue_as_given_and_keep_their_order() { + let mut queue = HostQueue::default(); + queue.text("wal"); + queue.pointer(960.0, 540.0, PointerEdge::Down); + queue.wheel(-2); + queue.text(""); + queue.pointer(1.0, 2.0, PointerEdge::Up); + assert_eq!( + queue.into_events(), + vec![ + HostEvent::Text("wal".into()), + HostEvent::Pointer { x: 960.0, y: 540.0, edge: PointerEdge::Down }, + HostEvent::Wheel { dy: -2 }, + HostEvent::Text(String::new()), + HostEvent::Pointer { x: 1.0, y: 2.0, edge: PointerEdge::Up }, + ] + ); + } +} diff --git a/rust-modules/src/app/exit.rs b/rust-modules/src/app/exit.rs index f0ff5bf38a..fbf5729d81 100644 --- a/rust-modules/src/app/exit.rs +++ b/rust-modules/src/app/exit.rs @@ -54,7 +54,7 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; /// Whether the application gave back every native resource it held before it returned. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Release { +pub enum Release { /// The teardown ran to its end and released the window and the GL context. Complete, /// Something is still held: a native worker is inside firmware, or the boot refused before any @@ -65,15 +65,15 @@ pub(crate) enum Release { /// What `run_application` returns to its entry. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Exit { +pub struct Exit { /// The process exit status: `1` after a failed recording or a refused boot, else `0`. - pub(crate) code: c_int, - pub(crate) release: Release, + pub code: c_int, + pub release: Release, } impl Exit { /// An early-boot refusal. Nothing was torn down, so nothing is released. - pub(crate) const fn refused(code: c_int) -> Self { + pub const fn refused(code: c_int) -> Self { Self { code, release: Release::Retained } } diff --git a/rust-modules/src/app/mod.rs b/rust-modules/src/app/mod.rs index 657912679a..71fa616fa5 100644 --- a/rust-modules/src/app/mod.rs +++ b/rust-modules/src/app/mod.rs @@ -78,7 +78,9 @@ mod hint_taught; mod recorder; mod window_activity; mod exit; -pub(crate) use exit::Exit; +// `pub`, not `pub(crate)`, because `host` re-exports them: a `pub use` cannot re-export a binding the crate +// only sees, and `app` itself is private, so this reaches no further than `host`. +pub use exit::{Exit, Release}; pub(crate) mod events; pub(crate) mod lifecycle; pub(crate) mod playback; diff --git a/rust-modules/src/app/platform.rs b/rust-modules/src/app/platform.rs index 7ff3228b10..d759fbe511 100644 --- a/rust-modules/src/app/platform.rs +++ b/rust-modules/src/app/platform.rs @@ -20,12 +20,17 @@ //! platform composed through [`publish_composition`], the one function that does, so the set of //! installed drivers and the resolver the planner reads cannot disagree. //! -//! `Shell`, `Surface`, `FrameProbe` and `Platform` are app-private on purpose: no type a platform's shell has -//! to match leaves the application crate until the platform contract is settled. The webOS value is -//! built by `port.rs`; `ci/check-deps.sh`'s `frame` gate pins the call text of the three +//! These types are reachable from outside the application crate ONLY through the narrow `host` module +//! (`crate::host`, `docs/platform-ports.md`, Target shape 8), which re-exports them for a platform crate +//! to build its `static` `Platform` against: the application's general API stays private, and so does +//! `HostEvent` (a platform reports input through [`EventSink`], which the application converts). The webOS +//! value is built by `port.rs`; `ci/check-deps.sh`'s `frame` gate pins the call text of the three //! privileged calls (`pump_bus`, `opaque_route`, `clear_opaque_region`) to `app/run.rs`. use super::Exit; use plx_base::task::MainThread; +use plx_machine::machine::Edge; +use plx_shell_sdl::event::{Lifecycle, PointerEdge}; +use plx_ui::consts::{Action, RawKey}; use plx_media::player::adapter::PlayerAdapter; use plx_media::route::uri_preflight::ResolvePort; use plx_media::route::PlaybackSession; @@ -34,8 +39,8 @@ use std::os::raw::c_void; /// What a platform's boot asks of SDL, as plain data: [`InitHooks`] (the two steps a platform runs /// around `SDL_Init`), and [`OpenAsk`] with its [`Placement`] (the window's title, place and size). The -/// shell crate's own types, re-exported rather than copied: they hold no SDL type, and W7a, which -/// publishes `Shell` and `Surface`, is where a platform-neutral spelling of them is decided. +/// shell crate's own types, re-exported rather than copied: they hold no SDL type. `host` re-exports +/// `OpenAsk` and `Placement` for a platform crate (`InitHooks` stays here: only the SDL helpers below take it). pub(crate) use plx_shell_sdl::{InitHooks, OpenAsk, Placement}; /// The platform's window, bus and pointer, as the application drives them: the SDL window and its @@ -48,7 +53,7 @@ pub(crate) use plx_shell_sdl::{InitHooks, OpenAsk, Placement}; /// request first, the session read, then the window. That is the order boot has always had, and /// `app::boot` pins it. A platform whose surface is not SDL's states its own pair; every SDL one is the /// shell crate's (`plx_shell_sdl`), reached through [`sdl_init`] and [`sdl_open`]. -pub(crate) trait Shell: Sync { +pub trait Shell: Sync { /// Bring the platform's windowing up and ask for the GL context, once, FIRST: before the stored /// session is read and before [`open`](Shell::open). A refusal ends the boot with that `Exit`. fn init(&self, mt: &MainThread) -> Result<(), Exit>; @@ -88,24 +93,36 @@ pub(crate) trait Shell: Sync { } /// The window the application presents to and reads events from, owned by `App` for the rest of the -/// process. App-private and thread-affine (not `Sync`) like [`Shell`], and for the same reason: no -/// type a platform has to match leaves the application crate until the platform contract is settled -/// (`docs/platform-ports.md`, Target shapes 1 and 8, which W7a publishes as `host`). +/// process. Thread-affine (not `Sync`, unlike [`Shell`], which returns it from [`Shell::open`] on the loop +/// thread). Published only through `host` (`docs/platform-ports.md`, Target shapes 1 and 8). /// /// `window` is the raw handle the [`Shell`]'s per-window calls still take (`bind_window`, /// `grab_surface`, and `textinput`'s focus read), so every call site the `frame` gate pins stays where -/// it is; W7a folds those into this trait. `poll` is SDL-shaped bytes until the platform's own event -/// sink replaces it. There is no destructor: the `App` is leaked at exit and a worker may still hold -/// the handle, so the end is the explicit, decided [`quit`](Surface::quit). -pub(crate) trait Surface { +/// it is; W9 folds those into this trait (plan, §1). **Two event paths, one of them temporary:** a +/// platform delivers its events through [`deliver`](Surface::deliver) and [`EventSink`]; the SDL shells +/// still deliver through [`poll`](Surface::poll), SDL-shaped bytes, and their `deliver` delivers nothing. +/// `poll` is retired once the SDL shells deliver through the sink (W9 at the latest). There is no +/// destructor: the `App` is leaked at exit and a worker may still hold the handle, so the end is the +/// explicit, decided [`quit`](Surface::quit). +pub trait Surface { /// The raw window handle, null for a surface that has none (the rig's). fn window(&self) -> *mut c_void; /// Present the frame. The compositor commit of the opaque-region request just made is this call's. fn swap(&self); /// 1 locks the frame rate to the panel's refresh, 0 uncaps it; the application computes which. fn set_swap_interval(&self, interval: i32); - /// Take the next event off the platform's queue into `ev`; `false` when there is none. - fn poll(&self, ev: &mut [u8; 128]) -> bool; + /// Take the next event off the platform's queue into `ev`; `false` when there is none. SDL's bytes: + /// only the SDL shells have a queue of that shape, so it is hidden and defaults to none. Retired with + /// the second path ([`deliver`](Surface::deliver) is the one that stays). + #[doc(hidden)] + fn poll(&self, _ev: &mut [u8; 128]) -> bool { + false + } + /// Hand the platform's pending input and window events to `sink`, in order, on the loop thread: called + /// once per drain, after [`poll`](Surface::poll) has been emptied. A platform whose callbacks arrive on + /// another thread queues them and delivers them here. Required: a surface with nothing to deliver + /// states it, as the SDL one does (its events still come through `poll`). + fn deliver(&self, sink: &mut dyn EventSink); /// End the platform's windowing for the process. /// /// # Safety @@ -130,11 +147,36 @@ impl Surface for plx_shell_sdl::Window { fn poll(&self, ev: &mut [u8; 128]) -> bool { plx_shell_sdl::event::poll(ev) } + /// Nothing: every SDL event, a synthetic one the dev tooling pushed included, still comes through + /// [`poll`](Surface::poll) exactly as before, so the SDL event path is unchanged. + fn deliver(&self, _sink: &mut dyn EventSink) {} unsafe fn quit(&self) { plx_shell_sdl::init::quit() } } +/// What a platform reports to the loop through [`Surface::deliver`]: the public face of the application's +/// input vocabulary, whose own event type (`HostEvent`) stays private. Every call runs on the loop thread, +/// in the order the platform saw the events. The application converts each into its event, so a platform +/// names no application type beyond these. +pub trait EventSink { + /// One edge of a key: its canonical [`Action`] where it has one, the raw pair where the platform has + /// one, and the [`Edge`]. A platform that is not SDL sends the action alone. `false` when the press is + /// refused and dropped: it carries neither field, or an action that is not what the pair names, or an + /// action no pair spells (`Action::Digit` above 9). + fn key(&mut self, action: Option, raw: Option, edge: Edge) -> bool; + /// One commit from the platform's text input, possibly empty. + fn text(&mut self, text: &str); + /// One pointer event at authored 1920x1080 coordinates. + fn pointer(&mut self, x: f32, y: f32, edge: PointerEdge); + /// One tick of the wheel, in signed whole ticks. + fn wheel(&mut self, dy: i32); + /// The window left or came back to the screen. + fn lifecycle(&mut self, edge: Lifecycle); + /// The host asks the application to end. + fn quit(&mut self); +} + /// [`Shell::init`] for an SDL platform: SDL up with the platform's two steps around `SDL_Init`, then the /// GL context request. `SDL_Init` refused ends the boot (`Exit::refused(1)`, the status it always had). /// @@ -165,7 +207,7 @@ pub(crate) fn detached_surface() -> Box { /// 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 { +pub 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. @@ -186,20 +228,20 @@ pub(crate) trait FrameProbe: Sync { /// /// `Composition::default()` is a platform that composed no URI driver (the Feed or nothing): no resolver. #[derive(Default)] -pub(crate) struct Composition { - pub(crate) resolver: Option, +pub struct Composition { + pub resolver: Option, } /// A platform's two playback steps at boot. Both are plain functions: the platform's entry states /// them once, in its `static`, and the boot calls them through [`Platform::media`]. -pub(crate) struct MediaBoot { +pub struct MediaBoot { /// Before the first adapter exists, once per process. The caller runs it only on a boot that /// touches the television (not a controlled one), so a platform's body never asks. - pub(crate) early_init: fn(&MainThread), + pub early_init: fn(&MainThread), /// Install this platform's drivers on the adapter, and return what the session must also be told. /// `controlled` is a replay or scripted Home, which touches no native port and so installs no /// native driver. It takes no session and publishes nothing: [`publish_composition`] does that. - pub(crate) compose: fn(&mut PlayerAdapter, controlled: bool) -> Composition, + pub compose: fn(&mut PlayerAdapter, controlled: bool) -> Composition, } /// Tell the route session what the platform composed: the resolver first, then the backend set the @@ -234,7 +276,7 @@ pub(crate) fn publish_composition( /// 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 struct Platform { services: &'static Services, pub(crate) shell: &'static dyn Shell, pub(crate) diag: &'static dyn FrameProbe, @@ -243,7 +285,7 @@ pub(crate) struct Platform { impl Platform { /// A platform's entry states its four parts once, in a `static`. - pub(crate) const fn new( + pub const fn new( services: &'static Services, shell: &'static dyn Shell, diag: &'static dyn FrameProbe, @@ -469,6 +511,52 @@ mod tests { assert!(!other.shell.release_surface(), "the rest of the shell answers as the host-test one does"); } + /// **The SDL surface delivers nothing through its sink, so on the television and a desktop every event + /// still comes through `poll`, exactly as before.** An SDL key is pushed onto SDL's queue; the surface's + /// `deliver` reports none of it (the sink is called zero times), and `poll` still returns it. The + /// two-path drain therefore changes nothing for an SDL platform. + #[test] + fn the_sdl_surface_delivers_nothing_and_its_events_still_come_through_poll() { + #[derive(Default)] + struct Count(usize); + impl EventSink for Count { + fn key(&mut self, _: Option, _: Option, _: Edge) -> bool { + self.0 += 1; + true + } + fn text(&mut self, _: &str) { + self.0 += 1; + } + fn pointer(&mut self, _: f32, _: f32, _: PointerEdge) { + self.0 += 1; + } + fn wheel(&mut self, _: i32) { + self.0 += 1; + } + fn lifecycle(&mut self, _: Lifecycle) { + self.0 += 1; + } + fn quit(&mut self) { + self.0 += 1; + } + } + let _serial = plx_base::testlock::serial(); + let _events = plx_shell_sdl::testing::EventsOnly::init(); + let surface = detached_surface(); + let mut ev = [0u8; 128]; + while surface.poll(&mut ev) {} + plx_shell_sdl::inject::synth_key(plx_ui::consts::SDLK_UP, 0); + let mut count = Count::default(); + surface.deliver(&mut count); + assert_eq!(count.0, 0, "an SDL surface delivers nothing through the sink"); + // `synth_key` pushes the two edges of a tap, down then up: both are still the queue's. + for edge in ["down", "up"] { + assert!(surface.poll(&mut ev), "the pushed key's {edge} edge is still the queue's, through `poll`"); + assert!(plx_shell_sdl::event::decode(&ev).is_some(), "and it decodes as before ({edge})"); + } + assert!(!surface.poll(&mut ev), "and the queue is empty after them"); + } + /// **The SDL calls the application still declares are the two that stay.** Everything SDL-shaped /// that is the stock shell's (the window, the GL context, the queue, the text-input panel) is /// `plx_shell_sdl`'s; what remains is `system.rs`'s `SDL_GetWindowWMInfo` handshake (the television's diff --git a/rust-modules/src/app/run.rs b/rust-modules/src/app/run.rs index 2ef8d7fb06..891c4cf129 100644 --- a/rust-modules/src/app/run.rs +++ b/rust-modules/src/app/run.rs @@ -1071,6 +1071,21 @@ unsafe fn drain_sdl(app: &mut App, fr: &mut Frame) { while app.surface.poll(&mut app.ev) { ingest_sdl_event(app, fr); } + // The second path: what the platform's surface delivers through its sink. An SDL surface delivers + // nothing here (every SDL event came through `poll` above), so on the television and a desktop this + // is an empty queue; a surface that is not SDL's has no `poll` and only this. `poll` is retired once + // the SDL shells deliver through the sink (W9 at the latest, `docs/platform-ports.md`). + deliver_events(app, fr); +} + +/// Take what the surface delivers through its sink into the loop, in the order the platform made it. +unsafe fn deliver_events(app: &mut App, fr: &mut Frame) { + let mut queue = super::events::HostQueue::default(); + app.surface.deliver(&mut queue); + let shell = app.platform.shell; + for event in queue.into_events() { + ingest_host_event(app, fr, event, |win| shell.grab_surface(win)); + } } unsafe fn ingress_token(app: &mut App, fr: &mut Frame, token: &str) -> bool { @@ -4267,6 +4282,36 @@ pub(in crate::app) mod lifecycle_regression_tests { assert_eq!(second.runtime.bridge(&mut second.bridge).consent_subhash(), second_consent); } + /// A surface that is not SDL's: it has no queue to `poll` and delivers its one event, the host's + /// request to end, through the sink it is handed. + struct SinkSurface; + + impl crate::app::platform::Surface for SinkSurface { + fn window(&self) -> *mut c_void { + std::ptr::null_mut() + } + fn swap(&self) {} + fn set_swap_interval(&self, _interval: i32) {} + fn deliver(&self, sink: &mut dyn crate::app::platform::EventSink) { + sink.quit(); + } + unsafe fn quit(&self) {} + } + + /// **The loop drains a surface's sink**: `drain_sdl` hands the surface a sink, and what it delivers + /// is ingested like any event (here the host's request to end, `HostEvent::Quit`, which stops the loop). + /// A surface with no `poll` of its own reaches the loop only through this call. + #[test] + fn a_surface_that_delivers_through_its_sink_reaches_the_loop_through_drain_sdl() { + let _serial = plx_base::testlock::serial(); + let mut app = app(); + app.surface = Box::new(SinkSurface); + let mut fr = Frame::begin(&app.player.session, app.runtime.metadata_view()); + app.running = true; + unsafe { drain_sdl(&mut app, &mut fr) }; + assert!(!app.running, "the delivered quit ended the loop"); + } + fn frame(app: &mut App, now: u32) { super::super::bridge::app_frame( app, diff --git a/rust-modules/src/host.rs b/rust-modules/src/host.rs new file mode 100644 index 0000000000..d68f91eb45 --- /dev/null +++ b/rust-modules/src/host.rs @@ -0,0 +1,240 @@ +//! The cross-crate construction interface: what a platform crate needs to build its `static` [`Platform`] +//! and hand it to the application (`docs/platform-ports.md`, Target shape 8). +//! +//! The application's modules are private (`mod app;`), so a crate that is a sibling of this one cannot +//! name `app::Platform` or implement a crate-private `Shell`. This is the one narrow public face: re-exports +//! of the types a platform builds or implements, an [`EventSink`] through which it reports input, and +//! [`run`], the one function in here (it hands the platform to the application's entry). No other module of the +//! application is public to a television build. A `hostsim` build also keeps the simulator binary's own doors, +//! each behind `feature = "hostsim"` in `lib.rs` (`grep -n 'feature = "hostsim"' rust-modules/src/lib.rs`): +//! `platform_desktop::run`, `hud_cli`, `sim_runtime_dir`, `sim_events_log`, `publish_sim_webos_major` and +//! `synthetic_home_initial`, the one `app` item re-exported at the crate root. `HostEvent`, the loop's own event type, stays +//! private: a platform reports input through [`EventSink`] and the application converts it. The owner's ruling (2026-11-21, Decision 3 +//! amended): the eight application-crate items `Platform`, `Shell`, `Surface`, `FrameProbe`, `MediaBoot`, +//! `Composition`, `Exit` and `Release` are reachable only through this module. `Services` is not one of the eight: +//! it is `plx_os::tv::Services`, already a `pub` type of a lower crate, which this module re-exports beside them. +//! A platform crate names the application crate's types through `host` alone; the hook tables a `Services` is +//! built from (`plx_os::tv`) and `PlayerAdapter`, which `MediaBoot::compose` takes (`plx_media`), come from +//! their own crates, which it depends on directly. +//! +//! The split is by thread. A [`Platform`] is registration data in a `static`: function pointers and +//! `&'static dyn` of `Sync` types, [`Shell`] included as a factory. The thread-affine state (the window, +//! the GL context, a toolkit's handles) lives only in the [`Surface`] that [`Shell::open`] returns on the +//! loop thread and that the application owns from then on. +//! +//! Beside the platform's own types, the vocabulary their signatures name is re-exported from the lower +//! layers it lives in ([`MainThread`], [`Action`], [`Edge`], [`RawKey`], [`Lifecycle`], [`PointerEdge`], +//! [`OpenAsk`], [`Placement`]), so a platform crate names the application crate's types, and the vocabulary they use, through `host` alone. +//! The two SDL helpers (`sdl_init`, `sdl_open`) are not here: W7b publishes what the two real platforms need. +use std::ffi::CStr; +use std::os::raw::c_int; + +pub use crate::app::platform::{Composition, EventSink, FrameProbe, MediaBoot, Platform, Shell, Surface}; +pub use crate::app::{Exit, Release}; +pub use plx_base::task::MainThread; +pub use plx_machine::machine::Edge; +pub use plx_os::tv::Services; +pub use plx_shell_sdl::event::{Lifecycle, PointerEdge}; +pub use plx_shell_sdl::{OpenAsk, Placement}; +pub use plx_ui::consts::{Action, RawKey}; + +/// Boot the application on `platform` and return the status it ended with: the application's entry +/// (`run_application`), which installs the platform's services, brings the window up through its +/// [`Shell`], runs the loop and tears down. Ending the process is the caller's, as for the television's +/// and the desktop's own entries: a process that hosts the application never does. +/// +/// `pms_host` and `pms_port` are the pair `plex_run` hands the entry and `platform_desktop::run` takes. +pub fn run(platform: &'static Platform, pms_host: &CStr, pms_port: u16) -> Exit { + crate::app::run_application(platform, pms_host.as_ptr(), c_int::from(pms_port)) +} + +/// **The owner's ruling, held in the source.** `tests/host_interface.rs` is a separate crate and reads only its own +/// spelling, so nothing there stops `lib.rs` from growing `pub mod app;` or `pub use app::platform::Shell;`: every +/// test would still pass. These pins read the crate's own source, in the style of the `include_str!` pins of +/// `port.rs` and `app/boot.rs`, and fail on that edit. The reason is Decision 3's amendment of 2026-11-21 +/// (`docs/platform-ports.md`): `host` is the only way a platform crate reaches the application's types. +#[cfg(test)] +mod surface_pin_tests { + use std::path::Path; + + /// What the crate root may make `pub`, by the head of the item: `host`, and the simulator binary's own doors + /// (a separate crate, so they must be `pub`), each existing only under `feature = "hostsim"`. `host` alone is + /// open to a television build. + const ROOT_ITEMS: [(&str, bool); 7] = [ + ("pub mod host", false), + ("pub mod hud_cli", true), + ("pub mod platform_desktop", true), + ("pub fn sim_runtime_dir", true), + ("pub fn publish_sim_webos_major", true), + ("pub fn sim_events_log", true), + ("pub use app::synthetic_home_initial", true), + ]; + + const HOW_TO_PROCEED: &str = "The application is reachable only through `host`, because the owner's 2026-11-21 amendment to \ + Decision 3 (docs/platform-ports.md) makes `host` the only way a platform crate reaches it. To publish an \ + application item (W7b's `sdl_init` and `sdl_open`, say), re-export it from host.rs, which the second pin allows. \ + Only a new simulator door that is NOT an application item, existing only under `feature = \"hostsim\"`, extends \ + ROOT_ITEMS in this test, and the reason is recorded in that amendment."; + + /// The text of an item's head: up to its first `;`, `{`, `(` or `<`. + fn head(line: &str) -> &str { + let end = line.find([';', '{', '(', '<']).unwrap_or(line.len()); + line[..end].trim() + } + + /// `(can be true, can be false)` for the cfg predicate at the start of `s` (whitespace removed), in a build with + /// neither `hostsim` nor `test` and whatever else set; also returns the rest of `s`. Any other predicate may be + /// either, so an `any(...)` naming another feature (`devtriggers` is on by default) can be true. + fn can_be(s: &str) -> ((bool, bool), &str) { + let end = s.find(|c: char| !(c.is_alphanumeric() || c == '_')).unwrap_or(s.len()); + let (name, rest) = s.split_at(end); + if let Some(mut rest) = rest.strip_prefix('(') { + let mut parts = Vec::new(); + while !rest.starts_with(')') { + assert!(!rest.is_empty(), "an unbalanced cfg predicate"); + let (part, after) = can_be(rest); + parts.push(part); + rest = after.strip_prefix(',').unwrap_or(after); + } + let result = match name { + "any" => (parts.iter().any(|p| p.0), parts.iter().all(|p| p.1)), + "all" => (parts.iter().all(|p| p.0), parts.iter().any(|p| p.1)), + "not" => (parts[0].1, parts[0].0), + other => panic!("an unknown cfg combinator `{other}`"), + }; + return (result, &rest[1..]); + } + if let Some(value) = rest.strip_prefix("=\"") { + let (value, after) = value.split_once('"').expect("a closed string"); + let never = name == "feature" && value == "hostsim"; + return ((!never, true), after); + } + (((name != "test"), true), rest) + } + + /// Whether the attribute `attr` (whitespace removed) is a `cfg` under which the item cannot exist without + /// `hostsim` or `test`: `feature = "hostsim"`, an `any` of those two, or an `all` with `hostsim` among its members. + fn confines_to_hostsim(attr: &str) -> bool { + let predicate = attr.strip_prefix("#[cfg(").and_then(|a| a.strip_suffix(")]")); + predicate.is_some_and(|p| !can_be(p).0 .0) + } + + /// The `pub` items of `source` (not `pub(crate)`, which has no space after `pub`) as `(line, head, confined)`. + /// An attribute may span lines, so each is read to its closing bracket and joined before it is judged. + fn public_items(source: &str) -> Vec<(usize, String, bool)> { + let mut found = Vec::new(); + let mut attrs: Vec = Vec::new(); + let mut lines = source.lines().enumerate(); + while let Some((at, line)) = lines.next() { + let line = line.trim(); + if line.is_empty() || line.starts_with("//") { + continue; + } + if line.starts_with("#[") { + let mut attr = line.to_string(); + while attr.matches('[').count() > attr.matches(']').count() { + match lines.next() { + Some((_, more)) => attr.push_str(more.trim()), + None => break, + } + } + attrs.push(attr.split_whitespace().collect()); + continue; + } + if line.starts_with("pub ") { + found.push((at + 1, head(line).to_string(), attrs.iter().any(|a| confines_to_hostsim(a)))); + } + attrs.clear(); + } + found + } + + #[test] + fn the_crate_root_publishes_host_and_the_simulators_hostsim_doors_and_nothing_else() { + let source = include_str!("lib.rs"); + let items = public_items(source); + for (at, item, confined) in &items { + let Some(&(_, hostsim_only)) = ROOT_ITEMS.iter().find(|&&(known, _)| known == item.as_str()) else { + panic!("lib.rs line {at} makes `{item}` public. {HOW_TO_PROCEED}"); + }; + assert!( + !hostsim_only || *confined, + "lib.rs line {at}: `{item}` is a simulator door and must exist only under `feature = \"hostsim\"` (with \ + `test` or `all(..)` at most): an `any(..)` naming another feature, `devtriggers` being on by default, \ + ships it in a television build. {HOW_TO_PROCEED}" + ); + } + for (known, _) in ROOT_ITEMS { + assert!( + items.iter().any(|(_, item, _)| item == known), + "lib.rs no longer makes `{known}` public: update ROOT_ITEMS to match. {HOW_TO_PROCEED}" + ); + } + // An exported macro is a public path into the crate that a `pub ` line scan cannot see. + assert!(!source.contains(concat!("#[macro_", "export")), "lib.rs exports a macro. {HOW_TO_PROCEED}"); + } + + /// `pub use` statements of `text`, each as `(line number, its text after `pub use` with whitespace removed)`. + /// A statement runs to its `;`, so a `{ ... }` list over several lines is one. + fn pub_uses(text: &str) -> Vec<(usize, String)> { + let mut found = Vec::new(); + let mut lines = text.lines().enumerate(); + while let Some((at, line)) = lines.next() { + let Some(rest) = line.trim_start().strip_prefix("pub use ") else { continue }; + let mut statement = rest.to_string(); + while !statement.contains(';') { + match lines.next() { + Some((_, more)) => statement.push_str(more), + None => break, + } + } + found.push((at + 1, statement.split_whitespace().collect())); + } + found + } + + /// Whether a `pub use` tree has `app` as a path segment anywhere: `crate::app::X`, `super::app::X` (from a module + /// directly under `src/`), `self::app::X` (from `lib.rs`), `app::X` and `crate::{host, app::X}` all do. + fn names_the_application(statement: &str) -> bool { + statement.split(|c: char| !(c.is_alphanumeric() || c == '_')).any(|segment| segment == "app") + } + + fn rust_sources(dir: &Path, root: &Path, out: &mut Vec<(String, String)>) { + let mut entries: Vec<_> = std::fs::read_dir(dir).expect("the source directory").map(|e| e.expect("an entry").path()).collect(); + entries.sort(); + for path in entries { + if path.is_dir() { + rust_sources(&path, root, out); + } else if path.extension().is_some_and(|e| e == "rs") { + let name = path.strip_prefix(root).expect("under the root").to_string_lossy().into_owned(); + out.push((name, std::fs::read_to_string(&path).expect("a source file"))); + } + } + } + + #[test] + fn host_is_the_only_place_that_re_exports_the_application() { + let root = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/src")); + let mut files = Vec::new(); + rust_sources(root, root, &mut files); + assert!(files.iter().any(|(name, _)| name == "host.rs"), "the scan did not read this crate's own sources"); + let mut in_host = 0; + for (name, text) in &files { + for (at, statement) in pub_uses(text) { + if !names_the_application(&statement) { + continue; + } + if name == "host.rs" { + in_host += 1; + } else { + // The one other: the root's `hostsim`-only `synthetic_home_initial`, which the simulator binary calls. + assert!( + name == "lib.rs" && statement == "app::synthetic_home_initial;", + "{name} line {at} re-exports from the application (`pub use {statement}`). {HOW_TO_PROCEED}" + ); + } + } + } + assert!(in_host >= 2, "host.rs re-exports the application's types: the scan found {in_host} `pub use` of `app`"); + } +} diff --git a/rust-modules/src/lib.rs b/rust-modules/src/lib.rs index f1fe806ea1..2d621e9d98 100644 --- a/rust-modules/src/lib.rs +++ b/rust-modules/src/lib.rs @@ -19,6 +19,11 @@ mod capture; // dev live UI capture stream: own-GLES-frame grab → MPEG1/TS or mod coldstart; // retires old last-page bookmarks; authenticated cold boots now stay on Home mod dev; // the /tmp/plxnative-* trigger surface, behind one `devtriggers` feature — read it before adding a trigger mod focusprobe; // dev: one diffable line naming everything app.rs's key ladder can move, logged when it changes +/// The one narrow public face of the application for a platform crate: the types it builds and implements +/// (`Platform`, `Shell`, `Surface`, `EventSink`, ...) and the entry `run`, as re-exports. Every other module of +/// the application stays private to a television build (`docs/platform-ports.md`, Target shape 8; a `hostsim` +/// build also exposes the simulator binary's own doors below). +pub mod host; // The simulator's HUD tools (`--hud-lint`, `--hud-schema`, `--hud-export`): a library function the thin // `src/bin/sim.rs` calls before it reads a PMS host. `pub` because that binary is a separate crate; absent // from the television build, which has no use for a linter and no argv to read it from. diff --git a/rust-modules/tests/host_interface.rs b/rust-modules/tests/host_interface.rs new file mode 100644 index 0000000000..b751cc7985 --- /dev/null +++ b/rust-modules/tests/host_interface.rs @@ -0,0 +1,313 @@ +//! W7a's gate: a platform built against the application crate through `plxnative_modules::host`, with the hook +//! tables of `plx_os::tv` and `plx_media`'s `PlayerAdapter` from their own crates (`docs/platform-ports.md`, +//! Target shape 8). +//! +//! This is an integration test, a separate crate that can name only the `pub` items of the application +//! crate, which is the point: a platform crate that is a sibling of the application has the same view. It +//! builds a `static PLATFORM` from a fake `Shell`, `Surface` and `FrameProbe` and boots it. +//! +//! **What "boots it" can mean here.** The real `run_application` runs, through [`host::run`], up to the +//! fake's `Shell::open`, which refuses: the boot ends with that `Exit`. It cannot go further, and no +//! fake could take it further: after `open` the boot makes real GL calls (`init_gl` links the renderer's +//! programs), which need a current GL context, and a surface that is not a real window has none. So this +//! test proves the construction interface and the boot order (the services installed, `init` before +//! `open`, `open` asked for the window the application means to ask for, the refusal returned as the +//! entry's `Exit`), not the loop. The loop's own fake-surface tests are in-crate (`make test-hostsim`). +//! +//! **The boot test needs `hostsim`** (the recipe `make test-host-interface` passes it): only there is the +//! runtime root steerable by `PLXNATIVE_RUNTIME_DIR`, so the boot's event log, crash log and diagnostics +//! land in a throwaway directory and not in a real install's. It refuses to run without that variable. +//! The rest of the file compiles in every configuration (`make lint` and `check-cargo-lint` build it), +//! which type-checks the interface from outside in the default non-hostsim feature set too. +//! +//! The application replaces the process's panic hook while it boots (`install_panic_logger`): it wraps +//! the previous hook, so a panic still reaches the test harness, and additionally writes one line to the +//! event log and the crash log in the runtime root. Only one test here boots, because the services are +//! installed once per process. +#![cfg_attr(not(feature = "hostsim"), allow(dead_code))] + +use plxnative_modules::host::{ + Action, Composition, Edge, EventSink, Exit, FrameProbe, Lifecycle, MainThread, MediaBoot, OpenAsk, Placement, + Platform, PointerEdge, RawKey, Services, Shell, Surface, +}; +#[cfg(feature = "hostsim")] +use plxnative_modules::host::Release; +use std::ffi::c_void; +#[cfg(feature = "hostsim")] +use std::ffi::CString; +use std::sync::Mutex; + +/// The refusal the fake `open` ends the boot with: a status no real refusal uses. +const REFUSAL: i32 = 73; + +/// Fake services: the production tables' `NONE` groups, and one hook of its own, so the test can see that +/// the platform's table was the one installed. +static SERVICES: Services = Services { + identity: plx_os::tv::IdentityHooks { system_locale: fake_locale, ..plx_os::tv::IdentityHooks::NONE }, + secure: plx_os::tv::SecureHooks::NONE, + system: plx_os::tv::SystemHooks::NONE, + storage: plx_os::tv::StorageHooks::NONE, + legacy_webos_media: plx_os::tv::LegacyWebosMedia::NONE, +}; + +fn fake_locale() -> plx_os::tv::LocaleReply { + plx_os::tv::LocaleReply::Reply("fake-host-locale".into()) +} + +/// A `Shell` of `Sync` state alone: an ordered call log and the window it was asked to open. +struct FakeShell { + log: Mutex>, + /// The window `open` was asked for: its title, placement and HiDPI flag. + asked: Mutex>, +} + +impl FakeShell { + fn note(&self, what: &'static str) { + self.log.lock().unwrap().push(what); + } +} + +impl Shell for FakeShell { + fn init(&self, _mt: &MainThread) -> Result<(), Exit> { + self.note("init"); + Ok(()) + } + fn open(&self, _mt: &MainThread, ask: &OpenAsk) -> Result, Exit> { + self.note("open"); + *self.asked.lock().unwrap() = Some((ask.title.to_string_lossy().into_owned(), ask.placement, ask.high_dpi)); + Err(Exit::refused(REFUSAL)) + } + fn bind_window(&self, _win: *mut c_void) { + self.note("bind_window"); + } + fn grab_surface(&self, _win: *mut c_void) { + self.note("grab_surface"); + } + fn release_surface(&self) -> bool { + self.note("release_surface"); + false + } + fn arm_opaque_region(&self) { + self.note("arm_opaque_region"); + } + fn opaque_route(&self, _player: bool) { + self.note("opaque_route"); + } + fn clear_opaque_region(&self) { + self.note("clear_opaque_region"); + } + fn pump_bus(&self) { + self.note("pump_bus"); + } + fn hide_pointer(&self) { + self.note("hide_pointer"); + } + fn show_pointer_after_motion(&self) { + self.note("show_pointer_after_motion"); + } + fn hide_is_cursor_swap(&self) -> bool { + false + } +} + +static SHELL: FakeShell = FakeShell { log: Mutex::new(Vec::new()), asked: Mutex::new(None) }; + +struct FakeProbe; + +impl FrameProbe for FakeProbe { + fn request(&self) {} + fn prepare_begin(&self) {} + fn prepare_end(&self) {} + fn waiting(&self) {} + fn acquired(&self) {} + fn fields(&self) -> String { + String::new() + } +} + +/// A surface that is not SDL's: it has no queue of bytes (`poll` is left at its default) and delivers its +/// events through the sink. Thread-affine state is its own (`!Sync`: a `Cell`), as a toolkit's would be. +struct FakeSurface { + frames: std::cell::Cell, +} + +impl Surface for FakeSurface { + fn window(&self) -> *mut c_void { + std::ptr::null_mut() + } + fn swap(&self) { + self.frames.set(self.frames.get() + 1); + } + fn set_swap_interval(&self, _interval: i32) {} + fn deliver(&self, sink: &mut dyn EventSink) { + sink.lifecycle(Lifecycle::DidForeground); + sink.pointer(10.0, 20.0, PointerEdge::Move); + sink.wheel(-1); + sink.text("ok"); + assert!(sink.key(Some(Action::Ok), None, Edge::Down), "an action alone is a key"); + assert!(!sink.key(None, None, Edge::Down), "a key of neither action nor pair is refused"); + sink.quit(); + } + unsafe fn quit(&self) {} +} + +fn early_init(_mt: &MainThread) {} + +fn compose(_adapter: &mut plx_media::player::adapter::PlayerAdapter, _controlled: bool) -> Composition { + Composition::default() +} + +/// The platform, as a sibling crate states it: a `static`, so every part of it is `Sync`. +static PLATFORM: Platform = + Platform::new(&SERVICES, &SHELL, &FakeProbe, MediaBoot { early_init, compose }); + +fn assert_sync(_: &T) {} + +/// The registration data is `Sync` (a `static` of it compiles), and the thread-affine surface is not +/// required to be: a `Surface` holding a `Cell` is accepted as `Box`. +#[test] +fn the_platform_is_registration_data_and_the_surface_may_be_thread_affine() { + assert_sync(&PLATFORM); + let surface: Box = Box::new(FakeSurface { frames: std::cell::Cell::new(0) }); + surface.swap(); + surface.set_swap_interval(1); + assert!(surface.window().is_null()); + let mut ev = [0u8; 128]; + assert!(!surface.poll(&mut ev), "a surface with no SDL queue has nothing to poll"); +} + +/// What a fake surface delivers is what its `EventSink` receives, in order, from outside the crate: the +/// sink is implementable here with the public vocabulary alone. +#[test] +fn an_event_sink_is_implementable_from_outside_and_receives_a_surfaces_events_in_order() { + #[derive(Default)] + struct Recorder(Vec); + impl EventSink for Recorder { + fn key(&mut self, action: Option, raw: Option, edge: Edge) -> bool { + self.0.push(format!("key {action:?} {raw:?} {edge:?}")); + action.is_some() || raw.is_some() + } + fn text(&mut self, text: &str) { + self.0.push(format!("text {text}")); + } + fn pointer(&mut self, x: f32, y: f32, edge: PointerEdge) { + self.0.push(format!("pointer {x} {y} {edge:?}")); + } + fn wheel(&mut self, dy: i32) { + self.0.push(format!("wheel {dy}")); + } + fn lifecycle(&mut self, edge: Lifecycle) { + self.0.push(format!("lifecycle {edge:?}")); + } + fn quit(&mut self) { + self.0.push("quit".into()); + } + } + let surface = FakeSurface { frames: std::cell::Cell::new(0) }; + let mut sink = Recorder::default(); + surface.deliver(&mut sink); + assert_eq!( + sink.0, + [ + "lifecycle DidForeground", + "pointer 10 20 Move", + "wheel -1", + "text ok", + "key Some(Ok) None Down", + "key None None Down", + "quit", + ] + ); +} + +/// **The one source rule of this file**, and it holds this file's own spelling only: every path into the +/// application crate starts `plxnative_modules::host`. What the crate itself makes reachable is not read here; +/// that is pinned in-crate, by the source pins in `host.rs`'s tests (the crate root's `pub` items, and `host.rs` as +/// the only `pub use` that names `app`). The lower-layer crates a platform crate lists as its +/// own dependencies (`plx_os`, `plx_media`) are fine to name, and this file must (a `Services` is built from +/// `plx_os::tv`'s hook tables, `MediaBoot::compose` takes `plx_media`'s `PlayerAdapter`); an edit to this file that +/// names the application crate any other way fails here. +#[test] +fn every_path_into_the_application_crate_goes_through_host() { + let source = include_str!("host_interface.rs"); + // Split, so this test's own text never matches. + let needle = concat!("plxnative_", "modules"); + let mut seen = 0; + for (at, _) in source.match_indices(needle) { + seen += 1; + let line = source[..at].matches('\n').count() + 1; + assert!( + source[at + needle.len()..].starts_with("::host"), + "line {line}: a name of the application crate that is not a path into `host`" + ); + } + assert!(seen > 0, "the scan found no path at all: it is not reading this file"); +} + +/// The entries of `dir` whose name starts with `plxnative-`, sorted. +#[cfg(feature = "hostsim")] +fn plxnative_entries(dir: &std::path::Path) -> Vec { + let mut names: Vec = std::fs::read_dir(dir) + .map(|rd| { + rd.filter_map(|e| e.ok()) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|n| n.starts_with("plxnative-")) + .collect() + }) + .unwrap_or_default(); + names.sort(); + names +} + +/// **The boot of the fake platform, to its refusal.** The real `run_application` runs on `PLATFORM`: +/// it installs the platform's services, brings the shell up (`init`), reads the stored session, then asks +/// the shell for the window (`open`), which refuses. The test asserts the order, the window asked for, the +/// installed services and the returned `Exit`, and that the boot's event log landed in the throwaway runtime root. +/// It also PRINTS the `plxnative-*` entries of `/tmp` (where a device's trigger files live) and of the runtime root +/// before and after, for a reader of `--nocapture`; it does not assert on `/tmp`, which other checkouts' test runs +/// write under concurrently. +#[cfg(feature = "hostsim")] +#[test] +fn run_boots_the_fake_platform_through_init_then_open_and_returns_the_refusal() { + let runtime = std::env::var_os("PLXNATIVE_RUNTIME_DIR").map(std::path::PathBuf::from).expect( + "PLXNATIVE_RUNTIME_DIR must name a throwaway directory: this test boots the application, which writes \ + its logs and reads its triggers under the runtime root (`make test-host-interface` sets it)", + ); + assert!(runtime.is_dir(), "the runtime root {} is not a directory", runtime.display()); + let tmp = std::path::Path::new("/tmp"); + // The recipe's own throwaway directories (`plxnative-check.XXXXXX`) come and go with other runs. + let outside = |names: Vec| -> Vec { + names.into_iter().filter(|n| !n.starts_with("plxnative-check.")).collect() + }; + let tmp_before = outside(plxnative_entries(tmp)); + let runtime_before = std::fs::read_dir(&runtime).map(|rd| rd.count()).unwrap_or(0); + + let host = CString::new("127.0.0.1").unwrap(); + let exit = plxnative_modules::host::run(&PLATFORM, &host, 32400); + + assert_eq!(exit, Exit { code: REFUSAL, release: Release::Retained }, "the fake's refusal is the entry's Exit"); + assert_eq!(*SHELL.log.lock().unwrap(), ["init", "open"], "init, then open, and nothing after the refusal"); + let (title, placement, high_dpi) = SHELL.asked.lock().unwrap().clone().expect("open was asked for a window"); + assert_eq!(title, "PlxNative", "the title a hostsim build asks for"); + assert_eq!(placement, Placement::Desktop, "a hostsim build asks for the desktop placement"); + eprintln!("open was asked for: title {title:?}, {placement:?}, high_dpi {high_dpi}"); + assert!( + matches!(plx_os::tv::system_locale(), plx_os::tv::LocaleReply::Reply(ref l) if l == "fake-host-locale"), + "the services the application installed are the platform's own table" + ); + + let tmp_after = outside(plxnative_entries(tmp)); + let runtime_after: Vec = std::fs::read_dir(&runtime) + .unwrap() + .filter_map(|e| e.ok()) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect(); + eprintln!("/tmp/plxnative-* (outside plxnative-check.*) before: {tmp_before:?}"); + eprintln!("/tmp/plxnative-* (outside plxnative-check.*) after: {tmp_after:?}"); + eprintln!("runtime root {}: {runtime_before} entries before, after: {runtime_after:?}", runtime.display()); + assert!( + runtime_after.iter().any(|n| n == "plxnative-events.log"), + "the boot's event log is not in the runtime root {}: {runtime_after:?}", + runtime.display() + ); +} diff --git a/rust-modules/ui/src/consts.rs b/rust-modules/ui/src/consts.rs index 69a25e4a3d..131c865486 100644 --- a/rust-modules/ui/src/consts.rs +++ b/rust-modules/ui/src/consts.rs @@ -491,6 +491,21 @@ pub fn is_remote_bound(sym: c_uint, wcode: c_uint) -> bool { action_of(sym, wcode).is_some() } +/// The raw `(sym, wcode)` pair a key arrived as. Kept beside the [`Action`] because three things +/// still read it: a press with no action (an unsupported key flows on as exactly the pair it was), +/// the lab trigger key (named by `lab.json`, not by an action), and the recorder's tape, whose +/// format IS the pair. A platform with no SDL pair sends none, and the loop builds [`raw_pair`] +/// for its action. +/// +/// It lives here, beside [`raw_pair`] and [`action_of`] whose pair it names, so a platform crate +/// reaches it without the application's private events module (`docs/platform-ports.md`, Target +/// shape 8: `host::EventSink::key` takes one). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RawKey { + pub sym: c_uint, + pub wcode: c_uint, +} + /// **A key press by what it MEANS, with no SDL in it** — the vocabulary a platform that has no SDL /// key pair hands the loop (`HostEvent::Key`'s `action`), and the one the screens move onto when /// they stop reading `(sym, wcode)` themselves. From 5ef30644fed8d8cc246a99e1ce542629737559f7 Mon Sep 17 00:00:00 2001 From: Tiago Pereira <1698241+tiper@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:20:04 +0000 Subject: [PATCH 24/26] Platform axis test expects FinNative's debug app id --- ci/test_platform_axis.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ci/test_platform_axis.py b/ci/test_platform_axis.py index cba11976a9..92f35638f8 100644 --- a/ci/test_platform_axis.py +++ b/ci/test_platform_axis.py @@ -144,7 +144,7 @@ def test_the_existing_queries_do_not_move(self): with self.subTest(platform=platform): proc = make("print-flavor", "print-appid", "print-appport", f"PLATFORM={platform}") self.assertEqual(proc.returncode, 0, proc.stderr) - self.assertEqual(proc.stdout.split(), ["debug", "com.beb.plxnative.debug", "8911"]) + self.assertEqual(proc.stdout.split(), ["debug", "io.github.tiper.finnative.debug", "8911"]) class ScratchTree(unittest.TestCase): From fc89f2ed34f1c330b1344ae433101aa3c3c1ac04 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 06:29:10 +0000 Subject: [PATCH 25/26] Search edit-key test types into the keyboard the arrival raised --- rust-modules/src/app/search_owned_tests.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/rust-modules/src/app/search_owned_tests.rs b/rust-modules/src/app/search_owned_tests.rs index 37ed412ed9..0f60ec3055 100644 --- a/rust-modules/src/app/search_owned_tests.rs +++ b/rust-modules/src/app/search_owned_tests.rs @@ -544,9 +544,8 @@ fn native_key_effect_search_edit_keys_edit_the_field() { frame(&mut d, &mut rig, AppArg::Search, tick(0), vec![]); let text = |s: &str, at| InputEvent { at, source: Source::Script, kind: InputKind::Text(plx_machine::machine::TextEdit::Commit(s.into())) }; - let mut events = script_key(Key::Ok, tick(1)); - events.push(text("abcd", tick(1))); - frame(&mut d, &mut rig, AppArg::Search, tick(1), events); + // The arrival raised the keyboard, so the text types straight into the field. + frame(&mut d, &mut rig, AppArg::Search, tick(1), vec![text("abcd", tick(1))]); assert_eq!(rig.stores.search.query(), "abcd", "premise: the field is editing and holds the text"); for (n, (sym, wcode, action, query)) in [ (8, 42, Action::Backspace, "abc"), From 331b328d772b300d76c0e235c582c4cae8fa1020 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 06:34:01 +0000 Subject: [PATCH 26/26] Host interface test expects the FinNative window title --- rust-modules/tests/host_interface.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust-modules/tests/host_interface.rs b/rust-modules/tests/host_interface.rs index b751cc7985..ffb59e05ef 100644 --- a/rust-modules/tests/host_interface.rs +++ b/rust-modules/tests/host_interface.rs @@ -288,7 +288,7 @@ fn run_boots_the_fake_platform_through_init_then_open_and_returns_the_refusal() assert_eq!(exit, Exit { code: REFUSAL, release: Release::Retained }, "the fake's refusal is the entry's Exit"); assert_eq!(*SHELL.log.lock().unwrap(), ["init", "open"], "init, then open, and nothing after the refusal"); let (title, placement, high_dpi) = SHELL.asked.lock().unwrap().clone().expect("open was asked for a window"); - assert_eq!(title, "PlxNative", "the title a hostsim build asks for"); + assert_eq!(title, "FinNative", "the title a hostsim build asks for"); assert_eq!(placement, Placement::Desktop, "a hostsim build asks for the desktop placement"); eprintln!("open was asked for: title {title:?}, {placement:?}, high_dpi {high_dpi}"); assert!(