diff --git a/ci/list-caps.ini b/ci/list-caps.ini index 008ada04a..1972afd6c 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 aca301317..8f13c51fc 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 b7388c7af..76d42bd71 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 89809248e..c38126a01 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 e08e35cfa..80a25c53e 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 90a8530e6..3aaa5ce67 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 5af3dd503..1dd299ca3 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 e6966f1e4..78370d23e 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 6c7465585..c0d8025e3 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 590b72411..ca2795272 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 8f521ff47..20b4f58ff 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 8fe4c7380..fe4d10434 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); + } +}