From cb160bf66563eb0a9b0ce3230fb533e161084f21 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 14:04:03 -0300 Subject: [PATCH 01/72] docs(plans): access control PR 4c part 2, plan 1 (follow-ups and keyboard) Co-Authored-By: Claude Opus 5.5 --- ...2026-12-01-access-control-pr4c-keyboard.md | 138 ++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md diff --git a/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md b/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md new file mode 100644 index 000000000..220dece2e --- /dev/null +++ b/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md @@ -0,0 +1,138 @@ +# Access control PR 4c part 2, plan 1: follow-ups and keyboard delivery under denial + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Close the 4c part 1 leftovers, then make a Receive denial take part in the keyboard routing decisions (focused walk, XI2-over-core shadowing, grabbed natural walk, grab-window delivery, raw key legs) as the approved spec section says. + +**Architecture:** A routing decision asks Receive once per recipient and form at the window it is deciding about, and the write uses the recipients that decision allowed, through the existing unchecked writer. With no policy installed `check_receive` returns `Allow` without calling anything, so every decision takes today's inputs and the bytes stay identical. + +**Tech Stack:** Rust, yserver-core (`core_loop/key_fanout.rs`, `core_loop/fanout.rs`), the access layer from PR 4a (`ServerState::check_receive`, `EventSubject`, `EventBatch`, `EventDescription`). + +**Spec:** `docs/superpowers/specs/2026-10-30-access-control-layer-design.md`, section "Input delivery under denial" (lines 353–527), approved by the user on 2026-11-25 and merged in #389. + +**Series context:** 4c part 2 is three plans in one PR: this plan (keyboard), plan 2 (pointer, including the XI1 router `xi1_route_device_event`, which keys share), plan 3 (replay, thaw, freeze). The XI1 key leg (`deliver_xi1_focused_key`) is NOT converted here; plan 2 converts the shared router. + +## Global Constraints + +- With no policy, and with an allow-all policy, every scenario's bytes on every client and the grab/freeze/focus state equal today's (spec l.357–359). +- A denied copy is a non-delivery: it does not stop a walk, shadow another form, qualify an owner, or reject a grab (spec l.370–373). +- A selection that stops a walk or shadows another form without producing bytes (synthetic-repeat release suppression: XI2 release, or core release for a detectable-repeat client) still does so, and Receive is NOT asked for it (spec l.374–380). +- One Receive result per recipient per form per delivery attempt; the write reuses it. A grab-window fallback is a distinct attempt with a fresh check (spec l.381–385). +- Subject is `EventSubject::Window()` for cooked keys; `EventSubject::Window(ROOT_WINDOW)` for raw root copies; `EventSubject::Window()` for the raw grab-window fallback (spec l.455–461). +- Descriptions: core key = `EventDescription::core(2)` / `core(3)` (KeyPress/KeyRelease); XI2 = `crate::xinput::xi2_event_description(evtype)`. +- Keep every encoder, the write order (core before XI2 at a window, slave form before master), and the per-client detectable-repeat eligibility. +- No new `YSERVER_*` environment variables. Reuse first: new code only where a decision needs a Receive result it cannot get today. +- Tests drive production entries (`key_event_fanout_to_state`, requests through `NotifyFixture::request`), not private helpers; each test names the mutation it kills. Cite Xorg at tag `xorg-server-21.1.24` as `dix/events.c:`, never local paths. +- Commits signed (`-S`), trailers `Co-Authored-By: Claude Opus 5.5 ` and `Implemented-By: Claude Haiku 5.5`. No session URL. +- Gate per task: `cargo fmt --all`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo build --bin yserver`, `cargo test -p yserver-core --lib -- ` and the whole `cargo test -p yserver-core --lib`. + +## Review Focus + +1. A client that selects both XI2 (master and slave forms) and core at one window: its XI2 forms share subject and description, so they get ONE check; allowed → both XI2 copies written and core shadowed with no core check recorded; denied → no XI2 copy and core reopened and checked. +2. A synthetic-repeat release where the only selector at the pointer window is XI2: the walk still stops there, nothing is written, no Receive call is recorded. +3. `owner_events` grab whose owner selected at a lower window and a foreign client at the same window is denied: the owner still gets it at that window; the foreign denial must not turn into a rejection. +4. A Receive check must never run for a client the code then does not write to for another reason (dead client, suppressed form): the trace would show a phantom check. +5. Passive key grab activation with the owner denied: the grab still activates, a sync grab still freezes with the stored event, and focus selectors get nothing. + +--- + +### Task 1: 4c part 1 follow-ups + +**Files:** +- Modify: `docs/status.md` (new entry for 4c part 1, #389, merged as 3e09d8a9) +- Modify: `crates/yserver-core/src/core_loop/fanout.rs:434`, `:479–539` +- Modify: `crates/yserver-core/src/core_loop/process_request/tests/{access_crossing_notify.rs, access_xi_notify.rs, access_notify_support.rs, xi2.rs}` + +- [ ] **Step 1: status.md.** One entry in the existing style: PR #389, the three areas (XI device notifications; crossings, focus, barriers, root/COW ConfigureNotify; native XKB), the subject rules (device subject for once-per-client XI notifications, XKB subject device 1), and "pointer, keyboard and replay delivery follow in the next PR". No task or plan references. +- [ ] **Step 2: F1.** `emit_xi2_focus_event_to_state` builds `EventDescription::extension(35, xi2_major_opcode, evtype)` inline (`fanout.rs:434`). Give `xi2_event_description` an opcode-taking sibling or parameter so both call sites share one constructor; the existing XI2 focus rows must still pass. +- [ ] **Step 3: delete `emit_xi2_device_changed_slave_pointer`** (`fanout.rs:479`) and `build_slave_pointer_class_block` (`:540`) if nothing else uses it. No production caller; it writes a little-endian class block to big-endian clients. Delete its tests in `xi2.rs` (`:2987–3130`) and the row at `access_xi_notify.rs:1145`. `cargo build --bin yserver` and the XI suites must stay green. +- [ ] **Step 4: test minors** (each only if still present after the #389 compaction; if gone, say so in the report): + - `access_crossing_notify.rs`: the `pointer_root` assertion message that credits MotionNotify with moving it: it only stays. + - C5 keyboard re-grab stream literal built twice: build it once. + - m1: C4 with `xi = true` asserts XI2 frames exist (extend `core_details` to XI2 frames). + - m2: the re-grab test makes ALLOWED select XI2 focus on both windows, and asserts no Receive call names ALLOWED. + - m3: in the R2+R3+R4 row, ALLOWED also selects the COW and its parent, and its R3/R4 copies are asserted. + - m5: add `dec16`/`dec32` beside `enc16`/`enc32` in `access_notify_support.rs` and use them for the duplicated readers (`read_u16`, `read_u32`, the inline decode in `xi2_describe`, the hard-coded `u16::from_be_bytes([frame[8], frame[9]])`). + - X5b: drop the tautological `no_policy.1.is_empty()` assertion. + - m4 (macro shapes) stays as is: readability only, and joske's XKB file has no macros. +- [ ] **Step 5: gate and commit.** Commits: `docs(status): access control PR 4c part 1`, `refactor(xi): one XI2 event description constructor`, `refactor(xi): drop the test-only slave DeviceChanged emitter`, `test(access): 4c part 1 review minors`. + +### Task 2: Receive-aware focused key delivery + +**Files:** +- Modify: `crates/yserver-core/src/core_loop/fanout.rs` (one helper) +- Modify: `crates/yserver-core/src/core_loop/key_fanout.rs` (`deliver_key_to_window` :709, `focused_walk_target` :1500, `key_selectors` :1543, callers :560, :651, :690) +- Create: `crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs` (+ `mod` line in `tests/mod.rs`) + +**Interfaces:** +- Produces: `pub(crate) fn receive_allows(state: &ServerState, client: ClientId, subject: EventSubject, events: &EventBatch<'_>) -> bool` in `fanout.rs` (`!matches!(check_receive(.., state.receive_request), Deny)`; `true` without asking when no policy is installed). Plan 2 uses it. +- Produces: `struct KeyCopies { core: Vec, xi2: Vec<(u16 /*device*/, u16 /*source*/, Vec)>, stops: bool }` and `fn key_copies_at(state, event, window, include_master_form, include_core_form, synthetic_repeat) -> KeyCopies` in `key_fanout.rs`: the per-window plan, checked once. +- Produces: `fn write_key_copies(state, event, window, copies: &KeyCopies, synthetic_repeat) -> Vec`: the existing writes, unchecked, on the allowed lists. +- Produces (test support): an input scenario harness in `access_key_input.rs`: build windows and selections through requests, set focus and pointer position, install a policy that denies a set of `(client, subject, EventDescription)`, drive `key_event_fanout_to_state`, return per-client `(description, event window)` frames and the Receive trace. Every scenario also runs with no policy and allow-all and asserts identical bytes. Plan 2 moves it to a shared `access_input_support.rs` if it needs it. + +Rules `key_copies_at` implements: +- Per client at `window`, its XI2 forms (filtered by `include_master_form`) produce copies unless suppressed (synthetic release). The forms share subject and description, so the client's XI2 copies get one check, reused for every form written to it. A client with allowed XI2 copies, or a suppressed XI2 selection, shadows core. +- The core copy (if `include_core_form`, the client selected core, it is not shadowed, and the detectable-repeat rule does not suppress it) is checked. +- `stops` is true if any client that selected the event at `window` in any form (today's `key_selectors` set, all forms, whatever the include flags) either has an allowed copy or produces no copy. False only when every client there produced a copy and every copy was denied. +- With no policy, `core`/`xi2` lists equal today's `core_targets`/`targets` and `stops == !key_selectors(..).is_empty()`. + +`focused_walk_target` returns `(ResourceId, KeyCopies)`: the first window in today's bounded chain whose copies `stops`, with those copies; otherwise the focus and its copies (no separate direct attempt, spec l.409–413). `deliver_key_to_window` becomes `key_copies_at` + `write_key_copies`; callers that pass a target directly (replay at :690, slave path at :560) call it the same way. + +- [ ] **Step 1: failing tests** in `access_key_input.rs`, each a scenario row (no policy == allow-all bytes asserted for every row): + - `k1_denied_pointer_window_selector_advances_the_focus_walk`: focus F, pointer in child C ⊂ F; A selects KeyPress on C, B on F; deny A at C → B gets the press at F, A nothing; trace = [A@C core, B@F core]. Kills: `stops` ignoring denial. + - `k2_one_allowed_selector_stops_the_walk`: A and B on C, D on F; deny A → B at C, D nothing. Kills: `stops` requiring all allowed. + - `k3_denied_xi2_copy_reopens_core_for_that_client`: A selects XI2 KeyPress (master) and core on C; deny A's XI2 → A gets core at C; deny both → walk continues to F. Kills: shadow computed from selection. + - `k4_xi2_forms_share_one_check`: A selects master and slave XI2 and core on C (slave keyboard origin, master transition accepted). Allowed → A gets both XI2 copies, no core copy, trace has exactly one call for A (XI2@C). XI2 denied → A gets only core at C, trace = [A XI2@C, A core@C]. Kills: one check per form; core check while shadowed. Review focus 1. + - `k5_suppressed_repeat_release_stops_without_a_check`: synthetic repeat release; A selects only XI2 KeyRelease on C, B core on F → nothing written, trace has no call for A, B nothing. Second row: A core on C with detectable repeat → same. Kills: asking Receive for a no-copy selection; treating no-copy as non-stop. + - `k6_all_denied_lands_on_focus`: every selector on the chain denied → the focus attempt writes only its allowed clients; no write elsewhere. +- [ ] **Step 2:** run `cargo test -p yserver-core --lib access_key_input`. Expected: k1, k2, k3, k6 FAIL (denied clients still stop and shadow); k4 and k5 may pass only on their allow paths. +- [ ] **Step 3: implement** `receive_allows`, `KeyCopies`, `key_copies_at`, `write_key_copies`, and the `focused_walk_target` change. The focus/slave/replay callers write the copies their target decision computed (no second check). +- [ ] **Step 4:** run the filter and the whole `--lib` suite. Expected: PASS; existing `key_fanout` tests unchanged. +- [ ] **Step 5: commit** `feat(access): Receive decides the focused key walk and form shadowing`. + +### Task 3: grabbed key delivery + +**Files:** +- Modify: `crates/yserver-core/src/core_loop/key_fanout.rs` (`deliver_key_to_grab_owner` :831, `key_grabbed_natural_target` :1570, `deliver_routed_key_with_master_status` :523–642) +- Test: `access_key_input.rs` + +**Interfaces:** +- Consumes: `receive_allows`, harness (Task 2). +- Produces: `key_grabbed_natural_target(state, event, owner, via_xi2, synthetic_repeat) -> Option` with the rules below; `deliver_key_to_grab_owner` checks the owner's one grab-protocol copy at its window and writes only if allowed (a denial counts as delivered: no fallback, no other recipient). + +Rules (spec l.414–429): +- At each window of today's walk, with `S` = today's selectors there: + - the owner qualifies if it is in `S` and its grab-protocol copy at that window is allowed or suppressed (core grab + detectable repeat release, or XI2 grab + synthetic release); + - a foreign client rejects if any form it selected there produces an allowed copy or produces no copy; + - owner qualifies → natural delivery at that window (the check result is reused for the write); else any foreign rejects → `None` (grab-window fallback); else continue to the next ancestor up to today's stop. +- The fallback and the `owner_events == false` / activating write are a fresh check at the grab window. +- Activation, freeze storage (`xi1_frozen`, `FrozenWithEvent`) and the XI1 leg are untouched. + +- [ ] **Step 1: failing tests:** + - `k7_denied_owner_copy_continues_the_natural_walk`: owner_events grab by O; O selects on C and P; deny O at C → O gets it at P. Kills: owner qualifying by selection. + - `k8_denied_owner_with_allowed_foreign_falls_back`: O on C denied, foreign F allowed on C → O gets it at the grab window (fresh check, trace shows O@C then O@grab window). + - `k9_denied_foreign_selector_does_not_reject`: F alone on C, denied; O on P allowed → O at P. Review focus 3 variant: O and F both on C, F denied, O allowed → O at C. + - `k10_suppressed_foreign_selector_still_rejects`: synthetic release, F selects XI2 KeyRelease on C (no copy), O on P → fallback to grab window; no Receive call for F. + - `k11_denied_grab_window_copy_is_delivered`: `owner_events` false, O denied at grab window → no bytes anywhere, focus selectors get nothing, grab still active. + - `k12_denied_activating_press_still_activates_and_freezes`: sync passive GrabKey, O denied → no bytes; `active_keyboard_grab` set; `xi1_frozen[device].stored` holds the press and the state is `FrozenWithEvent`. Review focus 5. +- [ ] **Step 2:** run; Expected: k7–k11 FAIL; k12 fails on the byte assertion only. +- [ ] **Step 3: implement.** +- [ ] **Step 4:** run filter + whole `--lib`; Expected PASS; existing grab tests (`sync_passive_key_grab_delivers_to_owner_and_freezes`, XTS-derived ones) unchanged. +- [ ] **Step 5: commit** `feat(access): Receive decides grabbed key delivery`. + +### Task 4: raw key legs + +**Files:** +- Modify: `crates/yserver-core/src/core_loop/key_fanout.rs` (`raw_key_event_to_state` :1062, `deliver_raw_key_master` :1120, `send_raw_key` :1199) +- Test: `access_key_input.rs` + +Rules (spec l.455–461): every root copy (slave and master root fanouts) is checked with subject `Window(ROOT_WINDOW)` and a denial drops only that copy; recipients, filters and order stay. Master XI2 grab leg: if today's `natural` holds, check the owner's root copy (subject root); allowed → send. Otherwise (not natural, or denied) and the grab mask has the raw bit → check with subject `Window(g.grab_window)`; allowed → send. At most one copy. The root fanout after it is unchanged, including the "owner skipped when the grab window is the root" filter. + +- [ ] **Step 1: failing tests:** + - `k13_denied_raw_root_copy_drops_only_that_copy`: A and B select RawKeyPress on root (master); deny A → B only; slave-form selector C unaffected. + - `k14_denied_raw_owner_root_copy_falls_back_to_the_grab_window`: XI2 grab, owner_events, focus PointerRoot, owner selected raw on root and grab mask has RawKeyPress; deny owner@root → owner gets one copy, trace = [O@root, O@grab window]. Without the raw bit in the grab mask → nothing. + - `k15_raw_owner_gets_at_most_one_copy`: allowed natural → one copy, no grab-window check. +- [ ] **Step 2:** run; Expected: k13, k14 FAIL. +- [ ] **Step 3: implement.** +- [ ] **Step 4:** run filter + whole `--lib` + the raw-key tests in `key_fanout.rs` (`raw_key_*`); Expected PASS. +- [ ] **Step 5: commit** `feat(access): Receive checks raw key copies and the grab leg`. From 4a23b092b1ce714423c176a136099200fbd644cb Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 14:09:54 -0300 Subject: [PATCH 02/72] docs(plans): 4c part 2 plan 1, review round 1 Co-Authored-By: Claude Opus 5.5 --- ...2026-12-01-access-control-pr4c-keyboard.md | 31 ++++++++++++------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md b/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md index 220dece2e..00e442763 100644 --- a/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md +++ b/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md @@ -24,7 +24,8 @@ - No new `YSERVER_*` environment variables. Reuse first: new code only where a decision needs a Receive result it cannot get today. - Tests drive production entries (`key_event_fanout_to_state`, requests through `NotifyFixture::request`), not private helpers; each test names the mutation it kills. Cite Xorg at tag `xorg-server-21.1.24` as `dix/events.c:`, never local paths. - Commits signed (`-S`), trailers `Co-Authored-By: Claude Opus 5.5 ` and `Implemented-By: Claude Haiku 5.5`. No session URL. -- Gate per task: `cargo fmt --all`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo build --bin yserver`, `cargo test -p yserver-core --lib -- ` and the whole `cargo test -p yserver-core --lib`. +- Gate per task: `cargo fmt --all`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo build --bin yserver` (alone, not with test features), `cargo test -p yserver-core --lib -- ` and the whole `cargo test -p yserver-core --lib`. Task 1 and Task 4 also run `cargo test --workspace --features xdmcp` (Task 1 deletes a pub fn). The CI `--ignored` lavapipe suite and loaded runs are the PR gate at the end of plan 3. +- Replay (`replay_frozen_key_to_focus_after_transition`) is converted here through `deliver_key_to_window`; plan 3 adds replay tests and does not convert it again. ## Review Focus @@ -68,15 +69,16 @@ - Produces: `pub(crate) fn receive_allows(state: &ServerState, client: ClientId, subject: EventSubject, events: &EventBatch<'_>) -> bool` in `fanout.rs` (`!matches!(check_receive(.., state.receive_request), Deny)`; `true` without asking when no policy is installed). Plan 2 uses it. - Produces: `struct KeyCopies { core: Vec, xi2: Vec<(u16 /*device*/, u16 /*source*/, Vec)>, stops: bool }` and `fn key_copies_at(state, event, window, include_master_form, include_core_form, synthetic_repeat) -> KeyCopies` in `key_fanout.rs`: the per-window plan, checked once. - Produces: `fn write_key_copies(state, event, window, copies: &KeyCopies, synthetic_repeat) -> Vec`: the existing writes, unchecked, on the allowed lists. -- Produces (test support): an input scenario harness in `access_key_input.rs`: build windows and selections through requests, set focus and pointer position, install a policy that denies a set of `(client, subject, EventDescription)`, drive `key_event_fanout_to_state`, return per-client `(description, event window)` frames and the Receive trace. Every scenario also runs with no policy and allow-all and asserts identical bytes. Plan 2 moves it to a shared `access_input_support.rs` if it needs it. +- Produces (test support): an input scenario harness in `access_key_input.rs`: build windows and selections through requests, set focus and pointer position, install a policy that denies a set of `(client, subject, EventDescription)`, drive `key_event_fanout_to_state`, return per-client `(description, event window)` frames and the Receive trace. Reuse the `NotifyFixture` helpers (`request`, `install_policy`, `receive_trace`, `split_frames`, `dec16`/`dec32`). Compare traces per client (`by_client`, as `Order::PerClient`), since `state.clients` is a HashMap. Keep only key and raw-key descriptions in the trace: drop the slave-switch DeviceChanged, XKB StateNotify and focus calls the same dispatch makes. Synthetic-repeat rows drive `key_event_fanout_after_transition(.., synthetic_repeat = true)`; a slave origin is `InputOrigin::XTest(5)`. Every scenario also runs with no policy and allow-all and asserts identical bytes. Plan 2 moves it to a shared `access_input_support.rs` if it needs it. Rules `key_copies_at` implements: - Per client at `window`, its XI2 forms (filtered by `include_master_form`) produce copies unless suppressed (synthetic release). The forms share subject and description, so the client's XI2 copies get one check, reused for every form written to it. A client with allowed XI2 copies, or a suppressed XI2 selection, shadows core. - The core copy (if `include_core_form`, the client selected core, it is not shadowed, and the detectable-repeat rule does not suppress it) is checked. -- `stops` is true if any client that selected the event at `window` in any form (today's `key_selectors` set, all forms, whatever the include flags) either has an allowed copy or produces no copy. False only when every client there produced a copy and every copy was denied. +- `stops` is per selection, not per client. Every selection at `window` counted by today's `key_selectors` (core mask, any XI2 form, whatever the include flags) stops the walk if it produces no copy or its copy is allowed. A selection produces no copy when an include flag excludes its form, when the synthetic-release rule suppresses it, or when an allowed or suppressed XI2 selection shadows it. `stops` is false only when every selection there produced a copy and every copy was denied. +- Put the per-selection predicate in one function that Task 3 reuses. Check a client's core copy only when it is not shadowed. A denied XI2 copy reopens core, and core is then checked. - With no policy, `core`/`xi2` lists equal today's `core_targets`/`targets` and `stops == !key_selectors(..).is_empty()`. -`focused_walk_target` returns `(ResourceId, KeyCopies)`: the first window in today's bounded chain whose copies `stops`, with those copies; otherwise the focus and its copies (no separate direct attempt, spec l.409–413). `deliver_key_to_window` becomes `key_copies_at` + `write_key_copies`; callers that pass a target directly (replay at :690, slave path at :560) call it the same way. +`focused_walk_target` takes the include flags and `synthetic_repeat` from its caller and returns `(ResourceId, KeyCopies)`: the first window in today's bounded chain whose copies `stops`, with those copies; otherwise the focus and its copies (no separate direct attempt, spec l.409–413). `deliver_key_to_window` becomes `key_copies_at` + `write_key_copies`; callers that pass a target directly (replay at :690, slave path at :560) call it the same way. - [ ] **Step 1: failing tests** in `access_key_input.rs`, each a scenario row (no policy == allow-all bytes asserted for every row): - `k1_denied_pointer_window_selector_advances_the_focus_walk`: focus F, pointer in child C ⊂ F; A selects KeyPress on C, B on F; deny A at C → B gets the press at F, A nothing; trace = [A@C core, B@F core]. Kills: `stops` ignoring denial. @@ -84,7 +86,9 @@ Rules `key_copies_at` implements: - `k3_denied_xi2_copy_reopens_core_for_that_client`: A selects XI2 KeyPress (master) and core on C; deny A's XI2 → A gets core at C; deny both → walk continues to F. Kills: shadow computed from selection. - `k4_xi2_forms_share_one_check`: A selects master and slave XI2 and core on C (slave keyboard origin, master transition accepted). Allowed → A gets both XI2 copies, no core copy, trace has exactly one call for A (XI2@C). XI2 denied → A gets only core at C, trace = [A XI2@C, A core@C]. Kills: one check per form; core check while shadowed. Review focus 1. - `k5_suppressed_repeat_release_stops_without_a_check`: synthetic repeat release; A selects only XI2 KeyRelease on C, B core on F → nothing written, trace has no call for A, B nothing. Second row: A core on C with detectable repeat → same. Kills: asking Receive for a no-copy selection; treating no-copy as non-stop. - - `k6_all_denied_lands_on_focus`: every selector on the chain denied → the focus attempt writes only its allowed clients; no write elsewhere. + - `k5b_form_excluded_by_the_include_flags_still_stops`: the slave path with the master transition rejected (`key_fanout.rs:556–562`). A selects core and master XI2 on C, with XI2 denied. B selects slave XI2 on F. The walk stops at C and writes nothing there, and B gets nothing. Kills: a per-client `stops`. + - `k5c_slave_paths`: the same slave origin goes through an exact slave XI2 grab (`:540–555`), and then through the slave focus path. Both reach their recipient with allow-all, and a denial drops the copy. + - `k6_all_denied_lands_on_focus`: A selects on C, and A and B select on F (the focus). A is denied everywhere. The walk passes C and lands on F, which still stops because B is allowed there. B gets the press at F. Second row: only A selects (on C and F), and A is denied. The attempt lands on the focus, nothing is written, and the trace shows A@C and A@F. - [ ] **Step 2:** run `cargo test -p yserver-core --lib access_key_input`. Expected: k1, k2, k3, k6 FAIL (denied clients still stop and shadow); k4 and k5 may pass only on their allow paths. - [ ] **Step 3: implement** `receive_allows`, `KeyCopies`, `key_copies_at`, `write_key_copies`, and the `focused_walk_target` change. The focus/slave/replay callers write the copies their target decision computed (no second check). - [ ] **Step 4:** run the filter and the whole `--lib` suite. Expected: PASS; existing `key_fanout` tests unchanged. @@ -98,18 +102,18 @@ Rules `key_copies_at` implements: **Interfaces:** - Consumes: `receive_allows`, harness (Task 2). -- Produces: `key_grabbed_natural_target(state, event, owner, via_xi2, synthetic_repeat) -> Option` with the rules below; `deliver_key_to_grab_owner` checks the owner's one grab-protocol copy at its window and writes only if allowed (a denial counts as delivered: no fallback, no other recipient). +- Produces: `key_grabbed_natural_target(state, event, owner, via_xi2, synthetic_repeat) -> Option`, following the rules below. A returned window means the owner's copy there is already allowed (or suppressed). The natural write uses the unchecked writer, with no second check. The grab-window write (owner_events false, activating, or fallback) goes through the existing `fanout_event_to_clients_with_receive`. That is a fresh check, and a denial counts as delivered: no other recipient. The trace for a natural delivery has exactly one owner call. Rules (spec l.414–429): - At each window of today's walk, with `S` = today's selectors there: - the owner qualifies if it is in `S` and its grab-protocol copy at that window is allowed or suppressed (core grab + detectable repeat release, or XI2 grab + synthetic release); - - a foreign client rejects if any form it selected there produces an allowed copy or produces no copy; + - check foreign clients only when the owner does not qualify, so that no phantom check is recorded. A foreign client rejects if any selection it has there stops under Task 2's predicate (allowed copy, or no copy); - owner qualifies → natural delivery at that window (the check result is reused for the write); else any foreign rejects → `None` (grab-window fallback); else continue to the next ancestor up to today's stop. - The fallback and the `owner_events == false` / activating write are a fresh check at the grab window. - Activation, freeze storage (`xi1_frozen`, `FrozenWithEvent`) and the XI1 leg are untouched. - [ ] **Step 1: failing tests:** - - `k7_denied_owner_copy_continues_the_natural_walk`: owner_events grab by O; O selects on C and P; deny O at C → O gets it at P. Kills: owner qualifying by selection. + - `k7_denied_owner_copy_continues_the_natural_walk`: owner_events grab by O; O selects on C and P; deny O at C → O gets it at P; trace for O exactly [O@C, O@P]. Kills: owner qualifying by selection; a second check on the natural write. - `k8_denied_owner_with_allowed_foreign_falls_back`: O on C denied, foreign F allowed on C → O gets it at the grab window (fresh check, trace shows O@C then O@grab window). - `k9_denied_foreign_selector_does_not_reject`: F alone on C, denied; O on P allowed → O at P. Review focus 3 variant: O and F both on C, F denied, O allowed → O at C. - `k10_suppressed_foreign_selector_still_rejects`: synthetic release, F selects XI2 KeyRelease on C (no copy), O on P → fallback to grab window; no Receive call for F. @@ -126,12 +130,17 @@ Rules (spec l.414–429): - Modify: `crates/yserver-core/src/core_loop/key_fanout.rs` (`raw_key_event_to_state` :1062, `deliver_raw_key_master` :1120, `send_raw_key` :1199) - Test: `access_key_input.rs` -Rules (spec l.455–461): every root copy (slave and master root fanouts) is checked with subject `Window(ROOT_WINDOW)` and a denial drops only that copy; recipients, filters and order stay. Master XI2 grab leg: if today's `natural` holds, check the owner's root copy (subject root); allowed → send. Otherwise (not natural, or denied) and the grab mask has the raw bit → check with subject `Window(g.grab_window)`; allowed → send. At most one copy. The root fanout after it is unchanged, including the "owner skipped when the grab window is the root" filter. +Rules (spec l.455–461): every root copy (slave and master root fanouts) is checked with subject `Window(ROOT_WINDOW)` and a denial drops only that copy; recipients, filters and order stay. Master XI2 grab leg: if today's `natural` holds, check the owner's root copy (subject root); allowed → send. Otherwise (not natural, or denied) and the grab mask has the raw bit → check with subject `Window(g.grab_window)`; allowed → send. At most one copy. The root fanout after it is unchanged, including the "owner skipped when the grab window is the root" filter. That fanout is a separate attempt with its own check, so with a non-root grab window the owner can still get its root-fanout copy as today (`raw_key_under_xi2_grab_matches_xorg`, G3/O1 = 2 copies). Root copies reuse `fanout_event_to_clients_with_receive`. - [ ] **Step 1: failing tests:** - `k13_denied_raw_root_copy_drops_only_that_copy`: A and B select RawKeyPress on root (master); deny A → B only; slave-form selector C unaffected. - - `k14_denied_raw_owner_root_copy_falls_back_to_the_grab_window`: XI2 grab, owner_events, focus PointerRoot, owner selected raw on root and grab mask has RawKeyPress; deny owner@root → owner gets one copy, trace = [O@root, O@grab window]. Without the raw bit in the grab mask → nothing. - - `k15_raw_owner_gets_at_most_one_copy`: allowed natural → one copy, no grab-window check. + - `k14_denied_raw_owner_root_copy_falls_back_to_the_grab_window`: XI2 grab on a child G (not root), owner_events, focus PointerRoot. The owner selected raw on root, and the grab mask has RawKeyPress. Deny the owner with subject root: + - The owner gets one copy, from the grab leg at G. Its root-fanout copy is denied too, since it has the same inputs. + - The owner's trace is [O@root, O@G, O@root]. + - Allow-all gives 2 copies, as today. + - Without the raw bit in the grab mask, the owner gets nothing and the trace is [O@root, O@root]. + - Kills: a missing fallback, and a fallback with the root subject. + - `k15_allowed_natural_raw_leg_skips_the_grab_window_check`: same setup, allowed. The trace has no O@G call. Kills: always checking the grab window. - [ ] **Step 2:** run; Expected: k13, k14 FAIL. - [ ] **Step 3: implement.** - [ ] **Step 4:** run filter + whole `--lib` + the raw-key tests in `key_fanout.rs` (`raw_key_*`); Expected PASS. From 9a76534a48eca7d79e9a74785698613d1c4b3f2d Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 14:11:10 -0300 Subject: [PATCH 03/72] docs(plans): 4c part 2 plan 1, review round 2 Co-Authored-By: Claude Opus 5.5 --- .../plans/2026-12-01-access-control-pr4c-keyboard.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md b/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md index 00e442763..d6fe50201 100644 --- a/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md +++ b/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md @@ -86,10 +86,10 @@ Rules `key_copies_at` implements: - `k3_denied_xi2_copy_reopens_core_for_that_client`: A selects XI2 KeyPress (master) and core on C; deny A's XI2 → A gets core at C; deny both → walk continues to F. Kills: shadow computed from selection. - `k4_xi2_forms_share_one_check`: A selects master and slave XI2 and core on C (slave keyboard origin, master transition accepted). Allowed → A gets both XI2 copies, no core copy, trace has exactly one call for A (XI2@C). XI2 denied → A gets only core at C, trace = [A XI2@C, A core@C]. Kills: one check per form; core check while shadowed. Review focus 1. - `k5_suppressed_repeat_release_stops_without_a_check`: synthetic repeat release; A selects only XI2 KeyRelease on C, B core on F → nothing written, trace has no call for A, B nothing. Second row: A core on C with detectable repeat → same. Kills: asking Receive for a no-copy selection; treating no-copy as non-stop. - - `k5b_form_excluded_by_the_include_flags_still_stops`: the slave path with the master transition rejected (`key_fanout.rs:556–562`). A selects core and master XI2 on C, with XI2 denied. B selects slave XI2 on F. The walk stops at C and writes nothing there, and B gets nothing. Kills: a per-client `stops`. - - `k5c_slave_paths`: the same slave origin goes through an exact slave XI2 grab (`:540–555`), and then through the slave focus path. Both reach their recipient with allow-all, and a denial drops the copy. + - `k5b_form_excluded_by_the_include_flags_still_stops`: the slave path with the master transition rejected (`key_fanout.rs:556–562`), driven by `key_event_fanout_after_transition(.., master_transition_accepted = false, ..)` with `InputOrigin::XTest(5)`. A selects slave XI2 KeyPress (denied) and core on C; core is excluded on this path, so it produces no copy. B selects slave XI2 on F. Expected: the walk stops at C, nothing is written, and B gets nothing. Kills: a per-client `stops` (under that mutation, B gets the press at F). + - `k5c_slave_paths`: the same slave origin goes through an exact slave XI2 grab (`:540–555`), and then through the slave focus path. Both reach their recipient with allow-all, and a denial drops the copy. Kills: the slave grab write left unchecked, and the slave focus path skipping `key_copies_at`. - `k6_all_denied_lands_on_focus`: A selects on C, and A and B select on F (the focus). A is denied everywhere. The walk passes C and lands on F, which still stops because B is allowed there. B gets the press at F. Second row: only A selects (on C and F), and A is denied. The attempt lands on the focus, nothing is written, and the trace shows A@C and A@F. -- [ ] **Step 2:** run `cargo test -p yserver-core --lib access_key_input`. Expected: k1, k2, k3, k6 FAIL (denied clients still stop and shadow); k4 and k5 may pass only on their allow paths. +- [ ] **Step 2:** run `cargo test -p yserver-core --lib access_key_input`. Expected: k1, k2, k3, k5b, k5c and k6 FAIL (denied clients still stop, shadow and receive). k4 and k5 may pass only on their allow paths. - [ ] **Step 3: implement** `receive_allows`, `KeyCopies`, `key_copies_at`, `write_key_copies`, and the `focused_walk_target` change. The focus/slave/replay callers write the copies their target decision computed (no second check). - [ ] **Step 4:** run the filter and the whole `--lib` suite. Expected: PASS; existing `key_fanout` tests unchanged. - [ ] **Step 5: commit** `feat(access): Receive decides the focused key walk and form shadowing`. @@ -108,15 +108,15 @@ Rules (spec l.414–429): - At each window of today's walk, with `S` = today's selectors there: - the owner qualifies if it is in `S` and its grab-protocol copy at that window is allowed or suppressed (core grab + detectable repeat release, or XI2 grab + synthetic release); - check foreign clients only when the owner does not qualify, so that no phantom check is recorded. A foreign client rejects if any selection it has there stops under Task 2's predicate (allowed copy, or no copy); - - owner qualifies → natural delivery at that window (the check result is reused for the write); else any foreign rejects → `None` (grab-window fallback); else continue to the next ancestor up to today's stop. + - owner qualifies → natural delivery at that window (the check result is reused for the write); else any foreign rejects → `None` (grab-window fallback); else continue to the next ancestor up to today's stop. Foreign selections are evaluated with both include flags true and the event's `synthetic_repeat`. The unchecked natural write keeps the suppression rules in `deliver_key_to_grab_owner` (synthetic XI2 release, detectable-repeat core release). - The fallback and the `owner_events == false` / activating write are a fresh check at the grab window. - Activation, freeze storage (`xi1_frozen`, `FrozenWithEvent`) and the XI1 leg are untouched. - [ ] **Step 1: failing tests:** - `k7_denied_owner_copy_continues_the_natural_walk`: owner_events grab by O; O selects on C and P; deny O at C → O gets it at P; trace for O exactly [O@C, O@P]. Kills: owner qualifying by selection; a second check on the natural write. - `k8_denied_owner_with_allowed_foreign_falls_back`: O on C denied, foreign F allowed on C → O gets it at the grab window (fresh check, trace shows O@C then O@grab window). - - `k9_denied_foreign_selector_does_not_reject`: F alone on C, denied; O on P allowed → O at P. Review focus 3 variant: O and F both on C, F denied, O allowed → O at C. - - `k10_suppressed_foreign_selector_still_rejects`: synthetic release, F selects XI2 KeyRelease on C (no copy), O on P → fallback to grab window; no Receive call for F. + - `k9_denied_foreign_selector_does_not_reject`: F alone on C, denied; O on P allowed → O at P. Review focus 3 variant: O and F both on C, F denied, O allowed → O at C, and the trace has no call for F (the owner qualified first). + - `k10_suppressed_foreign_selector_still_rejects`: a core grab whose owner O has no detectable repeat. O selects on P, the grab window is G ≠ P, and F selects XI2 KeyRelease on C. A synthetic release (F's XI2 copy is suppressed) → O gets the release with event window G, and there is no Receive call for F. Kills: the no-copy rule ignored for foreign selectors (under that mutation, O gets it at P). - `k11_denied_grab_window_copy_is_delivered`: `owner_events` false, O denied at grab window → no bytes anywhere, focus selectors get nothing, grab still active. - `k12_denied_activating_press_still_activates_and_freezes`: sync passive GrabKey, O denied → no bytes; `active_keyboard_grab` set; `xi1_frozen[device].stored` holds the press and the state is `FrozenWithEvent`. Review focus 5. - [ ] **Step 2:** run; Expected: k7–k11 FAIL; k12 fails on the byte assertion only. From 2ad6d227d3249b0984615b55a913df73a0948c12 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 14:11:43 -0300 Subject: [PATCH 04/72] docs(plans): 4c part 2 plan 1, review round 3 minors Co-Authored-By: Claude Opus 5.5 --- .../plans/2026-12-01-access-control-pr4c-keyboard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md b/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md index d6fe50201..50b7fe8eb 100644 --- a/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md +++ b/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md @@ -116,10 +116,10 @@ Rules (spec l.414–429): - `k7_denied_owner_copy_continues_the_natural_walk`: owner_events grab by O; O selects on C and P; deny O at C → O gets it at P; trace for O exactly [O@C, O@P]. Kills: owner qualifying by selection; a second check on the natural write. - `k8_denied_owner_with_allowed_foreign_falls_back`: O on C denied, foreign F allowed on C → O gets it at the grab window (fresh check, trace shows O@C then O@grab window). - `k9_denied_foreign_selector_does_not_reject`: F alone on C, denied; O on P allowed → O at P. Review focus 3 variant: O and F both on C, F denied, O allowed → O at C, and the trace has no call for F (the owner qualified first). - - `k10_suppressed_foreign_selector_still_rejects`: a core grab whose owner O has no detectable repeat. O selects on P, the grab window is G ≠ P, and F selects XI2 KeyRelease on C. A synthetic release (F's XI2 copy is suppressed) → O gets the release with event window G, and there is no Receive call for F. Kills: the no-copy rule ignored for foreign selectors (under that mutation, O gets it at P). + - `k10_suppressed_foreign_selector_still_rejects` (today's behaviour kept): an explicit core `GrabKeyboard` with `owner_events = true` on grab window G. O has no detectable repeat. C lies inside P, on the walk to the focus. O selects on P, the grab window is G ≠ P, and F selects XI2 KeyRelease on C. A synthetic release (F's XI2 copy is suppressed) → O gets the release with event window G, and there is no Receive call for F. Kills: the no-copy rule ignored for foreign selectors (under that mutation, O gets it at P). - `k11_denied_grab_window_copy_is_delivered`: `owner_events` false, O denied at grab window → no bytes anywhere, focus selectors get nothing, grab still active. - `k12_denied_activating_press_still_activates_and_freezes`: sync passive GrabKey, O denied → no bytes; `active_keyboard_grab` set; `xi1_frozen[device].stored` holds the press and the state is `FrozenWithEvent`. Review focus 5. -- [ ] **Step 2:** run; Expected: k7–k11 FAIL; k12 fails on the byte assertion only. +- [ ] **Step 2:** run; Expected: k7, k8, k9 and k11 FAIL; k12 fails on the byte assertion only. k10 passes today: it guards today's behaviour against the change. - [ ] **Step 3: implement.** - [ ] **Step 4:** run filter + whole `--lib`; Expected PASS; existing grab tests (`sync_passive_key_grab_delivers_to_owner_and_freezes`, XTS-derived ones) unchanged. - [ ] **Step 5: commit** `feat(access): Receive decides grabbed key delivery`. From 882b592f40166c8b8f3d390b5b4280746e3450be Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 14:34:27 -0300 Subject: [PATCH 05/72] docs(status): access control PR 4c part 1 Records PR #389 (merged as 3e09d8a9): XI device notifications, crossings, focus, barriers and root/COW ConfigureNotify, and native XKB Receive checks. Pointer, keyboard and replay delivery follow in the next PR. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Haiku 5.5 --- docs/status.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/status.md b/docs/status.md index ee96d7246..1f7c21822 100644 --- a/docs/status.md +++ b/docs/status.md @@ -39,6 +39,7 @@ lives in [`code-quality-audit-2026-07-26.md`](code-quality-audit-2026-07-26.md). a server reset restores the startup value. This is a client scaling hint, not a change to physical dimensions or rendering. +- **2026-12-01 Access control layer, PR 4c part 1: Receive checks on input notifications (#389, merged as 3e09d8a9):** three areas. XI device notifications: XI1 and XI2 device notifications check each recipient before encoding, and a notification that is once per client uses the device as its subject. Crossings, focus, barriers and root/COW ConfigureNotify: the crossing, focus and barrier sites and the root and composite-overlay ConfigureNotify copies check their selectors, and a denied copy is a non-delivery that leaves the walk, the grab and the pointer state as allow-all left them. Native XKB: XKB notifications check their recipients with the XKB event as the description and device 1 as the subject. With no policy installed, bytes and state are unchanged. Pointer, keyboard and replay delivery follow in the next PR. - **2026-11-24 PR #379 review round 2 (`feat/passive-grab-activation`):** rebased on master; the maintainer's second-round items. (1) A slave Motion's `child` is taken toward its pre-move target in the event-window shortcut too. (2) XI1 classes 0-6 and 8 replace the device's selection as Xorg's `CreateMaskFromList` does; classes 0-6 keep private aggregate bits 19-25. (3) DeviceOwnerGrabButton (8) shares DeviceButtonGrab's bit: exclusive per window and device, owner priority. (4) DeviceButtonGrab on a buttonless device is accepted again. (5) Core AllowEvents, XIAllowEvents and paired modes share one `AllowSome` routine (Xorg 21.1.24 `dix/events.c:1825-1926`): admission is `(thisGrabbed && frozen) || thisSynced`, the time bound comes only from the requester's own grabs, Sync from a synced-only client is a no-op, paired modes act on masters only and need `othersFrozen`, Replay on a `FrozenNoEvent` slave is a no-op. A hardware run (marco click-to-focus) found a stuck master button after `ReplayPointer` when only the master was frozen (from the per-device freeze): the replay set the already-released slave bit again, so the queued master release was refused; the replay now takes the master-only transition (Xvfb-measured regression). XTest's axis-slot guard is restored and the branch's Xorg citations are pinned to 21.1.24. Sequences measured on Xvfb 21.1.24 are request-driven regressions. Gate: workspace `xdmcp` 5223/0, lavapipe `--ignored` 778/0, `just man`, rule F 5/5. Follow-ups: XI2 recipient order and implicit owner among equal selections (Xorg: selection order, once per matching InputClients entry; yserver: hash order), slave-keyboard/XI1 grabs carry no grab time (no lower bound), XI1 AllowDeviceEvents AsyncAll over several slave grabs, XI2 slave motion coordinates, projection cost of `refresh_xi_client_selection_projection`. - **2026-11-23 PR #379 review fixes (`feat/passive-grab-activation`):** the maintainer's five before-merge items. (1) AllowEvents(ReplayPointer/ReplayKeyboard) replays only for the client whose grab froze the device in `FrozenWithEvent`, checked before any state change (Xorg `AllowSome`); a synced-only client no longer panics the server, and a sync passive key grab now enters `FrozenWithEvent` as the pointer path does. (2) A slave Motion's `child` comes from the pre-move target it was routed from. (3) XTest DeviceValuator chunks are validated in `ProcXTestFakeInput`'s order (type, contiguity, 1..6, axis sum, detail); eight error rows match Xvfb. (4) A press the master already holds activates no master-pass grab (`UpdateDeviceState`). (5) The XI1 implicit grab owner follows Xorg's window InputClients list, now modelled explicitly per window (newest first, duplicate nodes, sticky XI1 aggregate, dont-propagate masks, server-owned node), created and freed at Xorg's request paths; DeviceButtonGrab is accepted and exclusive per window and device. 33 sequences measured on Xvfb 21.1.24 (raw client) are request-driven regressions. Oracles P1-P5, PR1-PR2, C1-C20, X1-X3 unchanged or matching Xvfb. Gate: workspace `xdmcp` 5194/0, lavapipe `--ignored` 774/0, `pointer_fanout` 5 runs under load. Follow-ups (user scope ruling): other XI1 classes creating positions, ClassFromMask aliases in GetSelectedExtensionEvents, device fields above 255, RetainPermanent/RetainTemporary close-down, duplicate nodes on XI2 and DeviceStateNotify paths, resource-hash freeing order; plus the maintainer's listed follow-ups (`host_x11` `as i16` wrap, `master_sprite_root` on macOS/Windows, UngrabButton vs AnyButton, XIPassiveGrabDevice conflicts) and post-move XI2 slave coordinates. - **2026-11-23 Shaped siblings in shared redirect backings (Tasks 1–3, `fix/shaped-sibling-clip`):** G1 subtracts each mapped higher sibling's bounding shape clipped to its border-inclusive outer rect, while unshaped siblings keep the full rect; G2 clips pixmap-background realization through the same `ClipByChildren` shape, sibling, and mapped-child regions as solid backgrounds while preserving tile phase and 32-bit rectangles. Lavapipe regressions cover T1/T2/T6 (shape, empty-shape, unshaped, border, and move-carry cases), T3/T4/T7/T8 (shape, child, leaf, and large-coordinate clears), and end-to-end T5. T5 passes before and after remap; reverting Task 1 alone fails the client-draw hole assertion at `(10,52)`, and reverting Task 2 alone fails the post-remap hole assertion there. Gate: workspace `xdmcp` 5,089 passed / 0 failed; lavapipe ignored suite 782 passed / 0 failed; fmt, all-target Clippy with `-D warnings`, `tools/check-layout.sh` and `just man` pass; the `paint_target` lavapipe tests passed five runs under 16 busy loops. Measured against Xvfb 21.1.24: a pixmap-background parent grown over a mapped child now leaves the child alone (Xvfb `0000ff`; before: `ff0000`). From 3221d494064a922f2d114185ca3af47c71395823 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 14:34:27 -0300 Subject: [PATCH 06/72] refactor(xi): one XI2 event description constructor xi2_event_description_with_opcode takes the runtime XI major opcode; xi2_event_description delegates to it with the build-time constant. The XI2 focus emitter uses the opcode-taking form, so both call sites share one constructor. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Haiku 5.5 --- crates/yserver-core/src/core_loop/fanout.rs | 5 ++++- crates/yserver-core/src/xinput/mod.rs | 8 +++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/yserver-core/src/core_loop/fanout.rs b/crates/yserver-core/src/core_loop/fanout.rs index 5b219ca5a..ca59020b1 100644 --- a/crates/yserver-core/src/core_loop/fanout.rs +++ b/crates/yserver-core/src/core_loop/fanout.rs @@ -431,7 +431,10 @@ pub fn emit_xi2_focus_event_to_state( let (origin_x, origin_y) = state.resources.window_absolute_position(window); let event_x = i16::try_from(i32::from(root_x).saturating_sub(origin_x)).unwrap_or(i16::MAX); let event_y = i16::try_from(i32::from(root_y).saturating_sub(origin_y)).unwrap_or(i16::MAX); - let events = [EventDescription::extension(35, xi2_major_opcode, evtype)]; + let events = [crate::xinput::xi2_event_description_with_opcode( + xi2_major_opcode, + evtype, + )]; let batch = EventBatch::new(&events); fanout_event_to_clients_with_receive( state, diff --git a/crates/yserver-core/src/xinput/mod.rs b/crates/yserver-core/src/xinput/mod.rs index cb3e85f8d..2dff982b1 100644 --- a/crates/yserver-core/src/xinput/mod.rs +++ b/crates/yserver-core/src/xinput/mod.rs @@ -65,7 +65,13 @@ pub(crate) fn xi1_event_description(offset: u8) -> EventDescription { /// Describe one XI2 GenericEvent for access-policy Receive checks. pub(crate) fn xi2_event_description(evtype: u16) -> EventDescription { - EventDescription::extension(35, XI2_MAJOR_OPCODE, evtype) + xi2_event_description_with_opcode(XI2_MAJOR_OPCODE, evtype) +} + +/// `xi2_event_description` for a caller that carries the XI extension's +/// runtime major opcode instead of the build-time constant. +pub(crate) fn xi2_event_description_with_opcode(major_opcode: u8, evtype: u16) -> EventDescription { + EventDescription::extension(35, major_opcode, evtype) } /// XI2 `XI_HierarchyChanged` event number (XI2.h:99). From 4520e4155435717b865c1da2d892b0be2d8bf585 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 14:34:33 -0300 Subject: [PATCH 07/72] refactor(xi): drop the test-only slave DeviceChanged emitter emit_xi2_device_changed_slave_pointer has no production caller, and its class block writes little-endian bytes to big-endian clients. Remove it with build_slave_pointer_class_block and the class builders only it used, along with its tests in xi2.rs and the access_xi_notify row. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Haiku 5.5 --- crates/yserver-core/src/core_loop/fanout.rs | 95 ----------- .../process_request/tests/access_xi_notify.rs | 80 +--------- .../core_loop/process_request/tests/xi2.rs | 149 ------------------ crates/yserver-core/src/xinput/query.rs | 13 -- 4 files changed, 2 insertions(+), 335 deletions(-) diff --git a/crates/yserver-core/src/core_loop/fanout.rs b/crates/yserver-core/src/core_loop/fanout.rs index ca59020b1..78f85cbbb 100644 --- a/crates/yserver-core/src/core_loop/fanout.rs +++ b/crates/yserver-core/src/core_loop/fanout.rs @@ -29,7 +29,6 @@ use crate::{ host_x11::{HostExposeEvent, HostXidMap}, resources::{MapState, ROOT_WINDOW}, server::ServerState, - xinput::XI2_DEVICE_CHANGED_MASK, }; /// Wire-frame classes emitted to clients while loop telemetry is enabled. @@ -462,100 +461,6 @@ pub fn emit_xi2_focus_event_to_state( ) } -/// `XIDeviceChange` reason (XI2.h:108) — the device's own classes/name -/// changed (as opposed to `XISlaveSwitch`, which reports a master's -/// active slave swap). -const XI_REASON_DEVICE_CHANGE: u8 = 2; - -/// Emit an XI2 `XI_DeviceChanged` for the bootstrapped virtual XTEST -/// pointer to clients that selected that device or `XIAllDevices`. -/// Physical registry facets are never represented by device 4 here. -/// The carried class set keeps the query-compatible button + 4 valuator -/// + 2 scroll shape. -/// -/// `XIAllMasterDevices` does not select this slave event. If no client -/// selected, this is a no-op. Returns clients whose outbound -/// buffer overflowed (for `ClientDisconnected` reporting). -/// -/// `xi2_major_opcode` is the XI extension's runtime-assigned major -/// opcode (137 in the current build). -pub fn emit_xi2_device_changed_slave_pointer( - state: &mut ServerState, - xi2_major_opcode: u8, -) -> Vec { - const XTEST_POINTER: u16 = crate::xinput::DEVICEID_XTEST_POINTER; - - // Clients select on (window, deviceid). DeviceChanged is a - // hierarchy-wide event clients select on the ROOT window (the same - // window `process_request`'s XISelectEvents bootstrap requires before - // it sends the initial DeviceChanged). Match the root window only — - // matching any window would spuriously deliver to a client that - // selected DeviceChanged on some unrelated child. The XTEST device - // matches its exact selector and XIAllDevices(0); it is not a master, - // so XIAllMasterDevices(1) does not match. - let targets: Vec = state - .clients - .iter() - .filter_map(|(id, client)| { - let selected = client.xi2_masks.iter().any(|(&(window, dev), &mask)| { - window == ROOT_WINDOW - && matches!(dev, XTEST_POINTER | 0) - && (mask & u64::from(XI2_DEVICE_CHANGED_MASK)) != 0 - }); - selected.then_some(ClientId(*id)) - }) - .collect(); - if targets.is_empty() { - return Vec::new(); - } - - let (classes, num_classes) = build_slave_pointer_class_block(state); - let time = state.timestamp_now(); - let event_description = crate::xinput::xi2_event_description(1); - let events = EventBatch::new(std::slice::from_ref(&event_description)); - fanout_event_to_clients_with_receive( - state, - &targets, - EventSubject::Window(ROOT_WINDOW), - &events, - |buf, seq, order| { - x11::encode_xi2_device_changed_event( - buf, - order, - seq, - xi2_major_opcode, - XTEST_POINTER, - time, - num_classes, - XTEST_POINTER, // sourceid = the XTEST device itself - XI_REASON_DEVICE_CHANGE, - &classes, - ); - }, - ) -} - -/// Build the XI2 device-class block for the virtual XTEST pointer. -/// -/// The query encoder owns the shared button/valuator/scroll class layout; -/// both XIQueryDevice and DeviceChanged use it so their class blocks remain -/// byte-identical for little-endian clients. -pub(crate) fn build_slave_pointer_class_block(state: &mut ServerState) -> (Vec, u16) { - build_pointer_class_block_for_device(state, crate::xinput::DEVICEID_XTEST_POINTER) -} - -pub(crate) fn build_pointer_class_block_for_device( - state: &mut ServerState, - device_id: u16, -) -> (Vec, u16) { - let class_data = pointer_class_data_for_device(state, device_id); - crate::xinput::query::build_pointer_classes( - ClientByteOrder::LittleEndian, - device_id, - class_data, - ) -} - pub(crate) fn pointer_class_data_for_device( state: &mut ServerState, device_id: u16, diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_xi_notify.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_xi_notify.rs index 70c6560a2..db49887f9 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_xi_notify.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_xi_notify.rs @@ -1,10 +1,9 @@ //! Receive checks on XI and XI2 notifications (sites X1–X10 of the PR 4c XI plan). //! //! Each row drives one site through its production entry under the shared -//! runner (`access_notify_support::check_row`). Focused tests cover the four +//! runner (`access_notify_support::check_row`). Focused tests cover the three //! places a caller has its own logic: the per-window loops of X1–X3 (one -//! client, two windows), the X4 bootstrap, the no-policy mapping orders, and -//! the XTEST DeviceChanged emitter, which has no production caller. +//! client, two windows), the X4 bootstrap, and the no-policy mapping orders. //! //! Frames are pinned at the offsets the site chooses (device, subject-facing //! fields, request, keycode, property atom), in the recipient's byte order. @@ -1112,78 +1111,3 @@ fn receive_xi_mapping_no_policy_order_matches_control() { } } } - -/// XTEST DeviceChanged (`emit_xi2_device_changed_slave_pointer`) has no production -/// caller, so this test calls it directly; the named exception to the entries rule. -#[test] -fn receive_xtest_device_changed_checks_root_selectors() { - let mut fixture = NotifyFixture::new(); - fixture.state.randr.screen_width = 800; - fixture.state.randr.screen_height = 600; - fixture.state.start_instant = std::time::Instant::now() + Duration::from_secs(30); - denied_big_endian(&mut fixture); - select_device_changed(&mut fixture, DENIED, DENIED_SEQ, ROOT_WINDOW, XTEST_POINTER); - select_device_changed( - &mut fixture, - ALLOWED, - ALLOWED_SEQ, - ROOT_WINDOW, - XTEST_POINTER, - ); - for client in [SENDER, DENIED, ALLOWED] { - fixture.drain(client); - } - let calls = fixture.install_policy(|_, call| { - if call.hook == ExtensionHook::Receive && call.client == DENIED { - DENY - } else { - Decision::Allow - } - }); - let before = xi_effects(&fixture); - assert!( - crate::core_loop::fanout::emit_xi2_device_changed_slave_pointer(&mut fixture.state, 137) - .is_empty(), - "policy denial is not a transport disconnect" - ); - assert_eq!( - xi_effects(&fixture), - before, - "denial leaves the device state unchanged" - ); - assert!( - crate::core_loop::client_io::failed_writers(&fixture.state.clients).is_empty(), - "denial does not fail a writer" - ); - let root = |client| ExpectedReceive { - client, - request: None, - subject: EventSubject::Window(ROOT_WINDOW), - events: vec![device_changed_event()], - }; - assert_eq!( - multiset(&receive_trace( - "XTEST DeviceChanged", - "policy", - &calls.lock().unwrap() - )), - multiset(&[root(DENIED), root(ALLOWED)]), - "the root selector of each receiver is checked" - ); - assert!( - fixture.drain(DENIED).is_empty(), - "denied receiver gets nothing" - ); - let allowed = fixture.drain(ALLOWED); - let frames = split_frames(&allowed, ClientByteOrder::LittleEndian); - assert_eq!(frames.len(), 1, "the other receiver gets its frame"); - assert_eq!( - read_u16(&frames[0][2..4], ClientByteOrder::LittleEndian), - ALLOWED_SEQ - ); - assert_eq!(frames[0][0], 35); - assert_eq!( - read_u16(&frames[0][8..10], ClientByteOrder::LittleEndian), - 1 - ); -} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/xi2.rs b/crates/yserver-core/src/core_loop/process_request/tests/xi2.rs index 594ada7f1..67ffe0197 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/xi2.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/xi2.rs @@ -2979,155 +2979,6 @@ fn a_fresh_master_keeps_core_pointer_classes_of_its_own_and_is_sent_no_bootstrap ); } -#[test] -fn legacy_device_changed_fanout_emits_for_selected_xtest_pointer() { - // Kills routing XTEST 4 through the generic physical pointer encoder; - // Xorg `CorePointerProc` defines 10 buttons and two relative axes. - use crate::{ - core_loop::fanout::emit_xi2_device_changed_slave_pointer, xinput::DEVICEID_XTEST_POINTER, - }; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let xtest_pointer = state - .xi_devices - .device(DEVICEID_XTEST_POINTER) - .expect("XTEST pointer"); - assert_eq!( - xtest_pointer.name, - crate::xinput::registry::NAME_XTEST_POINTER - ); - assert!( - xtest_pointer - .properties - .contains_key(&state.xtest_device_atom) - ); - let before = xi_query_side_effect_snapshot(&state, 1); - // Install the real XISelectEvents mask through the core dispatcher. - let mut select_body = Vec::new(); - select_body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - select_body.extend_from_slice(&1u16.to_le_bytes()); // num_masks - select_body.extend_from_slice(&0u16.to_le_bytes()); // pad - select_body.extend_from_slice(&DEVICEID_XTEST_POINTER.to_le_bytes()); - select_body.extend_from_slice(&1u16.to_le_bytes()); // mask_len - select_body.extend_from_slice(&XI2_DEVICE_CHANGED_MASK.to_le_bytes()); - assert!(dispatch_xi_request_wire(&mut state, &mut peer, 1, 46, &select_body).is_empty()); - assert!( - state.clients[&1] - .xi2_masks - .contains_key(&(ROOT_WINDOW, DEVICEID_XTEST_POINTER)) - ); - - // This helper emits only the bootstrapped XTEST pointer event; the - // physical source registry owns all dynamically allocated facets. - let dropped = emit_xi2_device_changed_slave_pointer(&mut state, 137); - assert!(dropped.is_empty()); - let wire = read_all_available(&mut peer); - let off = (0..wire.len().saturating_sub(32)) - .find(|&i| wire[i] == 35 && u16::from_le_bytes([wire[i + 8], wire[i + 9]]) == 1) - .expect("legacy XI_DeviceChanged fanout"); - assert_eq!(wire[off + 10], 4, "deviceid = XTEST pointer"); - assert_eq!(wire[off + 18], 4, "sourceid = the XTEST pointer itself"); - assert_eq!(wire[off + 20], 2, "reason = XIDeviceChange"); - assert_eq!(wire[off + 16], 3, "Button + two Valuator classes"); - - // A second helper call exercises the same selected-device fanout. - let dropped = emit_xi2_device_changed_slave_pointer(&mut state, 137); - assert!(dropped.is_empty()); - let wire = read_all_available(&mut peer); - let off = (0..wire.len().saturating_sub(32)) - .find(|&i| wire[i] == 35 && u16::from_le_bytes([wire[i + 8], wire[i + 9]]) == 1) - .expect("second legacy XI_DeviceChanged fanout"); - assert_eq!(wire[off + 10], 4, "deviceid = XTEST pointer"); - - // Clear the selection through XISelectEvents and confirm no request - // or event state remains after this scenario. - let mut unselect_body = Vec::new(); - unselect_body.extend_from_slice(&ROOT_WINDOW.0.to_le_bytes()); - unselect_body.extend_from_slice(&1u16.to_le_bytes()); // num_masks - unselect_body.extend_from_slice(&0u16.to_le_bytes()); // pad - unselect_body.extend_from_slice(&DEVICEID_XTEST_POINTER.to_le_bytes()); - unselect_body.extend_from_slice(&0u16.to_le_bytes()); // mask_len = remove - assert!(dispatch_xi_request_wire(&mut state, &mut peer, 4, 46, &unselect_body).is_empty()); - assert!( - !state.clients[&1] - .xi2_masks - .contains_key(&(ROOT_WINDOW, DEVICEID_XTEST_POINTER)) - ); - assert_eq!(xi_query_side_effect_snapshot(&state, 1), before); -} - -#[test] -fn xtest_device_changed_is_not_selected_by_all_master_devices() { - use crate::core_loop::fanout::emit_xi2_device_changed_slave_pointer; - - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - state - .clients - .get_mut(&1) - .unwrap() - .xi2_masks - .insert((ROOT_WINDOW, 1), u64::from(XI2_DEVICE_CHANGED_MASK)); - - let dropped = emit_xi2_device_changed_slave_pointer(&mut state, 137); - assert!(dropped.is_empty()); - assert!( - read_all_available(&mut peer).is_empty(), - "XIAllMasterDevices must not receive DeviceChanged for XTEST slave 4", - ); - assert_eq!( - state - .xi_devices - .device(crate::xinput::DEVICEID_XTEST_POINTER) - .map(|d| d.id), - Some(crate::xinput::DEVICEID_XTEST_POINTER), - "only the static XTEST pointer is involved", - ); - assert_eq!( - state.xi_devices.source_ids().len(), - 0, - "the event must not pretend a physical source is device 4", - ); -} - -#[test] -fn device_changed_is_noop_when_no_client_selected() { - use crate::core_loop::fanout::emit_xi2_device_changed_slave_pointer; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - // No xi2_masks selection → no event. - let dropped = emit_xi2_device_changed_slave_pointer(&mut state, 137); - assert!(dropped.is_empty()); - assert!( - read_all_available(&mut peer).is_empty(), - "no DeviceChanged when nothing selected" - ); -} - -#[test] -fn device_changed_not_sent_for_selection_on_non_root_window() { - // DeviceChanged is a root-window hierarchy event. A client that - // selected it on some unrelated (non-root) window must NOT get it - // — otherwise the fanout spuriously delivers to the wrong window. - use crate::{ - core_loop::fanout::emit_xi2_device_changed_slave_pointer, xinput::DEVICEID_XTEST_POINTER, - }; - let mut state = ServerState::new(); - let mut peer = install_client(&mut state, 1); - let non_root = ResourceId(0x4000_0001); - state.clients.get_mut(&1).unwrap().xi2_masks.insert( - (non_root, DEVICEID_XTEST_POINTER), - u64::from(XI2_DEVICE_CHANGED_MASK), - ); - let dropped = emit_xi2_device_changed_slave_pointer(&mut state, 137); - assert!(dropped.is_empty()); - assert!( - read_all_available(&mut peer).is_empty(), - "selection on a non-root window must not receive DeviceChanged" - ); -} - #[test] fn xi_list_properties_wire() { let mut state = ServerState::new(); diff --git a/crates/yserver-core/src/xinput/query.rs b/crates/yserver-core/src/xinput/query.rs index 15b8929c4..9bced7e92 100644 --- a/crates/yserver-core/src/xinput/query.rs +++ b/crates/yserver-core/src/xinput/query.rs @@ -159,19 +159,6 @@ fn write_device_info( Ok(()) } -pub(crate) fn build_pointer_classes( - byte_order: ClientByteOrder, - source_id: u16, - data: XiQueryClassData, -) -> (Vec, u16) { - let shape = if source_id == super::DEVICEID_XTEST_POINTER { - XiClassShape::CorePointer - } else { - XiClassShape::PhysicalPointer - }; - build_pointer_classes_for_shape(byte_order, source_id, data, shape, false) -} - /// `report_button_state` follows Xorg's caller split: XIQueryDevice's /// `ListDeviceClasses` passes `rc == Success` to `ListButtonInfo` /// (`Xi/xiquerydevice.c:577-584`), while DeviceChanged zeroes its button mask From 05fa519c1481a9de049be04b1108325c8f6abf41 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 14:34:33 -0300 Subject: [PATCH 08/72] test(access): 4c part 1 review minors Test-only follow-ups from the #389 review. The C4 grab chains check the XI2 frames with the same detail and mode triples as core. The re-grab test gives ALLOWED XI2 focus on both windows and checks that no Receive call names it. The R2+R3+R4 resize row gives ALLOWED the overlay and the root substructure selections and checks its copies. dec16 and dec32 sit beside enc16 and enc32 and replace the duplicated readers. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Haiku 5.5 --- .../tests/access_crossing_notify.rs | 129 ++++++++++-------- .../tests/access_notify_support.rs | 18 +++ .../process_request/tests/access_xi_notify.rs | 22 +-- 3 files changed, 94 insertions(+), 75 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_crossing_notify.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_crossing_notify.rs index 9948a7a7b..4b0790662 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_crossing_notify.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_crossing_notify.rs @@ -13,7 +13,8 @@ use super::{ access_notify_support::{ DENY, ExpectedReceive, FieldPins, NOTIFY_RECEIVER_ALLOWED as ALLOWED, NOTIFY_RECEIVER_DENIED as DENIED, NOTIFY_SENDER as SENDER, NotifyFixture, Order, Row, - by_client, check_row, enc16, enc32, receive_trace, request_opcodes, split_frames, + by_client, check_row, dec16, dec32, enc16, enc32, receive_trace, request_opcodes, + split_frames, }, extensions::{ExtensionHook, RecordedExtensionCheck}, *, @@ -497,13 +498,7 @@ fn xi2_describe( order: ClientByteOrder, frame: &[u8], ) -> Option { - (frame[0] == 35 && frame[1] == XI_MAJOR).then(|| { - let bytes: [u8; 2] = frame[8..10].try_into().expect("evtype bytes"); - xi2_event(match order { - ClientByteOrder::LittleEndian => u16::from_le_bytes(bytes), - ClientByteOrder::BigEndian => u16::from_be_bytes(bytes), - }) - }) + (frame[0] == 35 && frame[1] == XI_MAJOR).then(|| xi2_event(dec16(&frame[8..10], order))) } /// XI1 events (the XI1 event range); the focus rows select no DeviceStateNotify. @@ -713,8 +708,8 @@ const R1_MONITOR_ROOT: Row = row!( /// RRSetScreenSize. The root gets the StructureNotify copy (R2, to both root selectors /// because DENIED selects both root bits) and the parent SubstructureNotify copy (R4, for -/// the overlay's parent); the overlay gets its StructureNotify copy (R3). DENIED receives -/// three copies, in that emitter order; ALLOWED receives R2. +/// the overlay's parent); the overlay gets its StructureNotify copy (R3). DENIED and ALLOWED +/// each receive the three copies in that emitter order. fn resize_setup(f: &mut NotifyFixture) { set_byte_orders(f); f.state @@ -722,7 +717,10 @@ fn resize_setup(f: &mut NotifyFixture) { .materialize_cow_resource(WindowHandle::from_raw_for_test(COMPOSITE_OVERLAY_WINDOW.0)); rx!(f, ALLOWED) .event_masks - .insert(ROOT_WINDOW, STRUCTURE_NOTIFY); + .insert(ROOT_WINDOW, STRUCTURE_NOTIFY | SUBSTRUCTURE_NOTIFY); + rx!(f, ALLOWED) + .event_masks + .insert(COMPOSITE_OVERLAY_WINDOW, STRUCTURE_NOTIFY); rx!(f, DENIED) .event_masks .insert(ROOT_WINDOW, STRUCTURE_NOTIFY | SUBSTRUCTURE_NOTIFY); @@ -777,6 +775,8 @@ const R234_SCREEN_RESIZE: Row = row!( call(DENIED, request, COMPOSITE_OVERLAY_WINDOW, root), call(DENIED, request, ROOT_WINDOW, root), call(ALLOWED, request, ROOT_WINDOW, root), + call(ALLOWED, request, COMPOSITE_OVERLAY_WINDOW, root), + call(ALLOWED, request, ROOT_WINDOW, root), ] }, configure_describe, @@ -1052,23 +1052,25 @@ fn receive_crossing_sites() { /// event's (offset 24), in the receiver's byte order. fn frame_window(frame: &[u8], order: ClientByteOrder) -> u32 { let at = if frame[0] == 35 { 24 } else { 12 }; - read_u32(&frame[at..at + 4], order) -} - -fn read_u32(bytes: &[u8], order: ClientByteOrder) -> u32 { - let bytes: [u8; 4] = bytes.try_into().expect("u32 bytes"); - match order { - ClientByteOrder::LittleEndian => u32::from_le_bytes(bytes), - ClientByteOrder::BigEndian => u32::from_be_bytes(bytes), - } + dec32(&frame[at..at + 4], order) } -/// (type, window, detail, mode) of every core crossing frame of `bytes`. +/// (evtype, window, detail, mode) of every crossing frame of `bytes`: core Enter/Leave +/// (7/8) and XI2 Enter/Leave (GenericEvent 35 with evtype 7/8). fn core_details(bytes: &[u8], order: ClientByteOrder) -> Vec<(u8, u32, u8, u8)> { split_frames(bytes, order) .into_iter() - .filter(|frame| matches!(frame[0], 7 | 8)) - .map(|frame| (frame[0], frame_window(frame, order), frame[1], frame[30])) + .filter_map(|frame| match frame[0] { + 7 | 8 => Some((frame[0], frame_window(frame, order), frame[1], frame[30])), + // XI2: evtype at 8, mode at 18, detail at 19. + 35 if matches!(dec16(&frame[8..10], order), 7 | 8) => Some(( + dec16(&frame[8..10], order) as u8, + frame_window(frame, order), + frame[19], + frame[18], + )), + _ => None, + }) .collect() } @@ -1210,19 +1212,18 @@ fn receive_pointer_grab_chains_drop_only_the_denied_link() { ); assert!(denied_f.state.active_pointer_grab.is_none()); - if !xi2 { - // Core details: Leave of the child (detail 0), Enter of the parent (detail 2). - assert_eq!( - core_details(&allow_grab[0], order), - vec![(8, CROSS_CHILD.0, 0, 1), (7, CROSS_PARENT.0, 2, 1)], - "core grab frames: window, detail and mode" - ); - assert_eq!( - core_details(&allow_ungrab[0], order), - vec![(8, CROSS_PARENT.0, 2, 2), (7, CROSS_CHILD.0, 0, 2)], - "core ungrab frames: window, detail and mode" - ); - } + // Details: Leave of the child (detail 0), Enter of the parent (detail 2). XI2 + // frames carry the same triple, so the XI2 run must yield its frames too. + assert_eq!( + core_details(&allow_grab[0], order), + vec![(8, CROSS_CHILD.0, 0, 1), (7, CROSS_PARENT.0, 2, 1)], + "xi2={xi2}: grab frames: window, detail and mode" + ); + assert_eq!( + core_details(&allow_ungrab[0], order), + vec![(8, CROSS_PARENT.0, 2, 2), (7, CROSS_CHILD.0, 0, 2)], + "xi2={xi2}: ungrab frames: window, detail and mode" + ); } } @@ -1556,6 +1557,13 @@ fn receive_xi1_focus_and_state_batches_independent() { fn receive_xi_keyboard_regrab_orders_focus_out_before_in() { let mut f = new_fixture(); grab_setup(&mut f); + // ALLOWED selects XI2 focus on both windows, so a Receive check for it would show here. + let keyboard_focus = (1 << XI_FOCUS_IN) | (1 << XI_FOCUS_OUT); + for window in [CROSS_CHILD, CROSS_PARENT] { + rx!(f, ALLOWED) + .xi2_masks + .insert((window, MASTER_KEYBOARD), keyboard_focus); + } drain_all(&mut f); let calls = allow_all(&mut f); let mask = xi_grab_event_mask(MASTER_KEYBOARD); @@ -1586,6 +1594,10 @@ fn receive_xi_keyboard_regrab_orders_focus_out_before_in() { seen.iter().all(|c| c.client == DENIED), "the grab's notifications reach only the owner" ); + assert!( + !seen.iter().any(|c| c.client == ALLOWED), + "no Receive call names ALLOWED, though it selects the focus" + ); let denied: Vec = seen.into_iter().filter(|c| c.client == DENIED).collect(); assert_eq!( denied, @@ -1679,7 +1691,7 @@ fn receive_xi_pointer_grab_chain_details() { .filter(|frame| frame[0] == 35) .map(|frame| { ( - u16::from_be_bytes([frame[8], frame[9]]), + dec16(&frame[8..10], ClientByteOrder::BigEndian), frame_window(frame, order), frame[19], frame[18], @@ -1760,7 +1772,7 @@ fn receive_core_cooked_pointer_unchecked() { let xi2_types: Vec = split_frames(&plain[0], ClientByteOrder::BigEndian) .into_iter() .filter(|frame| frame[0] == 35) - .map(|frame| u16::from_be_bytes([frame[8], frame[9]])) + .map(|frame| dec16(&frame[8..10], ClientByteOrder::BigEndian)) .collect(); assert_eq!( xi2_types, @@ -1771,8 +1783,8 @@ fn receive_core_cooked_pointer_unchecked() { assert!(seen.is_empty(), "no Receive call for cooked pointer events"); } -/// A RRSetScreenSize copy carries its own window: DENIED's three copies name the root, the -/// overlay and the root again, as event and window. A subject-only check cannot see a copy +/// A RRSetScreenSize copy carries its own window: each receiver's three copies name the root, +/// the overlay and the root again, as event and window. A subject-only check cannot see a copy /// whose window field is wrong. #[test] fn receive_resize_copies_carry_their_windows() { @@ -1780,24 +1792,21 @@ fn receive_resize_copies_carry_their_windows() { resize_setup(&mut f); drain_all(&mut f); resize_drive(&mut f); - let order = f.state.clients[&DENIED.0].byte_order; - let copies: Vec<(u32, u32)> = split_frames(&f.drain(DENIED), order) - .into_iter() - .filter(|frame| frame[0] == 22) - .map(|frame| { - ( - read_u32(&frame[4..8], order), - read_u32(&frame[8..12], order), - ) - }) - .collect(); - assert_eq!( - copies, - vec![ - (ROOT_WINDOW.0, ROOT_WINDOW.0), - (COMPOSITE_OVERLAY_WINDOW.0, COMPOSITE_OVERLAY_WINDOW.0), - (ROOT_WINDOW.0, COMPOSITE_OVERLAY_WINDOW.0), - ], - "R2 root, R3 overlay, R4 parent (the overlay as window)" - ); + for client in [DENIED, ALLOWED] { + let order = f.state.clients[&client.0].byte_order; + let copies: Vec<(u32, u32)> = split_frames(&f.drain(client), order) + .into_iter() + .filter(|frame| frame[0] == 22) + .map(|frame| (dec32(&frame[4..8], order), dec32(&frame[8..12], order))) + .collect(); + assert_eq!( + copies, + vec![ + (ROOT_WINDOW.0, ROOT_WINDOW.0), + (COMPOSITE_OVERLAY_WINDOW.0, COMPOSITE_OVERLAY_WINDOW.0), + (ROOT_WINDOW.0, COMPOSITE_OVERLAY_WINDOW.0), + ], + "{client:?}: R2 root, R3 overlay, R4 parent (the overlay as window)" + ); + } } diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_notify_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_notify_support.rs index a255912b9..ee482179e 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_notify_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_notify_support.rs @@ -344,6 +344,24 @@ pub(super) fn enc32(order: ClientByteOrder, value: u32) -> Vec { bytes } +/// Decoding of one 16-bit field of a frame in `order`; the reader of `enc16`. +pub(super) fn dec16(bytes: &[u8], order: ClientByteOrder) -> u16 { + let bytes: [u8; 2] = bytes.try_into().expect("u16 field bytes"); + match order { + ClientByteOrder::LittleEndian => u16::from_le_bytes(bytes), + ClientByteOrder::BigEndian => u16::from_be_bytes(bytes), + } +} + +/// Decoding of one 32-bit field of a frame in `order`; the reader of `enc32`. +pub(super) fn dec32(bytes: &[u8], order: ClientByteOrder) -> u32 { + let bytes: [u8; 4] = bytes.try_into().expect("u32 field bytes"); + match order { + ClientByteOrder::LittleEndian => u32::from_le_bytes(bytes), + ClientByteOrder::BigEndian => u32::from_be_bytes(bytes), + } +} + fn assert_row_trace( row: &Row, expected: &[ExpectedReceive], diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_xi_notify.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_xi_notify.rs index db49887f9..5c01dd97d 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_xi_notify.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_xi_notify.rs @@ -13,7 +13,7 @@ use super::{ access_notify_support::{ DENY, ExpectedReceive, FieldPins, NOTIFY_RECEIVER_ALLOWED as ALLOWED, NOTIFY_RECEIVER_DENIED as DENIED, NOTIFY_SENDER as SENDER, NotifyFixture, Order, Row, - check_row, enc16, enc32, receive_trace, request_opcodes, split_frames, + check_row, dec16, enc16, enc32, receive_trace, request_opcodes, split_frames, }, extensions::ExtensionHook, xi_hotplug::{ @@ -312,7 +312,7 @@ fn xi_describe( 35 => Some(EventDescription::extension( 35, XI_MAJOR, - read_u16(&frame[8..10], order), + dec16(&frame[8..10], order), )), event if (first..first + 20).contains(&event) => Some(EventDescription::extension( event, @@ -323,14 +323,6 @@ fn xi_describe( } } -fn read_u16(bytes: &[u8], order: ClientByteOrder) -> u16 { - let bytes: [u8; 2] = bytes.try_into().unwrap(); - match order { - ClientByteOrder::LittleEndian => u16::from_le_bytes(bytes), - ClientByteOrder::BigEndian => u16::from_be_bytes(bytes), - } -} - /// Receive calls to both receivers for one subject and event. fn receivers( request: Option, @@ -979,8 +971,8 @@ fn receive_xi_bootstrap_drops_only_the_denied_master() { .iter() .zip([(MASTER_POINTER, POINTER_ID), (MASTER_KEYBOARD, keyboard_id)]) { - assert_eq!(read_u16(&frame[10..12], ClientByteOrder::BigEndian), master); - assert_eq!(read_u16(&frame[18..20], ClientByteOrder::BigEndian), slave); + assert_eq!(dec16(&frame[10..12], ClientByteOrder::BigEndian), master); + assert_eq!(dec16(&frame[18..20], ClientByteOrder::BigEndian), slave); } let (deny_trace, deny_bytes, _) = run(true); @@ -996,14 +988,14 @@ fn receive_xi_bootstrap_drops_only_the_denied_master() { /// client's byte order: `num_classes` (header bytes 16..18) blocks, each sized by /// its own length field (class bytes 2..4, in 4-byte units), filling the frame. fn assert_class_blocks_walk(frame: &[u8], order: ClientByteOrder) { - let num_classes = read_u16(&frame[16..18], order); + let num_classes = dec16(&frame[16..18], order); let mut offset = 32; for _ in 0..num_classes { assert!( offset + 4 <= frame.len(), "class block at {offset} runs past the frame" ); - let units = usize::from(read_u16(&frame[offset + 2..offset + 4], order)); + let units = usize::from(dec16(&frame[offset + 2..offset + 4], order)); assert!(units > 0, "class block at {offset} has no length"); offset += 4 * units; } @@ -1105,7 +1097,7 @@ fn receive_xi_mapping_no_policy_order_matches_control() { let bytes = fixture.drain(client); let got: Vec<(u8, u16)> = split_frames(&bytes, order) .iter() - .map(|frame| (frame[0], read_u16(&frame[2..4], order))) + .map(|frame| (frame[0], dec16(&frame[2..4], order))) .collect(); assert_eq!(got, want, "{request:?}: {client:?} stream"); } From 0f902e7e0467aa3d344b52c63dfda44de42d573f Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 14:39:00 -0300 Subject: [PATCH 09/72] test(access): regrab doc names ALLOWED's selections Co-Authored-By: Claude Opus 5.5 --- .../core_loop/process_request/tests/access_crossing_notify.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_crossing_notify.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_crossing_notify.rs index 4b0790662..3def27599 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_crossing_notify.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_crossing_notify.rs @@ -1551,8 +1551,8 @@ fn receive_xi1_focus_and_state_batches_independent() { } /// Keyboard re-grab: XIGrabDevice on the child, then on the parent by the same client. The -/// old window's FocusOut precedes the new window's FocusIn. No selections: the synthetic -/// notifications go to the grab owner only. +/// old window's FocusOut precedes the new window's FocusIn. ALLOWED selects XI2 focus on both +/// windows, yet the synthetic notifications go to the grab owner only and ALLOWED is never checked. #[test] fn receive_xi_keyboard_regrab_orders_focus_out_before_in() { let mut f = new_fixture(); From cee27ad34645b366dcd09c7bbdedf48ae6ec3cbc Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 14:50:40 -0300 Subject: [PATCH 10/72] feat(access): Receive decides the focused key walk and form shadowing Under a policy, a key selection takes part in the focused walk and in XI2 form shadowing only when the copy it would produce is allowed. A denied copy does not stop the walk and does not shadow another form. A denied XI2 copy reopens core for that client. A selection that produces no copy (XI2 release suppression, a detectable-repeat core release, or a form the include flags exclude) still stops the walk, and Receive is not asked for it. key_copies_at plans one window's copies and asks Receive once per recipient and XI2 form class; write_key_copies writes the plan unchecked. focused_walk_target returns the stopping window with its plan, so the focus is checked once. The focus, slave and replay callers write the plan their decision computed. The grab owner's single copy is checked at its own fanout, which covers the slave grab write. With no policy, or an allow-all policy, the output bytes are unchanged. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Haiku 5.5 --- crates/yserver-core/src/core_loop/fanout.rs | 14 + .../yserver-core/src/core_loop/key_fanout.rs | 300 ++++-- .../process_request/tests/access_key_input.rs | 924 ++++++++++++++++++ .../core_loop/process_request/tests/mod.rs | 1 + .../core_loop/process_request/tests/xi2.rs | 2 +- 5 files changed, 1146 insertions(+), 95 deletions(-) create mode 100644 crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs diff --git a/crates/yserver-core/src/core_loop/fanout.rs b/crates/yserver-core/src/core_loop/fanout.rs index 78f85cbbb..88bd39235 100644 --- a/crates/yserver-core/src/core_loop/fanout.rs +++ b/crates/yserver-core/src/core_loop/fanout.rs @@ -292,6 +292,20 @@ where fanout_event_to_clients_inner(state, client_ids, Some((subject, events)), encode) } +/// Whether `client` may receive `events` for `subject`. Without an installed +/// policy the answer is `true` and no policy is asked. +pub(crate) fn receive_allows( + state: &ServerState, + client: ClientId, + subject: EventSubject, + events: &EventBatch<'_>, +) -> bool { + !matches!( + state.check_receive(client, subject, events, state.receive_request), + Decision::Deny(_) + ) +} + fn fanout_event_to_clients_inner( state: &mut ServerState, client_ids: &[ClientId], diff --git a/crates/yserver-core/src/core_loop/key_fanout.rs b/crates/yserver-core/src/core_loop/key_fanout.rs index f49c8ad36..cd0753fa1 100644 --- a/crates/yserver-core/src/core_loop/key_fanout.rs +++ b/crates/yserver-core/src/core_loop/key_fanout.rs @@ -15,7 +15,8 @@ use yserver_protocol::x11::{self, ClientId, ResourceId}; use crate::{ - core_loop::fanout::{fanout_event_to_clients, subscribers_by_id}, + access::{EventBatch, EventDescription, EventSubject}, + core_loop::fanout::{fanout_event_to_clients, receive_allows, subscribers_by_id}, host_x11::HostKeyEvent, nested::XI2_MAJOR_OPCODE, resources::ROOT_WINDOW, @@ -557,8 +558,9 @@ fn deliver_routed_key_with_master_status( let mut dropped = if focus == ResourceId(0) { Vec::new() } else { - let target = focused_walk_target(state, focus, &event); - deliver_key_to_window(state, &event, target, false, false, synthetic_repeat) + let (target, copies) = + focused_walk_target(state, focus, &event, false, false, synthetic_repeat); + write_key_copies(state, &event, target, &copies, synthetic_repeat) }; merge_dropped( &mut dropped, @@ -648,15 +650,15 @@ fn deliver_routed_key_with_master_status( // window from the pointer window up (bounded at the // focus) where a client selected the event — Xorg // DeliverFocusedEvent's pointer-walk leg. - let target = focused_walk_target(state, window, &event); - let mut dropped = deliver_key_to_window( + let (target, copies) = focused_walk_target( state, + window, &event, - target, master_transition_accepted, master_transition_accepted, synthetic_repeat, ); + let mut dropped = write_key_copies(state, &event, target, &copies, synthetic_repeat); merge_dropped( &mut dropped, deliver_xi1_focused_key(state, &event, synthetic_repeat), @@ -688,7 +690,7 @@ pub(crate) fn replay_frozen_key_to_focus_after_transition( if focus == ResourceId(0) { return Vec::new(); } - let mut dropped = deliver_key_to_window( + let copies = key_copies_at( state, &event, focus, @@ -696,6 +698,7 @@ pub(crate) fn replay_frozen_key_to_focus_after_transition( master_transition_accepted, synthetic_repeat, ); + let mut dropped = write_key_copies(state, &event, focus, &copies, synthetic_repeat); merge_dropped( &mut dropped, deliver_xi1_focused_key(state, &event, synthetic_repeat), @@ -703,109 +706,200 @@ pub(crate) fn replay_frozen_key_to_focus_after_transition( dropped } -/// Deliver a key event to a single window's subscribers — the normal -/// path (focus window, or an explicit-grab window). Core key events and -/// parallel XI2 device events go to their respective selectors. -fn deliver_key_to_window( - state: &mut ServerState, +/// The copies one key event produces at a window, with every Receive decision +/// made once. `core` and `xi2` are written unchecked by `write_key_copies`. +/// `stops` says whether the focus walk stops at this window. +struct KeyCopies { + core: Vec, + /// (device, source, recipients) per XI2 form, slave form before master. + xi2: Vec<(u16, u16, Vec)>, + stops: bool, +} + +/// Plans the key copies at `window` (Xorg `DeliverDeviceEvents`, one window). +/// +/// XI2 shadows core per client: a client with an allowed XI2 copy, or a +/// suppressed XI2 selection, does not get the core form (Xorg behaviour). A +/// client that selects both core and XI2, such as Chromium's Ozone X11 layer, +/// would otherwise get every keystroke twice. A denied XI2 copy reopens core +/// for that client. The forms of one client share subject and description, so +/// that client's XI2 copies take one Receive check. +/// +/// `stops` is per selection: every selection counted by `key_selectors` +/// stops the walk when it produces no copy or its copy is allowed. +fn key_copies_at( + state: &ServerState, event: &HostKeyEvent, - target_window: ResourceId, + window: ResourceId, include_master_form: bool, include_core_form: bool, synthetic_repeat: bool, -) -> Vec { +) -> KeyCopies { let mask_bit = if event.pressed { KEY_PRESS_MASK } else { KEY_RELEASE_MASK }; - let fields = key_window_fields(state, event, target_window); - - // Clients that selected XI2 for this key event on the window. Computed - // first because XI2 *shadows* core per client: a client receiving the - // XI2 form must NOT also receive the core form of the same physical - // event (Xorg behaviour). Without this, a client that selects both - // core (XSelectInput KeyPressMask) and XI2 (XISelectEvents) — e.g. - // Chromium's Ozone X11 layer — gets every keystroke twice. - let xi2_evtype = xi2_evtype_for(event); - let forms = key_xi2_forms(state, event.origin) - .into_iter() + let evtype = xi2_evtype_for(event); + let subject = EventSubject::Window(window); + let xi2_suppressed = synthetic_repeat && !event.pressed; + let all_forms = key_xi2_forms(state, event.origin); + let forms: Vec<(u16, u16)> = all_forms + .iter() + .copied() .filter(|(device_id, _)| include_master_form || *device_id != XI2_MASTER_KEYBOARD_DEVICE_ID) - .collect::>(); - let mut xi2_targets = Vec::new(); - for (device_id, _) in &forms { - for (id, client) in &state.clients { - if key_xi2_form_selected(client, target_window, *device_id, xi2_evtype) - && !xi2_targets.contains(&ClientId(*id)) - { - xi2_targets.push(ClientId(*id)); - } + .collect(); + let core_subscribers = subscribers_by_id(state, window, mask_bit); + let detectable_suppressed = |client: &ClientId| { + synthetic_repeat + && !event.pressed + && state + .xkb_clients + .get(&client.0) + .is_some_and(|flags| flags.wants_detectable_auto_repeat()) + }; + + // Clients with a selection in an included form, in write order. + let xi2_selected: Vec = state + .clients + .iter() + .filter(|(_, client)| { + forms + .iter() + .any(|(device_id, _)| key_xi2_form_selected(client, window, *device_id, evtype)) + }) + .map(|(id, _)| ClientId(*id)) + .collect(); + let xi2_batch = [crate::xinput::xi2_event_description(evtype)]; + let allowed_xi2: Vec = if xi2_suppressed { + Vec::new() + } else { + xi2_selected + .iter() + .copied() + .filter(|client| receive_allows(state, *client, subject, &EventBatch::new(&xi2_batch))) + .collect() + }; + // A suppressed XI2 selection shadows core too; a denied copy does not. + let shadows_core = |client: &ClientId| { + if xi2_suppressed { + xi2_selected.contains(client) + } else { + allowed_xi2.contains(client) } - } + }; - // Core KeyPress/KeyRelease to KeyPressMask/KeyReleaseMask subscribers, - // excluding any client already getting the XI2 form above. - let core_targets: Vec = if include_core_form { - subscribers_by_id(state, target_window, mask_bit) - .into_iter() - .filter(|c| { - !xi2_targets.contains(c) - && !(synthetic_repeat - && !event.pressed - && state - .xkb_clients - .get(&c.0) - .is_some_and(|flags| flags.wants_detectable_auto_repeat())) + let core_batch = [EventDescription::core(if event.pressed { 2 } else { 3 })]; + let core: Vec = core_subscribers + .iter() + .copied() + .filter(|client| { + include_core_form && !shadows_core(client) && !detectable_suppressed(client) + }) + .filter(|client| receive_allows(state, *client, subject, &EventBatch::new(&core_batch))) + .collect(); + + let xi2 = if xi2_suppressed { + Vec::new() + } else { + forms + .iter() + .map(|&(device_id, source_id)| { + let targets = state + .clients + .iter() + .filter_map(|(id, client)| { + let id = ClientId(*id); + (allowed_xi2.contains(&id) + && key_xi2_form_selected(client, window, device_id, evtype)) + .then_some(id) + }) + .collect(); + (device_id, source_id, targets) }) .collect() - } else { - Vec::new() }; - let mut dropped = if core_targets.is_empty() { + + // Every selection key_selectors counts: a form the include flag excludes, + // a suppressed form, or an allowed form stops the walk; a denied one does not. + let form_stops = state.clients.iter().any(|(id, client)| { + let id = ClientId(*id); + all_forms.iter().any(|(device_id, _)| { + key_xi2_form_selected(client, window, *device_id, evtype) + && (!forms.iter().any(|(included, _)| included == device_id) + || xi2_suppressed + || allowed_xi2.contains(&id)) + }) + }); + let core_stops = core_subscribers.iter().any(|client| { + !include_core_form + || shadows_core(client) + || detectable_suppressed(client) + || core.contains(client) + }); + + KeyCopies { + core, + xi2, + stops: form_stops || core_stops, + } +} + +/// Writes a planned key event at `window`: the core form, then each XI2 form +/// in plan order. Unchecked: the plan holds the Receive decisions. +fn write_key_copies( + state: &mut ServerState, + event: &HostKeyEvent, + window: ResourceId, + copies: &KeyCopies, + synthetic_repeat: bool, +) -> Vec { + let fields = key_window_fields(state, event, window); + let mut dropped = if copies.core.is_empty() { Vec::new() } else { - fanout_event_to_clients(state, &core_targets, |buf, seq, order| { + fanout_event_to_clients(state, &copies.core, |buf, seq, order| { x11::encode_key_event(buf, order, key_event_wire(event, seq, fields)); }) }; - - // Keep XI2-selected clients in `xi2_targets` above while suppressing the - // synthetic XI2 release here: XI2 still shadows the core form for that - // client, even though it receives no release form. - if synthetic_repeat && !event.pressed { - return dropped; - } - - for (device_id, source_id) in forms { - let targets: Vec = state - .clients - .iter() - .filter_map(|(id, client)| { - key_xi2_form_selected(client, target_window, device_id, xi2_evtype) - .then_some(ClientId(*id)) - }) - .collect(); + for (device_id, source_id, targets) in &copies.xi2 { if targets.is_empty() { continue; } - let xi2_dropped = fanout_event_to_clients(state, &targets, |buf, seq, order| { + let xi2_dropped = fanout_event_to_clients(state, targets, |buf, seq, order| { encode_key_xi2_for_device( buf, order, seq, event, fields, - device_id, - source_id, + *device_id, + *source_id, synthetic_repeat, ); }); merge_dropped(&mut dropped, xi2_dropped); } - dropped } +/// The Receive check for a grab owner's single copy. A missing owner gets no +/// copy, so it is not asked. +fn grab_owner_allows( + state: &ServerState, + owner: ClientId, + grab_window: ResourceId, + description: EventDescription, +) -> bool { + state.clients.contains_key(&owner.0) + && receive_allows( + state, + owner, + EventSubject::Window(grab_window), + &EventBatch::new(&[description]), + ) +} + /// Deliver a key event to the grab owner client, addressed to the /// grab window. When a passive (or explicit) keyboard grab is active, /// X11 delivers to the *grab owner* using the grab's event mask, not @@ -842,6 +936,10 @@ fn deliver_key_to_grab_owner( if synthetic_repeat && !event.pressed { return Vec::new(); } + let description = crate::xinput::xi2_event_description(xi2_evtype_for(event)); + if !grab_owner_allows(state, owner, grab_window, description) { + return Vec::new(); + } let source_id = resolve_key_xi_source(state, event.origin).map_or(device_id, |source| source.sourceid); fanout_event_to_clients(state, &[owner], |buf, seq, order| { @@ -866,6 +964,10 @@ fn deliver_key_to_grab_owner( { return Vec::new(); } + let description = EventDescription::core(if event.pressed { 2 } else { 3 }); + if !grab_owner_allows(state, owner, grab_window, description) { + return Vec::new(); + } fanout_event_to_clients(state, &[owner], |buf, seq, order| { x11::encode_key_event(buf, order, key_event_wire(event, seq, fields)); }) @@ -1492,17 +1594,19 @@ fn deliver_xi1_focused_key( ) } -/// Pointer-walk leg of Xorg `DeliverFocusedEvent`: if the pointer -/// window P is the focus or a descendant of it, the event window is -/// the first window from P upward (bounded at the focus, inclusive) -/// where any client selected the event; otherwise the focus itself. -/// Under PointerRoot the walk is bounded at the root, not at P. -fn focused_walk_target(state: &ServerState, focus: ResourceId, event: &HostKeyEvent) -> ResourceId { - let mask_bit = if event.pressed { - KEY_PRESS_MASK - } else { - KEY_RELEASE_MASK - }; +/// Pointer-walk leg of Xorg `DeliverFocusedEvent`: if the pointer window P is +/// the focus or a descendant of it, the walk starts at P and goes up to the +/// focus. It stops at the first window whose copies `stop`; otherwise the +/// focus is the target. Returns the target with its copies, so the focus is +/// checked once. Under PointerRoot the walk is bounded at the root, not at P. +fn focused_walk_target( + state: &ServerState, + focus: ResourceId, + event: &HostKeyEvent, + include_master_form: bool, + include_core_form: bool, + synthetic_repeat: bool, +) -> (ResourceId, KeyCopies) { let focus = if state.core_focus.raw == 1 { ROOT_WINDOW } else { @@ -1521,18 +1625,26 @@ fn focused_walk_target(state: &ServerState, focus: ResourceId, event: &HostKeyEv chain.push(w.parent); cur = w.parent; } - if !chain.contains(&focus) { - return focus; - } - for w in chain { - if !key_selectors(state, event, w, mask_bit).is_empty() { - return w; - } - if w == focus { - break; + let copies_at = |window: ResourceId| { + key_copies_at( + state, + event, + window, + include_master_form, + include_core_form, + synthetic_repeat, + ) + }; + let Some(depth) = chain.iter().position(|w| *w == focus) else { + return (focus, copies_at(focus)); + }; + for window in &chain[..depth] { + let copies = copies_at(*window); + if copies.stops { + return (*window, copies); } } - focus + (focus, copies_at(focus)) } /// Clients that selected this key event on `window` in any form: the core diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs new file mode 100644 index 000000000..30e729673 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -0,0 +1,924 @@ +//! Receive decisions in the focused key walk and XI2-over-core shadowing +//! (PR 4c part 2, plan 1, task 2). +//! +//! Each row builds its windows and selections through requests, pins the +//! pointer and focus, drives one host key through a production key entry, and +//! checks three runs: no policy, an explicit allow-all policy, and a policy +//! that denies the listed (client, description, window) copies. The no-policy +//! and allow-all runs must produce identical bytes. Each run is also checked +//! against literal per-client frames and literal Receive calls. A denied run's +//! bytes must be the allow-all bytes minus the denied key frames. +//! +//! Receive calls are compared per client: `state.clients` is a HashMap, so the +//! order across clients is not part of the contract. + +use super::{ + access_notify_support::{DENY, NotifyFixture, dec16, dec32, split_frames}, + extensions::{ExtensionHook, RecordedExtensionCheck}, + xi2::xi_select_body, +}; +use crate::{ + access::{Decision, EventDescription, EventSubject}, + core_loop::{ + InputOrigin, client_io, + key_fanout::{key_event_fanout_after_transition, key_event_fanout_to_state}, + process_request::RequestOutcome, + }, + host_x11::HostKeyEvent, + nested::XI2_MAJOR_OPCODE, + resources::ROOT_WINDOW, + server::{ActiveKeyboardGrab, ActiveKeyboardGrabSource}, + xinput::{DEVICEID_MASTER_KEYBOARD, DEVICEID_XTEST_KEYBOARD}, +}; +use std::{collections::BTreeMap, sync::atomic::Ordering}; +use yserver_protocol::x11::{ClientByteOrder, ClientId, RequestHeader, ResourceId, SequenceNumber}; + +const SEND_CLIENT: u32 = 1; +/// The client that selects on the child window (A in the brief). +const A: u32 = 2; +/// The client that selects on the focus window (B in the brief). +const B: u32 = 3; +const FOCUS: u32 = 0x0061_0001; +const CHILD: u32 = 0x0061_0002; +const POINTER: (i16, i16) = (120, 120); +const KEYCODE: u8 = 38; +const TIME: u32 = 0x5678; +const XI_MAJOR: u8 = 137; +const XI_SELECT_EVENTS: u8 = 46; +const CORE_CHANGE_WINDOW_ATTRIBUTES: u8 = 2; +const CORE_CREATE_WINDOW: u8 = 1; +const CORE_MAP_WINDOW: u8 = 8; +const CORE_SET_INPUT_FOCUS: u8 = 42; +const CW_EVENT_MASK: u32 = 0x800; +const KEY_PRESS: u32 = 1; +const KEY_RELEASE: u32 = 2; +/// XI2 mask word for KeyPress (bit 2) and KeyRelease (bit 3). +const XI_KEY_PRESS: u32 = 1 << 2; +const XI_KEY_RELEASE: u32 = 1 << 3; +const XI_KEY_PRESS_AND_RELEASE: u32 = XI_KEY_PRESS | XI_KEY_RELEASE; + +/// One frame the server writes: (client, what it is, event window). +type Frame = (u32, Kind, u32); +/// One Receive call the server makes: (client, description, subject window). +type Call = (u32, CallKind, u32); + +/// What a key frame is. `Xi2` carries the form's device id. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + Core, + Xi2(u16), +} + +/// What a Receive check names. An XI2 check names the description, not the +/// form, so it carries no device. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum CallKind { + Core, + Xi2, +} + +#[derive(Clone, Copy)] +enum Drive { + /// `key_event_fanout_to_state`: the transition-checked entry. + Entry { origin: InputOrigin, pressed: bool }, + /// `key_event_fanout_after_transition` with explicit master and synthetic flags. + After { + origin: InputOrigin, + pressed: bool, + master: bool, + synthetic: bool, + }, +} + +impl Drive { + fn pressed(self) -> bool { + match self { + Drive::Entry { pressed, .. } | Drive::After { pressed, .. } => pressed, + } + } +} + +struct Expect { + frames: &'static [Frame], + calls: &'static [Call], +} + +struct Row { + name: &'static str, + setup: fn(&mut NotifyFixture), + drive: Drive, + /// (client, check, window) Receive calls to deny. + deny: &'static [Call], + allow: Expect, + denied: Expect, +} + +// ---- request helpers ----------------------------------------------------- + +/// Sends one request from `client` with the next sequence number of that +/// client, and checks it was handled with no error and no writer failure. +fn send(f: &mut NotifyFixture, client: u32, opcode: u8, data: u8, body: &[u8]) { + let sequence = { + let state = &f.state.clients[&client]; + let next = state.last_sequence.load(Ordering::Relaxed).wrapping_add(1); + state.last_sequence.store(next, Ordering::Relaxed); + next + }; + let header = RequestHeader { + opcode, + data, + length_units: u32::try_from((4 + body.len()) / 4).expect("request length"), + }; + let outcome = f + .request(ClientId(client), SequenceNumber(sequence), header, body) + .expect("request through process_request"); + assert!( + matches!(outcome, RequestOutcome::Handled), + "request handled" + ); + assert!( + client_io::failed_writers(&f.state.clients).is_empty(), + "request queued a disconnect" + ); + assert!(f.drain(ClientId(client)).is_empty(), "requester got bytes"); +} + +/// Two windows: FOCUS (100,100) 200x200 and CHILD inside it at (10,10), both +/// mapped. Focus is FOCUS, the pointer is inside CHILD. +fn tree(f: &mut NotifyFixture) { + for (client, base) in [(SEND_CLIENT, 0x0100), (A, 0x0200), (B, 0x0300)] { + f.state.clients[&client] + .last_sequence + .store(base, Ordering::Relaxed); + } + for (window, parent, x, y, size) in [ + (FOCUS, ROOT_WINDOW.0, 100, 100, 200), + (CHILD, FOCUS, 10, 10, 50), + ] { + let mut body = Vec::with_capacity(32); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&parent.to_le_bytes()); + body.extend_from_slice(&(x as i16).to_le_bytes()); + body.extend_from_slice(&(y as i16).to_le_bytes()); + body.extend_from_slice(&(size as u16).to_le_bytes()); + body.extend_from_slice(&(size as u16).to_le_bytes()); + body.extend_from_slice(&0_u16.to_le_bytes()); // border + body.extend_from_slice(&1_u16.to_le_bytes()); // InputOutput + body.extend_from_slice(&crate::resources::ROOT_VISUAL.0.to_le_bytes()); + body.extend_from_slice(&0_u32.to_le_bytes()); // value mask + send(f, SEND_CLIENT, CORE_CREATE_WINDOW, 24, &body); + send(f, SEND_CLIENT, CORE_MAP_WINDOW, 0, &window.to_le_bytes()); + } + send( + f, + SEND_CLIENT, + CORE_SET_INPUT_FOCUS, + 0, + &[FOCUS.to_le_bytes(), 0_u32.to_le_bytes()].concat(), + ); + f.state.pointer_root = POINTER; +} + +/// Core KeyPress/KeyRelease selection on `window` for `client`. +fn select_core(f: &mut NotifyFixture, client: u32, window: u32, mask: u32) { + let body = [ + window.to_le_bytes(), + CW_EVENT_MASK.to_le_bytes(), + mask.to_le_bytes(), + ] + .concat(); + send(f, client, CORE_CHANGE_WINDOW_ATTRIBUTES, 0, &body); +} + +/// XI2 key selection of one device on `window` for `client`. +fn select_xi2(f: &mut NotifyFixture, client: u32, window: u32, device: u16, mask: u32) { + let body = xi_select_body(window, &[(device, &[mask])]); + send(f, client, XI_MAJOR, XI_SELECT_EVENTS, &body); +} + +/// `client` gets the core key form for both key events on `window` (the +/// detectable-repeat client of the synthetic-release rows). +fn set_detectable_repeat(f: &mut NotifyFixture, client: u32) { + f.state + .xkb_clients + .entry(client) + .or_default() + .per_client_flags = 1; +} + +/// The slave keyboard's exact XI2 grab owned by `owner` on `grab_window`. +fn grab_slave_keyboard(f: &mut NotifyFixture, owner: u32, grab_window: u32) { + f.state.xi2_keyboard_grabs.insert( + DEVICEID_XTEST_KEYBOARD, + ActiveKeyboardGrab { + owner: ClientId(owner), + grab_window: ResourceId(grab_window), + source: ActiveKeyboardGrabSource::Explicit, + owner_events: false, + via_xi2: true, + xi2_mask: XI_KEY_PRESS, + }, + ); +} + +// ---- run and decode ------------------------------------------------------ + +fn key_event(origin: InputOrigin, pressed: bool) -> HostKeyEvent { + HostKeyEvent { + origin, + pressed, + keycode: KEYCODE, + time: TIME, + root_x: POINTER.0, + root_y: POINTER.1, + event_x: 0, + event_y: 0, + state: 0, + } +} + +fn drive(f: &mut NotifyFixture, drive: Drive) { + let dropped = match drive { + Drive::Entry { origin, pressed } => { + key_event_fanout_to_state(&mut f.state, &mut f.backend, key_event(origin, pressed)) + } + Drive::After { + origin, + pressed, + master, + synthetic, + } => key_event_fanout_after_transition( + &mut f.state, + &mut f.backend, + key_event(origin, pressed), + master, + synthetic, + ), + }; + assert!(dropped.is_empty(), "delivery queued a disconnect"); +} + +/// The key-related description a Receive call names, or `None` for other events. +fn key_call(description: &EventDescription) -> Option<(CallKind, bool)> { + match description.extension { + None if description.type_code == 2 || description.type_code == 3 => { + Some((CallKind::Core, description.type_code == 2)) + } + Some(extension) + if description.type_code == 35 + && extension.major_opcode == XI2_MAJOR_OPCODE + && (extension.event_type == 2 || extension.event_type == 3) => + { + Some((CallKind::Xi2, extension.event_type == 2)) + } + _ => None, + } +} + +/// Denies exactly the listed (client, kind, window) Receive checks, matched by +/// hook, subject and description. +fn decide(denied: &[Call], pressed: bool, call: &RecordedExtensionCheck) -> Decision { + if call.hook != ExtensionHook::Receive { + return Decision::Allow; + } + let (Some(EventSubject::Window(window)), Some(events)) = (call.receive, call.events.as_deref()) + else { + return Decision::Allow; + }; + let [description] = events else { + return Decision::Allow; + }; + let Some((kind, press)) = key_call(description) else { + return Decision::Allow; + }; + if press != pressed { + return Decision::Allow; + } + if denied.contains(&(call.client.0, kind, window.0)) { + DENY + } else { + Decision::Allow + } +} + +/// Decodes a frame the key walk writes: a core KeyPress/KeyRelease (event +/// window at byte 12) or an XI2 key GenericEvent (device at byte 10, event +/// window at byte 24). `None` for any other frame. +fn decode(frame: &[u8], order: ClientByteOrder) -> Option<(Kind, u32)> { + match frame[0] & 0x7f { + 2 | 3 => Some((Kind::Core, dec32(&frame[12..16], order))), + 35 if frame[1] == XI2_MAJOR_OPCODE && matches!(dec16(&frame[8..10], order), 2 | 3) => { + Some(( + Kind::Xi2(dec16(&frame[10..12], order)), + dec32(&frame[24..28], order), + )) + } + _ => None, + } +} + +struct ClientBytes { + client: u32, + order: ClientByteOrder, + sequence: u16, + bytes: Vec, +} + +struct Run { + clients: Vec, + calls: Vec, + state: String, +} + +fn run(row: &Row, policy: Option<&'static [Call]>) -> Run { + let mut f = NotifyFixture::new(); + (row.setup)(&mut f); + f.state.clients.get_mut(&A).expect("client A").byte_order = ClientByteOrder::BigEndian; + for client in [SEND_CLIENT, A, B] { + f.drain(ClientId(client)); + } + let calls = policy.map(|denied| { + let pressed = row.drive.pressed(); + f.install_policy(move |_, call| decide(denied, pressed, call)) + }); + drive(&mut f, row.drive); + assert!( + client_io::failed_writers(&f.state.clients).is_empty(), + "{}: delivery queued a disconnect", + row.name + ); + let clients = [SEND_CLIENT, A, B] + .into_iter() + .map(|client| { + let state = &f.state.clients[&client]; + ClientBytes { + client, + order: state.byte_order, + sequence: state.last_sequence.load(Ordering::Relaxed), + bytes: f.drain(ClientId(client)), + } + }) + .collect(); + let calls = calls + .map(|calls| { + calls + .lock() + .unwrap() + .iter() + .filter(|call| call.hook == ExtensionHook::Receive) + .filter_map(|call| { + let subject = match call.receive? { + EventSubject::Window(window) => window.0, + other => panic!("{}: key Receive subject {other:?}", row.name), + }; + let [description] = call.events.as_deref()? else { + return None; + }; + let (kind, pressed) = key_call(description)?; + assert_eq!( + pressed, + row.drive.pressed(), + "{}: Receive names the other key event", + row.name + ); + Some((call.client.0, kind, subject)) + }) + .collect() + }) + .unwrap_or_default(); + let state = format!("{:?}", (f.state.core_focus.raw, f.state.keys_down)); + Run { + clients, + calls, + state, + } +} + +fn grouped(items: impl IntoIterator) -> BTreeMap> { + let mut out: BTreeMap> = BTreeMap::new(); + for (client, item) in items { + out.entry(client).or_default().push(item); + } + out +} + +/// The key frames a run wrote, with the client byte order and sequence checked. +fn delivered(name: &str, run: &Run) -> Vec { + let mut frames = Vec::new(); + for client in &run.clients { + for frame in split_frames(&client.bytes, client.order) { + if let Some((kind, window)) = decode(frame, client.order) { + let sequence = match client.order { + ClientByteOrder::LittleEndian => client.sequence.to_le_bytes(), + ClientByteOrder::BigEndian => client.sequence.to_be_bytes(), + }; + assert_eq!( + &frame[2..4], + sequence.as_slice(), + "{name}: client {} frame sequence", + client.client + ); + let keycode = match kind { + Kind::Core => u32::from(frame[1]), + Kind::Xi2(_) => dec32(&frame[16..20], client.order), + }; + assert_eq!(keycode, u32::from(KEYCODE), "{name}: frame keycode"); + frames.push((client.client, kind, window)); + } + } + } + frames +} + +fn check_run(row: &Row, run: &Run, expect: &Expect, mode: &str) { + let name = row.name; + assert_eq!( + grouped(run.calls.iter().map(|&(c, kind, w)| (c, (kind, w)))), + grouped(expect.calls.iter().map(|&(c, kind, w)| (c, (kind, w)))), + "{name} [{mode}]: Receive calls per client" + ); + assert_eq!( + grouped( + delivered(name, run) + .into_iter() + .map(|(c, k, w)| (c, (k, w))) + ), + grouped(expect.frames.iter().map(|&(c, k, w)| (c, (k, w)))), + "{name} [{mode}]: frames per client" + ); +} + +/// Runs one row under the three modes and checks it against its literal +/// expectations, the byte identity of no-policy and allow-all, and the +/// denied run's bytes as the allow-all bytes minus the denied key frames. +fn check_row(row: &Row) { + let name = row.name; + let plain = run(row, None); + let allow = run(row, Some(&[])); + assert_eq!( + allow.clients.iter().map(|c| &c.bytes).collect::>(), + plain.clients.iter().map(|c| &c.bytes).collect::>(), + "{name}: allow-all changed the bytes" + ); + assert_eq!(allow.state, plain.state, "{name}: allow-all changed state"); + check_run( + row, + &plain, + &Expect { + frames: row.allow.frames, + calls: &[], + }, + "no policy", + ); + check_run(row, &allow, &row.allow, "allow-all"); + + let denied = run(row, Some(row.deny)); + check_run(row, &denied, &row.denied, "denial"); + assert_eq!(denied.state, allow.state, "{name}: denial changed state"); + // A frame that exists in both runs has the same bytes. A denial can also + // add a frame the allow-all run did not write (the walk moved on), which + // the literal frame list above already pins. + for (got, allowed) in denied.clients.iter().zip(&allow.clients) { + let allowed_frames: Vec<(Kind, u32, &[u8])> = split_frames(&allowed.bytes, allowed.order) + .into_iter() + .filter_map(|frame| { + decode(frame, allowed.order).map(|(kind, window)| (kind, window, frame)) + }) + .collect(); + for frame in split_frames(&got.bytes, got.order) { + let Some((kind, window)) = decode(frame, got.order) else { + continue; + }; + if let Some((_, _, same)) = allowed_frames + .iter() + .find(|(k, w, _)| *k == kind && *w == window) + { + assert_eq!( + frame, *same, + "{name}: client {} {kind:?} @{window:#x} bytes under denial", + got.client + ); + } + } + } +} + +// ---- rows ---------------------------------------------------------------- + +fn setup_child_core_and_focus_core(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, CHILD, KEY_PRESS); + select_core(f, B, FOCUS, KEY_PRESS); +} + +const K1: Row = Row { + name: "k1_denied_pointer_window_selector_advances_the_focus_walk", + setup: setup_child_core_and_focus_core, + drive: Drive::Entry { + origin: InputOrigin::NestedHost, + pressed: true, + }, + deny: &[(A, CallKind::Core, CHILD)], + allow: Expect { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + }, + denied: Expect { + frames: &[(B, Kind::Core, FOCUS)], + calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, FOCUS)], + }, +}; + +fn setup_k2(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, CHILD, KEY_PRESS); + select_core(f, B, CHILD, KEY_PRESS); + select_core(f, SEND_CLIENT, FOCUS, KEY_PRESS); +} + +const K2: Row = Row { + name: "k2_one_allowed_selector_stops_the_walk", + setup: setup_k2, + drive: Drive::Entry { + origin: InputOrigin::NestedHost, + pressed: true, + }, + deny: &[(A, CallKind::Core, CHILD)], + allow: Expect { + frames: &[(A, Kind::Core, CHILD), (B, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, CHILD)], + }, + denied: Expect { + frames: &[(B, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, CHILD)], + }, +}; + +/// A selects XI2 (master) and core on CHILD; B selects core on FOCUS. +fn setup_k3(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, CHILD, KEY_PRESS); + select_xi2(f, A, CHILD, DEVICEID_MASTER_KEYBOARD, XI_KEY_PRESS); + select_core(f, B, FOCUS, KEY_PRESS); +} + +const K3_XI2_DENIED: Row = Row { + name: "k3_denied_xi2_copy_reopens_core_for_that_client", + setup: setup_k3, + drive: Drive::Entry { + origin: InputOrigin::NestedHost, + pressed: true, + }, + deny: &[(A, CallKind::Xi2, CHILD)], + allow: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], + }, +}; + +const K3_BOTH_DENIED: Row = Row { + name: "k3_both_denied_walks_on_to_the_focus", + setup: setup_k3, + drive: Drive::Entry { + origin: InputOrigin::NestedHost, + pressed: true, + }, + deny: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], + allow: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[(B, Kind::Core, FOCUS)], + calls: &[ + (A, CallKind::Xi2, CHILD), + (A, CallKind::Core, CHILD), + (B, CallKind::Core, FOCUS), + ], + }, +}; + +/// A selects XI2 on the master (3) and slave (5) keyboards and core on CHILD. +fn setup_k4(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, CHILD, KEY_PRESS); + select_xi2( + f, + A, + CHILD, + DEVICEID_MASTER_KEYBOARD, + XI_KEY_PRESS_AND_RELEASE, + ); + select_xi2( + f, + A, + CHILD, + DEVICEID_XTEST_KEYBOARD, + XI_KEY_PRESS_AND_RELEASE, + ); +} + +const K4_ALLOWED: Row = Row { + name: "k4_xi2_forms_share_one_check_allowed", + setup: setup_k4, + drive: Drive::Entry { + origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), + pressed: true, + }, + deny: &[], + allow: Expect { + frames: &[ + (A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD), + (A, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), CHILD), + ], + calls: &[(A, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[ + (A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD), + (A, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), CHILD), + ], + calls: &[(A, CallKind::Xi2, CHILD)], + }, +}; + +const K4_XI2_DENIED: Row = Row { + name: "k4_xi2_forms_share_one_check_denied_reopens_core", + setup: setup_k4, + drive: Drive::Entry { + origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), + pressed: true, + }, + deny: &[(A, CallKind::Xi2, CHILD)], + allow: Expect { + frames: &[ + (A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD), + (A, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), CHILD), + ], + calls: &[(A, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], + }, +}; + +/// Synthetic release: A selects only XI2 KeyRelease on CHILD; B core on FOCUS. +fn setup_k5_xi2_release(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, CHILD, DEVICEID_MASTER_KEYBOARD, XI_KEY_RELEASE); + select_core(f, B, FOCUS, KEY_RELEASE); +} + +const K5_XI2_SUPPRESSED: Row = Row { + name: "k5_suppressed_xi2_release_stops_without_a_check", + setup: setup_k5_xi2_release, + drive: Drive::After { + origin: InputOrigin::NestedHost, + pressed: false, + master: true, + synthetic: true, + }, + deny: &[(A, CallKind::Xi2, CHILD)], + allow: Expect { + frames: &[], + calls: &[], + }, + denied: Expect { + frames: &[], + calls: &[], + }, +}; + +/// Synthetic release with a detectable-repeat core selector on CHILD. +fn setup_k5_detectable(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, CHILD, KEY_RELEASE); + select_core(f, B, FOCUS, KEY_RELEASE); + set_detectable_repeat(f, A); +} + +const K5_DETECTABLE_SUPPRESSED: Row = Row { + name: "k5_suppressed_detectable_core_release_stops_without_a_check", + setup: setup_k5_detectable, + drive: Drive::After { + origin: InputOrigin::NestedHost, + pressed: false, + master: true, + synthetic: true, + }, + deny: &[(A, CallKind::Core, CHILD)], + allow: Expect { + frames: &[], + calls: &[], + }, + denied: Expect { + frames: &[], + calls: &[], + }, +}; + +/// Slave origin with the master transition rejected: the core form is excluded +/// on this path. A selects slave XI2 and core on CHILD; B slave XI2 on FOCUS. +fn setup_k5b(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, CHILD, DEVICEID_XTEST_KEYBOARD, XI_KEY_PRESS); + select_core(f, A, CHILD, KEY_PRESS); + select_xi2(f, B, FOCUS, DEVICEID_XTEST_KEYBOARD, XI_KEY_PRESS); +} + +const K5B_EXCLUDED_FORM_STILL_STOPS: Row = Row { + name: "k5b_form_excluded_by_the_include_flags_still_stops", + setup: setup_k5b, + drive: Drive::After { + origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), + pressed: true, + master: false, + synthetic: false, + }, + deny: &[(A, CallKind::Xi2, CHILD)], + allow: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[], + calls: &[(A, CallKind::Xi2, CHILD)], + }, +}; + +/// The slave origin through its exact XI2 grab: the grab owner gets the copy. +fn setup_k5c_grab(f: &mut NotifyFixture) { + tree(f); + grab_slave_keyboard(f, A, FOCUS); +} + +const K5C_SLAVE_GRAB_OWNER: Row = Row { + name: "k5c_slave_grab_write_is_checked", + setup: setup_k5c_grab, + drive: Drive::After { + origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), + pressed: true, + master: false, + synthetic: false, + }, + deny: &[(A, CallKind::Xi2, FOCUS)], + allow: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), FOCUS)], + calls: &[(A, CallKind::Xi2, FOCUS)], + }, + denied: Expect { + frames: &[], + calls: &[(A, CallKind::Xi2, FOCUS)], + }, +}; + +/// The slave origin through the slave focus path, with no grab. +fn setup_k5c_focus(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, CHILD, DEVICEID_XTEST_KEYBOARD, XI_KEY_PRESS); +} + +const K5C_SLAVE_FOCUS_PATH: Row = Row { + name: "k5c_slave_focus_path_is_checked", + setup: setup_k5c_focus, + drive: Drive::After { + origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), + pressed: true, + master: false, + synthetic: false, + }, + deny: &[(A, CallKind::Xi2, CHILD)], + allow: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[], + calls: &[(A, CallKind::Xi2, CHILD)], + }, +}; + +/// A selects core on CHILD and FOCUS; B selects core on FOCUS. +fn setup_k6a(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, CHILD, KEY_PRESS); + select_core(f, A, FOCUS, KEY_PRESS); + select_core(f, B, FOCUS, KEY_PRESS); +} + +const K6A_ALL_DENIED_LANDS_ON_FOCUS: Row = Row { + name: "k6_all_denied_lands_on_focus_with_a_stopping_focus_selector", + setup: setup_k6a, + drive: Drive::Entry { + origin: InputOrigin::NestedHost, + pressed: true, + }, + deny: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + allow: Expect { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + }, + denied: Expect { + frames: &[(B, Kind::Core, FOCUS)], + calls: &[ + (A, CallKind::Core, CHILD), + (A, CallKind::Core, FOCUS), + (B, CallKind::Core, FOCUS), + ], + }, +}; + +/// Only A selects, on CHILD and FOCUS, and A is denied everywhere. +fn setup_k6b(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, CHILD, KEY_PRESS); + select_core(f, A, FOCUS, KEY_PRESS); +} + +const K6B_ATTEMPT_LANDS_ON_FOCUS: Row = Row { + name: "k6_only_selector_denied_lands_on_focus_and_writes_nothing", + setup: setup_k6b, + drive: Drive::Entry { + origin: InputOrigin::NestedHost, + pressed: true, + }, + deny: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + allow: Expect { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + }, + denied: Expect { + frames: &[], + calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + }, +}; + +#[test] +fn k1_denied_pointer_window_selector_advances_the_focus_walk() { + check_row(&K1); +} + +#[test] +fn k2_one_allowed_selector_stops_the_walk() { + check_row(&K2); +} + +#[test] +fn k3_denied_xi2_copy_reopens_core_for_that_client() { + check_row(&K3_XI2_DENIED); +} + +#[test] +fn k3_both_denied_walks_on_to_the_focus() { + check_row(&K3_BOTH_DENIED); +} + +#[test] +fn k4_xi2_forms_share_one_check_allowed() { + check_row(&K4_ALLOWED); +} + +#[test] +fn k4_xi2_forms_share_one_check_denied_reopens_core() { + check_row(&K4_XI2_DENIED); +} + +#[test] +fn k5_suppressed_xi2_release_stops_without_a_check() { + check_row(&K5_XI2_SUPPRESSED); +} + +#[test] +fn k5_suppressed_detectable_core_release_stops_without_a_check() { + check_row(&K5_DETECTABLE_SUPPRESSED); +} + +#[test] +fn k5b_form_excluded_by_the_include_flags_still_stops() { + check_row(&K5B_EXCLUDED_FORM_STILL_STOPS); +} + +#[test] +fn k5c_slave_grab_write_is_checked() { + check_row(&K5C_SLAVE_GRAB_OWNER); +} + +#[test] +fn k5c_slave_focus_path_is_checked() { + check_row(&K5C_SLAVE_FOCUS_PATH); +} + +#[test] +fn k6_all_denied_lands_on_focus_with_a_stopping_focus_selector() { + check_row(&K6A_ALL_DENIED_LANDS_ON_FOCUS); +} + +#[test] +fn k6_only_selector_denied_lands_on_focus_and_writes_nothing() { + check_row(&K6B_ATTEMPT_LANDS_ON_FOCUS); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/mod.rs b/crates/yserver-core/src/core_loop/process_request/tests/mod.rs index bac92c541..7ac3a9b66 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/mod.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/mod.rs @@ -7,6 +7,7 @@ mod access_gc_font; mod access_glx; mod access_grabs; mod access_input; +mod access_key_input; mod access_notify_egress; mod access_notify_exemptions; mod access_notify_lifecycle; diff --git a/crates/yserver-core/src/core_loop/process_request/tests/xi2.rs b/crates/yserver-core/src/core_loop/process_request/tests/xi2.rs index 67ffe0197..5c87feeac 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/xi2.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/xi2.rs @@ -829,7 +829,7 @@ fn xi_unknown_minor_is_bad_request() { } } -fn xi_select_body(window: u32, masks: &[(u16, &[u32])]) -> Vec { +pub(super) fn xi_select_body(window: u32, masks: &[(u16, &[u32])]) -> Vec { let mut b = Vec::new(); b.extend_from_slice(&window.to_le_bytes()); b.extend_from_slice(&u16::try_from(masks.len()).unwrap().to_le_bytes()); From d0d7308cddaf881ca9d6a395716e56bb66cb5a6d Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 15:01:47 -0300 Subject: [PATCH 11/72] fix(access): key stop predicate and grab owner writer (review r1) The per-selection stop decision is one function, client_key_plan, for one client at one window. It asks Receive lazily, only for a copy it would write, and returns that client's copies and whether one of its selections stops the focus walk. key_copies_at is the "any" of it over the window's clients, so Task 3 can call the same predicate for one foreign client. The grab owner's single copy goes through fanout_event_to_clients_with_receive with subject Window(grab window) and the core or XI2 key description. The key-specific grab_owner_allows helper is gone. Tests: frames a denial moves to another window are pinned in full with literal bytes (child, event coordinates, state), not by identity. Every such frame must have a literal entry and every entry must be written. Detectable repeat is set through XkbUseExtension and XkbPerClientFlags, and the slave grab through XIGrabDevice, not by seeding state. A new row covers an excluded XI2 master form that still stops the walk. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Haiku 5.5 --- .../yserver-core/src/core_loop/key_fanout.rs | 305 ++++++++++-------- .../process_request/tests/access_key_input.rs | 267 ++++++++++++--- 2 files changed, 391 insertions(+), 181 deletions(-) diff --git a/crates/yserver-core/src/core_loop/key_fanout.rs b/crates/yserver-core/src/core_loop/key_fanout.rs index cd0753fa1..b03304f02 100644 --- a/crates/yserver-core/src/core_loop/key_fanout.rs +++ b/crates/yserver-core/src/core_loop/key_fanout.rs @@ -16,7 +16,9 @@ use yserver_protocol::x11::{self, ClientId, ResourceId}; use crate::{ access::{EventBatch, EventDescription, EventSubject}, - core_loop::fanout::{fanout_event_to_clients, receive_allows, subscribers_by_id}, + core_loop::fanout::{ + fanout_event_to_clients, fanout_event_to_clients_with_receive, receive_allows, + }, host_x11::HostKeyEvent, nested::XI2_MAJOR_OPCODE, resources::ROOT_WINDOW, @@ -716,133 +718,161 @@ struct KeyCopies { stops: bool, } -/// Plans the key copies at `window` (Xorg `DeliverDeviceEvents`, one window). -/// -/// XI2 shadows core per client: a client with an allowed XI2 copy, or a -/// suppressed XI2 selection, does not get the core form (Xorg behaviour). A -/// client that selects both core and XI2, such as Chromium's Ozone X11 layer, -/// would otherwise get every keystroke twice. A denied XI2 copy reopens core -/// for that client. The forms of one client share subject and description, so -/// that client's XI2 copies take one Receive check. +/// One client's decision for one key event at one window. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct ClientKeyPlan { + /// The client gets its XI2 copies (allowed, not suppressed). + xi2_copy: bool, + /// The client gets the core copy. + core_copy: bool, + /// One of the client's selections here stops the focus walk. + stops: bool, +} + +/// The per-selection predicate of the input routing (spec l.353–420), for one +/// client at one window: whether its selections stop the focus walk, and which +/// copies it gets. The focus walk takes the "any" over the window's clients, and +/// a foreign-selector rejection (Task 3) calls the same function for one client. /// -/// `stops` is per selection: every selection counted by `key_selectors` -/// stops the walk when it produces no copy or its copy is allowed. -fn key_copies_at( +/// `receive` decides a copy's Receive result and is called only for a copy the +/// client would be written: a suppressed or excluded selection is never asked. +/// The XI2 forms of the client share one call. Core is asked only when not +/// shadowed by an allowed or suppressed XI2 selection. +fn client_key_plan( state: &ServerState, event: &HostKeyEvent, window: ResourceId, + client: ClientId, include_master_form: bool, include_core_form: bool, synthetic_repeat: bool, -) -> KeyCopies { + receive: &dyn Fn(EventDescription) -> bool, +) -> ClientKeyPlan { + let no_selection = ClientKeyPlan { + xi2_copy: false, + core_copy: false, + stops: false, + }; + let Some(record) = state.clients.get(&client.0) else { + return no_selection; + }; let mask_bit = if event.pressed { KEY_PRESS_MASK } else { KEY_RELEASE_MASK }; let evtype = xi2_evtype_for(event); - let subject = EventSubject::Window(window); let xi2_suppressed = synthetic_repeat && !event.pressed; - let all_forms = key_xi2_forms(state, event.origin); - let forms: Vec<(u16, u16)> = all_forms + let forms = key_xi2_forms(state, event.origin); + let included = + |device_id: u16| include_master_form || device_id != XI2_MASTER_KEYBOARD_DEVICE_ID; + let selected = |device_id: u16| key_xi2_form_selected(record, window, device_id, evtype); + let mut stops = false; + + // An XI2 selection the include flags exclude produces no copy: it stops. + if forms .iter() - .copied() - .filter(|(device_id, _)| include_master_form || *device_id != XI2_MASTER_KEYBOARD_DEVICE_ID) - .collect(); - let core_subscribers = subscribers_by_id(state, window, mask_bit); - let detectable_suppressed = |client: &ClientId| { - synthetic_repeat - && !event.pressed - && state - .xkb_clients - .get(&client.0) - .is_some_and(|flags| flags.wants_detectable_auto_repeat()) - }; + .any(|(device_id, _)| !included(*device_id) && selected(*device_id)) + { + stops = true; + } - // Clients with a selection in an included form, in write order. - let xi2_selected: Vec = state - .clients + // Included XI2 selections: a suppressed one produces no copy and stops; an + // allowed one produces a copy and stops; a denied one neither. + let selects_included_xi2 = forms .iter() - .filter(|(_, client)| { - forms - .iter() - .any(|(device_id, _)| key_xi2_form_selected(client, window, *device_id, evtype)) - }) - .map(|(id, _)| ClientId(*id)) - .collect(); - let xi2_batch = [crate::xinput::xi2_event_description(evtype)]; - let allowed_xi2: Vec = if xi2_suppressed { - Vec::new() + .any(|(device_id, _)| included(*device_id) && selected(*device_id)); + let xi2_copy = if !selects_included_xi2 { + false + } else if xi2_suppressed { + stops = true; + false } else { - xi2_selected - .iter() - .copied() - .filter(|client| receive_allows(state, *client, subject, &EventBatch::new(&xi2_batch))) - .collect() + let allowed = receive(crate::xinput::xi2_event_description(evtype)); + stops |= allowed; + allowed }; - // A suppressed XI2 selection shadows core too; a denied copy does not. - let shadows_core = |client: &ClientId| { - if xi2_suppressed { - xi2_selected.contains(client) - } else { - allowed_xi2.contains(client) - } - }; - - let core_batch = [EventDescription::core(if event.pressed { 2 } else { 3 })]; - let core: Vec = core_subscribers - .iter() - .copied() - .filter(|client| { - include_core_form && !shadows_core(client) && !detectable_suppressed(client) - }) - .filter(|client| receive_allows(state, *client, subject, &EventBatch::new(&core_batch))) - .collect(); - let xi2 = if xi2_suppressed { - Vec::new() + // Core: shadowed by an XI2 selection that is suppressed or allowed, excluded + // by the include flag, or detectable-repeat suppressed => no copy, stops. + let shadows_core = selects_included_xi2 && (xi2_suppressed || xi2_copy); + let core_selected = record.event_masks.get(&window).copied().unwrap_or(0) & mask_bit != 0; + let detectable_suppressed = xi2_suppressed + && state + .xkb_clients + .get(&client.0) + .is_some_and(|flags| flags.wants_detectable_auto_repeat()); + let core_copy = if !core_selected { + false + } else if !include_core_form || shadows_core || detectable_suppressed { + stops = true; + false } else { - forms - .iter() - .map(|&(device_id, source_id)| { - let targets = state - .clients - .iter() - .filter_map(|(id, client)| { - let id = ClientId(*id); - (allowed_xi2.contains(&id) - && key_xi2_form_selected(client, window, device_id, evtype)) - .then_some(id) - }) - .collect(); - (device_id, source_id, targets) - }) - .collect() + let allowed = receive(EventDescription::core(if event.pressed { 2 } else { 3 })); + stops |= allowed; + allowed }; - // Every selection key_selectors counts: a form the include flag excludes, - // a suppressed form, or an allowed form stops the walk; a denied one does not. - let form_stops = state.clients.iter().any(|(id, client)| { - let id = ClientId(*id); - all_forms.iter().any(|(device_id, _)| { - key_xi2_form_selected(client, window, *device_id, evtype) - && (!forms.iter().any(|(included, _)| included == device_id) - || xi2_suppressed - || allowed_xi2.contains(&id)) - }) - }); - let core_stops = core_subscribers.iter().any(|client| { - !include_core_form - || shadows_core(client) - || detectable_suppressed(client) - || core.contains(client) - }); - - KeyCopies { - core, - xi2, - stops: form_stops || core_stops, + ClientKeyPlan { + xi2_copy, + core_copy, + stops, + } +} + +/// Plans the key copies at `window` (Xorg `DeliverDeviceEvents`, one window): +/// the "any" of `client_key_plan` over the window's clients, in `state.clients` +/// order. Each recipient's Receive decisions are made by its plan, once. +fn key_copies_at( + state: &ServerState, + event: &HostKeyEvent, + window: ResourceId, + include_master_form: bool, + include_core_form: bool, + synthetic_repeat: bool, +) -> KeyCopies { + let subject = EventSubject::Window(window); + let mut stops = false; + let mut core = Vec::new(); + let mut xi2_recipients = Vec::new(); + for id in state.clients.keys() { + let client = ClientId(*id); + let plan = client_key_plan( + state, + event, + window, + client, + include_master_form, + include_core_form, + synthetic_repeat, + &|description| receive_allows(state, client, subject, &EventBatch::new(&[description])), + ); + stops |= plan.stops; + if plan.core_copy { + core.push(client); + } + if plan.xi2_copy { + xi2_recipients.push(client); + } } + let xi2 = key_xi2_forms(state, event.origin) + .into_iter() + .filter(|(device_id, _)| include_master_form || *device_id != XI2_MASTER_KEYBOARD_DEVICE_ID) + .map(|(device_id, source_id)| { + let targets = state + .clients + .iter() + .filter_map(|(id, record)| { + let client = ClientId(*id); + (xi2_recipients.contains(&client) + && key_xi2_form_selected(record, window, device_id, xi2_evtype_for(event))) + .then_some(client) + }) + .collect(); + (device_id, source_id, targets) + }) + .collect(); + KeyCopies { core, xi2, stops } } /// Writes a planned key event at `window`: the core form, then each XI2 form @@ -883,23 +913,6 @@ fn write_key_copies( dropped } -/// The Receive check for a grab owner's single copy. A missing owner gets no -/// copy, so it is not asked. -fn grab_owner_allows( - state: &ServerState, - owner: ClientId, - grab_window: ResourceId, - description: EventDescription, -) -> bool { - state.clients.contains_key(&owner.0) - && receive_allows( - state, - owner, - EventSubject::Window(grab_window), - &EventBatch::new(&[description]), - ) -} - /// Deliver a key event to the grab owner client, addressed to the /// grab window. When a passive (or explicit) keyboard grab is active, /// X11 delivers to the *grab owner* using the grab's event mask, not @@ -937,23 +950,26 @@ fn deliver_key_to_grab_owner( return Vec::new(); } let description = crate::xinput::xi2_event_description(xi2_evtype_for(event)); - if !grab_owner_allows(state, owner, grab_window, description) { - return Vec::new(); - } let source_id = resolve_key_xi_source(state, event.origin).map_or(device_id, |source| source.sourceid); - fanout_event_to_clients(state, &[owner], |buf, seq, order| { - encode_key_xi2_for_device( - buf, - order, - seq, - event, - fields, - device_id, - source_id, - synthetic_repeat, - ); - }) + fanout_event_to_clients_with_receive( + state, + &[owner], + EventSubject::Window(grab_window), + &EventBatch::new(&[description]), + |buf, seq, order| { + encode_key_xi2_for_device( + buf, + order, + seq, + event, + fields, + device_id, + source_id, + synthetic_repeat, + ); + }, + ) } else { if synthetic_repeat && !event.pressed @@ -965,12 +981,15 @@ fn deliver_key_to_grab_owner( return Vec::new(); } let description = EventDescription::core(if event.pressed { 2 } else { 3 }); - if !grab_owner_allows(state, owner, grab_window, description) { - return Vec::new(); - } - fanout_event_to_clients(state, &[owner], |buf, seq, order| { - x11::encode_key_event(buf, order, key_event_wire(event, seq, fields)); - }) + fanout_event_to_clients_with_receive( + state, + &[owner], + EventSubject::Window(grab_window), + &EventBatch::new(&[description]), + |buf, seq, order| { + x11::encode_key_event(buf, order, key_event_wire(event, seq, fields)); + }, + ) } } @@ -1596,7 +1615,7 @@ fn deliver_xi1_focused_key( /// Pointer-walk leg of Xorg `DeliverFocusedEvent`: if the pointer window P is /// the focus or a descendant of it, the walk starts at P and goes up to the -/// focus. It stops at the first window whose copies `stop`; otherwise the +/// focus. It stops at the first window whose copies stop (`KeyCopies::stops`); otherwise the /// focus is the target. Returns the target with its copies, so the focus is /// checked once. Under PointerRoot the walk is bounded at the root, not at P. fn focused_walk_target( diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs index 30e729673..15e732a37 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -1,19 +1,26 @@ //! Receive decisions in the focused key walk and XI2-over-core shadowing //! (PR 4c part 2, plan 1, task 2). //! -//! Each row builds its windows and selections through requests, pins the -//! pointer and focus, drives one host key through a production key entry, and -//! checks three runs: no policy, an explicit allow-all policy, and a policy -//! that denies the listed (client, description, window) copies. The no-policy -//! and allow-all runs must produce identical bytes. Each run is also checked -//! against literal per-client frames and literal Receive calls. A denied run's -//! bytes must be the allow-all bytes minus the denied key frames. +//! Each row builds its windows, selections, detectable repeat and slave grab +//! through requests, pins the pointer and focus, drives one host key through a +//! production key entry, and checks three runs: no policy, an explicit +//! allow-all policy, and a policy that denies the listed (client, check, +//! window) Receive calls. +//! +//! Every run is checked against literal per-client frames (kind, XI2 device, +//! event window, sequence, keycode) and literal per-client Receive calls. The +//! no-policy and allow-all streams must be byte-identical. A frame that both +//! the allow-all and the denied run write has the same bytes in both. A frame +//! only the denied run writes (a denial moved the walk to another window) is +//! pinned in full by the row's literal `moved` entry: child, event coordinates +//! and state. Every such frame must have a `moved` entry, and every entry must +//! be written. //! //! Receive calls are compared per client: `state.clients` is a HashMap, so the //! order across clients is not part of the contract. use super::{ - access_notify_support::{DENY, NotifyFixture, dec16, dec32, split_frames}, + access_notify_support::{DENY, NotifyFixture, dec16, dec32, enc16, enc32, split_frames}, extensions::{ExtensionHook, RecordedExtensionCheck}, xi2::xi_select_body, }; @@ -27,11 +34,10 @@ use crate::{ host_x11::HostKeyEvent, nested::XI2_MAJOR_OPCODE, resources::ROOT_WINDOW, - server::{ActiveKeyboardGrab, ActiveKeyboardGrabSource}, xinput::{DEVICEID_MASTER_KEYBOARD, DEVICEID_XTEST_KEYBOARD}, }; use std::{collections::BTreeMap, sync::atomic::Ordering}; -use yserver_protocol::x11::{ClientByteOrder, ClientId, RequestHeader, ResourceId, SequenceNumber}; +use yserver_protocol::x11::{ClientByteOrder, ClientId, RequestHeader, SequenceNumber}; const SEND_CLIENT: u32 = 1; /// The client that selects on the child window (A in the brief). @@ -103,12 +109,25 @@ struct Expect { calls: &'static [Call], } +/// A frame the denial moves to another window: the literal bytes the row pins. +/// Core KeyPress/KeyRelease only; the event is the key's, so only its window, +/// child and coordinates vary. +#[derive(Clone, Copy)] +struct Moved { + client: u32, + window: u32, + child: u32, + event: (i16, i16), +} + struct Row { name: &'static str, setup: fn(&mut NotifyFixture), drive: Drive, /// (client, check, window) Receive calls to deny. deny: &'static [Call], + /// Frames only the denied run writes, pinned in full. + moved: &'static [Moved], allow: Expect, denied: Expect, } @@ -116,8 +135,15 @@ struct Row { // ---- request helpers ----------------------------------------------------- /// Sends one request from `client` with the next sequence number of that -/// client, and checks it was handled with no error and no writer failure. -fn send(f: &mut NotifyFixture, client: u32, opcode: u8, data: u8, body: &[u8]) { +/// client, checks it was handled with no writer failure, and returns the bytes +/// the requester was sent (a reply, or nothing). +fn send_with_reply( + f: &mut NotifyFixture, + client: u32, + opcode: u8, + data: u8, + body: &[u8], +) -> Vec { let sequence = { let state = &f.state.clients[&client]; let next = state.last_sequence.load(Ordering::Relaxed).wrapping_add(1); @@ -140,7 +166,15 @@ fn send(f: &mut NotifyFixture, client: u32, opcode: u8, data: u8, body: &[u8]) { client_io::failed_writers(&f.state.clients).is_empty(), "request queued a disconnect" ); - assert!(f.drain(ClientId(client)).is_empty(), "requester got bytes"); + f.drain(ClientId(client)) +} + +/// `send_with_reply` for a request that has no reply and no error. +fn send(f: &mut NotifyFixture, client: u32, opcode: u8, data: u8, body: &[u8]) { + assert!( + send_with_reply(f, client, opcode, data, body).is_empty(), + "requester got bytes" + ); } /// Two windows: FOCUS (100,100) 200x200 and CHILD inside it at (10,10), both @@ -196,29 +230,71 @@ fn select_xi2(f: &mut NotifyFixture, client: u32, window: u32, device: u16, mask send(f, client, XI_MAJOR, XI_SELECT_EVENTS, &body); } -/// `client` gets the core key form for both key events on `window` (the -/// detectable-repeat client of the synthetic-release rows). +/// Detectable autorepeat for `client`: XkbPerClientFlags with +/// `XkbPCF_DetectableAutoRepeatMask`, after XkbUseExtension. Both go through the +/// XKB request dispatcher (`handle_xkb_request`), as the XKB tests drive them. fn set_detectable_repeat(f: &mut NotifyFixture, client: u32) { - f.state + const XKB_MAJOR: u8 = 136; + const XKB_USE_EXTENSION: u8 = 0; + const XKB_PER_CLIENT_FLAGS: u8 = 21; + const DETECTABLE_AUTO_REPEAT: u32 = 1; + xkb_request(f, client, XKB_MAJOR, XKB_USE_EXTENSION, &[1, 0, 0, 0]); + let mut body = vec![0_u8; 24]; + body[0..2].copy_from_slice(&0x0100_u16.to_le_bytes()); // XkbUseCoreKbd + body[4..8].copy_from_slice(&DETECTABLE_AUTO_REPEAT.to_le_bytes()); // change + body[8..12].copy_from_slice(&DETECTABLE_AUTO_REPEAT.to_le_bytes()); // value + xkb_request(f, client, XKB_MAJOR, XKB_PER_CLIENT_FLAGS, &body); + let flags = f + .state .xkb_clients - .entry(client) - .or_default() - .per_client_flags = 1; + .get(&client) + .copied() + .unwrap_or_default(); + assert!( + flags.wants_detectable_auto_repeat(), + "XkbPerClientFlags set detectable repeat" + ); } -/// The slave keyboard's exact XI2 grab owned by `owner` on `grab_window`. -fn grab_slave_keyboard(f: &mut NotifyFixture, owner: u32, grab_window: u32) { - f.state.xi2_keyboard_grabs.insert( - DEVICEID_XTEST_KEYBOARD, - ActiveKeyboardGrab { - owner: ClientId(owner), - grab_window: ResourceId(grab_window), - source: ActiveKeyboardGrabSource::Explicit, - owner_events: false, - via_xi2: true, - xi2_mask: XI_KEY_PRESS, +/// One XKB request through `handle_xkb_request`, with its reply drained. +fn xkb_request(f: &mut NotifyFixture, client: u32, opcode: u8, minor: u8, body: &[u8]) { + let sequence = { + let state = &f.state.clients[&client]; + let next = state.last_sequence.load(Ordering::Relaxed).wrapping_add(1); + state.last_sequence.store(next, Ordering::Relaxed); + next + }; + crate::core_loop::process_request::xkb::handle_xkb_request( + &mut f.state, + &mut f.backend, + None, + ClientId(client), + SequenceNumber(sequence), + RequestHeader { + opcode, + data: minor, + length_units: u32::try_from(1 + body.len().div_ceil(4)).expect("request length"), }, - ); + body, + ) + .expect("XKB request through handle_xkb_request"); + f.drain(ClientId(client)); +} + +/// The slave keyboard's exact XI2 grab owned by `owner` on `grab_window`, made +/// with XIGrabDevice (asynchronous, not owner-events, KeyPress mask). +fn grab_slave_keyboard(f: &mut NotifyFixture, owner: u32, grab_window: u32) { + const XI_GRAB_DEVICE: u8 = 51; + let mut body = Vec::with_capacity(28); + body.extend_from_slice(&grab_window.to_le_bytes()); + body.extend_from_slice(&[0; 8]); // CurrentTime, no cursor + body.extend_from_slice(&DEVICEID_XTEST_KEYBOARD.to_le_bytes()); + body.extend_from_slice(&[1, 1, 0, 0]); // async modes, owner_events false + body.extend_from_slice(&1_u16.to_le_bytes()); // one mask word + body.extend_from_slice(&XI_KEY_PRESS.to_le_bytes()); + let bytes = send_with_reply(f, owner, XI_MAJOR, XI_GRAB_DEVICE, &body); + let reply = &bytes[bytes.len() - 32..]; + assert_eq!((reply[0], reply[8]), (1, 0), "XIGrabDevice replies Success"); } // ---- run and decode ------------------------------------------------------ @@ -448,9 +524,29 @@ fn check_run(row: &Row, run: &Run, expect: &Expect, mode: &str) { ); } -/// Runs one row under the three modes and checks it against its literal -/// expectations, the byte identity of no-policy and allow-all, and the -/// denied run's bytes as the allow-all bytes minus the denied key frames. +/// The full 32 bytes of a core key frame the denial moved, with the row's +/// press flag, the frame's sequence and the recipient's byte order. +fn literal_moved(pressed: bool, order: ClientByteOrder, sequence: u16, moved: &Moved) -> Vec { + let mut bytes = vec![if pressed { 2 } else { 3 }, KEYCODE]; + bytes.extend(enc16(order, sequence)); + bytes.extend(enc32(order, TIME)); + bytes.extend(enc32(order, ROOT_WINDOW.0)); + bytes.extend(enc32(order, moved.window)); + bytes.extend(enc32(order, moved.child)); + bytes.extend(enc16(order, POINTER.0 as u16)); + bytes.extend(enc16(order, POINTER.1 as u16)); + bytes.extend(enc16(order, moved.event.0 as u16)); + bytes.extend(enc16(order, moved.event.1 as u16)); + bytes.extend(enc16(order, 0)); // state + bytes.extend([1, 0]); // same-screen, pad + assert_eq!(bytes.len(), 32); + bytes +} + +/// Runs one row under the three modes and checks it: literal frames and Receive +/// calls per run, byte identity of no-policy and allow-all, identical bytes for +/// a frame both allow-all and denied write, and literal bytes for each frame +/// only the denied run writes. fn check_row(row: &Row) { let name = row.name; let plain = run(row, None); @@ -475,10 +571,13 @@ fn check_row(row: &Row) { let denied = run(row, Some(row.deny)); check_run(row, &denied, &row.denied, "denial"); assert_eq!(denied.state, allow.state, "{name}: denial changed state"); - // A frame that exists in both runs has the same bytes. A denial can also - // add a frame the allow-all run did not write (the walk moved on), which - // the literal frame list above already pins. - for (got, allowed) in denied.clients.iter().zip(&allow.clients) { + let mut moved_seen = 0; + for got in &denied.clients { + let allowed = allow + .clients + .iter() + .find(|c| c.client == got.client) + .expect("allow-all stream for the client"); let allowed_frames: Vec<(Kind, u32, &[u8])> = split_frames(&allowed.bytes, allowed.order) .into_iter() .filter_map(|frame| { @@ -498,9 +597,28 @@ fn check_row(row: &Row) { "{name}: client {} {kind:?} @{window:#x} bytes under denial", got.client ); + continue; } + let moved = row + .moved + .iter() + .find(|m| m.client == got.client && m.window == window && kind == Kind::Core) + .unwrap_or_else(|| { + panic!( + "{name}: client {} {kind:?} @{window:#x} is moved by the denial and has no literal", + got.client + ) + }); + assert_eq!( + frame, + literal_moved(row.drive.pressed(), got.order, got.sequence, moved).as_slice(), + "{name}: client {} moved frame @{window:#x}", + got.client + ); + moved_seen += 1; } } + assert_eq!(moved_seen, row.moved.len(), "{name}: moved frames written"); } // ---- rows ---------------------------------------------------------------- @@ -527,6 +645,12 @@ const K1: Row = Row { frames: &[(B, Kind::Core, FOCUS)], calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, FOCUS)], }, + moved: &[Moved { + client: B, + window: FOCUS, + child: CHILD, + event: (20, 20), + }], }; fn setup_k2(f: &mut NotifyFixture) { @@ -552,6 +676,7 @@ const K2: Row = Row { frames: &[(B, Kind::Core, CHILD)], calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, CHILD)], }, + moved: &[], }; /// A selects XI2 (master) and core on CHILD; B selects core on FOCUS. @@ -578,6 +703,12 @@ const K3_XI2_DENIED: Row = Row { frames: &[(A, Kind::Core, CHILD)], calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], }, + moved: &[Moved { + client: A, + window: CHILD, + child: 0, + event: (10, 10), + }], }; const K3_BOTH_DENIED: Row = Row { @@ -600,6 +731,12 @@ const K3_BOTH_DENIED: Row = Row { (B, CallKind::Core, FOCUS), ], }, + moved: &[Moved { + client: B, + window: FOCUS, + child: CHILD, + event: (20, 20), + }], }; /// A selects XI2 on the master (3) and slave (5) keyboards and core on CHILD. @@ -644,6 +781,7 @@ const K4_ALLOWED: Row = Row { ], calls: &[(A, CallKind::Xi2, CHILD)], }, + moved: &[], }; const K4_XI2_DENIED: Row = Row { @@ -665,6 +803,12 @@ const K4_XI2_DENIED: Row = Row { frames: &[(A, Kind::Core, CHILD)], calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], }, + moved: &[Moved { + client: A, + window: CHILD, + child: 0, + event: (10, 10), + }], }; /// Synthetic release: A selects only XI2 KeyRelease on CHILD; B core on FOCUS. @@ -692,6 +836,7 @@ const K5_XI2_SUPPRESSED: Row = Row { frames: &[], calls: &[], }, + moved: &[], }; /// Synthetic release with a detectable-repeat core selector on CHILD. @@ -720,6 +865,7 @@ const K5_DETECTABLE_SUPPRESSED: Row = Row { frames: &[], calls: &[], }, + moved: &[], }; /// Slave origin with the master transition rejected: the core form is excluded @@ -749,6 +895,37 @@ const K5B_EXCLUDED_FORM_STILL_STOPS: Row = Row { frames: &[], calls: &[(A, CallKind::Xi2, CHILD)], }, + moved: &[], +}; + +/// Slave origin with the master transition rejected: A also selects the master +/// XI2 form on CHILD, which the include flags exclude, so it stops the walk with +/// no copy and no Receive call. B selects the slave form on FOCUS. +fn setup_k5b_master(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, CHILD, DEVICEID_MASTER_KEYBOARD, XI_KEY_PRESS); + select_xi2(f, B, FOCUS, DEVICEID_XTEST_KEYBOARD, XI_KEY_PRESS); +} + +const K5B_EXCLUDED_MASTER_FORM_STILL_STOPS: Row = Row { + name: "k5b_excluded_master_form_still_stops", + setup: setup_k5b_master, + drive: Drive::After { + origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), + pressed: true, + master: false, + synthetic: false, + }, + deny: &[(A, CallKind::Xi2, CHILD)], + moved: &[], + allow: Expect { + frames: &[], + calls: &[], + }, + denied: Expect { + frames: &[], + calls: &[], + }, }; /// The slave origin through its exact XI2 grab: the grab owner gets the copy. @@ -775,6 +952,7 @@ const K5C_SLAVE_GRAB_OWNER: Row = Row { frames: &[], calls: &[(A, CallKind::Xi2, FOCUS)], }, + moved: &[], }; /// The slave origin through the slave focus path, with no grab. @@ -801,6 +979,7 @@ const K5C_SLAVE_FOCUS_PATH: Row = Row { frames: &[], calls: &[(A, CallKind::Xi2, CHILD)], }, + moved: &[], }; /// A selects core on CHILD and FOCUS; B selects core on FOCUS. @@ -831,6 +1010,12 @@ const K6A_ALL_DENIED_LANDS_ON_FOCUS: Row = Row { (B, CallKind::Core, FOCUS), ], }, + moved: &[Moved { + client: B, + window: FOCUS, + child: CHILD, + event: (20, 20), + }], }; /// Only A selects, on CHILD and FOCUS, and A is denied everywhere. @@ -856,6 +1041,7 @@ const K6B_ATTEMPT_LANDS_ON_FOCUS: Row = Row { frames: &[], calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], }, + moved: &[], }; #[test] @@ -903,6 +1089,11 @@ fn k5b_form_excluded_by_the_include_flags_still_stops() { check_row(&K5B_EXCLUDED_FORM_STILL_STOPS); } +#[test] +fn k5b_excluded_master_form_still_stops() { + check_row(&K5B_EXCLUDED_MASTER_FORM_STILL_STOPS); +} + #[test] fn k5c_slave_grab_write_is_checked() { check_row(&K5C_SLAVE_GRAB_OWNER); From 4a4aa747e06d72b15ebc71147a2f8f1bcbb94861 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 15:04:21 -0300 Subject: [PATCH 12/72] docs(plans): 4c part 2 plan 1, Task 3 expectations after Task 2 Co-Authored-By: Claude Opus 5.5 --- .../plans/2026-12-01-access-control-pr4c-keyboard.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md b/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md index 50b7fe8eb..5b28688cb 100644 --- a/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md +++ b/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md @@ -119,7 +119,7 @@ Rules (spec l.414–429): - `k10_suppressed_foreign_selector_still_rejects` (today's behaviour kept): an explicit core `GrabKeyboard` with `owner_events = true` on grab window G. O has no detectable repeat. C lies inside P, on the walk to the focus. O selects on P, the grab window is G ≠ P, and F selects XI2 KeyRelease on C. A synthetic release (F's XI2 copy is suppressed) → O gets the release with event window G, and there is no Receive call for F. Kills: the no-copy rule ignored for foreign selectors (under that mutation, O gets it at P). - `k11_denied_grab_window_copy_is_delivered`: `owner_events` false, O denied at grab window → no bytes anywhere, focus selectors get nothing, grab still active. - `k12_denied_activating_press_still_activates_and_freezes`: sync passive GrabKey, O denied → no bytes; `active_keyboard_grab` set; `xi1_frozen[device].stored` holds the press and the state is `FrozenWithEvent`. Review focus 5. -- [ ] **Step 2:** run; Expected: k7, k8, k9 and k11 FAIL; k12 fails on the byte assertion only. k10 passes today: it guards today's behaviour against the change. +- [ ] **Step 2:** run; Expected: k7, k8 and k9 FAIL. k10, k11 and k12 pass already: Task 2 routes every grab-owner write through `fanout_event_to_clients_with_receive` (grab-window check, denial counts as delivered), so they guard that behaviour. Task 3 must remove that check from the natural owner-events write, because the natural decision's result is reused there (k7 asserts exactly one owner call per window). - [ ] **Step 3: implement.** - [ ] **Step 4:** run filter + whole `--lib`; Expected PASS; existing grab tests (`sync_passive_key_grab_delivers_to_owner_and_freezes`, XTS-derived ones) unchanged. - [ ] **Step 5: commit** `feat(access): Receive decides grabbed key delivery`. From 8cfdf64ccd33a19e783658abc5fa2bb5f313bc6b Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 15:12:37 -0300 Subject: [PATCH 13/72] feat(access): Receive decides grabbed key delivery The natural owner_events walk asks Receive once per window, for the grab owner's copy in the grab's protocol. An allowed or suppressed copy qualifies the owner and the natural write reuses that answer, unchecked. A denied copy does not qualify it, and the walk continues. A foreign selector rejects the grabbed walk only when its copy stops under the per-selection predicate, with both form classes included, and the event's synthetic repeat. Foreign clients are checked only when the owner does not qualify, so no phantom check is recorded. The grab-window copy (owner_events false, the activating press, and the fallback) stays a fresh checked write, and a denial counts as delivered. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Haiku 5.5 --- .../yserver-core/src/core_loop/key_fanout.rs | 201 ++++++--- .../process_request/tests/access_key_input.rs | 397 ++++++++++++++++++ 2 files changed, 548 insertions(+), 50 deletions(-) diff --git a/crates/yserver-core/src/core_loop/key_fanout.rs b/crates/yserver-core/src/core_loop/key_fanout.rs index b03304f02..c9f853ae6 100644 --- a/crates/yserver-core/src/core_loop/key_fanout.rs +++ b/crates/yserver-core/src/core_loop/key_fanout.rs @@ -12,7 +12,7 @@ //! mirrors it across clients), so the helper picks the first non-ROOT //! focus it sees. When every client is rooted, the event is dropped. -use yserver_protocol::x11::{self, ClientId, ResourceId}; +use yserver_protocol::x11::{self, ClientByteOrder, ClientId, ResourceId, SequenceNumber}; use crate::{ access::{EventBatch, EventDescription, EventSubject}, @@ -549,6 +549,7 @@ fn deliver_routed_key_with_master_status( grab.via_xi2, device_id, synthetic_repeat, + true, ); merge_dropped( &mut dropped, @@ -610,10 +611,12 @@ fn deliver_routed_key_with_master_status( // The activating press skips the walk: ActivatePassiveGrab // sends it to the grab window (GH #277). let natural = if owner_events && !activating { - key_grabbed_natural_target(state, &event, owner) + key_grabbed_natural_target(state, &event, owner, via_xi2, synthetic_repeat) } else { None }; + // A natural target was already decided by `key_grabbed_natural_target` + // (unchecked write). The grab-window copy is a fresh check. let mut dropped = if let Some(target) = natural { deliver_key_to_grab_owner( state, @@ -623,6 +626,7 @@ fn deliver_routed_key_with_master_status( via_xi2, grab_device_id, synthetic_repeat, + false, ) } else { deliver_key_to_grab_owner( @@ -633,6 +637,7 @@ fn deliver_routed_key_with_master_status( via_xi2, grab_device_id, synthetic_repeat, + true, ) }; // XI1 leg runs under grabs too — the router handles its @@ -935,6 +940,7 @@ fn write_key_copies( /// state — observed as "can't type in the Cinnamon keyring dialog" /// (x11trace: keycode delivered as both core KeyPress and XI2 /// XI_KeyPress to the same window). +#[allow(clippy::too_many_arguments)] fn deliver_key_to_grab_owner( state: &mut ServerState, event: &HostKeyEvent, @@ -943,54 +949,140 @@ fn deliver_key_to_grab_owner( via_xi2: bool, device_id: u16, synthetic_repeat: bool, + checked: bool, ) -> Vec { + if grab_owner_copy_suppressed(state, event, owner, via_xi2, synthetic_repeat) { + return Vec::new(); + } let fields = key_window_fields(state, event, grab_window); + let subject = EventSubject::Window(grab_window); + let description = grab_owner_description(event, via_xi2); + // `checked` is false only for a natural target whose owner copy + // `key_grabbed_natural_target` already decided: the write then skips Receive. if via_xi2 { - if synthetic_repeat && !event.pressed { - return Vec::new(); - } - let description = crate::xinput::xi2_event_description(xi2_evtype_for(event)); let source_id = resolve_key_xi_source(state, event.origin).map_or(device_id, |source| source.sourceid); - fanout_event_to_clients_with_receive( - state, - &[owner], - EventSubject::Window(grab_window), - &EventBatch::new(&[description]), - |buf, seq, order| { - encode_key_xi2_for_device( - buf, - order, - seq, - event, - fields, - device_id, - source_id, - synthetic_repeat, - ); - }, - ) + let encode = |buf: &mut Vec, seq: SequenceNumber, order: ClientByteOrder| { + encode_key_xi2_for_device( + buf, + order, + seq, + event, + fields, + device_id, + source_id, + synthetic_repeat, + ); + }; + if checked { + fanout_event_to_clients_with_receive( + state, + &[owner], + subject, + &EventBatch::new(&[description]), + encode, + ) + } else { + fanout_event_to_clients(state, &[owner], encode) + } } else { - if synthetic_repeat - && !event.pressed - && state - .xkb_clients - .get(&owner.0) - .is_some_and(|flags| flags.wants_detectable_auto_repeat()) - { - return Vec::new(); + let encode = |buf: &mut Vec, seq: SequenceNumber, order: ClientByteOrder| { + x11::encode_key_event(buf, order, key_event_wire(event, seq, fields)); + }; + if checked { + fanout_event_to_clients_with_receive( + state, + &[owner], + subject, + &EventBatch::new(&[description]), + encode, + ) + } else { + fanout_event_to_clients(state, &[owner], encode) } - let description = EventDescription::core(if event.pressed { 2 } else { 3 }); - fanout_event_to_clients_with_receive( + } +} + +/// The grab owner's copy is not written: a synthetic XI2 release, or a +/// synthetic core release to a detectable-repeat owner (Xorg suppresses the +/// same copies, dix/events.c). The suppressed copy is never asked of Receive. +fn grab_owner_copy_suppressed( + state: &ServerState, + event: &HostKeyEvent, + owner: ClientId, + via_xi2: bool, + synthetic_repeat: bool, +) -> bool { + if !synthetic_repeat || event.pressed { + return false; + } + via_xi2 + || state + .xkb_clients + .get(&owner.0) + .is_some_and(|flags| flags.wants_detectable_auto_repeat()) +} + +/// The description of the owner's copy in the grab's protocol. +fn grab_owner_description(event: &HostKeyEvent, via_xi2: bool) -> EventDescription { + if via_xi2 { + crate::xinput::xi2_event_description(xi2_evtype_for(event)) + } else { + EventDescription::core(if event.pressed { 2 } else { 3 }) + } +} + +/// Whether the grab owner qualifies for the key at `window`: its copy in the +/// grab's protocol is suppressed, or Receive allows it. It is asked once here, +/// and the natural write reuses the answer. +fn grab_owner_qualifies( + state: &ServerState, + event: &HostKeyEvent, + owner: ClientId, + window: ResourceId, + via_xi2: bool, + synthetic_repeat: bool, +) -> bool { + grab_owner_copy_suppressed(state, event, owner, via_xi2, synthetic_repeat) + || receive_allows( state, - &[owner], - EventSubject::Window(grab_window), - &EventBatch::new(&[description]), - |buf, seq, order| { - x11::encode_key_event(buf, order, key_event_wire(event, seq, fields)); - }, + owner, + EventSubject::Window(window), + &EventBatch::new(&[grab_owner_description(event, via_xi2)]), ) - } +} + +/// Whether a client other than `owner` rejects the grabbed walk at `window`: +/// one of its selections there stops under the per-selection predicate, with +/// both form classes included. A denied copy does not reject. +fn foreign_selection_rejects( + state: &ServerState, + event: &HostKeyEvent, + owner: ClientId, + window: ResourceId, + synthetic_repeat: bool, +) -> bool { + let subject = EventSubject::Window(window); + state + .clients + .keys() + .map(|id| ClientId(*id)) + .filter(|client| *client != owner) + .any(|client| { + client_key_plan( + state, + event, + window, + client, + true, + true, + synthetic_repeat, + &|description| { + receive_allows(state, client, subject, &EventBatch::new(&[description])) + }, + ) + .stops + }) } fn xi2_evtype_for(event: &HostKeyEvent) -> u16 { @@ -1692,16 +1784,20 @@ fn key_selectors( clients } -/// Natural-delivery probe for an `owner_events` keyboard grab — the -/// keyboard analogue of `pointer_fanout::grabbed_natural_target` -/// (Xorg `DeliverDeviceEvents` with the grab as client filter): walk -/// from the pointer window (if inside the focus subtree) or the focus -/// up; at the FIRST window with any subscriber, deliver there if the -/// grab owner is among them, else abort (grab-window fallback). +/// Natural-delivery probe for an `owner_events` keyboard grab, Xorg +/// `DeliverDeviceEvents` with the grab as client filter. It walks from the +/// pointer window (if inside the focus subtree) or the focus up. At each window: +/// the owner qualifies when it selects the key there and its copy in the grab's +/// protocol is allowed or suppressed, and the walk delivers there. Otherwise a +/// foreign selector whose copy stops the walk rejects it, and the grab window +/// gets the key (`None`). Otherwise the walk continues to today's stop. +/// Foreign clients are checked only when the owner does not qualify. fn key_grabbed_natural_target( state: &ServerState, event: &HostKeyEvent, owner: ClientId, + via_xi2: bool, + synthetic_repeat: bool, ) -> Option { let mask_bit = if event.pressed { KEY_PRESS_MASK @@ -1735,9 +1831,14 @@ fn key_grabbed_natural_target( }; let mut cur = start; for _ in 0..256 { - let subs = key_selectors(state, event, cur, mask_bit); - if !subs.is_empty() { - return subs.contains(&owner).then_some(cur); + let owner_selects = key_selectors(state, event, cur, mask_bit).contains(&owner); + if owner_selects + && grab_owner_qualifies(state, event, owner, cur, via_xi2, synthetic_repeat) + { + return Some(cur); + } + if foreign_selection_rejects(state, event, owner, cur, synthetic_repeat) { + return None; } if cur == stop { return None; diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs index 15e732a37..da86dbe92 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -34,6 +34,7 @@ use crate::{ host_x11::HostKeyEvent, nested::XI2_MAJOR_OPCODE, resources::ROOT_WINDOW, + server::{QueuedInputEvent, Xi1SyncState}, xinput::{DEVICEID_MASTER_KEYBOARD, DEVICEID_XTEST_KEYBOARD}, }; use std::{collections::BTreeMap, sync::atomic::Ordering}; @@ -62,6 +63,8 @@ const KEY_RELEASE: u32 = 2; const XI_KEY_PRESS: u32 = 1 << 2; const XI_KEY_RELEASE: u32 = 1 << 3; const XI_KEY_PRESS_AND_RELEASE: u32 = XI_KEY_PRESS | XI_KEY_RELEASE; +/// The grab window of the grab rows: the root is on no walk to FOCUS. +const ROOT: u32 = ROOT_WINDOW.0; /// One frame the server writes: (client, what it is, event window). type Frame = (u32, Kind, u32); @@ -297,6 +300,39 @@ fn grab_slave_keyboard(f: &mut NotifyFixture, owner: u32, grab_window: u32) { assert_eq!((reply[0], reply[8]), (1, 0), "XIGrabDevice replies Success"); } +/// The core GrabKeyboard request by `owner` on `window`, asynchronous pointer +/// mode, with `owner_events`. The reply must be Success. +fn grab_keyboard(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: bool) { + const CORE_GRAB_KEYBOARD: u8 = 31; + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&[0; 4]); // CurrentTime + body.extend_from_slice(&[1, 1, 0, 0]); // async pointer, async keyboard + let bytes = send_with_reply(f, owner, CORE_GRAB_KEYBOARD, u8::from(owner_events), &body); + let reply = &bytes[bytes.len() - 32..]; + assert_eq!((reply[0], reply[1]), (1, 0), "GrabKeyboard replies Success"); +} + +/// The core GrabKey request by `owner` on `window` for `KEYCODE` with no +/// modifiers, asynchronous pointer mode and the given keyboard mode. +fn grab_key( + f: &mut NotifyFixture, + owner: u32, + window: u32, + owner_events: bool, + keyboard_sync: bool, +) { + const CORE_GRAB_KEY: u8 = 33; + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&0_u16.to_le_bytes()); // modifiers + body.push(KEYCODE); + body.push(1); // pointer async + body.push(u8::from(!keyboard_sync)); // keyboard: 0 sync, 1 async + body.extend_from_slice(&[0; 3]); + send(f, owner, CORE_GRAB_KEY, u8::from(owner_events), &body); +} + // ---- run and decode ------------------------------------------------------ fn key_event(origin: InputOrigin, pressed: bool) -> HostKeyEvent { @@ -400,10 +436,19 @@ struct ClientBytes { bytes: Vec, } +/// The keyboard grab and the master XI1 freeze after a run: whether an active +/// keyboard grab exists, and the master freeze state with the stored press. +#[derive(Debug, PartialEq, Eq)] +struct GrabState { + active: bool, + freeze: Option<(Xi1SyncState, Option<(bool, u8)>)>, +} + struct Run { clients: Vec, calls: Vec, state: String, + grab: GrabState, } fn run(row: &Row, policy: Option<&'static [Call]>) -> Run { @@ -463,10 +508,27 @@ fn run(row: &Row, policy: Option<&'static [Call]>) -> Run { }) .unwrap_or_default(); let state = format!("{:?}", (f.state.core_focus.raw, f.state.keys_down)); + let grab = GrabState { + active: f.state.active_keyboard_grab.is_some(), + freeze: f + .state + .xi1_frozen + .get(&DEVICEID_MASTER_KEYBOARD) + .map(|freeze| { + let stored = match &freeze.stored { + Some(QueuedInputEvent::HostKeyTransition(event, _, _)) => { + Some((event.pressed, event.keycode)) + } + _ => None, + }; + (freeze.state, stored) + }), + }; Run { clients, calls, state, + grab, } } @@ -571,6 +633,10 @@ fn check_row(row: &Row) { let denied = run(row, Some(row.deny)); check_run(row, &denied, &row.denied, "denial"); assert_eq!(denied.state, allow.state, "{name}: denial changed state"); + assert_eq!( + denied.grab, allow.grab, + "{name}: denial changed the grab and freeze state" + ); let mut moved_seen = 0; for got in &denied.clients { let allowed = allow @@ -1044,6 +1110,280 @@ const K6B_ATTEMPT_LANDS_ON_FOCUS: Row = Row { moved: &[], }; +// ---- grabbed rows: A is the grab owner (O), B is the foreign selector (F) ---- + +/// A grabs the keyboard with owner_events on the root and selects core presses +/// on CHILD (the pointer window) and FOCUS. +fn setup_k7(f: &mut NotifyFixture) { + tree(f); + grab_keyboard(f, A, ROOT, true); + select_core(f, A, CHILD, KEY_PRESS); + select_core(f, A, FOCUS, KEY_PRESS); +} + +const K7_OWNER_DENIED_ON_POINTER_WINDOW: Row = Row { + name: "k7_denied_owner_copy_continues_the_natural_walk", + setup: setup_k7, + drive: Drive::Entry { + origin: InputOrigin::NestedHost, + pressed: true, + }, + deny: &[(A, CallKind::Core, CHILD)], + allow: Expect { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Core, FOCUS)], + calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + }, + moved: &[Moved { + client: A, + window: FOCUS, + child: CHILD, + event: (20, 20), + }], +}; + +/// A grabs with owner_events on the root and selects core on CHILD; B selects +/// core on CHILD too. A is denied at CHILD, so B's allowed copy is the +/// foreign rejection and the grab window gets the key. +fn setup_k8(f: &mut NotifyFixture) { + tree(f); + grab_keyboard(f, A, ROOT, true); + select_core(f, A, CHILD, KEY_PRESS); + select_core(f, B, CHILD, KEY_PRESS); +} + +const K8_ALLOWED_FOREIGN_FALLS_BACK: Row = Row { + name: "k8_denied_owner_with_allowed_foreign_falls_back", + setup: setup_k8, + drive: Drive::Entry { + origin: InputOrigin::NestedHost, + pressed: true, + }, + deny: &[(A, CallKind::Core, CHILD)], + allow: Expect { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Core, ROOT)], + calls: &[ + (A, CallKind::Core, CHILD), + (B, CallKind::Core, CHILD), + (A, CallKind::Core, ROOT), + ], + }, + moved: &[Moved { + client: A, + window: ROOT, + child: FOCUS, + event: (120, 120), + }], +}; + +/// B alone selects core on CHILD and is denied there, so it does not reject; +/// A selects core on FOCUS, which is allowed. +fn setup_k9(f: &mut NotifyFixture) { + tree(f); + grab_keyboard(f, A, ROOT, true); + select_core(f, B, CHILD, KEY_PRESS); + select_core(f, A, FOCUS, KEY_PRESS); +} + +const K9_DENIED_FOREIGN_DOES_NOT_REJECT: Row = Row { + name: "k9_denied_foreign_selector_does_not_reject", + setup: setup_k9, + drive: Drive::Entry { + origin: InputOrigin::NestedHost, + pressed: true, + }, + deny: &[(B, CallKind::Core, CHILD)], + allow: Expect { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, ROOT)], + }, + denied: Expect { + frames: &[(A, Kind::Core, FOCUS)], + calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + }, + moved: &[Moved { + client: A, + window: FOCUS, + child: CHILD, + event: (20, 20), + }], +}; + +/// A and B both select core on CHILD and B is denied. A qualifies first, so the +/// walk stops at CHILD and no check is made for B. +fn setup_k9_same_window(f: &mut NotifyFixture) { + tree(f); + grab_keyboard(f, A, ROOT, true); + select_core(f, A, CHILD, KEY_PRESS); + select_core(f, B, CHILD, KEY_PRESS); +} + +const K9_OWNER_QUALIFIES_FIRST: Row = Row { + name: "k9_owner_on_the_same_window_qualifies_first", + setup: setup_k9_same_window, + drive: Drive::Entry { + origin: InputOrigin::NestedHost, + pressed: true, + }, + deny: &[(B, CallKind::Core, CHILD)], + allow: Expect { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + }, + moved: &[], +}; + +/// A selects core release on FOCUS and grabs with owner_events on the root. B +/// selects XI2 release on CHILD: the synthetic release of that form is +/// suppressed, so B stops the walk with no copy and no Receive call. +fn setup_k10(f: &mut NotifyFixture) { + tree(f); + grab_keyboard(f, A, ROOT, true); + select_core(f, A, FOCUS, KEY_RELEASE); + select_xi2(f, B, CHILD, DEVICEID_MASTER_KEYBOARD, XI_KEY_RELEASE); +} + +const K10_SUPPRESSED_FOREIGN_STILL_REJECTS: Row = Row { + name: "k10_suppressed_foreign_selector_still_rejects", + setup: setup_k10, + drive: Drive::After { + origin: InputOrigin::NestedHost, + pressed: false, + master: true, + synthetic: true, + }, + deny: &[], + allow: Expect { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(A, CallKind::Core, ROOT)], + }, + denied: Expect { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(A, CallKind::Core, ROOT)], + }, + moved: &[], +}; + +/// A grabs with owner_events false on the root; B selects core press on FOCUS. +/// The grab-window copy is denied: no bytes, and B gets nothing. +fn setup_k11(f: &mut NotifyFixture) { + tree(f); + grab_keyboard(f, A, ROOT, false); + select_core(f, B, FOCUS, KEY_PRESS); +} + +const K11_GRAB_WINDOW_DENIAL_DELIVERS: Row = Row { + name: "k11_denied_grab_window_copy_is_delivered", + setup: setup_k11, + drive: Drive::Entry { + origin: InputOrigin::NestedHost, + pressed: true, + }, + deny: &[(A, CallKind::Core, ROOT)], + allow: Expect { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(A, CallKind::Core, ROOT)], + }, + denied: Expect { + frames: &[], + calls: &[(A, CallKind::Core, ROOT)], + }, + moved: &[], +}; + +/// A holds a synchronous passive GrabKey on the root (owner_events false) and +/// B selects core press on FOCUS. The activating press is denied to A: the +/// grab still activates and freezes with the press stored. +fn setup_k12(f: &mut NotifyFixture) { + tree(f); + grab_key(f, A, ROOT, false, true); + select_core(f, B, FOCUS, KEY_PRESS); +} + +const K12_ACTIVATING_DENIAL_ACTIVATES: Row = Row { + name: "k12_denied_activating_press_still_activates_and_freezes", + setup: setup_k12, + drive: Drive::Entry { + origin: InputOrigin::NestedHost, + pressed: true, + }, + deny: &[(A, CallKind::Core, ROOT)], + allow: Expect { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(A, CallKind::Core, ROOT)], + }, + denied: Expect { + frames: &[], + calls: &[(A, CallKind::Core, ROOT)], + }, + moved: &[], +}; + +/// A holds the slave keyboard's exact XI2 grab on FOCUS (owner_events false). +/// The synthetic XI2 release is suppressed in the grab's protocol: no bytes and +/// no Receive call. +const K13_SYNTHETIC_XI2_RELEASE_SUPPRESSED: Row = Row { + name: "k13_synthetic_xi2_release_to_a_grab_owner_is_suppressed", + setup: setup_k5c_grab, + drive: Drive::After { + origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), + pressed: false, + master: false, + synthetic: true, + }, + deny: &[], + allow: Expect { + frames: &[], + calls: &[], + }, + denied: Expect { + frames: &[], + calls: &[], + }, + moved: &[], +}; + +/// A holds a core keyboard grab on the root (owner_events false) and has +/// detectable repeat. The synthetic core release is suppressed for A: no bytes, +/// no Receive call. +fn setup_k13_detectable(f: &mut NotifyFixture) { + tree(f); + grab_keyboard(f, A, ROOT, false); + set_detectable_repeat(f, A); +} + +const K13_DETECTABLE_CORE_RELEASE_SUPPRESSED: Row = Row { + name: "k13_synthetic_detectable_core_release_to_a_grab_owner_is_suppressed", + setup: setup_k13_detectable, + drive: Drive::After { + origin: InputOrigin::NestedHost, + pressed: false, + master: true, + synthetic: true, + }, + deny: &[], + allow: Expect { + frames: &[], + calls: &[], + }, + denied: Expect { + frames: &[], + calls: &[], + }, + moved: &[], +}; + #[test] fn k1_denied_pointer_window_selector_advances_the_focus_walk() { check_row(&K1); @@ -1113,3 +1453,60 @@ fn k6_all_denied_lands_on_focus_with_a_stopping_focus_selector() { fn k6_only_selector_denied_lands_on_focus_and_writes_nothing() { check_row(&K6B_ATTEMPT_LANDS_ON_FOCUS); } + +#[test] +fn k7_denied_owner_copy_continues_the_natural_walk() { + check_row(&K7_OWNER_DENIED_ON_POINTER_WINDOW); +} + +#[test] +fn k8_denied_owner_with_allowed_foreign_falls_back() { + check_row(&K8_ALLOWED_FOREIGN_FALLS_BACK); +} + +#[test] +fn k9_denied_foreign_selector_does_not_reject() { + check_row(&K9_DENIED_FOREIGN_DOES_NOT_REJECT); +} + +#[test] +fn k9_owner_on_the_same_window_qualifies_first() { + check_row(&K9_OWNER_QUALIFIES_FIRST); +} + +#[test] +fn k10_suppressed_foreign_selector_still_rejects() { + check_row(&K10_SUPPRESSED_FOREIGN_STILL_REJECTS); +} + +#[test] +fn k11_denied_grab_window_copy_is_delivered() { + check_row(&K11_GRAB_WINDOW_DENIAL_DELIVERS); +} + +#[test] +fn k12_denied_activating_press_still_activates_and_freezes() { + check_row(&K12_ACTIVATING_DENIAL_ACTIVATES); + let denied = run( + &K12_ACTIVATING_DENIAL_ACTIVATES, + Some(K12_ACTIVATING_DENIAL_ACTIVATES.deny), + ); + assert_eq!( + denied.grab, + GrabState { + active: true, + freeze: Some((Xi1SyncState::FrozenWithEvent, Some((true, KEYCODE)))), + }, + "the denied activating press activates the grab and freezes with the press stored" + ); +} + +#[test] +fn k13_synthetic_xi2_release_to_a_grab_owner_is_suppressed() { + check_row(&K13_SYNTHETIC_XI2_RELEASE_SUPPRESSED); +} + +#[test] +fn k13_synthetic_detectable_core_release_to_a_grab_owner_is_suppressed() { + check_row(&K13_DETECTABLE_CORE_RELEASE_SUPPRESSED); +} From 59986f3c545f036ec442413aa25f20752519eaed Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 15:20:11 -0300 Subject: [PATCH 14/72] fix(access): grabbed key review r1 Every foreign selector is evaluated where the owner does not qualify, with no short-circuit, so the Receive calls do not depend on the iteration order of the clients map. k9b pins it. Adds k13_suppressed_owner_qualifies_on_the_natural_walk: a suppressed owner copy on an owner_events walk qualifies without a Receive call. The grab-owner write takes an OwnerWrite enum (Decided / FreshCheck) instead of a bool, and the checked and unchecked branches share one helper. The too_many_arguments allow is dropped: the workspace lints already allow it. The core detectable-repeat suppression cites dix/events.c:2102-2116. The XI2 case is a yserver rule and is described as such. k11 asserts its grab state literally. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Haiku 5.5 --- .../yserver-core/src/core_loop/key_fanout.rs | 126 +++++++++++------- .../process_request/tests/access_key_input.rs | 92 +++++++++++++ 2 files changed, 168 insertions(+), 50 deletions(-) diff --git a/crates/yserver-core/src/core_loop/key_fanout.rs b/crates/yserver-core/src/core_loop/key_fanout.rs index c9f853ae6..a818a64f9 100644 --- a/crates/yserver-core/src/core_loop/key_fanout.rs +++ b/crates/yserver-core/src/core_loop/key_fanout.rs @@ -549,7 +549,7 @@ fn deliver_routed_key_with_master_status( grab.via_xi2, device_id, synthetic_repeat, - true, + OwnerWrite::FreshCheck, ); merge_dropped( &mut dropped, @@ -615,8 +615,6 @@ fn deliver_routed_key_with_master_status( } else { None }; - // A natural target was already decided by `key_grabbed_natural_target` - // (unchecked write). The grab-window copy is a fresh check. let mut dropped = if let Some(target) = natural { deliver_key_to_grab_owner( state, @@ -626,7 +624,7 @@ fn deliver_routed_key_with_master_status( via_xi2, grab_device_id, synthetic_repeat, - false, + OwnerWrite::Decided, ) } else { deliver_key_to_grab_owner( @@ -637,7 +635,7 @@ fn deliver_routed_key_with_master_status( via_xi2, grab_device_id, synthetic_repeat, - true, + OwnerWrite::FreshCheck, ) }; // XI1 leg runs under grabs too — the router handles its @@ -918,6 +916,41 @@ fn write_key_copies( dropped } +/// How the grab owner's copy is written. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum OwnerWrite { + /// The natural target: `key_grabbed_natural_target` already asked Receive + /// for this copy at this window. The write does not ask again. + Decided, + /// A fresh write at the grab window (owner_events false, the activating + /// press, the fallback, the slave exact grab): Receive is asked here. + FreshCheck, +} + +/// Writes the owner's copy through `write`'s policy. The encoder is shared. +fn fanout_to_grab_owner( + state: &mut ServerState, + owner: ClientId, + grab_window: ResourceId, + description: EventDescription, + write: OwnerWrite, + encode: F, +) -> Vec +where + F: Fn(&mut Vec, SequenceNumber, ClientByteOrder), +{ + match write { + OwnerWrite::Decided => fanout_event_to_clients(state, &[owner], encode), + OwnerWrite::FreshCheck => fanout_event_to_clients_with_receive( + state, + &[owner], + EventSubject::Window(grab_window), + &EventBatch::new(&[description]), + encode, + ), + } +} + /// Deliver a key event to the grab owner client, addressed to the /// grab window. When a passive (or explicit) keyboard grab is active, /// X11 delivers to the *grab owner* using the grab's event mask, not @@ -940,7 +973,6 @@ fn write_key_copies( /// state — observed as "can't type in the Cinnamon keyring dialog" /// (x11trace: keycode delivered as both core KeyPress and XI2 /// XI_KeyPress to the same window). -#[allow(clippy::too_many_arguments)] fn deliver_key_to_grab_owner( state: &mut ServerState, event: &HostKeyEvent, @@ -949,63 +981,54 @@ fn deliver_key_to_grab_owner( via_xi2: bool, device_id: u16, synthetic_repeat: bool, - checked: bool, + write: OwnerWrite, ) -> Vec { if grab_owner_copy_suppressed(state, event, owner, via_xi2, synthetic_repeat) { return Vec::new(); } let fields = key_window_fields(state, event, grab_window); - let subject = EventSubject::Window(grab_window); let description = grab_owner_description(event, via_xi2); - // `checked` is false only for a natural target whose owner copy - // `key_grabbed_natural_target` already decided: the write then skips Receive. if via_xi2 { let source_id = resolve_key_xi_source(state, event.origin).map_or(device_id, |source| source.sourceid); - let encode = |buf: &mut Vec, seq: SequenceNumber, order: ClientByteOrder| { - encode_key_xi2_for_device( - buf, - order, - seq, - event, - fields, - device_id, - source_id, - synthetic_repeat, - ); - }; - if checked { - fanout_event_to_clients_with_receive( - state, - &[owner], - subject, - &EventBatch::new(&[description]), - encode, - ) - } else { - fanout_event_to_clients(state, &[owner], encode) - } + fanout_to_grab_owner( + state, + owner, + grab_window, + description, + write, + |buf: &mut Vec, seq: SequenceNumber, order: ClientByteOrder| { + encode_key_xi2_for_device( + buf, + order, + seq, + event, + fields, + device_id, + source_id, + synthetic_repeat, + ); + }, + ) } else { - let encode = |buf: &mut Vec, seq: SequenceNumber, order: ClientByteOrder| { - x11::encode_key_event(buf, order, key_event_wire(event, seq, fields)); - }; - if checked { - fanout_event_to_clients_with_receive( - state, - &[owner], - subject, - &EventBatch::new(&[description]), - encode, - ) - } else { - fanout_event_to_clients(state, &[owner], encode) - } + fanout_to_grab_owner( + state, + owner, + grab_window, + description, + write, + |buf: &mut Vec, seq: SequenceNumber, order: ClientByteOrder| { + x11::encode_key_event(buf, order, key_event_wire(event, seq, fields)); + }, + ) } } /// The grab owner's copy is not written: a synthetic XI2 release, or a -/// synthetic core release to a detectable-repeat owner (Xorg suppresses the -/// same copies, dix/events.c). The suppressed copy is never asked of Receive. +/// synthetic core release to a detectable-repeat owner. The core case follows +/// Xorg's fake repeat release, which only clients without detectable +/// autorepeat get (dix/events.c:2102-2116); the XI2 case is a yserver rule. +/// The suppressed copy is never asked of Receive. fn grab_owner_copy_suppressed( state: &ServerState, event: &HostKeyEvent, @@ -1063,12 +1086,14 @@ fn foreign_selection_rejects( synthetic_repeat: bool, ) -> bool { let subject = EventSubject::Window(window); + // Every foreign client is evaluated, with no short-circuit: the set of + // Receive calls must not depend on the iteration order of `state.clients`. state .clients .keys() .map(|id| ClientId(*id)) .filter(|client| *client != owner) - .any(|client| { + .map(|client| { client_key_plan( state, event, @@ -1083,6 +1108,7 @@ fn foreign_selection_rejects( ) .stops }) + .fold(false, |rejects, stops| rejects | stops) } fn xi2_evtype_for(event: &HostKeyEvent) -> u16 { diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs index da86dbe92..7dcd3a0ad 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -1384,6 +1384,80 @@ const K13_DETECTABLE_CORE_RELEASE_SUPPRESSED: Row = Row { moved: &[], }; +/// A grabs with owner_events on the root. A, B and SEND_CLIENT select core +/// press on CHILD. A is denied there; B and SEND_CLIENT are allowed. Every +/// foreign selector is asked, and A falls back to the root grab window. +fn setup_k9b(f: &mut NotifyFixture) { + tree(f); + grab_keyboard(f, A, ROOT, true); + select_core(f, A, CHILD, KEY_PRESS); + select_core(f, B, CHILD, KEY_PRESS); + select_core(f, SEND_CLIENT, CHILD, KEY_PRESS); +} + +const K9B_EVERY_FOREIGN_SELECTOR_IS_CHECKED: Row = Row { + name: "k9b_every_foreign_selector_is_checked", + setup: setup_k9b, + drive: Drive::Entry { + origin: InputOrigin::NestedHost, + pressed: true, + }, + deny: &[(A, CallKind::Core, CHILD)], + allow: Expect { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Core, ROOT)], + calls: &[ + (A, CallKind::Core, CHILD), + (B, CallKind::Core, CHILD), + (SEND_CLIENT, CallKind::Core, CHILD), + (A, CallKind::Core, ROOT), + ], + }, + moved: &[Moved { + client: A, + window: ROOT, + child: FOCUS, + event: (120, 120), + }], +}; + +/// A grabs with owner_events on the root and has detectable repeat. A selects +/// core release on CHILD and B selects core release on FOCUS. A's synthetic +/// release is suppressed in the grab's protocol, so A qualifies at CHILD with +/// no Receive call, the walk stops there, and nothing is written. The denial +/// of A at CHILD changes nothing, because no copy is checked. +fn setup_k13_natural(f: &mut NotifyFixture) { + tree(f); + grab_keyboard(f, A, ROOT, true); + set_detectable_repeat(f, A); + select_core(f, A, CHILD, KEY_RELEASE); + select_core(f, B, FOCUS, KEY_RELEASE); +} + +const K13_SUPPRESSED_OWNER_QUALIFIES_ON_THE_NATURAL_WALK: Row = Row { + name: "k13_suppressed_owner_qualifies_on_the_natural_walk", + setup: setup_k13_natural, + drive: Drive::After { + origin: InputOrigin::NestedHost, + pressed: false, + master: true, + synthetic: true, + }, + deny: &[(A, CallKind::Core, CHILD)], + allow: Expect { + frames: &[], + calls: &[], + }, + denied: Expect { + frames: &[], + calls: &[], + }, + moved: &[], +}; + #[test] fn k1_denied_pointer_window_selector_advances_the_focus_walk() { check_row(&K1); @@ -1482,6 +1556,14 @@ fn k10_suppressed_foreign_selector_still_rejects() { #[test] fn k11_denied_grab_window_copy_is_delivered() { check_row(&K11_GRAB_WINDOW_DENIAL_DELIVERS); + let denied = run( + &K11_GRAB_WINDOW_DENIAL_DELIVERS, + Some(K11_GRAB_WINDOW_DENIAL_DELIVERS.deny), + ); + assert!( + matches!(denied.grab, GrabState { active: true, .. }), + "the denied grab-window copy leaves the keyboard grab active" + ); } #[test] @@ -1510,3 +1592,13 @@ fn k13_synthetic_xi2_release_to_a_grab_owner_is_suppressed() { fn k13_synthetic_detectable_core_release_to_a_grab_owner_is_suppressed() { check_row(&K13_DETECTABLE_CORE_RELEASE_SUPPRESSED); } + +#[test] +fn k9b_every_foreign_selector_is_checked() { + check_row(&K9B_EVERY_FOREIGN_SELECTOR_IS_CHECKED); +} + +#[test] +fn k13_suppressed_owner_qualifies_on_the_natural_walk() { + check_row(&K13_SUPPRESSED_OWNER_QUALIFIES_ON_THE_NATURAL_WALK); +} From 301e35ee152a6d1f4927fb8ec0f2e78409bb90e3 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 15:28:34 -0300 Subject: [PATCH 15/72] feat(access): Receive checks raw key copies and the grab leg Each root copy of a raw key event (the slave and master root fanouts) is checked with the root as subject, and a denial drops only that copy. The master grab leg sends at most one copy to the grab owner: when the natural owner_events copy holds, it is checked with the root as subject; when that copy is absent or denied and the grab mask has the raw bit, the copy is checked with the grab window as subject. The root fanout after it keeps its filters, including the owner skip for a root grab window, and is a separate attempt with its own check. The grab-leg write reuses the decision it was checked under, and a dead owner is not asked. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Haiku 5.5 --- .../yserver-core/src/core_loop/key_fanout.rs | 60 +++- .../process_request/tests/access_key_input.rs | 262 ++++++++++++++++-- 2 files changed, 292 insertions(+), 30 deletions(-) diff --git a/crates/yserver-core/src/core_loop/key_fanout.rs b/crates/yserver-core/src/core_loop/key_fanout.rs index a818a64f9..5a526e8ec 100644 --- a/crates/yserver-core/src/core_loop/key_fanout.rs +++ b/crates/yserver-core/src/core_loop/key_fanout.rs @@ -1388,10 +1388,26 @@ pub(crate) fn deliver_raw_key_master(state: &mut ServerState, event: RawKeyEvent && state.clients.get(&g.owner.0).is_some_and(|c| { xi2_mask_for_client(c, ROOT_WINDOW, ROOT_WINDOW, &master_devices) & bit != 0 }); - if natural || u64::from(g.xi2_mask) & bit != 0 { + // One copy at most. The natural copy is checked with the root as + // subject; a denied or absent one falls back to the grab mask's + // copy, checked with the grab window as subject. A dead owner is + // not asked. + let description = [crate::xinput::xi2_event_description(evtype)]; + let events = EventBatch::new(&description); + let natural_allowed = + natural && receive_allows(state, g.owner, EventSubject::Window(ROOT_WINDOW), &events); + let grab_allowed = !natural_allowed + && u64::from(g.xi2_mask) & bit != 0 + && state.clients.contains_key(&g.owner.0) + && receive_allows(state, g.owner, EventSubject::Window(g.grab_window), &events); + if natural_allowed || grab_allowed { merge_dropped( &mut dropped, - send_raw_key(state, &[g.owner], event, master_id, source.sourceid), + fanout_event_to_clients( + state, + &[g.owner], + raw_key_encoder(event, master_id, source.sourceid), + ), ); } } @@ -1432,20 +1448,14 @@ fn raw_key_root_selectors(state: &ServerState, devices: &[u16], evtype: u16) -> .collect() } -/// Write one raw key event with the given `deviceid` and `sourceid` to each -/// target. Keys carry no valuators; the valuator mask is two zero words -/// (Xorg `eventToRawEvent`). -fn send_raw_key( - state: &mut ServerState, - targets: &[ClientId], +/// The encoder of one raw key copy with `deviceid` and `sourceid`. Keys carry +/// no valuators; the valuator mask is two zero words (Xorg `eventToRawEvent`). +fn raw_key_encoder( event: RawKeyEvent, deviceid: u16, sourceid: u16, -) -> Vec { - if targets.is_empty() { - return Vec::new(); - } - fanout_event_to_clients(state, targets, |buf, seq, order| { +) -> impl Fn(&mut Vec, SequenceNumber, ClientByteOrder) { + move |buf, seq, order| { x11::encode_xi2_raw_event( buf, order, @@ -1459,7 +1469,29 @@ fn send_raw_key( 0, 0, ); - }) + } +} + +/// Write one raw key event to each root selector in `targets`. Each copy is +/// checked with the root as subject; a denial drops only that copy. +fn send_raw_key( + state: &mut ServerState, + targets: &[ClientId], + event: RawKeyEvent, + deviceid: u16, + sourceid: u16, +) -> Vec { + if targets.is_empty() { + return Vec::new(); + } + let description = [crate::xinput::xi2_event_description(event.evtype())]; + fanout_event_to_clients_with_receive( + state, + targets, + EventSubject::Window(ROOT_WINDOW), + &EventBatch::new(&description), + raw_key_encoder(event, deviceid, sourceid), + ) } fn merge_dropped(into: &mut Vec, more: Vec) { diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs index 7dcd3a0ad..a00136eba 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -28,7 +28,10 @@ use crate::{ access::{Decision, EventDescription, EventSubject}, core_loop::{ InputOrigin, client_io, - key_fanout::{key_event_fanout_after_transition, key_event_fanout_to_state}, + key_fanout::{ + RawKeyEvent, key_event_fanout_after_transition, key_event_fanout_to_state, + raw_key_event_to_state, + }, process_request::RequestOutcome, }, host_x11::HostKeyEvent, @@ -63,6 +66,8 @@ const KEY_RELEASE: u32 = 2; const XI_KEY_PRESS: u32 = 1 << 2; const XI_KEY_RELEASE: u32 = 1 << 3; const XI_KEY_PRESS_AND_RELEASE: u32 = XI_KEY_PRESS | XI_KEY_RELEASE; +/// XI2 mask word for RawKeyPress (bit 13) and RawKeyRelease (bit 14). +const XI_RAW_KEY_PRESS: u32 = 1 << 13; /// The grab window of the grab rows: the root is on no walk to FOCUS. const ROOT: u32 = ROOT_WINDOW.0; @@ -76,6 +81,8 @@ type Call = (u32, CallKind, u32); enum Kind { Core, Xi2(u16), + /// A raw key copy: its device, always on the root. + Raw(u16), } /// What a Receive check names. An XI2 check names the description, not the @@ -84,6 +91,7 @@ enum Kind { enum CallKind { Core, Xi2, + Raw, } #[derive(Clone, Copy)] @@ -97,12 +105,16 @@ enum Drive { master: bool, synthetic: bool, }, + /// `raw_key_event_to_state`: the XI2 raw copies of one device key. + Raw { origin: InputOrigin, pressed: bool }, } impl Drive { fn pressed(self) -> bool { match self { - Drive::Entry { pressed, .. } | Drive::After { pressed, .. } => pressed, + Drive::Entry { pressed, .. } + | Drive::After { pressed, .. } + | Drive::Raw { pressed, .. } => pressed, } } } @@ -287,19 +299,51 @@ fn xkb_request(f: &mut NotifyFixture, client: u32, opcode: u8, minor: u8, body: /// The slave keyboard's exact XI2 grab owned by `owner` on `grab_window`, made /// with XIGrabDevice (asynchronous, not owner-events, KeyPress mask). fn grab_slave_keyboard(f: &mut NotifyFixture, owner: u32, grab_window: u32) { + grab_keyboard_device( + f, + owner, + DEVICEID_XTEST_KEYBOARD, + grab_window, + false, + XI_KEY_PRESS, + ); +} + +/// XIGrabDevice of `device` by `owner` on `grab_window` with the given +/// owner_events and one mask word. A master keyboard grab is the +/// `active_keyboard_grab` the raw master leg reads; a slave grab is per device. +fn grab_keyboard_device( + f: &mut NotifyFixture, + owner: u32, + device: u16, + grab_window: u32, + owner_events: bool, + mask: u32, +) { const XI_GRAB_DEVICE: u8 = 51; let mut body = Vec::with_capacity(28); body.extend_from_slice(&grab_window.to_le_bytes()); body.extend_from_slice(&[0; 8]); // CurrentTime, no cursor - body.extend_from_slice(&DEVICEID_XTEST_KEYBOARD.to_le_bytes()); - body.extend_from_slice(&[1, 1, 0, 0]); // async modes, owner_events false + body.extend_from_slice(&device.to_le_bytes()); + body.extend_from_slice(&[1, 1, u8::from(owner_events), 0]); // async modes body.extend_from_slice(&1_u16.to_le_bytes()); // one mask word - body.extend_from_slice(&XI_KEY_PRESS.to_le_bytes()); + body.extend_from_slice(&mask.to_le_bytes()); let bytes = send_with_reply(f, owner, XI_MAJOR, XI_GRAB_DEVICE, &body); let reply = &bytes[bytes.len() - 32..]; assert_eq!((reply[0], reply[8]), (1, 0), "XIGrabDevice replies Success"); } +/// SetInputFocus(PointerRoot) from the requester. +fn set_focus_pointer_root(f: &mut NotifyFixture) { + send( + f, + SEND_CLIENT, + CORE_SET_INPUT_FOCUS, + 0, + &[1_u32.to_le_bytes(), 0_u32.to_le_bytes()].concat(), + ); +} + /// The core GrabKeyboard request by `owner` on `window`, asynchronous pointer /// mode, with `owner_events`. The reply must be Success. fn grab_keyboard(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: bool) { @@ -366,6 +410,17 @@ fn drive(f: &mut NotifyFixture, drive: Drive) { master, synthetic, ), + Drive::Raw { origin, pressed } => raw_key_event_to_state( + &mut f.state, + RawKeyEvent { + origin, + keycode: KEYCODE, + pressed, + time: TIME, + }, + false, + false, + ), }; assert!(dropped.is_empty(), "delivery queued a disconnect"); } @@ -377,11 +432,13 @@ fn key_call(description: &EventDescription) -> Option<(CallKind, bool)> { Some((CallKind::Core, description.type_code == 2)) } Some(extension) - if description.type_code == 35 - && extension.major_opcode == XI2_MAJOR_OPCODE - && (extension.event_type == 2 || extension.event_type == 3) => + if description.type_code == 35 && extension.major_opcode == XI2_MAJOR_OPCODE => { - Some((CallKind::Xi2, extension.event_type == 2)) + match extension.event_type { + 2 | 3 => Some((CallKind::Xi2, extension.event_type == 2)), + 13 | 14 => Some((CallKind::Raw, extension.event_type == 13)), + _ => None, + } } _ => None, } @@ -414,17 +471,20 @@ fn decide(denied: &[Call], pressed: bool, call: &RecordedExtensionCheck) -> Deci } /// Decodes a frame the key walk writes: a core KeyPress/KeyRelease (event -/// window at byte 12) or an XI2 key GenericEvent (device at byte 10, event -/// window at byte 24). `None` for any other frame. +/// window at byte 12), an XI2 key GenericEvent (device at byte 10, event +/// window at byte 24) or a raw key GenericEvent (device at byte 10, always the +/// root). `None` for any other frame. fn decode(frame: &[u8], order: ClientByteOrder) -> Option<(Kind, u32)> { match frame[0] & 0x7f { 2 | 3 => Some((Kind::Core, dec32(&frame[12..16], order))), - 35 if frame[1] == XI2_MAJOR_OPCODE && matches!(dec16(&frame[8..10], order), 2 | 3) => { - Some(( + 35 if frame[1] == XI2_MAJOR_OPCODE => match dec16(&frame[8..10], order) { + 2 | 3 => Some(( Kind::Xi2(dec16(&frame[10..12], order)), dec32(&frame[24..28], order), - )) - } + )), + 13 | 14 => Some((Kind::Raw(dec16(&frame[10..12], order)), ROOT)), + _ => None, + }, _ => None, } } @@ -558,7 +618,7 @@ fn delivered(name: &str, run: &Run) -> Vec { ); let keycode = match kind { Kind::Core => u32::from(frame[1]), - Kind::Xi2(_) => dec32(&frame[16..20], client.order), + Kind::Xi2(_) | Kind::Raw(_) => dec32(&frame[16..20], client.order), }; assert_eq!(keycode, u32::from(KEYCODE), "{name}: frame keycode"); frames.push((client.client, kind, window)); @@ -1602,3 +1662,173 @@ fn k9b_every_foreign_selector_is_checked() { fn k13_suppressed_owner_qualifies_on_the_natural_walk() { check_row(&K13_SUPPRESSED_OWNER_QUALIFIES_ON_THE_NATURAL_WALK); } + +// ---- raw key copies (task 4) --------------------------------------------- + +/// A and B select RawKeyPress on the root for the master keyboard. SEND_CLIENT +/// (the slave-form selector) selects it for the slave keyboard. +fn setup_k13_raw(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, ROOT, DEVICEID_MASTER_KEYBOARD, XI_RAW_KEY_PRESS); + select_xi2(f, B, ROOT, DEVICEID_MASTER_KEYBOARD, XI_RAW_KEY_PRESS); + select_xi2( + f, + SEND_CLIENT, + ROOT, + DEVICEID_XTEST_KEYBOARD, + XI_RAW_KEY_PRESS, + ); +} + +/// The slave-form copy goes first (slave pass), then the master copies of A +/// and B. Denying A's master root copy drops only A's copy. +const K13_RAW_ROOT_COPY_DENIAL: Row = Row { + name: "k13_denied_raw_root_copy_drops_only_that_copy", + setup: setup_k13_raw, + drive: Drive::Raw { + origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), + pressed: true, + }, + deny: &[(A, CallKind::Raw, ROOT)], + allow: Expect { + frames: &[ + (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + (B, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + (SEND_CLIENT, Kind::Raw(DEVICEID_XTEST_KEYBOARD), ROOT), + ], + calls: &[ + (SEND_CLIENT, CallKind::Raw, ROOT), + (A, CallKind::Raw, ROOT), + (B, CallKind::Raw, ROOT), + ], + }, + denied: Expect { + frames: &[ + (B, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + (SEND_CLIENT, Kind::Raw(DEVICEID_XTEST_KEYBOARD), ROOT), + ], + calls: &[ + (SEND_CLIENT, CallKind::Raw, ROOT), + (A, CallKind::Raw, ROOT), + (B, CallKind::Raw, ROOT), + ], + }, + moved: &[], +}; + +#[test] +fn k13_denied_raw_root_copy_drops_only_that_copy() { + check_row(&K13_RAW_ROOT_COPY_DENIAL); +} + +/// A holds the master keyboard's XI2 grab on CHILD with owner_events, the grab +/// mask selects RawKeyPress, and focus is PointerRoot. A selects RawKeyPress on +/// the root for the master keyboard, so the natural walk reaches it. +fn setup_k14(f: &mut NotifyFixture) { + setup_k14_with_mask(f, XI_KEY_PRESS | XI_RAW_KEY_PRESS); +} + +fn setup_k14_with_mask(f: &mut NotifyFixture, mask: u32) { + tree(f); + set_focus_pointer_root(f); + grab_keyboard_device(f, A, DEVICEID_MASTER_KEYBOARD, CHILD, true, mask); + select_xi2(f, A, ROOT, DEVICEID_MASTER_KEYBOARD, XI_RAW_KEY_PRESS); +} + +fn setup_k14_without_raw_bit(f: &mut NotifyFixture) { + setup_k14_with_mask(f, XI_KEY_PRESS); +} + +/// Denying A's root copy: the natural copy falls back to the grab window (a +/// fresh check with CHILD as subject), and the root fanout is denied too. +const K14_RAW_OWNER_FALLS_BACK_TO_GRAB_WINDOW: Row = Row { + name: "k14_denied_raw_owner_root_copy_falls_back_to_the_grab_window", + setup: setup_k14, + drive: Drive::Raw { + origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), + pressed: true, + }, + deny: &[(A, CallKind::Raw, ROOT)], + allow: Expect { + frames: &[ + (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + ], + calls: &[(A, CallKind::Raw, ROOT), (A, CallKind::Raw, ROOT)], + }, + denied: Expect { + frames: &[(A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT)], + calls: &[ + (A, CallKind::Raw, ROOT), + (A, CallKind::Raw, CHILD), + (A, CallKind::Raw, ROOT), + ], + }, + moved: &[], +}; + +#[test] +fn k14_denied_raw_owner_root_copy_falls_back_to_the_grab_window() { + check_row(&K14_RAW_OWNER_FALLS_BACK_TO_GRAB_WINDOW); +} + +/// Same as k14 without RawKeyPress in the grab mask: nothing falls back, so +/// the owner gets no copy when its root copy is denied. +const K14_NO_RAW_BIT_NO_FALLBACK: Row = Row { + name: "k14b_denied_raw_owner_without_raw_grab_bit_gets_nothing", + setup: setup_k14_without_raw_bit, + drive: Drive::Raw { + origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), + pressed: true, + }, + deny: &[(A, CallKind::Raw, ROOT)], + allow: Expect { + frames: &[ + (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + ], + calls: &[(A, CallKind::Raw, ROOT), (A, CallKind::Raw, ROOT)], + }, + denied: Expect { + frames: &[], + calls: &[(A, CallKind::Raw, ROOT), (A, CallKind::Raw, ROOT)], + }, + moved: &[], +}; + +#[test] +fn k14b_denied_raw_owner_without_raw_grab_bit_gets_nothing() { + check_row(&K14_NO_RAW_BIT_NO_FALLBACK); +} + +/// An allowed natural copy is the only copy from the grab leg: the grab window +/// is never asked. +const K15_ALLOWED_NATURAL_SKIPS_GRAB_WINDOW: Row = Row { + name: "k15_allowed_natural_raw_leg_skips_the_grab_window_check", + setup: setup_k14, + drive: Drive::Raw { + origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), + pressed: true, + }, + deny: &[], + allow: Expect { + frames: &[ + (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + ], + calls: &[(A, CallKind::Raw, ROOT), (A, CallKind::Raw, ROOT)], + }, + denied: Expect { + frames: &[ + (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + ], + calls: &[(A, CallKind::Raw, ROOT), (A, CallKind::Raw, ROOT)], + }, + moved: &[], +}; + +#[test] +fn k15_allowed_natural_raw_leg_skips_the_grab_window_check() { + check_row(&K15_ALLOWED_NATURAL_SKIPS_GRAB_WINDOW); +} From aa8338c3bd9b673cd0e0327ded91a52fb69736c1 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 15:31:32 -0300 Subject: [PATCH 16/72] fix(access): raw key review minors Drop the grab leg's dead-owner guard: process_disconnect releases the keyboard grab before it removes the client, so the owner is always live when the grab leg asks. Document on Kind::Raw that the grab-leg and root copies decode alike and only the Receive trace separates them. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Haiku 5.5 --- crates/yserver-core/src/core_loop/key_fanout.rs | 4 +--- .../src/core_loop/process_request/tests/access_key_input.rs | 4 +++- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/yserver-core/src/core_loop/key_fanout.rs b/crates/yserver-core/src/core_loop/key_fanout.rs index 5a526e8ec..f8ca7af00 100644 --- a/crates/yserver-core/src/core_loop/key_fanout.rs +++ b/crates/yserver-core/src/core_loop/key_fanout.rs @@ -1390,15 +1390,13 @@ pub(crate) fn deliver_raw_key_master(state: &mut ServerState, event: RawKeyEvent }); // One copy at most. The natural copy is checked with the root as // subject; a denied or absent one falls back to the grab mask's - // copy, checked with the grab window as subject. A dead owner is - // not asked. + // copy, checked with the grab window as subject. let description = [crate::xinput::xi2_event_description(evtype)]; let events = EventBatch::new(&description); let natural_allowed = natural && receive_allows(state, g.owner, EventSubject::Window(ROOT_WINDOW), &events); let grab_allowed = !natural_allowed && u64::from(g.xi2_mask) & bit != 0 - && state.clients.contains_key(&g.owner.0) && receive_allows(state, g.owner, EventSubject::Window(g.grab_window), &events); if natural_allowed || grab_allowed { merge_dropped( diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs index a00136eba..d884e6c63 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -81,7 +81,9 @@ type Call = (u32, CallKind, u32); enum Kind { Core, Xi2(u16), - /// A raw key copy: its device, always on the root. + /// A raw key copy: its device, always on the root. A raw frame has no + /// event window, so the grab-leg copy and the root-fanout copy decode the + /// same; only the Receive trace tells them apart. Raw(u16), } From bc63b3fa07f3a7df7155922d121ad56fe3924a2b Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 17:00:46 -0300 Subject: [PATCH 17/72] docs(plan): access control PR 4c part 2, plan 2 (pointer and XI1) Co-Authored-By: Claude Opus 5.5 --- .../2026-12-01-access-control-pr4c-pointer.md | 177 ++++++++++++++++++ 1 file changed, 177 insertions(+) create mode 100644 docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md diff --git a/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md b/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md new file mode 100644 index 000000000..08bb58bb7 --- /dev/null +++ b/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md @@ -0,0 +1,177 @@ +# Access control PR 4c part 2, plan 2: pointer and XI1 delivery under denial + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Make a Receive denial take part in the pointer routing decisions (core walk and XI2 absorption, per-client form shadowing, XI2 form walks, owner-events resolution, grab-window delivery, passive activation, implicit-grab winners, slave press protocol choice, raw and scroll copies) and in the shared XI1 router, as the approved spec section says. + +**Architecture:** One pointer dispatch (`pointer_event_fanout_to_state_inner`) owns one `ReceiveMemo`. Every selection-based decision asks the memo, which calls `check_receive` once per (client, subject, batch) and returns the stored result after that, so the resolvers that run more than once per dispatch (`owner_events_route`, the per-client form windows in the XI2 writer, the core candidate) see one result and the write reuses it. Grab-window writes are distinct attempts and check fresh through the existing `fanout_event_to_clients_with_receive`. With no policy, `receive_allows` returns `true` without asking, so every decision takes today's inputs and the bytes stay identical. + +**Tech Stack:** Rust, yserver-core (`core_loop/pointer_fanout.rs`, `core_loop/pointer_fanout/owner_events.rs`, `core_loop/fanout.rs`, `core_loop/key_fanout.rs` for the XI1 key leg), the access layer (`ServerState::check_receive`, `EventSubject`, `EventBatch`, `EventDescription`). + +**Spec:** `docs/superpowers/specs/2026-10-30-access-control-layer-design.md`, section "Input delivery under denial" (lines 353–527), approved 2026-11-25, merged in #389. + +**Series context:** plan 1 (keyboard, done at `aa8338c3`) converted the focused, grabbed and raw key paths with per-call lazy checks; this plan converts the pointer and the XI1 router, which the XI1 key leg (`deliver_xi1_focused_key`) shares. Plan 3 (replay, thaw, freeze) adds the re-delivery tests and does not convert these sites again. Why a memo here and not plan 1's callbacks: the pointer recomputes the same decision in several places of one dispatch (see Architecture), and a memo makes them agree without threading result lists through the 2300-line dispatch. + +## Global Constraints + +- With no policy, and with an allow-all policy, every scenario's bytes on every client, the order per client, and the grab/freeze/implicit-grab state equal today's (spec l.357–359). +- A denied copy is a non-delivery: it does not stop a walk, shadow another form, qualify an owner, or reject a grab (spec l.370–373). A selection that produces no copy still decides as today and Receive is not asked for it (spec l.374–380). +- One Receive result per recipient per delivery attempt, reused by the write. A grab-window fallback, an `owner_events = false` grab write and a passive activating write are distinct attempts with a fresh check; a denial there counts as delivered (spec l.381–385, 424–429). +- Subjects: `EventSubject::Window()` for cooked copies; `Window(ROOT_WINDOW)` for raw root copies (spec l.455–461). +- Descriptions: core `EventDescription::core(4|5|6)` (ButtonPress, ButtonRelease, MotionNotify); XI2 `crate::xinput::xi2_event_description(evtype)` (slave and master forms share it); raw `xi2_event_description(raw evtype)`; XI1 `crate::xinput::xi1_event_description(offset)`. Batches: XI1 `DeviceMotionNotify` + its `DeviceValuator` = one `EventBatch` of two descriptions; the smooth-scroll stop = one batch of two XI2 Motion descriptions (spec l.463–475). +- Crossings keep their existing local check after the XI2-over-core dedup and are NOT routed through the memo; a denied XI2 crossing does not expose a core crossing (spec l.480–484). +- Keep every encoder, the write order (slave form before master per connection, deferred core after its client's slave form), and the multiplicity. +- No new `YSERVER_*` environment variables. Reuse first: new code only where a decision needs a Receive result it cannot get today. +- Tests drive production entries (`pointer_event_fanout_to_state`, `emit_scroll_stop_to_state`, `key_event_fanout_to_state`, requests through `NotifyFixture::request`), not private helpers; each test names the mutation it kills. Cite Xorg at `xorg-server-21.1.24` as `dix/events.c:`. +- Commits signed (`-S`), a blank line before the trailers `Co-Authored-By: Claude Opus 5.5 ` and `Implemented-By: Claude Haiku 5.5`; check with `git log -1 --format='%(trailers:only)'`. No session URL. +- Gate per task: `cargo +nightly fmt --all`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo build --bin yserver` alone, `cargo test -p yserver-core --lib -- `, the whole `cargo test -p yserver-core --lib`. Task 5 also runs `cargo test --workspace --features xdmcp`. The `--ignored` lavapipe suite and loaded runs are the PR gate at the end of plan 3. + +## Review Focus + +1. A Receive call for a copy the dispatch never emits is a phantom: the master form when `button_transition.master_accepted` is false, a form excluded by the replay flags, a scroll-motion-only grab copy that encodes nothing, an owner-events foreign selector when the owner already qualified at that window, the trace-level click-hit diagnostic (`yserver::input::clickhit`), which must route with `None`. Test p7 pins the first. +2. A client that selects master XI2 and core at one window: allowed XI2 shadows core with no core call; denied XI2 neither absorbs the core walk nor shadows that client's core copy (p2, p5). +3. A deferred core copy (slave origin, client also selects the slave XI2 form) is checked once at admission and keeps slave-before-core order; the flush does not check (p6). +4. Owner-events: the owner qualifying in a later protocol at the same window (core after a foreign XI2 selector) still wins with no foreign call (p11). +5. Passive activation with the owner denied: the grab still activates, a sync grab still freezes with the stored press, and nobody else gets the press (p14). + +--- + +### Task 1: the memo and the natural pointer attempt + +**Files:** +- Modify: `crates/yserver-core/src/core_loop/fanout.rs` (`ReceiveMemo` beside `receive_allows` :297; `pointer_propagation_target_by_id` :200 and `xi2_pointer_selected_on` :166) +- Modify: `crates/yserver-core/src/core_loop/pointer_fanout.rs` (memo created in `pointer_event_fanout_to_state_inner` :521; `xi2_form_selected_on_for_source` :4483, `xi2_route_window_for_source` :4509, `xi2_form_targets_for_source` :4531, `compute_xi2_targets_for_source` :4594, `xi2_pointer_forms_for_source` :4767; core step 4 and its XI2 dedup; the XI2 writer :2560–2830; `fanout_core_pointer_event_ordered` :4043 and the deferral :4009–4185) +- Create: `crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs` (helpers moved from `access_key_input.rs`: `send`, `send_with_reply`, `select_core`, `select_xi2`, the policy/trace plumbing, per-client trace comparison) and `access_pointer_input.rs` (+ `mod` lines) + +**Interfaces:** +- Produces in `fanout.rs`: + ```rust + pub(crate) struct ReceiveMemo { /* private */ } + impl ReceiveMemo { + pub(crate) fn new() -> Self; + /// First call per (client, subject, batch) asks `receive_allows`; + /// later calls return the stored result without asking. + pub(crate) fn allows(&self, state: &ServerState, client: ClientId, + subject: EventSubject, events: &EventBatch<'_>) -> bool; + } + ``` + Interior mutability so read-only resolvers taking `&ServerState` can use it. Keys compare by equality (the access types derive `Eq`, not `Hash`; a small `Vec` is fine). +- Produces: every pointer routing helper listed above takes `receive: Option<&ReceiveMemo>`. `None` = today's selection-only routing (crossings, the scroll stop, the click-hit diagnostic). `Some` = a selection at window W counts only if its copy is allowed: `selected && memo.allows(client, Window(W),
)`. +- Produces in `pointer_fanout.rs`: `enum PointerWrite<'a> { Decided(&'a ReceiveMemo), Fresh }`. `Decided`: the writer keeps the recipients the memo allows (cache hits, no new call) and writes through the unchecked `fanout_event_to_clients`. `Fresh`: `fanout_event_to_clients_with_receive` (a denial = delivered). `fanout_core_pointer_event_ordered` takes it; core Enter/Leave pass `Fresh` (today's local check). Deferred core copies: `Decided` filters by the memo at admission, `Fresh` checks with `receive_allows` at admission; the flush writes unchecked. +- Produces (test support): `access_pointer_input.rs` scenario rows in plan 1's style: windows and selections through requests (`CreateWindow`, `ChangeWindowAttributes`, `XISelectEvents`, XI1 `SelectExtensionEvent`), a policy denying a set of `(client, subject, description)`, `pointer_event_fanout_to_state(.., handle_grabs = true, is_replay = false)` with a `HostPointerEvent` builder (reuse the one in `access_crossing_notify.rs:305`), per-client frames `(description, event window, child)` and the per-client Receive trace filtered to pointer, XI1 and raw descriptions (crossings, DeviceChanged and focus calls dropped). Slave origin = the XTEST pointer (`InputOrigin::XTest()`). Every row also runs with no policy and allow-all and asserts identical bytes and grab state. + +Rules: +- Core walk (`pointer_propagation_target_by_id`): at each window, the XI2 absorption asks the master-form description for each client with a master-form selection there (devices 2, 1, 0) and absorbs only if one is allowed; then the core subscribers that are allowed stop the walk and are the recipients. +- XI2 form walks: `xi2_route_window_for_source` stops at the first window with an allowed selector of that form; `xi2_form_targets_for_source` returns the allowed ones; `xi2_pointer_forms_for_source` and the writer's per-form window use the same memo, so a client's slave and master forms at one window share one call. +- Core step 4 XI2 dedup: a client's core copy is shadowed only by its allowed master XI2 copy at the same window. The implicit-grab core candidate comes from the allowed core recipients. +- The XI2 writer: natural geometry → `Decided` (`delivered = allowed && not transport-failed`, which feeds `consider_xi2_press`); fixed grab-window geometry (`xi2_grab_window_target`, `xi2_slave_grab_window_target`, `xi2_grab_delivery`) → `Fresh` (Task 2 tests it); crossings → today's local check. No call for a form the dispatch does not write (`button_want` false, scroll-motion-only grab copy with no bytes). + +- [ ] **Step 1: move the shared helpers** into `access_input_support.rs`; `access_key_input` stays 29/29 green, no behaviour change. Commit `test(access): share the input scenario helpers`. +- [ ] **Step 2: failing tests** in `access_pointer_input.rs` (tree: root ⊃ P ⊃ C, pointer over C; ButtonPress unless stated): + - `p1_denied_core_selector_does_not_stop_the_core_walk`: B core on C, A core on P; deny B@C → A gets it at P with child C; trace [B@C core, A@P core]. Kills: stop on selection. + - `p2_denied_xi2_selector_does_not_absorb_core`: X master XI2 on C, A core on P. No policy: A nothing (absorbed). Deny X@C XI2 → A gets core at P, X nothing; X's trace has exactly one XI2@C call although absorption and the XI2 walk both ask. Kills: absorption from selection; a second check. + - `p3_xi2_walk_skips_a_denied_window`: X master XI2 on C denied, Y on P → Y gets XI2 at P, child C. Kills: route window from selection. + - `p4_slave_and_master_forms_share_one_check`: slave origin; X selects XIAllDevices on C. Allowed → slave then master form, one call. Denied → nothing for X, Y (master XI2 on P) gets the master form at P. Kills: one check per form. + - `p5_denied_xi2_reopens_that_clients_core`: A selects master XI2 and core on C. Allowed → XI2 only, no core call. XI2 denied → core at C, trace [A XI2@C, A core@C]. Kills: shadow from selection. + - `p6_deferred_core_copy_is_checked_at_admission`: slave origin; A selects slave XI2 and core on C (core deferred). Allow-all → slave XI2 then core, as today. Core denied → slave XI2 only; one core call. Kills: check at flush; no check. + - `p7_no_check_for_a_form_not_emitted`: hold button 1 through one slave, press button 1 through the XTEST slave (master bitmap unchanged, `master_accepted` false); X selects master XI2 ButtonPress on C → no call for X. Kills: phantom master-form check. Review focus 1. +- [ ] **Step 3:** run `cargo test -p yserver-core --lib access_pointer_input`. Expected: p1, p2, p3, p4 (denied row), p5 and p6 FAIL; p7 passes (guards the implementation). +- [ ] **Step 4: implement** `ReceiveMemo`, the `receive` parameters, `PointerWrite`, the memo in the dispatch. Existing callers outside the dispatch (crossing producers, diagnostics) pass `None`. +- [ ] **Step 5:** run the filter, `pointer_fanout::tests`, `access_crossing_notify` and the whole `--lib`. Expected PASS, existing tests unchanged. +- [ ] **Step 6: commit** `feat(access): Receive decides the natural pointer walks`. + +### Task 2: grabs and passive activation + +**Files:** +- Modify: `crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs` (`owner_events_route` :384, `xi2_motion_targets_for_source` callers inside) +- Modify: `crates/yserver-core/src/core_loop/pointer_fanout.rs` (core grab block :1430–1555, XI2 grab block :2220–2310, passive activation :1560–1700) +- Test: `access_pointer_input.rs` + +**Interfaces:** +- Consumes: `ReceiveMemo`, `PointerWrite`, the harness (Task 1). +- Produces: `owner_events_route(.., receive: Option<&ReceiveMemo>)` following the rules below; `OwnerEventsRoute::Natural` means the owner's copy there is already allowed. + +Rules (spec l.414–429, 431–440): +- At each window: the owner first, in today's protocol order (XI2, XI1, core), qualifies through the first protocol it selected whose copy is allowed. Only if it qualifies in none are the foreign selectors of all three protocols evaluated, every one (no short-circuit), and any allowed one rejects → `Fallback`. Else continue to the parent. With `None` this equals today's result. +- Natural core write → `PointerWrite::Decided`. Fallback and `owner_events = false` writes (core and XI2), the XI2 slave grab delivery and the passive activating press → `Fresh` with subject `Window(grab_window)`; a denial still sets `handled_core_via_grab` and nobody else gets the copy. Where today's grab mask filters the copy no write happens, so no check is made either (Ruling: Xorg checks before the mask, `dix/events.c:4388-4398`; the outcome is the same, no bytes and input captured). +- Activation, `CheckGrabForSyncs`, the stored event, confinement and the activation crossings are untouched. + +- [ ] **Step 1: failing tests:** + - `p9_denied_owner_copy_continues_the_natural_walk`: core `GrabPointer` owner_events by O on G, O selects ButtonPress on C and P; deny O@C → O gets it at P; O's trace [C, P]. Kills: qualifying by selection; a second check on the write. + - `p10_denied_owner_with_allowed_foreign_falls_back`: O on C denied, F on C allowed, grab mask has ButtonPress → O gets it at G; trace O@C then O@G. Kills: the fallback reusing the memo. + - `p11_denied_foreign_selector_does_not_reject`: F alone on C denied, O on P → O at P. Variant: O and F on C, O allowed → no call for F. + - `p12_owner_qualifies_in_a_later_protocol`: F master XI2 on C, O core on C; allowed → O core at C, no F call; O denied → F's allowed XI2 rejects → fallback to G. Kills: foreign evaluated before the owner; latching F before O's core. Review focus 4. + - `p13_grab_window_denial_counts_as_delivered`: owner_events false, O denied at G → no bytes for anyone (C's selectors included), grab still active. Same row through `XIGrabDevice` (master, XI2). + - `p14_xi2_owner_events_fallback_is_fresh`: `XIGrabDevice` master owner_events by O with ButtonPress in the mask; O selects XI2 on C, denied; F XI2 on C allowed → O at G; trace O@C, O@G. + - `p15_denied_activating_press_still_activates_and_freezes`: sync `GrabButton` by O on G; deny O@G → no bytes; `active_pointer_grab` set; the master's `xi1_frozen` entry is `FrozenWithEvent` with the press stored; a following motion is queued. Same through `XIPassiveGrabDevice`. Review focus 5. +- [ ] **Step 2:** run; Expected: p8, p9, p10, p11 (denied row) and p13 FAIL; p12 and p14 may pass (the grab-window writes become `Fresh` here, and these rows guard it). +- [ ] **Step 3: implement.** +- [ ] **Step 4:** run the filter, `pointer_fanout::tests` (grab and XTS-derived rows) and the whole `--lib`. Expected PASS. +- [ ] **Step 5: commit** `feat(access): Receive decides grabbed pointer delivery`. + +### Task 3: implicit grab and the slave press protocol choice + +**Files:** +- Modify: `crates/yserver-core/src/core_loop/pointer_fanout.rs` (`resolve_slave_press_delivery` :3360; nothing else if Task 1 holds) +- Test: `access_pointer_input.rs` + +Rules (spec l.392–397): Receive-denied candidates leave each winner calculation, which then runs as today; no candidate → no implicit grab. `resolve_slave_press_delivery` takes the memo: at each window, the allowed slave XI2 selectors, else the allowed XI1 `DeviceButtonPress` selectors (XI1 description), else the parent. Its recipients are already decided: the XI1 write the router makes for them must not check again (Task 5 relies on this). + +- [ ] **Step 1: failing tests:** + - `p16_denied_candidate_is_not_the_implicit_owner`: A core on C denied, B core on P → B gets the press, B owns the implicit grab: after moving the pointer over C, the release goes to B at P. + - `p17_all_denied_no_implicit_grab`: A alone on C, denied → `active_pointer_grab` is `None` after the press. + - `p18_xi2_owner_preference_among_allowed`: the window's owner W and another client X both select master XI2 on C; deny W → X owns the implicit grab (today W would). + - `p19_denied_slave_xi2_falls_to_xi1`: slave origin; X slave XI2 on C denied, Y XI1 `DeviceButtonPress` on C → Y gets `DeviceButtonPress` at C and owns the XI1 implicit grab; Y's trace has one call. Kills: protocol choice by selection; a second XI1 check. + - `p20_denied_xi1_press_continues`: Y XI1 on C denied, Z XI1 on P → Z. +- [ ] **Step 2:** run; Expected: p18, p19 FAIL; p15–p17 pass if Task 1 holds (they pin it). +- [ ] **Step 3: implement.** +- [ ] **Step 4:** run the filter + whole `--lib`. Expected PASS. +- [ ] **Step 5: commit** `feat(access): Receive decides the slave press protocol`. + +### Task 4: raw and scroll + +**Files:** +- Modify: `crates/yserver-core/src/core_loop/pointer_fanout.rs` (raw writes :2340–2375, scroll Motion :2400–2440, `emit_scroll_stop_to_state` :2953) +- Modify: `crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs` (`xi2_motion_targets_for_source` :88 takes `receive: Option<&ReceiveMemo>`) +- Test: `access_pointer_input.rs` + +Rules (spec l.455–475): each raw root copy (slave and master fanouts, recipients and order unchanged) is checked with subject `Window(ROOT_WINDOW)` through `fanout_event_to_clients_with_receive`; a denial drops only that copy. The scroll Motion of a wheel press follows the ordinary walk: `xi2_motion_targets_for_source(.., Some(&memo))`, natural writes `Decided`, grab-window writes `Fresh`. The scroll stop routes with `None` (today's window) and checks each recipient once with the two-Motion batch; a denial drops both events and the walk does not resume. + +- [ ] **Step 1: failing tests:** + - `p21_denied_raw_root_copy_drops_only_that_copy`: A and B select master RawButtonPress on root, S selects the slave form; deny A → B and S get theirs. + - `p22_scroll_motion_follows_the_walk`: wheel press (button 4) from a source with a scroll class; X master XI2 Motion on C denied, Y on P → Y gets the scroll Motion at P. + - `p23_scroll_stop_is_not_rerouted`: `emit_scroll_stop_to_state`; X on C denied, Y on P → nobody gets the stop; X's trace has one call whose batch is two XI2 Motion descriptions; Y has none. Allowed → X gets both events. Kills: routing the stop through the memo; one check per event. +- [ ] **Step 2:** run; Expected: p20, p21, p22 FAIL. +- [ ] **Step 3: implement.** +- [ ] **Step 4:** run the filter, the raw and scroll rows in `pointer_fanout::tests`, and the whole `--lib`. Expected PASS. +- [ ] **Step 5: commit** `feat(access): Receive checks raw pointer and scroll copies`. + +### Task 5: the XI1 router + +**Files:** +- Modify: `crates/yserver-core/src/core_loop/pointer_fanout.rs` (`xi1_route_device_event` :3064, `compute_xi1_route_targets` :3337, `compute_xi1_targets_bounded` :3861, `xi1_fan_device_event` :3418) +- Modify: `crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs` (`xi1_window_selectors`, `xi1_window_selectors_with_grab_class` take the memo, or the router filters their result) +- Modify: callers: the pointer dispatch (passes its memo), `deliver_xi1_focused_key` (`key_fanout.rs`, fresh memo), the thaw path (fresh memo) +- Test: `access_pointer_input.rs`, `access_key_input.rs` (key rows) + +**Interfaces:** +- Consumes: `ReceiveMemo`, `PointerWrite` (Task 1); `SlavePressDelivery` recipients already decided (Task 3). +- Produces: `xi1_route_device_event(state, q, allow_freeze, slave_press_delivery, receive: &ReceiveMemo)`; `xi1_fan_device_event(state, targets, window, q, write: PointerWrite<'_>)`. Plan 3 calls the router from thaw with a fresh memo. + +Rules: +- The XI1 batch for one recipient: `DeviceMotionNotify` + its `DeviceValuator` = one batch of two descriptions; other events one description. The routing and the write use the same batch. +- Natural walk (`Walk`, `WalkUpTo`, `WindowOnly`): a window stops the walk when it has an allowed selector or a no-copy selector (a synthetic repeat release to a detectable-repeat client: no call). `WindowOnly` with every copy denied → no delivery (no direct attempt, spec l.409–413). Selection writes are `Decided`; `SlavePressDelivery::Xi1` recipients are `Decided`. +- XI1 grab: the owner gets the event at the natural window when `owner_events` and its copy there is allowed (`Decided`); otherwise at the grab window, `Fresh`, a denial = delivered. The passive XI1 activating write is `Fresh`; activation, sync freeze and the stored event are untouched. `xi1_freeze_this_event_if_needed` and `xi1_check_grab_for_syncs` run as today. +- XI1 implicit owner: computed from the allowed recipients; none → no implicit grab. + +- [ ] **Step 1: failing tests:** + - `p24_denied_xi1_selector_advances_the_walk`: slave origin motion; X `DeviceMotionNotify` on C denied, Y on P → Y at P. + - `p25_device_motion_and_valuator_are_one_batch`: X selects `DeviceMotionNotify` on C. Allowed → both frames; denied → neither, one call with the two-description batch. Kills: checking per event. + - `p26_xi1_grab`: `GrabDevice` owner_events by O on G; O selects on C, denied → O at G, trace O@C, O@G. `owner_events` false, O denied → no bytes, grab active. + - `p27_xi1_implicit_owner_from_allowed`: two XI1 press selectors on C, the one with the grab class denied → the other owns the implicit grab. + - `k16_xi1_focused_key_denial_advances_the_focus_walk` (in `access_key_input.rs`): XTEST keyboard origin; X `DeviceKeyPress` on C (pointer window under focus F) denied, Y on F → Y at F. + - `k17_xi1_detectable_repeat_release_stops_without_a_check`: synthetic repeat release; X (detectable repeat) selects `DeviceKeyRelease` on C, Y on F → nothing written, no call for X. +- [ ] **Step 2:** run; Expected: p23, p24, p25 (first row), p26, k16 FAIL; k17 passes (guard). +- [ ] **Step 3: implement.** +- [ ] **Step 4:** run the filters, `xi1` tests, `pointer_fanout::tests`, `key_fanout` tests, the whole `--lib`, and `cargo test --workspace --features xdmcp`. Expected PASS. +- [ ] **Step 5: commit** `feat(access): Receive decides XI1 device event delivery`. From fc18f1043917c69e5f12ecf523d587bb625b4d6e Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 17:00:55 -0300 Subject: [PATCH 18/72] docs(plan): number plan 2 rows consecutively Co-Authored-By: Claude Opus 5.5 --- .../2026-12-01-access-control-pr4c-pointer.md | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md b/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md index 08bb58bb7..12c9f3828 100644 --- a/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md +++ b/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md @@ -97,13 +97,13 @@ Rules (spec l.414–429, 431–440): - Activation, `CheckGrabForSyncs`, the stored event, confinement and the activation crossings are untouched. - [ ] **Step 1: failing tests:** - - `p9_denied_owner_copy_continues_the_natural_walk`: core `GrabPointer` owner_events by O on G, O selects ButtonPress on C and P; deny O@C → O gets it at P; O's trace [C, P]. Kills: qualifying by selection; a second check on the write. - - `p10_denied_owner_with_allowed_foreign_falls_back`: O on C denied, F on C allowed, grab mask has ButtonPress → O gets it at G; trace O@C then O@G. Kills: the fallback reusing the memo. - - `p11_denied_foreign_selector_does_not_reject`: F alone on C denied, O on P → O at P. Variant: O and F on C, O allowed → no call for F. - - `p12_owner_qualifies_in_a_later_protocol`: F master XI2 on C, O core on C; allowed → O core at C, no F call; O denied → F's allowed XI2 rejects → fallback to G. Kills: foreign evaluated before the owner; latching F before O's core. Review focus 4. - - `p13_grab_window_denial_counts_as_delivered`: owner_events false, O denied at G → no bytes for anyone (C's selectors included), grab still active. Same row through `XIGrabDevice` (master, XI2). - - `p14_xi2_owner_events_fallback_is_fresh`: `XIGrabDevice` master owner_events by O with ButtonPress in the mask; O selects XI2 on C, denied; F XI2 on C allowed → O at G; trace O@C, O@G. - - `p15_denied_activating_press_still_activates_and_freezes`: sync `GrabButton` by O on G; deny O@G → no bytes; `active_pointer_grab` set; the master's `xi1_frozen` entry is `FrozenWithEvent` with the press stored; a following motion is queued. Same through `XIPassiveGrabDevice`. Review focus 5. + - `p8_denied_owner_copy_continues_the_natural_walk`: core `GrabPointer` owner_events by O on G, O selects ButtonPress on C and P; deny O@C → O gets it at P; O's trace [C, P]. Kills: qualifying by selection; a second check on the write. + - `p9_denied_owner_with_allowed_foreign_falls_back`: O on C denied, F on C allowed, grab mask has ButtonPress → O gets it at G; trace O@C then O@G. Kills: the fallback reusing the memo. + - `p10_denied_foreign_selector_does_not_reject`: F alone on C denied, O on P → O at P. Variant: O and F on C, O allowed → no call for F. + - `p11_owner_qualifies_in_a_later_protocol`: F master XI2 on C, O core on C; allowed → O core at C, no F call; O denied → F's allowed XI2 rejects → fallback to G. Kills: foreign evaluated before the owner; latching F before O's core. Review focus 4. + - `p12_grab_window_denial_counts_as_delivered`: owner_events false, O denied at G → no bytes for anyone (C's selectors included), grab still active. Same row through `XIGrabDevice` (master, XI2). + - `p13_xi2_owner_events_fallback_is_fresh`: `XIGrabDevice` master owner_events by O with ButtonPress in the mask; O selects XI2 on C, denied; F XI2 on C allowed → O at G; trace O@C, O@G. + - `p14_denied_activating_press_still_activates_and_freezes`: sync `GrabButton` by O on G; deny O@G → no bytes; `active_pointer_grab` set; the master's `xi1_frozen` entry is `FrozenWithEvent` with the press stored; a following motion is queued. Same through `XIPassiveGrabDevice`. Review focus 5. - [ ] **Step 2:** run; Expected: p8, p9, p10, p11 (denied row) and p13 FAIL; p12 and p14 may pass (the grab-window writes become `Fresh` here, and these rows guard it). - [ ] **Step 3: implement.** - [ ] **Step 4:** run the filter, `pointer_fanout::tests` (grab and XTS-derived rows) and the whole `--lib`. Expected PASS. @@ -118,11 +118,11 @@ Rules (spec l.414–429, 431–440): Rules (spec l.392–397): Receive-denied candidates leave each winner calculation, which then runs as today; no candidate → no implicit grab. `resolve_slave_press_delivery` takes the memo: at each window, the allowed slave XI2 selectors, else the allowed XI1 `DeviceButtonPress` selectors (XI1 description), else the parent. Its recipients are already decided: the XI1 write the router makes for them must not check again (Task 5 relies on this). - [ ] **Step 1: failing tests:** - - `p16_denied_candidate_is_not_the_implicit_owner`: A core on C denied, B core on P → B gets the press, B owns the implicit grab: after moving the pointer over C, the release goes to B at P. - - `p17_all_denied_no_implicit_grab`: A alone on C, denied → `active_pointer_grab` is `None` after the press. - - `p18_xi2_owner_preference_among_allowed`: the window's owner W and another client X both select master XI2 on C; deny W → X owns the implicit grab (today W would). - - `p19_denied_slave_xi2_falls_to_xi1`: slave origin; X slave XI2 on C denied, Y XI1 `DeviceButtonPress` on C → Y gets `DeviceButtonPress` at C and owns the XI1 implicit grab; Y's trace has one call. Kills: protocol choice by selection; a second XI1 check. - - `p20_denied_xi1_press_continues`: Y XI1 on C denied, Z XI1 on P → Z. + - `p15_denied_candidate_is_not_the_implicit_owner`: A core on C denied, B core on P → B gets the press, B owns the implicit grab: after moving the pointer over C, the release goes to B at P. + - `p16_all_denied_no_implicit_grab`: A alone on C, denied → `active_pointer_grab` is `None` after the press. + - `p17_xi2_owner_preference_among_allowed`: the window's owner W and another client X both select master XI2 on C; deny W → X owns the implicit grab (today W would). + - `p18_denied_slave_xi2_falls_to_xi1`: slave origin; X slave XI2 on C denied, Y XI1 `DeviceButtonPress` on C → Y gets `DeviceButtonPress` at C and owns the XI1 implicit grab; Y's trace has one call. Kills: protocol choice by selection; a second XI1 check. + - `p19_denied_xi1_press_continues`: Y XI1 on C denied, Z XI1 on P → Z. - [ ] **Step 2:** run; Expected: p18, p19 FAIL; p15–p17 pass if Task 1 holds (they pin it). - [ ] **Step 3: implement.** - [ ] **Step 4:** run the filter + whole `--lib`. Expected PASS. @@ -138,9 +138,9 @@ Rules (spec l.392–397): Receive-denied candidates leave each winner calculatio Rules (spec l.455–475): each raw root copy (slave and master fanouts, recipients and order unchanged) is checked with subject `Window(ROOT_WINDOW)` through `fanout_event_to_clients_with_receive`; a denial drops only that copy. The scroll Motion of a wheel press follows the ordinary walk: `xi2_motion_targets_for_source(.., Some(&memo))`, natural writes `Decided`, grab-window writes `Fresh`. The scroll stop routes with `None` (today's window) and checks each recipient once with the two-Motion batch; a denial drops both events and the walk does not resume. - [ ] **Step 1: failing tests:** - - `p21_denied_raw_root_copy_drops_only_that_copy`: A and B select master RawButtonPress on root, S selects the slave form; deny A → B and S get theirs. - - `p22_scroll_motion_follows_the_walk`: wheel press (button 4) from a source with a scroll class; X master XI2 Motion on C denied, Y on P → Y gets the scroll Motion at P. - - `p23_scroll_stop_is_not_rerouted`: `emit_scroll_stop_to_state`; X on C denied, Y on P → nobody gets the stop; X's trace has one call whose batch is two XI2 Motion descriptions; Y has none. Allowed → X gets both events. Kills: routing the stop through the memo; one check per event. + - `p20_denied_raw_root_copy_drops_only_that_copy`: A and B select master RawButtonPress on root, S selects the slave form; deny A → B and S get theirs. + - `p21_scroll_motion_follows_the_walk`: wheel press (button 4) from a source with a scroll class; X master XI2 Motion on C denied, Y on P → Y gets the scroll Motion at P. + - `p22_scroll_stop_is_not_rerouted`: `emit_scroll_stop_to_state`; X on C denied, Y on P → nobody gets the stop; X's trace has one call whose batch is two XI2 Motion descriptions; Y has none. Allowed → X gets both events. Kills: routing the stop through the memo; one check per event. - [ ] **Step 2:** run; Expected: p20, p21, p22 FAIL. - [ ] **Step 3: implement.** - [ ] **Step 4:** run the filter, the raw and scroll rows in `pointer_fanout::tests`, and the whole `--lib`. Expected PASS. @@ -165,10 +165,10 @@ Rules: - XI1 implicit owner: computed from the allowed recipients; none → no implicit grab. - [ ] **Step 1: failing tests:** - - `p24_denied_xi1_selector_advances_the_walk`: slave origin motion; X `DeviceMotionNotify` on C denied, Y on P → Y at P. - - `p25_device_motion_and_valuator_are_one_batch`: X selects `DeviceMotionNotify` on C. Allowed → both frames; denied → neither, one call with the two-description batch. Kills: checking per event. - - `p26_xi1_grab`: `GrabDevice` owner_events by O on G; O selects on C, denied → O at G, trace O@C, O@G. `owner_events` false, O denied → no bytes, grab active. - - `p27_xi1_implicit_owner_from_allowed`: two XI1 press selectors on C, the one with the grab class denied → the other owns the implicit grab. + - `p23_denied_xi1_selector_advances_the_walk`: slave origin motion; X `DeviceMotionNotify` on C denied, Y on P → Y at P. + - `p24_device_motion_and_valuator_are_one_batch`: X selects `DeviceMotionNotify` on C. Allowed → both frames; denied → neither, one call with the two-description batch. Kills: checking per event. + - `p25_xi1_grab`: `GrabDevice` owner_events by O on G; O selects on C, denied → O at G, trace O@C, O@G. `owner_events` false, O denied → no bytes, grab active. + - `p26_xi1_implicit_owner_from_allowed`: two XI1 press selectors on C, the one with the grab class denied → the other owns the implicit grab. - `k16_xi1_focused_key_denial_advances_the_focus_walk` (in `access_key_input.rs`): XTEST keyboard origin; X `DeviceKeyPress` on C (pointer window under focus F) denied, Y on F → Y at F. - `k17_xi1_detectable_repeat_release_stops_without_a_check`: synthetic repeat release; X (detectable repeat) selects `DeviceKeyRelease` on C, Y on F → nothing written, no call for X. - [ ] **Step 2:** run; Expected: p23, p24, p25 (first row), p26, k16 FAIL; k17 passes (guard). From bb838412c6a4cae1e2f43a6bfde647feea9e640c Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 17:15:49 -0300 Subject: [PATCH 19/72] docs(plan): plan 2 review round 1 Co-Authored-By: Claude Opus 5.5 --- .../2026-12-01-access-control-pr4c-pointer.md | 187 ++++++++++-------- 1 file changed, 102 insertions(+), 85 deletions(-) diff --git a/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md b/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md index 12c9f3828..600e95a41 100644 --- a/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md +++ b/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md @@ -4,22 +4,23 @@ **Goal:** Make a Receive denial take part in the pointer routing decisions (core walk and XI2 absorption, per-client form shadowing, XI2 form walks, owner-events resolution, grab-window delivery, passive activation, implicit-grab winners, slave press protocol choice, raw and scroll copies) and in the shared XI1 router, as the approved spec section says. -**Architecture:** One pointer dispatch (`pointer_event_fanout_to_state_inner`) owns one `ReceiveMemo`. Every selection-based decision asks the memo, which calls `check_receive` once per (client, subject, batch) and returns the stored result after that, so the resolvers that run more than once per dispatch (`owner_events_route`, the per-client form windows in the XI2 writer, the core candidate) see one result and the write reuses it. Grab-window writes are distinct attempts and check fresh through the existing `fanout_event_to_clients_with_receive`. With no policy, `receive_allows` returns `true` without asking, so every decision takes today's inputs and the bytes stay identical. +**Architecture:** One pointer dispatch (`pointer_event_fanout_to_state_inner`) owns one `ReceiveMemo`. A decision whose result becomes a write asks the memo, which calls `check_receive` once per (client, subject, batch) and returns the stored result after that, so the resolvers that run more than once per dispatch (`owner_events_route`, the per-client form windows in the XI2 writer, the core shadow) see one result and the write reuses it. A computation whose result does not become a write decides from selection, with no check. Grab-window writes are distinct attempts and check fresh. With no policy, `receive_allows` returns `true` without asking, so every decision takes today's inputs and the bytes stay identical. **Tech Stack:** Rust, yserver-core (`core_loop/pointer_fanout.rs`, `core_loop/pointer_fanout/owner_events.rs`, `core_loop/fanout.rs`, `core_loop/key_fanout.rs` for the XI1 key leg), the access layer (`ServerState::check_receive`, `EventSubject`, `EventBatch`, `EventDescription`). **Spec:** `docs/superpowers/specs/2026-10-30-access-control-layer-design.md`, section "Input delivery under denial" (lines 353–527), approved 2026-11-25, merged in #389. -**Series context:** plan 1 (keyboard, done at `aa8338c3`) converted the focused, grabbed and raw key paths with per-call lazy checks; this plan converts the pointer and the XI1 router, which the XI1 key leg (`deliver_xi1_focused_key`) shares. Plan 3 (replay, thaw, freeze) adds the re-delivery tests and does not convert these sites again. Why a memo here and not plan 1's callbacks: the pointer recomputes the same decision in several places of one dispatch (see Architecture), and a memo makes them agree without threading result lists through the 2300-line dispatch. +**Series context:** plan 1 (keyboard, done at `aa8338c3`) converted the focused, grabbed and raw key paths with per-call lazy checks. This plan converts the pointer and the XI1 router, which the XI1 key leg (`deliver_xi1_focused_key`) and the thaw re-entries share. Plan 3 (replay, thaw, freeze) adds the re-delivery tests and does not convert these sites again. The pointer uses a memo instead of plan 1's callbacks because it recomputes the same decision in several places of one dispatch; the memo makes them agree without threading result lists through the 2300-line dispatch. ## Global Constraints - With no policy, and with an allow-all policy, every scenario's bytes on every client, the order per client, and the grab/freeze/implicit-grab state equal today's (spec l.357–359). -- A denied copy is a non-delivery: it does not stop a walk, shadow another form, qualify an owner, or reject a grab (spec l.370–373). A selection that produces no copy still decides as today and Receive is not asked for it (spec l.374–380). -- One Receive result per recipient per delivery attempt, reused by the write. A grab-window fallback, an `owner_events = false` grab write and a passive activating write are distinct attempts with a fresh check; a denial there counts as delivered (spec l.381–385, 424–429). -- Subjects: `EventSubject::Window()` for cooked copies; `Window(ROOT_WINDOW)` for raw root copies (spec l.455–461). -- Descriptions: core `EventDescription::core(4|5|6)` (ButtonPress, ButtonRelease, MotionNotify); XI2 `crate::xinput::xi2_event_description(evtype)` (slave and master forms share it); raw `xi2_event_description(raw evtype)`; XI1 `crate::xinput::xi1_event_description(offset)`. Batches: XI1 `DeviceMotionNotify` + its `DeviceValuator` = one `EventBatch` of two descriptions; the smooth-scroll stop = one batch of two XI2 Motion descriptions (spec l.463–475). -- Crossings keep their existing local check after the XI2-over-core dedup and are NOT routed through the memo; a denied XI2 crossing does not expose a core crossing (spec l.480–484). +- A denied copy is a non-delivery: it does not stop a walk, shadow another form, qualify an owner, or reject a grab (spec l.370–373). A selection that produces no copy (shadowed, suppressed, or of a form this dispatch does not write) still decides as today, and Receive is not asked for it (spec l.374–380). +- Receive is asked for a (client, window, form) copy only when this dispatch writes that copy if it is allowed. One result per recipient per attempt, reused by the write (spec l.381–385). +- Grab-window delivery (fallback, `owner_events = false`, XI2 grab delivery, passive activating write) is a distinct attempt with a fresh check in the grab's protocol (core grab: core; XI2 grab: XI2; XI1 grab: XI1), made BEFORE the grab mask, the implicit `device_mask` and the `!via_xi2` guard; a denial counts as delivered (spec l.424–429, `dix/events.c:4388-4398`). +- Subjects: `EventSubject::Window()`; `Window(ROOT_WINDOW)` for raw root copies (spec l.455–461). +- Descriptions: core `EventDescription::core(4|5|6)` (ButtonPress, ButtonRelease, MotionNotify); XI2 `crate::xinput::xi2_event_description(evtype)` (slave and master forms share it); raw `xi2_event_description(raw evtype)`; XI1 `crate::xinput::xi1_event_description(offset)`. Batches (spec l.463–475): XI1 `DeviceMotionNotify` + `DeviceValuator` = one batch of two descriptions, used by routing and write alike; the smooth-scroll stop = one batch of two XI2 Motion descriptions. +- Crossings keep their existing local check after the XI2-over-core dedup and are not routed through the memo; a denied XI2 crossing does not expose a core crossing (spec l.480–484). - Keep every encoder, the write order (slave form before master per connection, deferred core after its client's slave form), and the multiplicity. - No new `YSERVER_*` environment variables. Reuse first: new code only where a decision needs a Receive result it cannot get today. - Tests drive production entries (`pointer_event_fanout_to_state`, `emit_scroll_stop_to_state`, `key_event_fanout_to_state`, requests through `NotifyFixture::request`), not private helpers; each test names the mutation it kills. Cite Xorg at `xorg-server-21.1.24` as `dix/events.c:`. @@ -28,20 +29,21 @@ ## Review Focus -1. A Receive call for a copy the dispatch never emits is a phantom: the master form when `button_transition.master_accepted` is false, a form excluded by the replay flags, a scroll-motion-only grab copy that encodes nothing, an owner-events foreign selector when the owner already qualified at that window, the trace-level click-hit diagnostic (`yserver::input::clickhit`), which must route with `None`. Test p7 pins the first. -2. A client that selects master XI2 and core at one window: allowed XI2 shadows core with no core call; denied XI2 neither absorbs the core walk nor shadows that client's core copy (p2, p5). -3. A deferred core copy (slave origin, client also selects the slave XI2 form) is checked once at admission and keeps slave-before-core order; the flush does not check (p6). -4. Owner-events: the owner qualifying in a later protocol at the same window (core after a foreign XI2 selector) still wins with no foreign call (p11). -5. Passive activation with the owner denied: the grab still activates, a sync grab still freezes with the stored press, and nobody else gets the press (p14). +1. Phantom checks: a Receive call for a copy the dispatch never writes. Sources: a form not emitted (`master_accepted` false, replay flags, floating slave, `is_replay`), a form owned or redirected by a grab (its natural selectors), clients `xi2_grab_delivery` drops, master selectors at the slave pass's earlier window, the deferral's `has_slave_form` probe, the click-hit diagnostic, a foreign selector where the owner already qualified (pointer and XI1 grabs), the XI1 grab's natural walk with `owner_events` false. Tests p7, p11, p12, p26 pin several. +2. Core shadowing: a client's core copy is shadowed when that client receives the allowed master XI2 form in this dispatch, wherever that copy goes (today's rule, not "same window"); a shadowed core selection stops the core walk with no core check (p5, p5b). +3. A deferred core copy is checked once at admission, keeps slave-before-core order, and a denied one is not the implicit-grab core candidate (p6). +4. Owner-events: the owner qualifying in a later protocol at the same window still wins with no foreign call (p11). +5. Passive activation with the owner denied: the grab still activates, a sync grab still freezes with the stored press, nobody else gets the press (p14). --- -### Task 1: the memo and the natural pointer attempt +### Task 1: the memo, the harness, and the natural pointer attempt **Files:** -- Modify: `crates/yserver-core/src/core_loop/fanout.rs` (`ReceiveMemo` beside `receive_allows` :297; `pointer_propagation_target_by_id` :200 and `xi2_pointer_selected_on` :166) -- Modify: `crates/yserver-core/src/core_loop/pointer_fanout.rs` (memo created in `pointer_event_fanout_to_state_inner` :521; `xi2_form_selected_on_for_source` :4483, `xi2_route_window_for_source` :4509, `xi2_form_targets_for_source` :4531, `compute_xi2_targets_for_source` :4594, `xi2_pointer_forms_for_source` :4767; core step 4 and its XI2 dedup; the XI2 writer :2560–2830; `fanout_core_pointer_event_ordered` :4043 and the deferral :4009–4185) -- Create: `crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs` (helpers moved from `access_key_input.rs`: `send`, `send_with_reply`, `select_core`, `select_xi2`, the policy/trace plumbing, per-client trace comparison) and `access_pointer_input.rs` (+ `mod` lines) +- Modify: `crates/yserver-core/src/core_loop/fanout.rs` (`ReceiveMemo` beside `receive_allows` :297; `pointer_propagation_target_by_id` :200, `xi2_pointer_selected_on` :166) +- Modify: `crates/yserver-core/src/core_loop/pointer_fanout.rs` (memo in `pointer_event_fanout_to_state_inner` :521; `xi2_route_window_for_source` :4509, `xi2_form_targets_for_source` :4531, `compute_xi2_targets_for_source` :4594, `xi2_pointer_forms_for_source` :4767, `xi2_stamp_deviceid_for_source` :4704; core step 4 and its dedup :1780–1930; the XI2 targets :2113–2160 and writer :2509–2830; `fanout_core_pointer_event_ordered` :4043 and the deferral :4009–4185; the click-hit diagnostic :1395) +- Modify: `crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs` (callers of the changed helpers, :187, :202, :404; routing semantics change in Task 2) +- Create: `crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs` (harness moved from `access_key_input.rs`) and `access_pointer_input.rs` (+ `mod` lines) **Interfaces:** - Produces in `fanout.rs`: @@ -51,79 +53,89 @@ pub(crate) fn new() -> Self; /// First call per (client, subject, batch) asks `receive_allows`; /// later calls return the stored result without asking. - pub(crate) fn allows(&self, state: &ServerState, client: ClientId, + pub(crate) fn allows(&mut self, state: &ServerState, client: ClientId, subject: EventSubject, events: &EventBatch<'_>) -> bool; } ``` - Interior mutability so read-only resolvers taking `&ServerState` can use it. Keys compare by equality (the access types derive `Eq`, not `Hash`; a small `Vec` is fine). -- Produces: every pointer routing helper listed above takes `receive: Option<&ReceiveMemo>`. `None` = today's selection-only routing (crossings, the scroll stop, the click-hit diagnostic). `Some` = a selection at window W counts only if its copy is allowed: `selected && memo.allows(client, Window(W), )`. -- Produces in `pointer_fanout.rs`: `enum PointerWrite<'a> { Decided(&'a ReceiveMemo), Fresh }`. `Decided`: the writer keeps the recipients the memo allows (cache hits, no new call) and writes through the unchecked `fanout_event_to_clients`. `Fresh`: `fanout_event_to_clients_with_receive` (a denial = delivered). `fanout_core_pointer_event_ordered` takes it; core Enter/Leave pass `Fresh` (today's local check). Deferred core copies: `Decided` filters by the memo at admission, `Fresh` checks with `receive_allows` at admission; the flush writes unchecked. -- Produces (test support): `access_pointer_input.rs` scenario rows in plan 1's style: windows and selections through requests (`CreateWindow`, `ChangeWindowAttributes`, `XISelectEvents`, XI1 `SelectExtensionEvent`), a policy denying a set of `(client, subject, description)`, `pointer_event_fanout_to_state(.., handle_grabs = true, is_replay = false)` with a `HostPointerEvent` builder (reuse the one in `access_crossing_notify.rs:305`), per-client frames `(description, event window, child)` and the per-client Receive trace filtered to pointer, XI1 and raw descriptions (crossings, DeviceChanged and focus calls dropped). Slave origin = the XTEST pointer (`InputOrigin::XTest()`). Every row also runs with no policy and allow-all and asserts identical bytes and grab state. + Keys compare by equality (the access types derive `Eq`, not `Hash`; a small `Vec` is fine). +- Produces: the routing helpers above take `receive: Option<&mut ReceiveMemo>`. `None` = today's selection-only routing. `Some` = a selection at window W counts only if its copy is allowed: selected and `allows(client, Window(W), )`. The client-state predicate `xi2_form_selected_on_for_source` stays selection-only; its callers add the check with the `ClientId` they have. +- Produces: writers take `fresh_check: bool`. `false`: the recipients were decided by the memo, the write is the unchecked `fanout_event_to_clients`. `true`: `fanout_event_to_clients_with_receive` (a denial = delivered). `fanout_core_pointer_event_ordered` takes it; core Enter/Leave keep today's check. Deferred core copies: admitted only if allowed (memo when decided, `receive_allows` when fresh); the flush writes unchecked. +- Produces (test support, `access_input_support.rs`): plan 1's harness, generalised: + - the policy denies and the trace records whole batches, as ordered description lists (today `decide` :451 and the trace :562 only match one description); + - it recognises core and XI2 key and pointer descriptions, raw descriptions, and XI1 device descriptions, and decodes the matching frames, including the `DeviceValuator` continuation; + - each row states the expected grab state of its denied run (active pointer and keyboard grab owner, window, implicit/passive flags, XI1 implicit grab, freeze state) instead of requiring it to equal allow-all; + - the no-policy and allow-all runs still assert identical bytes and grab state; + - a pointer driver: `pointer_event_fanout_to_state(.., handle_grabs = true, is_replay = false)` with `core_pointer_event` (`access_crossing_notify.rs:299`); master origin `InputOrigin::XTest(2)`, slave origin `XTest(4)`, a second slave as `InputOrigin::Physical` (as in `pointer_fanout/tests/implicit_grabs.rs:741`). + `access_key_input` keeps 29/29 after the move. Rules: -- Core walk (`pointer_propagation_target_by_id`): at each window, the XI2 absorption asks the master-form description for each client with a master-form selection there (devices 2, 1, 0) and absorbs only if one is allowed; then the core subscribers that are allowed stop the walk and are the recipients. -- XI2 form walks: `xi2_route_window_for_source` stops at the first window with an allowed selector of that form; `xi2_form_targets_for_source` returns the allowed ones; `xi2_pointer_forms_for_source` and the writer's per-form window use the same memo, so a client's slave and master forms at one window share one call. -- Core step 4 XI2 dedup: a client's core copy is shadowed only by its allowed master XI2 copy at the same window. The implicit-grab core candidate comes from the allowed core recipients. -- The XI2 writer: natural geometry → `Decided` (`delivered = allowed && not transport-failed`, which feeds `consider_xi2_press`); fixed grab-window geometry (`xi2_grab_window_target`, `xi2_slave_grab_window_target`, `xi2_grab_delivery`) → `Fresh` (Task 2 tests it); crossings → today's local check. No call for a form the dispatch does not write (`button_want` false, scroll-motion-only grab copy with no bytes). - -- [ ] **Step 1: move the shared helpers** into `access_input_support.rs`; `access_key_input` stays 29/29 green, no behaviour change. Commit `test(access): share the input scenario helpers`. -- [ ] **Step 2: failing tests** in `access_pointer_input.rs` (tree: root ⊃ P ⊃ C, pointer over C; ButtonPress unless stated): - - `p1_denied_core_selector_does_not_stop_the_core_walk`: B core on C, A core on P; deny B@C → A gets it at P with child C; trace [B@C core, A@P core]. Kills: stop on selection. - - `p2_denied_xi2_selector_does_not_absorb_core`: X master XI2 on C, A core on P. No policy: A nothing (absorbed). Deny X@C XI2 → A gets core at P, X nothing; X's trace has exactly one XI2@C call although absorption and the XI2 walk both ask. Kills: absorption from selection; a second check. - - `p3_xi2_walk_skips_a_denied_window`: X master XI2 on C denied, Y on P → Y gets XI2 at P, child C. Kills: route window from selection. - - `p4_slave_and_master_forms_share_one_check`: slave origin; X selects XIAllDevices on C. Allowed → slave then master form, one call. Denied → nothing for X, Y (master XI2 on P) gets the master form at P. Kills: one check per form. - - `p5_denied_xi2_reopens_that_clients_core`: A selects master XI2 and core on C. Allowed → XI2 only, no core call. XI2 denied → core at C, trace [A XI2@C, A core@C]. Kills: shadow from selection. - - `p6_deferred_core_copy_is_checked_at_admission`: slave origin; A selects slave XI2 and core on C (core deferred). Allow-all → slave XI2 then core, as today. Core denied → slave XI2 only; one core call. Kills: check at flush; no check. - - `p7_no_check_for_a_form_not_emitted`: hold button 1 through one slave, press button 1 through the XTEST slave (master bitmap unchanged, `master_accepted` false); X selects master XI2 ButtonPress on C → no call for X. Kills: phantom master-form check. Review focus 1. -- [ ] **Step 3:** run `cargo test -p yserver-core --lib access_pointer_input`. Expected: p1, p2, p3, p4 (denied row), p5 and p6 FAIL; p7 passes (guards the implementation). -- [ ] **Step 4: implement** `ReceiveMemo`, the `receive` parameters, `PointerWrite`, the memo in the dispatch. Existing callers outside the dispatch (crossing producers, diagnostics) pass `None`. -- [ ] **Step 5:** run the filter, `pointer_fanout::tests`, `access_crossing_notify` and the whole `--lib`. Expected PASS, existing tests unchanged. +- **Emitted forms.** Before routing, the dispatch knows which XI2 forms it writes: the slave form when it is pushed (`replay_has_slave_form`, `source_accepted`, not a slave activation), the master form when it is pushed (`replay_has_master_form`, `master_accepted`, the attached-master condition at :2593, not `is_replay`). A form that is not written, or whose delivery a grab owns or redirects (master grab, slave grab, `xi2_grab_delivery`), routes its natural selectors with `None`. The earlier-window computation (:2158) uses the memo only for the slave form. The deferral's `has_slave_form` probe (:4068) and the click-hit diagnostic use `None`. +- **XI2 form walks.** For an emitted, ungrabbed form: the route window is the first window with an allowed selector of that form; the recipients are the allowed ones; `xi2_pointer_forms_for_source` and the writer's per-form window use the same memo, so a client's slave and master forms at one window share one call. +- **Core shadow and walk.** The master route is resolved before the core walk. A client's core copy is shadowed when the client is among the master form's allowed recipients, wherever that copy goes (today's dedup, `:1838–1869`, with `xi2_stamp_deviceid_for_source` deciding from the same memo entries). At each core-walk window: the window absorbs when it is the master form's route window (selection-only when the master form is not emitted); a shadowed core subscriber stops the walk with no core check; the unshadowed subscribers are checked, and the walk stops if any is allowed or shadowed. The recipients are the allowed unshadowed ones. +- **Implicit-grab candidates.** The core candidate comes from the core copies actually admitted (immediate allowed, or deferred and admitted). The XI2 candidate: `delivered = allowed && not transport-failed`. +- **XI2 writer.** Natural geometry → `fresh_check = false`. Fixed grab-window geometry (`xi2_grab_window_target`, `xi2_slave_grab_window_target`, `xi2_grab_delivery`) → fresh (Task 2 tests it). Crossings → today's local check. + +- [ ] **Step 1: move and generalise the harness** (batches, XI1, per-row denied grab state); `access_key_input` 29/29. Commit `test(access): share the input scenario helpers`. +- [ ] **Step 2: failing tests** in `access_pointer_input.rs` (tree: root ⊃ P ⊃ C, pointer over C; master origin and ButtonPress unless stated): + - `p1_denied_core_selector_does_not_stop_the_core_walk`: B core on C, A core on P; deny B@C → A gets it at P with child C; trace [B@C core, A@P core]; denied grab: implicit owner A at P. Kills: stop on selection. + - `p2_denied_xi2_selector_does_not_absorb_core`: X master XI2 on C, A core on P. No policy: A nothing. Deny X@C XI2 → A gets core at P; X has exactly one call. Kills: absorption from selection; a second check. + - `p3_xi2_walk_skips_a_denied_window`: X master XI2 on C denied, Y on P → Y at P, child C. Kills: route window from selection. + - `p4_slave_and_master_forms_share_one_check`: slave origin; X selects XIAllDevices on C. Allowed → slave then master form, one call. Denied → X nothing, Y (master XI2 on P) gets the master form at P. Kills: one check per form. + - `p5_denied_xi2_reopens_that_clients_core`: A master XI2 and core on C. Allowed → XI2 only, no core call. XI2 denied → core at C, trace [A XI2@C, A core@C]. Kills: shadow from selection. + - `p5b_shadow_follows_the_master_copy_anywhere`: A core on C and master XI2 on P, B core on P. Allow-all: A gets XI2 at P only, as today. Deny A's core at C → same bytes, no A core call, B nothing. Deny A's XI2 at P → A gets core at C. Kills: a same-window shadow; checking a shadowed core copy (walk then dedup). + - `p5c_stamp_uses_the_allowed_route`: slave origin; X master XI2 on C denied; A selects master XI2, slave XI2 and core on P → A gets the slave and master XI2 forms at P and no core. Kills: a selection-only `xi2_stamp_deviceid_for_source`. + - `p6_deferred_core_copy_is_checked_at_admission`: slave origin; A slave XI2 and core on C (core deferred). Allow-all → slave XI2 then core, as today. Core denied → slave XI2 only, one core call, no master implicit grab owned by A. Kills: check at flush; no check. + - `p7_no_check_for_a_form_not_emitted`: the `Physical` slave holds button 1; the XTEST slave then presses button 1 (`master_accepted` false); X master XI2 ButtonPress on C → no call for X on the second press. Kills: phantom master-form check. +- [ ] **Step 3:** run `cargo test -p yserver-core --lib access_pointer_input`. Expected: p1, p2, p3, p4 (denied row), p5, p5b (denied rows), p5c, p6 FAIL; p7 passes (guard). +- [ ] **Step 4: implement.** +- [ ] **Step 5:** run the filter, `pointer_fanout::tests`, `access_crossing_notify`, `access_key_input` and the whole `--lib`. Expected PASS, existing tests unchanged. - [ ] **Step 6: commit** `feat(access): Receive decides the natural pointer walks`. ### Task 2: grabs and passive activation **Files:** -- Modify: `crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs` (`owner_events_route` :384, `xi2_motion_targets_for_source` callers inside) -- Modify: `crates/yserver-core/src/core_loop/pointer_fanout.rs` (core grab block :1430–1555, XI2 grab block :2220–2310, passive activation :1560–1700) +- Modify: `crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs` (`owner_events_route` :384) +- Modify: `crates/yserver-core/src/core_loop/pointer_fanout.rs` (core grab block :1430–1555, passive activation :1560–1700, XI2 grab block :2220–2310) - Test: `access_pointer_input.rs` **Interfaces:** -- Consumes: `ReceiveMemo`, `PointerWrite`, the harness (Task 1). -- Produces: `owner_events_route(.., receive: Option<&ReceiveMemo>)` following the rules below; `OwnerEventsRoute::Natural` means the owner's copy there is already allowed. +- Consumes: `ReceiveMemo`, `fresh_check`, the harness (Task 1). +- Produces: `owner_events_route(.., receive: Option<&mut ReceiveMemo>)`; `OwnerEventsRoute::Natural` means the owner's copy there is allowed. `fn xi1_batch(evcode: u8) -> Vec` (two descriptions for `DeviceMotionNotify`, one otherwise), used by the XI1 leg here and by Task 5. Rules (spec l.414–429, 431–440): -- At each window: the owner first, in today's protocol order (XI2, XI1, core), qualifies through the first protocol it selected whose copy is allowed. Only if it qualifies in none are the foreign selectors of all three protocols evaluated, every one (no short-circuit), and any allowed one rejects → `Fallback`. Else continue to the parent. With `None` this equals today's result. -- Natural core write → `PointerWrite::Decided`. Fallback and `owner_events = false` writes (core and XI2), the XI2 slave grab delivery and the passive activating press → `Fresh` with subject `Window(grab_window)`; a denial still sets `handled_core_via_grab` and nobody else gets the copy. Where today's grab mask filters the copy no write happens, so no check is made either (Ruling: Xorg checks before the mask, `dix/events.c:4388-4398`; the outcome is the same, no bytes and input captured). +- At each window: the owner first, in today's protocol order (XI2, XI1 with `xi1_batch`, core), qualifies through the first protocol it selected whose copy is allowed. Only if it qualifies in none are the foreign selectors of the three protocols evaluated, every one (no short-circuit); any allowed one → `Fallback`. Else the parent. With `None` this equals today's result. +- Natural core write: `fresh_check = false`. Every grab-window write (core fallback and `owner_events = false` at :1494–1540, the XI2 master and slave fallbacks, the passive activating press at :1680) checks fresh in the grab's protocol, before the grab mask and the `!via_xi2` guard: a core grab checks the core copy, an XI2 grab the XI2 copy (in the XI2 block, before `xi2_grab_accepts_event`). A denial sets `handled_core_via_grab` as today and nobody else gets the copy. - Activation, `CheckGrabForSyncs`, the stored event, confinement and the activation crossings are untouched. -- [ ] **Step 1: failing tests:** - - `p8_denied_owner_copy_continues_the_natural_walk`: core `GrabPointer` owner_events by O on G, O selects ButtonPress on C and P; deny O@C → O gets it at P; O's trace [C, P]. Kills: qualifying by selection; a second check on the write. - - `p9_denied_owner_with_allowed_foreign_falls_back`: O on C denied, F on C allowed, grab mask has ButtonPress → O gets it at G; trace O@C then O@G. Kills: the fallback reusing the memo. - - `p10_denied_foreign_selector_does_not_reject`: F alone on C denied, O on P → O at P. Variant: O and F on C, O allowed → no call for F. - - `p11_owner_qualifies_in_a_later_protocol`: F master XI2 on C, O core on C; allowed → O core at C, no F call; O denied → F's allowed XI2 rejects → fallback to G. Kills: foreign evaluated before the owner; latching F before O's core. Review focus 4. - - `p12_grab_window_denial_counts_as_delivered`: owner_events false, O denied at G → no bytes for anyone (C's selectors included), grab still active. Same row through `XIGrabDevice` (master, XI2). - - `p13_xi2_owner_events_fallback_is_fresh`: `XIGrabDevice` master owner_events by O with ButtonPress in the mask; O selects XI2 on C, denied; F XI2 on C allowed → O at G; trace O@C, O@G. - - `p14_denied_activating_press_still_activates_and_freezes`: sync `GrabButton` by O on G; deny O@G → no bytes; `active_pointer_grab` set; the master's `xi1_frozen` entry is `FrozenWithEvent` with the press stored; a following motion is queued. Same through `XIPassiveGrabDevice`. Review focus 5. -- [ ] **Step 2:** run; Expected: p8, p9, p10, p11 (denied row) and p13 FAIL; p12 and p14 may pass (the grab-window writes become `Fresh` here, and these rows guard it). +- [ ] **Step 1: failing tests** (core grabs through `GrabPointer`/`GrabButton`, XI2 through `XIGrabDevice`/`XIPassiveGrabDevice`; each names its origin): + - `p8_denied_owner_copy_continues_the_natural_walk`: core grab, owner_events, by O on G; O selects on C and P; deny O@C → O at P; O's trace [C, P]. Kills: qualifying by selection; a second check on the write. + - `p9_denied_owner_with_allowed_foreign_falls_back`: O on C denied, F on C allowed → O at G; trace O@C then O@G. Kills: the fallback reusing the memo. + - `p10_denied_foreign_selector_does_not_reject`: F alone on C denied, O on P → O at P. + - `p11_owner_qualifies_in_a_later_protocol`: core grab; F master XI2 on C, O core on C. Allowed → O core at C, no call for F (also not from the XI2 target computation). O denied → F's allowed XI2 rejects → O at G. Kills: foreign before owner; F asked under a grab-owned master form. + - `p12_grab_window_denial_counts_as_delivered`: `owner_events` false, O denied at G → no bytes for anyone, C's selectors included; grab active. Second row: the grab mask lacks ButtonPress, O denied → O's trace still has the G call (check before the mask). XI2 row: `XIGrabDevice` master, master origin, foreign master XI2 selector on C → no call for it. + - `p13_xi2_owner_events_fallback_is_fresh`: `XIGrabDevice` master owner_events by O, ButtonPress in the mask, master origin; O XI2 on C denied, F XI2 on C allowed → O at G; trace O@C, O@G. + - `p14_denied_activating_press_still_activates_and_freezes`: sync `GrabButton` by O on G; deny O@G → no bytes; `active_pointer_grab` set; the master's `xi1_frozen` entry is `FrozenWithEvent` with the press stored; a following motion is queued. Same through `XIPassiveGrabDevice` on the master from an attached slave origin (the master `Fallback` block path). +- [ ] **Step 2:** run; Expected: p8, p9, p10, p11 (both rows), p12 (second row), p13 FAIL; p12 (first row) and p14 pass already (Task 1 left these writes checked through the old path) and guard the conversion. - [ ] **Step 3: implement.** -- [ ] **Step 4:** run the filter, `pointer_fanout::tests` (grab and XTS-derived rows) and the whole `--lib`. Expected PASS. +- [ ] **Step 4:** run the filter, `pointer_fanout::tests` (grab and XTS-derived rows), the whole `--lib`. Expected PASS. - [ ] **Step 5: commit** `feat(access): Receive decides grabbed pointer delivery`. ### Task 3: implicit grab and the slave press protocol choice **Files:** -- Modify: `crates/yserver-core/src/core_loop/pointer_fanout.rs` (`resolve_slave_press_delivery` :3360; nothing else if Task 1 holds) +- Modify: `crates/yserver-core/src/core_loop/pointer_fanout.rs` (`resolve_slave_press_delivery` :3360) - Test: `access_pointer_input.rs` -Rules (spec l.392–397): Receive-denied candidates leave each winner calculation, which then runs as today; no candidate → no implicit grab. `resolve_slave_press_delivery` takes the memo: at each window, the allowed slave XI2 selectors, else the allowed XI1 `DeviceButtonPress` selectors (XI1 description), else the parent. Its recipients are already decided: the XI1 write the router makes for them must not check again (Task 5 relies on this). +Rules (spec l.392–397): Receive-denied candidates leave each winner calculation, which then runs as today; no candidate → no implicit grab. `resolve_slave_press_delivery` takes the memo: at each window the allowed slave XI2 selectors, else the allowed XI1 `DeviceButtonPress` selectors, else the parent. Its XI1 recipients are decided: the router writes them unchecked and picks the XI1 implicit owner among them. -- [ ] **Step 1: failing tests:** - - `p15_denied_candidate_is_not_the_implicit_owner`: A core on C denied, B core on P → B gets the press, B owns the implicit grab: after moving the pointer over C, the release goes to B at P. - - `p16_all_denied_no_implicit_grab`: A alone on C, denied → `active_pointer_grab` is `None` after the press. - - `p17_xi2_owner_preference_among_allowed`: the window's owner W and another client X both select master XI2 on C; deny W → X owns the implicit grab (today W would). - - `p18_denied_slave_xi2_falls_to_xi1`: slave origin; X slave XI2 on C denied, Y XI1 `DeviceButtonPress` on C → Y gets `DeviceButtonPress` at C and owns the XI1 implicit grab; Y's trace has one call. Kills: protocol choice by selection; a second XI1 check. +- [ ] **Step 1: tests:** + - `p15_denied_candidate_is_not_the_implicit_owner`: A core on C denied, B core on P → B gets the press and owns the implicit grab at P; the release, with the pointer still over C, goes to B at P. + - `p16_all_denied_no_implicit_grab`: A alone on C, denied → no active pointer grab after the press. + - `p17_xi2_owner_preference_among_allowed`: C's owner W and X both select master XI2 on C; deny W → X owns the implicit grab (allow-all: W). + - `p18_denied_slave_xi2_falls_to_xi1`: slave origin; X slave XI2 on C denied, Y XI1 `DeviceButtonPress` on C → Y gets it at C and owns the XI1 implicit grab; Y has one call. Kills: protocol choice by selection; a second XI1 check. - `p19_denied_xi1_press_continues`: Y XI1 on C denied, Z XI1 on P → Z. -- [ ] **Step 2:** run; Expected: p18, p19 FAIL; p15–p17 pass if Task 1 holds (they pin it). + - `p20_xi1_implicit_owner_from_allowed`: slave origin; two XI1 press selectors on C, the one with the grab class denied → the other owns the XI1 implicit grab. +- [ ] **Step 2:** run; Expected: p18, p19, p20 FAIL; p15–p17 pass if Task 1 holds (they pin it). - [ ] **Step 3: implement.** - [ ] **Step 4:** run the filter + whole `--lib`. Expected PASS. - [ ] **Step 5: commit** `feat(access): Receive decides the slave press protocol`. @@ -132,46 +144,51 @@ Rules (spec l.392–397): Receive-denied candidates leave each winner calculatio **Files:** - Modify: `crates/yserver-core/src/core_loop/pointer_fanout.rs` (raw writes :2340–2375, scroll Motion :2400–2440, `emit_scroll_stop_to_state` :2953) -- Modify: `crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs` (`xi2_motion_targets_for_source` :88 takes `receive: Option<&ReceiveMemo>`) +- Modify: `crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs` (`xi2_motion_targets_for_source` :89 takes `receive: Option<&mut ReceiveMemo>`) - Test: `access_pointer_input.rs` -Rules (spec l.455–475): each raw root copy (slave and master fanouts, recipients and order unchanged) is checked with subject `Window(ROOT_WINDOW)` through `fanout_event_to_clients_with_receive`; a denial drops only that copy. The scroll Motion of a wheel press follows the ordinary walk: `xi2_motion_targets_for_source(.., Some(&memo))`, natural writes `Decided`, grab-window writes `Fresh`. The scroll stop routes with `None` (today's window) and checks each recipient once with the two-Motion batch; a denial drops both events and the walk does not resume. +Rules (spec l.455–475): +- Each raw root copy (slave and master fanouts, recipients and order unchanged) is checked with subject `Window(ROOT_WINDOW)` through `fanout_event_to_clients_with_receive`; a denial drops only that copy. +- The scroll Motion of a wheel press follows the ordinary walk: `xi2_motion_targets_for_source(.., Some(memo))` for emitted, ungrabbed forms; natural writes unchecked, grab-window writes fresh. +- The scroll stop routes with `None` (today's windows). Each recipient is checked once per window with the two-Motion batch (a client whose slave and master forms resolve to the same window shares one call, as in p4); a denial drops that recipient's events there and the walk does not resume. - [ ] **Step 1: failing tests:** - - `p20_denied_raw_root_copy_drops_only_that_copy`: A and B select master RawButtonPress on root, S selects the slave form; deny A → B and S get theirs. - - `p21_scroll_motion_follows_the_walk`: wheel press (button 4) from a source with a scroll class; X master XI2 Motion on C denied, Y on P → Y gets the scroll Motion at P. - - `p22_scroll_stop_is_not_rerouted`: `emit_scroll_stop_to_state`; X on C denied, Y on P → nobody gets the stop; X's trace has one call whose batch is two XI2 Motion descriptions; Y has none. Allowed → X gets both events. Kills: routing the stop through the memo; one check per event. -- [ ] **Step 2:** run; Expected: p20, p21, p22 FAIL. + - `p21_denied_raw_root_copy_drops_only_that_copy`: A and B master RawButtonPress on root, S the slave form; slave origin; deny A → B and S get theirs. + - `p22_scroll_motion_follows_the_walk`: wheel press (button 4) from a source with a scroll class; X master XI2 Motion on C denied, Y on P → Y gets the scroll Motion at P. + - `p23_scroll_stop_is_not_rerouted`: `emit_scroll_stop_to_state`, with `master_sprite_root` over C (slave motion routes from the previous sprite position); X master XI2 Motion on C denied, Y on P → nobody gets the stop; X has one call, batch = two XI2 Motion descriptions; Y none. Allowed → X gets both events. Two-form row: X selects XIAllDevices on C → allowed: both forms, one call. Kills: routing the stop through the memo; one check per event; one per form. +- [ ] **Step 2:** run; Expected: p21, p22, p23 FAIL. - [ ] **Step 3: implement.** -- [ ] **Step 4:** run the filter, the raw and scroll rows in `pointer_fanout::tests`, and the whole `--lib`. Expected PASS. +- [ ] **Step 4:** run the filter, the raw and scroll rows in `pointer_fanout::tests`, the whole `--lib`. Expected PASS. - [ ] **Step 5: commit** `feat(access): Receive checks raw pointer and scroll copies`. ### Task 5: the XI1 router **Files:** - Modify: `crates/yserver-core/src/core_loop/pointer_fanout.rs` (`xi1_route_device_event` :3064, `compute_xi1_route_targets` :3337, `compute_xi1_targets_bounded` :3861, `xi1_fan_device_event` :3418) -- Modify: `crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs` (`xi1_window_selectors`, `xi1_window_selectors_with_grab_class` take the memo, or the router filters their result) -- Modify: callers: the pointer dispatch (passes its memo), `deliver_xi1_focused_key` (`key_fanout.rs`, fresh memo), the thaw path (fresh memo) -- Test: `access_pointer_input.rs`, `access_key_input.rs` (key rows) +- Modify: `crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs` (`xi1_selection_filter_for_slave_grab` :226) +- Modify: callers: the pointer dispatch (its memo), `deliver_xi1_focused_key` (`key_fanout.rs`, a new memo), the thaw re-entries `pointer_fanout.rs:3610` and `process_request/xi/dispatch/grabs.rs:1958` (a new memo each) +- Test: `access_pointer_input.rs`, `access_key_input.rs` **Interfaces:** -- Consumes: `ReceiveMemo`, `PointerWrite` (Task 1); `SlavePressDelivery` recipients already decided (Task 3). -- Produces: `xi1_route_device_event(state, q, allow_freeze, slave_press_delivery, receive: &ReceiveMemo)`; `xi1_fan_device_event(state, targets, window, q, write: PointerWrite<'_>)`. Plan 3 calls the router from thaw with a fresh memo. +- Consumes: `ReceiveMemo`, `fresh_check` (Task 1); `xi1_batch` (Task 2); decided `SlavePressDelivery::Xi1` recipients (Task 3). +- Produces: `xi1_route_device_event(state, q, allow_freeze, slave_press_delivery, receive: &mut ReceiveMemo)`; `xi1_fan_device_event(state, targets, window, q, fresh_check: bool)`. Plan 3 calls the router from thaw with a fresh memo. Rules: -- The XI1 batch for one recipient: `DeviceMotionNotify` + its `DeviceValuator` = one batch of two descriptions; other events one description. The routing and the write use the same batch. -- Natural walk (`Walk`, `WalkUpTo`, `WindowOnly`): a window stops the walk when it has an allowed selector or a no-copy selector (a synthetic repeat release to a detectable-repeat client: no call). `WindowOnly` with every copy denied → no delivery (no direct attempt, spec l.409–413). Selection writes are `Decided`; `SlavePressDelivery::Xi1` recipients are `Decided`. -- XI1 grab: the owner gets the event at the natural window when `owner_events` and its copy there is allowed (`Decided`); otherwise at the grab window, `Fresh`, a denial = delivered. The passive XI1 activating write is `Fresh`; activation, sync freeze and the stored event are untouched. `xi1_freeze_this_event_if_needed` and `xi1_check_grab_for_syncs` run as today. -- XI1 implicit owner: computed from the allowed recipients; none → no implicit grab. +- Routing and write use `xi1_batch(q.evcode)`. +- Natural walk (`Walk`, `WalkUpTo`, `WindowOnly`): a window stops the walk when it has an allowed selector or a no-copy selector (a synthetic repeat release to a detectable-repeat client: no call). `WindowOnly` with every copy denied → no delivery (no direct attempt, spec l.409–413). Selection writes are unchecked. +- XI1 grab (:3149): with `owner_events` false, no natural walk is checked; the owner gets the event at the grab window, checked fresh before the implicit `device_mask` gate (:3164); a denial = delivered. With `owner_events` true, at each window the owner first (allowed → natural, unchecked write), then the foreign selectors where the owner does not qualify (any allowed → grab window, fresh); with `None` this is today's "first window with any selector, owner among them". The passive XI1 activating write (:3235) is fresh; activation, freezes and the stored event are untouched. +- XI2 slave grab filter (`xi1_selection_filter_for_slave_grab`): its `owner_events_route` uses the dispatch memo. On `Natural { protocol: Xi1, window }` the router writes the owner at that window without walking the selectors again; on `Fallback` the XI1 selection path delivers nothing to the owner (today's `Client(owner)` filter on the walk result). +- XI1 implicit owner (thaw re-entry, `slave_press_delivery = None`): chosen among the allowed recipients; none → no implicit grab. - [ ] **Step 1: failing tests:** - - `p23_denied_xi1_selector_advances_the_walk`: slave origin motion; X `DeviceMotionNotify` on C denied, Y on P → Y at P. - - `p24_device_motion_and_valuator_are_one_batch`: X selects `DeviceMotionNotify` on C. Allowed → both frames; denied → neither, one call with the two-description batch. Kills: checking per event. - - `p25_xi1_grab`: `GrabDevice` owner_events by O on G; O selects on C, denied → O at G, trace O@C, O@G. `owner_events` false, O denied → no bytes, grab active. - - `p26_xi1_implicit_owner_from_allowed`: two XI1 press selectors on C, the one with the grab class denied → the other owns the implicit grab. - - `k16_xi1_focused_key_denial_advances_the_focus_walk` (in `access_key_input.rs`): XTEST keyboard origin; X `DeviceKeyPress` on C (pointer window under focus F) denied, Y on F → Y at F. - - `k17_xi1_detectable_repeat_release_stops_without_a_check`: synthetic repeat release; X (detectable repeat) selects `DeviceKeyRelease` on C, Y on F → nothing written, no call for X. -- [ ] **Step 2:** run; Expected: p23, p24, p25 (first row), p26, k16 FAIL; k17 passes (guard). + - `p24_denied_xi1_selector_advances_the_walk`: slave origin motion with `master_sprite_root` over C; X `DeviceMotionNotify` on C denied, Y on P → Y at P. + - `p25_device_motion_and_valuator_are_one_batch`: X `DeviceMotionNotify` on C. Allowed → both frames; denied → neither, one call with the two-description batch. Kills: checking per event. + - `p26_xi1_grab`: `GrabDevice` owner_events by O on G; O on C denied, F on C allowed → O at G, trace O@C, O@G. O allowed → O at C, no F call. `owner_events` false, O denied, F on C → no bytes, no F call, grab active. + - `p27_xi1_slave_grab_filter_agrees_with_the_xi2_route`: `XIGrabDevice` on the slave, owner_events, O selects XI1 `DeviceButtonPress` on C; O's XI1 copy at C denied → O gets no XI1 copy and the XI2 fallback at G as Task 2 decides; one O@C XI1 call. Kills: a selection-only filter (double delivery). + - `p28_thawed_xi1_press_picks_the_owner_from_allowed`: sync `GrabDevice` on the slave freezes it, a press is queued, `UngrabDevice` thaws it through the re-entry with `slave_press_delivery = None`; two XI1 press selectors on C, the one with the grab class denied → the other owns the XI1 implicit grab. + - `k16_xi1_focused_key_denial_advances_the_focus_walk` (`access_key_input.rs`): XTEST keyboard origin; X `DeviceKeyPress` on C (pointer window under focus F) denied, Y on F → Y at F. + - `k17_xi1_detectable_repeat_release_stops_without_a_check`: synthetic repeat release; X (detectable repeat) selects `DeviceKeyRelease` on C, Y on F → nothing written, no X call. Must fail if X is asked. +- [ ] **Step 2:** run; Expected: p24, p25, p26, p27, p28, k16 FAIL; k17 passes (guard). - [ ] **Step 3: implement.** - [ ] **Step 4:** run the filters, `xi1` tests, `pointer_fanout::tests`, `key_fanout` tests, the whole `--lib`, and `cargo test --workspace --features xdmcp`. Expected PASS. - [ ] **Step 5: commit** `feat(access): Receive decides XI1 device event delivery`. From 879bd45edd2f6a79c416cd61abb1a0ead2828165 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 17:23:22 -0300 Subject: [PATCH 20/72] docs(plan): plan 2 review round 2 Co-Authored-By: Claude Opus 5.5 --- .../2026-12-01-access-control-pr4c-pointer.md | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md b/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md index 600e95a41..fe4ee334e 100644 --- a/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md +++ b/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md @@ -41,7 +41,7 @@ **Files:** - Modify: `crates/yserver-core/src/core_loop/fanout.rs` (`ReceiveMemo` beside `receive_allows` :297; `pointer_propagation_target_by_id` :200, `xi2_pointer_selected_on` :166) -- Modify: `crates/yserver-core/src/core_loop/pointer_fanout.rs` (memo in `pointer_event_fanout_to_state_inner` :521; `xi2_route_window_for_source` :4509, `xi2_form_targets_for_source` :4531, `compute_xi2_targets_for_source` :4594, `xi2_pointer_forms_for_source` :4767, `xi2_stamp_deviceid_for_source` :4704; core step 4 and its dedup :1780–1930; the XI2 targets :2113–2160 and writer :2509–2830; `fanout_core_pointer_event_ordered` :4043 and the deferral :4009–4185; the click-hit diagnostic :1395) +- Modify: `crates/yserver-core/src/core_loop/pointer_fanout.rs` (memo in `pointer_event_fanout_to_state_inner` :521; `xi2_route_window_for_source` :4509, `xi2_form_targets_for_source` :4531, `compute_xi2_targets_for_source` :4594, `xi2_pointer_forms_for_source` :4767, core step 4 and its dedup :1780–1930; the XI2 targets :2113–2160 and writer :2509–2830; `fanout_core_pointer_event_ordered` :4043 and the deferral :4009–4185; the click-hit diagnostic :1395) - Modify: `crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs` (callers of the changed helpers, :187, :202, :404; routing semantics change in Task 2) - Create: `crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs` (harness moved from `access_key_input.rs`) and `access_pointer_input.rs` (+ `mod` lines) @@ -57,9 +57,9 @@ subject: EventSubject, events: &EventBatch<'_>) -> bool; } ``` - Keys compare by equality (the access types derive `Eq`, not `Hash`; a small `Vec` is fine). -- Produces: the routing helpers above take `receive: Option<&mut ReceiveMemo>`. `None` = today's selection-only routing. `Some` = a selection at window W counts only if its copy is allowed: selected and `allows(client, Window(W), )`. The client-state predicate `xi2_form_selected_on_for_source` stays selection-only; its callers add the check with the `ClientId` they have. -- Produces: writers take `fresh_check: bool`. `false`: the recipients were decided by the memo, the write is the unchecked `fanout_event_to_clients`. `true`: `fanout_event_to_clients_with_receive` (a denial = delivered). `fanout_core_pointer_event_ordered` takes it; core Enter/Leave keep today's check. Deferred core copies: admitted only if allowed (memo when decided, `receive_allows` when fresh); the flush writes unchecked. + Keys compare by equality (the access types derive `Eq`, not `Hash`; a small `Vec` is fine). With no policy installed it records nothing. +- Produces: the routing helpers above take `receive: Option<&mut ReceiveMemo>`. The two-form helpers (`compute_xi2_targets_for_source`, `xi2_pointer_forms_for_source`) also take which forms are checked (slave, master), since one call can need the memo for one form and selection-only for the other. `None`, or an unchecked form, = today's selection-only routing. `Some` = a selection at window W counts only if its copy is allowed: selected and `allows(client, Window(W), )`. The client-state predicate `xi2_form_selected_on_for_source` stays selection-only; its callers add the check with the `ClientId` they have. +- Produces: writers take `fresh_check: bool`. In this task every core grab-block write and the passive activating press (:1471, :1503, :1527, :1680) pass `true`, so they are checked at the write as a fixed recipient; Task 2 moves that check before the mask. `false`: the recipients were decided by the memo, the write is the unchecked `fanout_event_to_clients`. `true`: `fanout_event_to_clients_with_receive` (a denial = delivered). `fanout_core_pointer_event_ordered` takes it; core Enter/Leave keep today's check. Deferred core copies: admitted only if allowed (memo when decided, `receive_allows` when fresh); the flush writes unchecked. - Produces (test support, `access_input_support.rs`): plan 1's harness, generalised: - the policy denies and the trace records whole batches, as ordered description lists (today `decide` :451 and the trace :562 only match one description); - it recognises core and XI2 key and pointer descriptions, raw descriptions, and XI1 device descriptions, and decodes the matching frames, including the `DeviceValuator` continuation; @@ -69,24 +69,24 @@ `access_key_input` keeps 29/29 after the move. Rules: -- **Emitted forms.** Before routing, the dispatch knows which XI2 forms it writes: the slave form when it is pushed (`replay_has_slave_form`, `source_accepted`, not a slave activation), the master form when it is pushed (`replay_has_master_form`, `master_accepted`, the attached-master condition at :2593, not `is_replay`). A form that is not written, or whose delivery a grab owns or redirects (master grab, slave grab, `xi2_grab_delivery`), routes its natural selectors with `None`. The earlier-window computation (:2158) uses the memo only for the slave form. The deferral's `has_slave_form` probe (:4068) and the click-hit diagnostic use `None`. +- **Emitted forms.** Before routing, the dispatch knows which XI2 forms it writes: the slave form when it is pushed (`replay_has_slave_form`, `source_accepted`, not a slave activation), the master form when it is pushed (`replay_has_master_form`, `master_accepted`, the attached-master condition at :2593, not `is_replay`). A form that is not written, or whose delivery a grab owns or redirects (master grab, slave grab, `xi2_grab_delivery`), routes its natural selectors with `None`. The earlier-window computation (:2158) uses the memo only for the slave form. The `owner_events_route` calls for a form that is not written (:2009, :2235), the deferral's `has_slave_form` probe (:4068) and the click-hit diagnostic use `None`. - **XI2 form walks.** For an emitted, ungrabbed form: the route window is the first window with an allowed selector of that form; the recipients are the allowed ones; `xi2_pointer_forms_for_source` and the writer's per-form window use the same memo, so a client's slave and master forms at one window share one call. -- **Core shadow and walk.** The master route is resolved before the core walk. A client's core copy is shadowed when the client is among the master form's allowed recipients, wherever that copy goes (today's dedup, `:1838–1869`, with `xi2_stamp_deviceid_for_source` deciding from the same memo entries). At each core-walk window: the window absorbs when it is the master form's route window (selection-only when the master form is not emitted); a shadowed core subscriber stops the walk with no core check; the unshadowed subscribers are checked, and the walk stops if any is allowed or shadowed. The recipients are the allowed unshadowed ones. +- **Core shadow and walk.** The master route is resolved before the core walk. A client's core copy is shadowed when the client is among the master form's allowed recipients, wherever that copy goes. With no policy this is what today's dedup (`:1838–1869`: the two-form `xi2_dedup` minus the slave-stamped clients) reduces to, so the dedup becomes that membership test and stops calling `xi2_stamp_deviceid_for_source` (its other uses stay). At each core-walk window: the window absorbs when it is the master form's route window (selection-only when the master form is not emitted); a shadowed core subscriber stops the walk with no core check; the unshadowed subscribers are checked, and the walk stops if any is allowed or shadowed. The recipients are the allowed unshadowed ones. - **Implicit-grab candidates.** The core candidate comes from the core copies actually admitted (immediate allowed, or deferred and admitted). The XI2 candidate: `delivered = allowed && not transport-failed`. -- **XI2 writer.** Natural geometry → `fresh_check = false`. Fixed grab-window geometry (`xi2_grab_window_target`, `xi2_slave_grab_window_target`, `xi2_grab_delivery`) → fresh (Task 2 tests it). Crossings → today's local check. +- **XI2 writer.** Every written copy is either decided by the memo or checked fresh. Natural geometry of an ungrabbed form → `fresh_check = false`. Fixed grab-window geometry (`xi2_grab_window_target`, `xi2_slave_grab_window_target`) and every owner copy under `xi2_grab_delivery`, whatever window it goes to (:2652, :2672, :2765) → fresh (Task 2 tests it). Crossings → today's local check. - [ ] **Step 1: move and generalise the harness** (batches, XI1, per-row denied grab state); `access_key_input` 29/29. Commit `test(access): share the input scenario helpers`. - [ ] **Step 2: failing tests** in `access_pointer_input.rs` (tree: root ⊃ P ⊃ C, pointer over C; master origin and ButtonPress unless stated): - `p1_denied_core_selector_does_not_stop_the_core_walk`: B core on C, A core on P; deny B@C → A gets it at P with child C; trace [B@C core, A@P core]; denied grab: implicit owner A at P. Kills: stop on selection. - `p2_denied_xi2_selector_does_not_absorb_core`: X master XI2 on C, A core on P. No policy: A nothing. Deny X@C XI2 → A gets core at P; X has exactly one call. Kills: absorption from selection; a second check. - `p3_xi2_walk_skips_a_denied_window`: X master XI2 on C denied, Y on P → Y at P, child C. Kills: route window from selection. - - `p4_slave_and_master_forms_share_one_check`: slave origin; X selects XIAllDevices on C. Allowed → slave then master form, one call. Denied → X nothing, Y (master XI2 on P) gets the master form at P. Kills: one check per form. + - `p4_slave_and_master_forms_share_one_check`: slave origin, Motion within C (a press's slave form is routed by `resolve_slave_press_delivery`, converted in Task 3); X selects XIAllDevices Motion on C. Allowed → slave then master form, one call. Denied → X nothing, Y (master XI2 on P) gets the master form at P. Kills: one check per form. - `p5_denied_xi2_reopens_that_clients_core`: A master XI2 and core on C. Allowed → XI2 only, no core call. XI2 denied → core at C, trace [A XI2@C, A core@C]. Kills: shadow from selection. - `p5b_shadow_follows_the_master_copy_anywhere`: A core on C and master XI2 on P, B core on P. Allow-all: A gets XI2 at P only, as today. Deny A's core at C → same bytes, no A core call, B nothing. Deny A's XI2 at P → A gets core at C. Kills: a same-window shadow; checking a shadowed core copy (walk then dedup). - - `p5c_stamp_uses_the_allowed_route`: slave origin; X master XI2 on C denied; A selects master XI2, slave XI2 and core on P → A gets the slave and master XI2 forms at P and no core. Kills: a selection-only `xi2_stamp_deviceid_for_source`. + - `p5c_shadow_uses_the_allowed_master_route`: slave origin, Motion; X master XI2 on C denied; A selects core on C and master and slave XI2 on P → A gets the slave and master XI2 forms at P and no core, and no A core call. Kills: a shadow computed from the selection-only master route (which ends at C, where A has no XI2 selection, so A would keep core at C). - `p6_deferred_core_copy_is_checked_at_admission`: slave origin; A slave XI2 and core on C (core deferred). Allow-all → slave XI2 then core, as today. Core denied → slave XI2 only, one core call, no master implicit grab owned by A. Kills: check at flush; no check. - `p7_no_check_for_a_form_not_emitted`: the `Physical` slave holds button 1; the XTEST slave then presses button 1 (`master_accepted` false); X master XI2 ButtonPress on C → no call for X on the second press. Kills: phantom master-form check. -- [ ] **Step 3:** run `cargo test -p yserver-core --lib access_pointer_input`. Expected: p1, p2, p3, p4 (denied row), p5, p5b (denied rows), p5c, p6 FAIL; p7 passes (guard). +- [ ] **Step 3:** run `cargo test -p yserver-core --lib access_pointer_input`. Expected: p1, p2, p3, p4 (denied row), p5, p5b (XI2-denied row), p5c, p6 FAIL; p7 passes (guard). - [ ] **Step 4: implement.** - [ ] **Step 5:** run the filter, `pointer_fanout::tests`, `access_crossing_notify`, `access_key_input` and the whole `--lib`. Expected PASS, existing tests unchanged. - [ ] **Step 6: commit** `feat(access): Receive decides the natural pointer walks`. @@ -104,7 +104,7 @@ Rules: Rules (spec l.414–429, 431–440): - At each window: the owner first, in today's protocol order (XI2, XI1 with `xi1_batch`, core), qualifies through the first protocol it selected whose copy is allowed. Only if it qualifies in none are the foreign selectors of the three protocols evaluated, every one (no short-circuit); any allowed one → `Fallback`. Else the parent. With `None` this equals today's result. -- Natural core write: `fresh_check = false`. Every grab-window write (core fallback and `owner_events = false` at :1494–1540, the XI2 master and slave fallbacks, the passive activating press at :1680) checks fresh in the grab's protocol, before the grab mask and the `!via_xi2` guard: a core grab checks the core copy, an XI2 grab the XI2 copy (in the XI2 block, before `xi2_grab_accepts_event`). A denial sets `handled_core_via_grab` as today and nobody else gets the copy. +- Natural core write: `fresh_check = false`. Every grab-window attempt (core fallback and `owner_events = false` at :1494–1540, the XI2 master and slave fallbacks, the passive activating press at :1680) checks fresh in the grab's protocol, before the grab mask and the `!via_xi2` guard: a core grab checks the core copy, an XI2 grab the XI2 copy (in the XI2 block, before `xi2_grab_accepts_event`). That check feeds the write, which is then unchecked: one call per attempt. A denial sets `handled_core_via_grab` as today and nobody else gets the copy. - Activation, `CheckGrabForSyncs`, the stored event, confinement and the activation crossings are untouched. - [ ] **Step 1: failing tests** (core grabs through `GrabPointer`/`GrabButton`, XI2 through `XIGrabDevice`/`XIPassiveGrabDevice`; each names its origin): @@ -114,8 +114,8 @@ Rules (spec l.414–429, 431–440): - `p11_owner_qualifies_in_a_later_protocol`: core grab; F master XI2 on C, O core on C. Allowed → O core at C, no call for F (also not from the XI2 target computation). O denied → F's allowed XI2 rejects → O at G. Kills: foreign before owner; F asked under a grab-owned master form. - `p12_grab_window_denial_counts_as_delivered`: `owner_events` false, O denied at G → no bytes for anyone, C's selectors included; grab active. Second row: the grab mask lacks ButtonPress, O denied → O's trace still has the G call (check before the mask). XI2 row: `XIGrabDevice` master, master origin, foreign master XI2 selector on C → no call for it. - `p13_xi2_owner_events_fallback_is_fresh`: `XIGrabDevice` master owner_events by O, ButtonPress in the mask, master origin; O XI2 on C denied, F XI2 on C allowed → O at G; trace O@C, O@G. - - `p14_denied_activating_press_still_activates_and_freezes`: sync `GrabButton` by O on G; deny O@G → no bytes; `active_pointer_grab` set; the master's `xi1_frozen` entry is `FrozenWithEvent` with the press stored; a following motion is queued. Same through `XIPassiveGrabDevice` on the master from an attached slave origin (the master `Fallback` block path). -- [ ] **Step 2:** run; Expected: p8, p9, p10, p11 (both rows), p12 (second row), p13 FAIL; p12 (first row) and p14 pass already (Task 1 left these writes checked through the old path) and guard the conversion. + - `p14_denied_activating_press_still_activates_and_freezes`: sync `GrabButton` by O on G; deny O@G → no bytes; `active_pointer_grab` set; the master's `xi1_frozen` entry is `FrozenWithEvent` with the press stored; a following motion is queued. Same through `XIPassiveGrabDevice` on the master from an attached slave origin (the master `Fallback` block path): a following motion delivers its slave part and defers the master part, so assert the `HostPointerMaster` queue entry. Third row: the same grab from a master origin (`xi2_grab_delivery`), O denied → no bytes, frozen with the press stored. +- [ ] **Step 2:** run; Expected: p8, p9, p10, p11 (both rows), p12 (second row), p13 FAIL; p12 (first row) and p14 pass after Task 1 (those writes are `fresh_check = true` there) and guard the move of the check before the mask. - [ ] **Step 3: implement.** - [ ] **Step 4:** run the filter, `pointer_fanout::tests` (grab and XTS-derived rows), the whole `--lib`. Expected PASS. - [ ] **Step 5: commit** `feat(access): Receive decides grabbed pointer delivery`. @@ -155,7 +155,7 @@ Rules (spec l.455–475): - [ ] **Step 1: failing tests:** - `p21_denied_raw_root_copy_drops_only_that_copy`: A and B master RawButtonPress on root, S the slave form; slave origin; deny A → B and S get theirs. - `p22_scroll_motion_follows_the_walk`: wheel press (button 4) from a source with a scroll class; X master XI2 Motion on C denied, Y on P → Y gets the scroll Motion at P. - - `p23_scroll_stop_is_not_rerouted`: `emit_scroll_stop_to_state`, with `master_sprite_root` over C (slave motion routes from the previous sprite position); X master XI2 Motion on C denied, Y on P → nobody gets the stop; X has one call, batch = two XI2 Motion descriptions; Y none. Allowed → X gets both events. Two-form row: X selects XIAllDevices on C → allowed: both forms, one call. Kills: routing the stop through the memo; one check per event; one per form. + - `p23_scroll_stop_is_not_rerouted`: `emit_scroll_stop_to_state`, with the stop's `root_x`/`root_y` over C (it routes from its own probe hit); X master XI2 Motion on C denied, Y on P → nobody gets the stop; X has one call, batch = two XI2 Motion descriptions; Y none. Allowed → X gets both events. Two-form row: X selects XIAllDevices on C → allowed: both forms, one call. Kills: routing the stop through the memo; one check per event; one per form. - [ ] **Step 2:** run; Expected: p21, p22, p23 FAIL. - [ ] **Step 3: implement.** - [ ] **Step 4:** run the filter, the raw and scroll rows in `pointer_fanout::tests`, the whole `--lib`. Expected PASS. @@ -176,16 +176,16 @@ Rules (spec l.455–475): Rules: - Routing and write use `xi1_batch(q.evcode)`. - Natural walk (`Walk`, `WalkUpTo`, `WindowOnly`): a window stops the walk when it has an allowed selector or a no-copy selector (a synthetic repeat release to a detectable-repeat client: no call). `WindowOnly` with every copy denied → no delivery (no direct attempt, spec l.409–413). Selection writes are unchecked. -- XI1 grab (:3149): with `owner_events` false, no natural walk is checked; the owner gets the event at the grab window, checked fresh before the implicit `device_mask` gate (:3164); a denial = delivered. With `owner_events` true, at each window the owner first (allowed → natural, unchecked write), then the foreign selectors where the owner does not qualify (any allowed → grab window, fresh); with `None` this is today's "first window with any selector, owner among them". The passive XI1 activating write (:3235) is fresh; activation, freezes and the stored event are untouched. +- XI1 grab (:3149): with `owner_events` false, no natural walk is checked; the owner gets the event at the grab window, checked fresh before the implicit `device_mask` gate (:3164) and after the synthetic-repeat filter (:3442–3456: an owner that gets no copy gets no call); that check feeds an unchecked write; a denial = delivered. With `owner_events` true, at each window the owner first (allowed → natural, unchecked write), then the foreign selectors where the owner does not qualify (any allowed → grab window, fresh); with `None` this is today's "first window with any selector, owner among them". The passive XI1 activating write (:3235) is fresh; activation, freezes and the stored event are untouched. - XI2 slave grab filter (`xi1_selection_filter_for_slave_grab`): its `owner_events_route` uses the dispatch memo. On `Natural { protocol: Xi1, window }` the router writes the owner at that window without walking the selectors again; on `Fallback` the XI1 selection path delivers nothing to the owner (today's `Client(owner)` filter on the walk result). - XI1 implicit owner (thaw re-entry, `slave_press_delivery = None`): chosen among the allowed recipients; none → no implicit grab. - [ ] **Step 1: failing tests:** - `p24_denied_xi1_selector_advances_the_walk`: slave origin motion with `master_sprite_root` over C; X `DeviceMotionNotify` on C denied, Y on P → Y at P. - `p25_device_motion_and_valuator_are_one_batch`: X `DeviceMotionNotify` on C. Allowed → both frames; denied → neither, one call with the two-description batch. Kills: checking per event. - - `p26_xi1_grab`: `GrabDevice` owner_events by O on G; O on C denied, F on C allowed → O at G, trace O@C, O@G. O allowed → O at C, no F call. `owner_events` false, O denied, F on C → no bytes, no F call, grab active. - - `p27_xi1_slave_grab_filter_agrees_with_the_xi2_route`: `XIGrabDevice` on the slave, owner_events, O selects XI1 `DeviceButtonPress` on C; O's XI1 copy at C denied → O gets no XI1 copy and the XI2 fallback at G as Task 2 decides; one O@C XI1 call. Kills: a selection-only filter (double delivery). - - `p28_thawed_xi1_press_picks_the_owner_from_allowed`: sync `GrabDevice` on the slave freezes it, a press is queued, `UngrabDevice` thaws it through the re-entry with `slave_press_delivery = None`; two XI1 press selectors on C, the one with the grab class denied → the other owns the XI1 implicit grab. + - `p26_xi1_grab`: slave origin; `GrabDevice` owner_events by O on G; O on C denied, F on C allowed → O at G, trace O@C, O@G. O allowed → O at C, no F call. `owner_events` false, O denied, F on C → no bytes, no F call, grab active. + - `p27_xi1_slave_grab_filter_agrees_with_the_xi2_route`: slave origin; `XIGrabDevice` on the slave, owner_events, ButtonPress in the mask, O selects XI1 `DeviceButtonPress` on C; O's XI1 copy at C denied → O gets no XI1 copy and the XI2 fallback at G as Task 2 decides; one O@C XI1 call. Kills: a selection-only filter (double delivery). + - `p28_thawed_xi1_press_picks_the_owner_from_allowed`: slave origin; a sync `GrabDeviceButton` on G activates on the press and stores it; `AllowDeviceEvents(ReplayThisDevice)` re-routes it through `grabs.rs:1958` with `slave_press_delivery = None`; two XI1 press selectors on C, the one with the grab class denied → the other owns the XI1 implicit grab. - `k16_xi1_focused_key_denial_advances_the_focus_walk` (`access_key_input.rs`): XTEST keyboard origin; X `DeviceKeyPress` on C (pointer window under focus F) denied, Y on F → Y at F. - `k17_xi1_detectable_repeat_release_stops_without_a_check`: synthetic repeat release; X (detectable repeat) selects `DeviceKeyRelease` on C, Y on F → nothing written, no X call. Must fail if X is asked. - [ ] **Step 2:** run; Expected: p24, p25, p26, p27, p28, k16 FAIL; k17 passes (guard). From fc67b4dc3beb71628eae154dc7a7b5f418963ef4 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 17:28:08 -0300 Subject: [PATCH 21/72] docs(plan): plan 2 review round 3 Co-Authored-By: Claude Opus 5.5 --- .../plans/2026-12-01-access-control-pr4c-pointer.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md b/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md index fe4ee334e..fdab4a3a3 100644 --- a/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md +++ b/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md @@ -71,9 +71,9 @@ Rules: - **Emitted forms.** Before routing, the dispatch knows which XI2 forms it writes: the slave form when it is pushed (`replay_has_slave_form`, `source_accepted`, not a slave activation), the master form when it is pushed (`replay_has_master_form`, `master_accepted`, the attached-master condition at :2593, not `is_replay`). A form that is not written, or whose delivery a grab owns or redirects (master grab, slave grab, `xi2_grab_delivery`), routes its natural selectors with `None`. The earlier-window computation (:2158) uses the memo only for the slave form. The `owner_events_route` calls for a form that is not written (:2009, :2235), the deferral's `has_slave_form` probe (:4068) and the click-hit diagnostic use `None`. - **XI2 form walks.** For an emitted, ungrabbed form: the route window is the first window with an allowed selector of that form; the recipients are the allowed ones; `xi2_pointer_forms_for_source` and the writer's per-form window use the same memo, so a client's slave and master forms at one window share one call. -- **Core shadow and walk.** The master route is resolved before the core walk. A client's core copy is shadowed when the client is among the master form's allowed recipients, wherever that copy goes. With no policy this is what today's dedup (`:1838–1869`: the two-form `xi2_dedup` minus the slave-stamped clients) reduces to, so the dedup becomes that membership test and stops calling `xi2_stamp_deviceid_for_source` (its other uses stay). At each core-walk window: the window absorbs when it is the master form's route window (selection-only when the master form is not emitted); a shadowed core subscriber stops the walk with no core check; the unshadowed subscribers are checked, and the walk stops if any is allowed or shadowed. The recipients are the allowed unshadowed ones. +- **Core shadow and walk.** The master route is resolved before the core walk. A client's core copy is shadowed when the client is among the master form's allowed recipients, wherever that copy goes. With no policy this is what today's dedup (`:1838–1869`: the two-form `xi2_dedup` minus the slave-stamped clients) reduces to, so the dedup becomes that membership test. `xi2_stamp_deviceid_for_source` then has no production caller: delete it and its unit test (`pointer_fanout/tests.rs:4537`). Crossings keep today's selection-only master recipients from `cross_start`. At each core-walk window: the window absorbs when it is the master form's route window (selection-only when the master form is not emitted); a shadowed core subscriber stops the walk with no core check; the unshadowed subscribers are checked, and the walk stops if any is allowed or shadowed. The recipients are the allowed unshadowed ones. - **Implicit-grab candidates.** The core candidate comes from the core copies actually admitted (immediate allowed, or deferred and admitted). The XI2 candidate: `delivered = allowed && not transport-failed`. -- **XI2 writer.** Every written copy is either decided by the memo or checked fresh. Natural geometry of an ungrabbed form → `fresh_check = false`. Fixed grab-window geometry (`xi2_grab_window_target`, `xi2_slave_grab_window_target`) and every owner copy under `xi2_grab_delivery`, whatever window it goes to (:2652, :2672, :2765) → fresh (Task 2 tests it). Crossings → today's local check. +- **XI2 writer.** Every written copy is either decided by the memo or checked fresh. Natural geometry of an ungrabbed form → `fresh_check = false`. Owner-events natural windows (:2618, :2645) are fresh in this task and memo-decided from Task 2. Fixed grab-window geometry (`xi2_grab_window_target`, `xi2_slave_grab_window_target`) and every owner copy under `xi2_grab_delivery`, whatever window it goes to (:2652, :2672, :2765) → fresh (Task 2 tests it). Crossings → today's local check. - [ ] **Step 1: move and generalise the harness** (batches, XI1, per-row denied grab state); `access_key_input` 29/29. Commit `test(access): share the input scenario helpers`. - [ ] **Step 2: failing tests** in `access_pointer_input.rs` (tree: root ⊃ P ⊃ C, pointer over C; master origin and ButtonPress unless stated): @@ -83,7 +83,7 @@ Rules: - `p4_slave_and_master_forms_share_one_check`: slave origin, Motion within C (a press's slave form is routed by `resolve_slave_press_delivery`, converted in Task 3); X selects XIAllDevices Motion on C. Allowed → slave then master form, one call. Denied → X nothing, Y (master XI2 on P) gets the master form at P. Kills: one check per form. - `p5_denied_xi2_reopens_that_clients_core`: A master XI2 and core on C. Allowed → XI2 only, no core call. XI2 denied → core at C, trace [A XI2@C, A core@C]. Kills: shadow from selection. - `p5b_shadow_follows_the_master_copy_anywhere`: A core on C and master XI2 on P, B core on P. Allow-all: A gets XI2 at P only, as today. Deny A's core at C → same bytes, no A core call, B nothing. Deny A's XI2 at P → A gets core at C. Kills: a same-window shadow; checking a shadowed core copy (walk then dedup). - - `p5c_shadow_uses_the_allowed_master_route`: slave origin, Motion; X master XI2 on C denied; A selects core on C and master and slave XI2 on P → A gets the slave and master XI2 forms at P and no core, and no A core call. Kills: a shadow computed from the selection-only master route (which ends at C, where A has no XI2 selection, so A would keep core at C). + - `p5c_shadow_uses_the_allowed_master_route`: slave origin, Motion within C; X master XI2 on C denied; A selects core on C and master and slave XI2 on P → A gets the slave and master XI2 forms at P and no core, and no A core call. Kills: a shadow computed from the selection-only master route (which ends at C, where A has no XI2 selection, so A would keep core at C). - `p6_deferred_core_copy_is_checked_at_admission`: slave origin; A slave XI2 and core on C (core deferred). Allow-all → slave XI2 then core, as today. Core denied → slave XI2 only, one core call, no master implicit grab owned by A. Kills: check at flush; no check. - `p7_no_check_for_a_form_not_emitted`: the `Physical` slave holds button 1; the XTEST slave then presses button 1 (`master_accepted` false); X master XI2 ButtonPress on C → no call for X on the second press. Kills: phantom master-form check. - [ ] **Step 3:** run `cargo test -p yserver-core --lib access_pointer_input`. Expected: p1, p2, p3, p4 (denied row), p5, p5b (XI2-denied row), p5c, p6 FAIL; p7 passes (guard). @@ -114,7 +114,7 @@ Rules (spec l.414–429, 431–440): - `p11_owner_qualifies_in_a_later_protocol`: core grab; F master XI2 on C, O core on C. Allowed → O core at C, no call for F (also not from the XI2 target computation). O denied → F's allowed XI2 rejects → O at G. Kills: foreign before owner; F asked under a grab-owned master form. - `p12_grab_window_denial_counts_as_delivered`: `owner_events` false, O denied at G → no bytes for anyone, C's selectors included; grab active. Second row: the grab mask lacks ButtonPress, O denied → O's trace still has the G call (check before the mask). XI2 row: `XIGrabDevice` master, master origin, foreign master XI2 selector on C → no call for it. - `p13_xi2_owner_events_fallback_is_fresh`: `XIGrabDevice` master owner_events by O, ButtonPress in the mask, master origin; O XI2 on C denied, F XI2 on C allowed → O at G; trace O@C, O@G. - - `p14_denied_activating_press_still_activates_and_freezes`: sync `GrabButton` by O on G; deny O@G → no bytes; `active_pointer_grab` set; the master's `xi1_frozen` entry is `FrozenWithEvent` with the press stored; a following motion is queued. Same through `XIPassiveGrabDevice` on the master from an attached slave origin (the master `Fallback` block path): a following motion delivers its slave part and defers the master part, so assert the `HostPointerMaster` queue entry. Third row: the same grab from a master origin (`xi2_grab_delivery`), O denied → no bytes, frozen with the press stored. + - `p14_denied_activating_press_still_activates_and_freezes`: sync `GrabButton` by O on G; deny O@G → no bytes; `active_pointer_grab` set; the master's `xi1_frozen` entry is `FrozenWithEvent` with the press stored; a following motion is queued. Same through `XIPassiveGrabDevice` on the master from an attached slave origin (the master `Fallback` block path): a following motion delivers its slave part and defers the master part, so assert the `HostPointerMaster` queue entry. Third row: the same grab from a master origin (`xi2_grab_delivery`); O also selects master XI2 ButtonPress on C; deny O's XI2 copy at C (its natural route window) → no bytes, one O XI2 call, frozen with the press stored. Kills: an unchecked owner write under `xi2_grab_delivery`. - [ ] **Step 2:** run; Expected: p8, p9, p10, p11 (both rows), p12 (second row), p13 FAIL; p12 (first row) and p14 pass after Task 1 (those writes are `fresh_check = true` there) and guard the move of the check before the mask. - [ ] **Step 3: implement.** - [ ] **Step 4:** run the filter, `pointer_fanout::tests` (grab and XTS-derived rows), the whole `--lib`. Expected PASS. @@ -185,7 +185,7 @@ Rules: - `p25_device_motion_and_valuator_are_one_batch`: X `DeviceMotionNotify` on C. Allowed → both frames; denied → neither, one call with the two-description batch. Kills: checking per event. - `p26_xi1_grab`: slave origin; `GrabDevice` owner_events by O on G; O on C denied, F on C allowed → O at G, trace O@C, O@G. O allowed → O at C, no F call. `owner_events` false, O denied, F on C → no bytes, no F call, grab active. - `p27_xi1_slave_grab_filter_agrees_with_the_xi2_route`: slave origin; `XIGrabDevice` on the slave, owner_events, ButtonPress in the mask, O selects XI1 `DeviceButtonPress` on C; O's XI1 copy at C denied → O gets no XI1 copy and the XI2 fallback at G as Task 2 decides; one O@C XI1 call. Kills: a selection-only filter (double delivery). - - `p28_thawed_xi1_press_picks_the_owner_from_allowed`: slave origin; a sync `GrabDeviceButton` on G activates on the press and stores it; `AllowDeviceEvents(ReplayThisDevice)` re-routes it through `grabs.rs:1958` with `slave_press_delivery = None`; two XI1 press selectors on C, the one with the grab class denied → the other owns the XI1 implicit grab. + - `p28_thawed_xi1_press_picks_the_owner_from_allowed`: slave origin; a sync `GrabDeviceButton` by O on G = P (on C's chain) activates on the press and stores it; O's `AllowDeviceEvents(ReplayThisDevice)` re-routes it through `grabs.rs:1958` with `slave_press_delivery = None`; two XI1 press selectors on C, the one with the grab class denied → the other owns the XI1 implicit grab. - `k16_xi1_focused_key_denial_advances_the_focus_walk` (`access_key_input.rs`): XTEST keyboard origin; X `DeviceKeyPress` on C (pointer window under focus F) denied, Y on F → Y at F. - `k17_xi1_detectable_repeat_release_stops_without_a_check`: synthetic repeat release; X (detectable repeat) selects `DeviceKeyRelease` on C, Y on F → nothing written, no X call. Must fail if X is asked. - [ ] **Step 2:** run; Expected: p24, p25, p26, p27, p28, k16 FAIL; k17 passes (guard). From e2f903fc0b3d6b35f8e6d1fa3b929543bc232972 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 19:00:14 -0300 Subject: [PATCH 22/72] test(access): share the input scenario helpers Moves the key harness's request helpers, run/decode/check machinery and Row shape into access_input_support.rs so later pointer scenarios can reuse them. access_key_input keeps its 29 rows unchanged. Batch matching, XI1 and pointer drivers, and per-row denied grab state are not in this commit. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Haiku 5.5 --- .../tests/access_input_support.rs | 741 ++++++++++++++++++ .../process_request/tests/access_key_input.rs | 730 +---------------- .../core_loop/process_request/tests/mod.rs | 1 + 3 files changed, 745 insertions(+), 727 deletions(-) create mode 100644 crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs new file mode 100644 index 000000000..c0722e9c2 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -0,0 +1,741 @@ +//! Shared scenario harness for the key and pointer Receive tests (PR 4c +//! part 2): request helpers, the run/decode/check machinery and the +//! `Row` shape. Scenario rows and tests live in the test modules that +//! import this file. + +use super::{ + access_notify_support::{DENY, NotifyFixture, dec16, dec32, enc16, enc32, split_frames}, + extensions::{ExtensionHook, RecordedExtensionCheck}, + xi2::xi_select_body, +}; +use crate::{ + access::{Decision, EventDescription, EventSubject}, + core_loop::{ + InputOrigin, client_io, + key_fanout::{ + RawKeyEvent, key_event_fanout_after_transition, key_event_fanout_to_state, + raw_key_event_to_state, + }, + process_request::RequestOutcome, + }, + host_x11::HostKeyEvent, + nested::XI2_MAJOR_OPCODE, + resources::ROOT_WINDOW, + server::{QueuedInputEvent, Xi1SyncState}, + xinput::{DEVICEID_MASTER_KEYBOARD, DEVICEID_XTEST_KEYBOARD}, +}; +use std::{collections::BTreeMap, sync::atomic::Ordering}; +use yserver_protocol::x11::{ClientByteOrder, ClientId, RequestHeader, SequenceNumber}; + +pub(super) const SEND_CLIENT: u32 = 1; +/// The client that selects on the child window (A in the brief). +pub(super) const A: u32 = 2; +/// The client that selects on the focus window (B in the brief). +pub(super) const B: u32 = 3; +pub(super) const FOCUS: u32 = 0x0061_0001; +pub(super) const CHILD: u32 = 0x0061_0002; +pub(super) const POINTER: (i16, i16) = (120, 120); +pub(super) const KEYCODE: u8 = 38; +pub(super) const TIME: u32 = 0x5678; +pub(super) const XI_MAJOR: u8 = 137; +pub(super) const XI_SELECT_EVENTS: u8 = 46; +pub(super) const CORE_CHANGE_WINDOW_ATTRIBUTES: u8 = 2; +pub(super) const CORE_CREATE_WINDOW: u8 = 1; +pub(super) const CORE_MAP_WINDOW: u8 = 8; +pub(super) const CORE_SET_INPUT_FOCUS: u8 = 42; +pub(super) const CW_EVENT_MASK: u32 = 0x800; +pub(super) const KEY_PRESS: u32 = 1; +pub(super) const KEY_RELEASE: u32 = 2; +/// XI2 mask word for KeyPress (bit 2) and KeyRelease (bit 3). +pub(super) const XI_KEY_PRESS: u32 = 1 << 2; +pub(super) const XI_KEY_RELEASE: u32 = 1 << 3; +pub(super) const XI_KEY_PRESS_AND_RELEASE: u32 = XI_KEY_PRESS | XI_KEY_RELEASE; +/// XI2 mask word for RawKeyPress (bit 13) and RawKeyRelease (bit 14). +pub(super) const XI_RAW_KEY_PRESS: u32 = 1 << 13; +/// The grab window of the grab rows: the root is on no walk to FOCUS. +pub(super) const ROOT: u32 = ROOT_WINDOW.0; + +/// One frame the server writes: (client, what it is, event window). +type Frame = (u32, Kind, u32); +/// One Receive call the server makes: (client, description, subject window). +type Call = (u32, CallKind, u32); + +/// What a key frame is. `Xi2` carries the form's device id. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Kind { + Core, + Xi2(u16), + /// A raw key copy: its device, always on the root. A raw frame has no + /// event window, so the grab-leg copy and the root-fanout copy decode the + /// same; only the Receive trace tells them apart. + Raw(u16), +} + +/// What a Receive check names. An XI2 check names the description, not the +/// form, so it carries no device. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum CallKind { + Core, + Xi2, + Raw, +} + +#[derive(Clone, Copy)] +pub(super) enum Drive { + /// `key_event_fanout_to_state`: the transition-checked entry. + Entry { origin: InputOrigin, pressed: bool }, + /// `key_event_fanout_after_transition` with explicit master and synthetic flags. + After { + origin: InputOrigin, + pressed: bool, + master: bool, + synthetic: bool, + }, + /// `raw_key_event_to_state`: the XI2 raw copies of one device key. + Raw { origin: InputOrigin, pressed: bool }, +} + +impl Drive { + fn pressed(self) -> bool { + match self { + Drive::Entry { pressed, .. } + | Drive::After { pressed, .. } + | Drive::Raw { pressed, .. } => pressed, + } + } +} + +pub(super) struct Expect { + pub(super) frames: &'static [Frame], + pub(super) calls: &'static [Call], +} + +/// A frame the denial moves to another window: the literal bytes the row pins. +/// Core KeyPress/KeyRelease only; the event is the key's, so only its window, +/// child and coordinates vary. +#[derive(Clone, Copy)] +pub(super) struct Moved { + pub(super) client: u32, + pub(super) window: u32, + pub(super) child: u32, + pub(super) event: (i16, i16), +} + +pub(super) struct Row { + pub(super) name: &'static str, + pub(super) setup: fn(&mut NotifyFixture), + pub(super) drive: Drive, + /// (client, check, window) Receive calls to deny. + pub(super) deny: &'static [Call], + /// Frames only the denied run writes, pinned in full. + pub(super) moved: &'static [Moved], + pub(super) allow: Expect, + pub(super) denied: Expect, +} + +// ---- request helpers ----------------------------------------------------- + +/// Sends one request from `client` with the next sequence number of that +/// client, checks it was handled with no writer failure, and returns the bytes +/// the requester was sent (a reply, or nothing). +pub(super) fn send_with_reply( + f: &mut NotifyFixture, + client: u32, + opcode: u8, + data: u8, + body: &[u8], +) -> Vec { + let sequence = { + let state = &f.state.clients[&client]; + let next = state.last_sequence.load(Ordering::Relaxed).wrapping_add(1); + state.last_sequence.store(next, Ordering::Relaxed); + next + }; + let header = RequestHeader { + opcode, + data, + length_units: u32::try_from((4 + body.len()) / 4).expect("request length"), + }; + let outcome = f + .request(ClientId(client), SequenceNumber(sequence), header, body) + .expect("request through process_request"); + assert!( + matches!(outcome, RequestOutcome::Handled), + "request handled" + ); + assert!( + client_io::failed_writers(&f.state.clients).is_empty(), + "request queued a disconnect" + ); + f.drain(ClientId(client)) +} + +/// `send_with_reply` for a request that has no reply and no error. +pub(super) fn send(f: &mut NotifyFixture, client: u32, opcode: u8, data: u8, body: &[u8]) { + assert!( + send_with_reply(f, client, opcode, data, body).is_empty(), + "requester got bytes" + ); +} + +/// Two windows: FOCUS (100,100) 200x200 and CHILD inside it at (10,10), both +/// mapped. Focus is FOCUS, the pointer is inside CHILD. +pub(super) fn tree(f: &mut NotifyFixture) { + for (client, base) in [(SEND_CLIENT, 0x0100), (A, 0x0200), (B, 0x0300)] { + f.state.clients[&client] + .last_sequence + .store(base, Ordering::Relaxed); + } + for (window, parent, x, y, size) in [ + (FOCUS, ROOT_WINDOW.0, 100, 100, 200), + (CHILD, FOCUS, 10, 10, 50), + ] { + let mut body = Vec::with_capacity(32); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&parent.to_le_bytes()); + body.extend_from_slice(&(x as i16).to_le_bytes()); + body.extend_from_slice(&(y as i16).to_le_bytes()); + body.extend_from_slice(&(size as u16).to_le_bytes()); + body.extend_from_slice(&(size as u16).to_le_bytes()); + body.extend_from_slice(&0_u16.to_le_bytes()); // border + body.extend_from_slice(&1_u16.to_le_bytes()); // InputOutput + body.extend_from_slice(&crate::resources::ROOT_VISUAL.0.to_le_bytes()); + body.extend_from_slice(&0_u32.to_le_bytes()); // value mask + send(f, SEND_CLIENT, CORE_CREATE_WINDOW, 24, &body); + send(f, SEND_CLIENT, CORE_MAP_WINDOW, 0, &window.to_le_bytes()); + } + send( + f, + SEND_CLIENT, + CORE_SET_INPUT_FOCUS, + 0, + &[FOCUS.to_le_bytes(), 0_u32.to_le_bytes()].concat(), + ); + f.state.pointer_root = POINTER; +} + +/// Core KeyPress/KeyRelease selection on `window` for `client`. +pub(super) fn select_core(f: &mut NotifyFixture, client: u32, window: u32, mask: u32) { + let body = [ + window.to_le_bytes(), + CW_EVENT_MASK.to_le_bytes(), + mask.to_le_bytes(), + ] + .concat(); + send(f, client, CORE_CHANGE_WINDOW_ATTRIBUTES, 0, &body); +} + +/// XI2 key selection of one device on `window` for `client`. +pub(super) fn select_xi2(f: &mut NotifyFixture, client: u32, window: u32, device: u16, mask: u32) { + let body = xi_select_body(window, &[(device, &[mask])]); + send(f, client, XI_MAJOR, XI_SELECT_EVENTS, &body); +} + +/// Detectable autorepeat for `client`: XkbPerClientFlags with +/// `XkbPCF_DetectableAutoRepeatMask`, after XkbUseExtension. Both go through the +/// XKB request dispatcher (`handle_xkb_request`), as the XKB tests drive them. +pub(super) fn set_detectable_repeat(f: &mut NotifyFixture, client: u32) { + const XKB_MAJOR: u8 = 136; + const XKB_USE_EXTENSION: u8 = 0; + const XKB_PER_CLIENT_FLAGS: u8 = 21; + const DETECTABLE_AUTO_REPEAT: u32 = 1; + xkb_request(f, client, XKB_MAJOR, XKB_USE_EXTENSION, &[1, 0, 0, 0]); + let mut body = vec![0_u8; 24]; + body[0..2].copy_from_slice(&0x0100_u16.to_le_bytes()); // XkbUseCoreKbd + body[4..8].copy_from_slice(&DETECTABLE_AUTO_REPEAT.to_le_bytes()); // change + body[8..12].copy_from_slice(&DETECTABLE_AUTO_REPEAT.to_le_bytes()); // value + xkb_request(f, client, XKB_MAJOR, XKB_PER_CLIENT_FLAGS, &body); + let flags = f + .state + .xkb_clients + .get(&client) + .copied() + .unwrap_or_default(); + assert!( + flags.wants_detectable_auto_repeat(), + "XkbPerClientFlags set detectable repeat" + ); +} + +/// One XKB request through `handle_xkb_request`, with its reply drained. +pub(super) fn xkb_request(f: &mut NotifyFixture, client: u32, opcode: u8, minor: u8, body: &[u8]) { + let sequence = { + let state = &f.state.clients[&client]; + let next = state.last_sequence.load(Ordering::Relaxed).wrapping_add(1); + state.last_sequence.store(next, Ordering::Relaxed); + next + }; + crate::core_loop::process_request::xkb::handle_xkb_request( + &mut f.state, + &mut f.backend, + None, + ClientId(client), + SequenceNumber(sequence), + RequestHeader { + opcode, + data: minor, + length_units: u32::try_from(1 + body.len().div_ceil(4)).expect("request length"), + }, + body, + ) + .expect("XKB request through handle_xkb_request"); + f.drain(ClientId(client)); +} + +/// The slave keyboard's exact XI2 grab owned by `owner` on `grab_window`, made +/// with XIGrabDevice (asynchronous, not owner-events, KeyPress mask). +pub(super) fn grab_slave_keyboard(f: &mut NotifyFixture, owner: u32, grab_window: u32) { + grab_keyboard_device( + f, + owner, + DEVICEID_XTEST_KEYBOARD, + grab_window, + false, + XI_KEY_PRESS, + ); +} + +/// XIGrabDevice of `device` by `owner` on `grab_window` with the given +/// owner_events and one mask word. A master keyboard grab is the +/// `active_keyboard_grab` the raw master leg reads; a slave grab is per device. +pub(super) fn grab_keyboard_device( + f: &mut NotifyFixture, + owner: u32, + device: u16, + grab_window: u32, + owner_events: bool, + mask: u32, +) { + const XI_GRAB_DEVICE: u8 = 51; + let mut body = Vec::with_capacity(28); + body.extend_from_slice(&grab_window.to_le_bytes()); + body.extend_from_slice(&[0; 8]); // CurrentTime, no cursor + body.extend_from_slice(&device.to_le_bytes()); + body.extend_from_slice(&[1, 1, u8::from(owner_events), 0]); // async modes + body.extend_from_slice(&1_u16.to_le_bytes()); // one mask word + body.extend_from_slice(&mask.to_le_bytes()); + let bytes = send_with_reply(f, owner, XI_MAJOR, XI_GRAB_DEVICE, &body); + let reply = &bytes[bytes.len() - 32..]; + assert_eq!((reply[0], reply[8]), (1, 0), "XIGrabDevice replies Success"); +} + +/// SetInputFocus(PointerRoot) from the requester. +pub(super) fn set_focus_pointer_root(f: &mut NotifyFixture) { + send( + f, + SEND_CLIENT, + CORE_SET_INPUT_FOCUS, + 0, + &[1_u32.to_le_bytes(), 0_u32.to_le_bytes()].concat(), + ); +} + +/// The core GrabKeyboard request by `owner` on `window`, asynchronous pointer +/// mode, with `owner_events`. The reply must be Success. +pub(super) fn grab_keyboard(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: bool) { + const CORE_GRAB_KEYBOARD: u8 = 31; + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&[0; 4]); // CurrentTime + body.extend_from_slice(&[1, 1, 0, 0]); // async pointer, async keyboard + let bytes = send_with_reply(f, owner, CORE_GRAB_KEYBOARD, u8::from(owner_events), &body); + let reply = &bytes[bytes.len() - 32..]; + assert_eq!((reply[0], reply[1]), (1, 0), "GrabKeyboard replies Success"); +} + +/// The core GrabKey request by `owner` on `window` for `KEYCODE` with no +/// modifiers, asynchronous pointer mode and the given keyboard mode. +pub(super) fn grab_key( + f: &mut NotifyFixture, + owner: u32, + window: u32, + owner_events: bool, + keyboard_sync: bool, +) { + const CORE_GRAB_KEY: u8 = 33; + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&0_u16.to_le_bytes()); // modifiers + body.push(KEYCODE); + body.push(1); // pointer async + body.push(u8::from(!keyboard_sync)); // keyboard: 0 sync, 1 async + body.extend_from_slice(&[0; 3]); + send(f, owner, CORE_GRAB_KEY, u8::from(owner_events), &body); +} + +// ---- run and decode ------------------------------------------------------ + +pub(super) fn key_event(origin: InputOrigin, pressed: bool) -> HostKeyEvent { + HostKeyEvent { + origin, + pressed, + keycode: KEYCODE, + time: TIME, + root_x: POINTER.0, + root_y: POINTER.1, + event_x: 0, + event_y: 0, + state: 0, + } +} + +pub(super) fn drive(f: &mut NotifyFixture, drive: Drive) { + let dropped = match drive { + Drive::Entry { origin, pressed } => { + key_event_fanout_to_state(&mut f.state, &mut f.backend, key_event(origin, pressed)) + } + Drive::After { + origin, + pressed, + master, + synthetic, + } => key_event_fanout_after_transition( + &mut f.state, + &mut f.backend, + key_event(origin, pressed), + master, + synthetic, + ), + Drive::Raw { origin, pressed } => raw_key_event_to_state( + &mut f.state, + RawKeyEvent { + origin, + keycode: KEYCODE, + pressed, + time: TIME, + }, + false, + false, + ), + }; + assert!(dropped.is_empty(), "delivery queued a disconnect"); +} + +/// The key-related description a Receive call names, or `None` for other events. +pub(super) fn key_call(description: &EventDescription) -> Option<(CallKind, bool)> { + match description.extension { + None if description.type_code == 2 || description.type_code == 3 => { + Some((CallKind::Core, description.type_code == 2)) + } + Some(extension) + if description.type_code == 35 && extension.major_opcode == XI2_MAJOR_OPCODE => + { + match extension.event_type { + 2 | 3 => Some((CallKind::Xi2, extension.event_type == 2)), + 13 | 14 => Some((CallKind::Raw, extension.event_type == 13)), + _ => None, + } + } + _ => None, + } +} + +/// Denies exactly the listed (client, kind, window) Receive checks, matched by +/// hook, subject and description. +pub(super) fn decide(denied: &[Call], pressed: bool, call: &RecordedExtensionCheck) -> Decision { + if call.hook != ExtensionHook::Receive { + return Decision::Allow; + } + let (Some(EventSubject::Window(window)), Some(events)) = (call.receive, call.events.as_deref()) + else { + return Decision::Allow; + }; + let [description] = events else { + return Decision::Allow; + }; + let Some((kind, press)) = key_call(description) else { + return Decision::Allow; + }; + if press != pressed { + return Decision::Allow; + } + if denied.contains(&(call.client.0, kind, window.0)) { + DENY + } else { + Decision::Allow + } +} + +/// Decodes a frame the key walk writes: a core KeyPress/KeyRelease (event +/// window at byte 12), an XI2 key GenericEvent (device at byte 10, event +/// window at byte 24) or a raw key GenericEvent (device at byte 10, always the +/// root). `None` for any other frame. +pub(super) fn decode(frame: &[u8], order: ClientByteOrder) -> Option<(Kind, u32)> { + match frame[0] & 0x7f { + 2 | 3 => Some((Kind::Core, dec32(&frame[12..16], order))), + 35 if frame[1] == XI2_MAJOR_OPCODE => match dec16(&frame[8..10], order) { + 2 | 3 => Some(( + Kind::Xi2(dec16(&frame[10..12], order)), + dec32(&frame[24..28], order), + )), + 13 | 14 => Some((Kind::Raw(dec16(&frame[10..12], order)), ROOT)), + _ => None, + }, + _ => None, + } +} + +pub(super) struct ClientBytes { + pub(super) client: u32, + pub(super) order: ClientByteOrder, + pub(super) sequence: u16, + pub(super) bytes: Vec, +} + +/// The keyboard grab and the master XI1 freeze after a run: whether an active +/// keyboard grab exists, and the master freeze state with the stored press. +#[derive(Debug, PartialEq, Eq)] +pub(super) struct GrabState { + pub(super) active: bool, + pub(super) freeze: Option<(Xi1SyncState, Option<(bool, u8)>)>, +} + +pub(super) struct Run { + pub(super) clients: Vec, + pub(super) calls: Vec, + pub(super) state: String, + pub(super) grab: GrabState, +} + +pub(super) fn run(row: &Row, policy: Option<&'static [Call]>) -> Run { + let mut f = NotifyFixture::new(); + (row.setup)(&mut f); + f.state.clients.get_mut(&A).expect("client A").byte_order = ClientByteOrder::BigEndian; + for client in [SEND_CLIENT, A, B] { + f.drain(ClientId(client)); + } + let calls = policy.map(|denied| { + let pressed = row.drive.pressed(); + f.install_policy(move |_, call| decide(denied, pressed, call)) + }); + drive(&mut f, row.drive); + assert!( + client_io::failed_writers(&f.state.clients).is_empty(), + "{}: delivery queued a disconnect", + row.name + ); + let clients = [SEND_CLIENT, A, B] + .into_iter() + .map(|client| { + let state = &f.state.clients[&client]; + ClientBytes { + client, + order: state.byte_order, + sequence: state.last_sequence.load(Ordering::Relaxed), + bytes: f.drain(ClientId(client)), + } + }) + .collect(); + let calls = calls + .map(|calls| { + calls + .lock() + .unwrap() + .iter() + .filter(|call| call.hook == ExtensionHook::Receive) + .filter_map(|call| { + let subject = match call.receive? { + EventSubject::Window(window) => window.0, + other => panic!("{}: key Receive subject {other:?}", row.name), + }; + let [description] = call.events.as_deref()? else { + return None; + }; + let (kind, pressed) = key_call(description)?; + assert_eq!( + pressed, + row.drive.pressed(), + "{}: Receive names the other key event", + row.name + ); + Some((call.client.0, kind, subject)) + }) + .collect() + }) + .unwrap_or_default(); + let state = format!("{:?}", (f.state.core_focus.raw, f.state.keys_down)); + let grab = GrabState { + active: f.state.active_keyboard_grab.is_some(), + freeze: f + .state + .xi1_frozen + .get(&DEVICEID_MASTER_KEYBOARD) + .map(|freeze| { + let stored = match &freeze.stored { + Some(QueuedInputEvent::HostKeyTransition(event, _, _)) => { + Some((event.pressed, event.keycode)) + } + _ => None, + }; + (freeze.state, stored) + }), + }; + Run { + clients, + calls, + state, + grab, + } +} + +pub(super) fn grouped( + items: impl IntoIterator, +) -> BTreeMap> { + let mut out: BTreeMap> = BTreeMap::new(); + for (client, item) in items { + out.entry(client).or_default().push(item); + } + out +} + +/// The key frames a run wrote, with the client byte order and sequence checked. +pub(super) fn delivered(name: &str, run: &Run) -> Vec { + let mut frames = Vec::new(); + for client in &run.clients { + for frame in split_frames(&client.bytes, client.order) { + if let Some((kind, window)) = decode(frame, client.order) { + let sequence = match client.order { + ClientByteOrder::LittleEndian => client.sequence.to_le_bytes(), + ClientByteOrder::BigEndian => client.sequence.to_be_bytes(), + }; + assert_eq!( + &frame[2..4], + sequence.as_slice(), + "{name}: client {} frame sequence", + client.client + ); + let keycode = match kind { + Kind::Core => u32::from(frame[1]), + Kind::Xi2(_) | Kind::Raw(_) => dec32(&frame[16..20], client.order), + }; + assert_eq!(keycode, u32::from(KEYCODE), "{name}: frame keycode"); + frames.push((client.client, kind, window)); + } + } + } + frames +} + +pub(super) fn check_run(row: &Row, run: &Run, expect: &Expect, mode: &str) { + let name = row.name; + assert_eq!( + grouped(run.calls.iter().map(|&(c, kind, w)| (c, (kind, w)))), + grouped(expect.calls.iter().map(|&(c, kind, w)| (c, (kind, w)))), + "{name} [{mode}]: Receive calls per client" + ); + assert_eq!( + grouped( + delivered(name, run) + .into_iter() + .map(|(c, k, w)| (c, (k, w))) + ), + grouped(expect.frames.iter().map(|&(c, k, w)| (c, (k, w)))), + "{name} [{mode}]: frames per client" + ); +} + +/// The full 32 bytes of a core key frame the denial moved, with the row's +/// press flag, the frame's sequence and the recipient's byte order. +pub(super) fn literal_moved( + pressed: bool, + order: ClientByteOrder, + sequence: u16, + moved: &Moved, +) -> Vec { + let mut bytes = vec![if pressed { 2 } else { 3 }, KEYCODE]; + bytes.extend(enc16(order, sequence)); + bytes.extend(enc32(order, TIME)); + bytes.extend(enc32(order, ROOT_WINDOW.0)); + bytes.extend(enc32(order, moved.window)); + bytes.extend(enc32(order, moved.child)); + bytes.extend(enc16(order, POINTER.0 as u16)); + bytes.extend(enc16(order, POINTER.1 as u16)); + bytes.extend(enc16(order, moved.event.0 as u16)); + bytes.extend(enc16(order, moved.event.1 as u16)); + bytes.extend(enc16(order, 0)); // state + bytes.extend([1, 0]); // same-screen, pad + assert_eq!(bytes.len(), 32); + bytes +} + +/// Runs one row under the three modes and checks it: literal frames and Receive +/// calls per run, byte identity of no-policy and allow-all, identical bytes for +/// a frame both allow-all and denied write, and literal bytes for each frame +/// only the denied run writes. +pub(super) fn check_row(row: &Row) { + let name = row.name; + let plain = run(row, None); + let allow = run(row, Some(&[])); + assert_eq!( + allow.clients.iter().map(|c| &c.bytes).collect::>(), + plain.clients.iter().map(|c| &c.bytes).collect::>(), + "{name}: allow-all changed the bytes" + ); + assert_eq!(allow.state, plain.state, "{name}: allow-all changed state"); + check_run( + row, + &plain, + &Expect { + frames: row.allow.frames, + calls: &[], + }, + "no policy", + ); + check_run(row, &allow, &row.allow, "allow-all"); + + let denied = run(row, Some(row.deny)); + check_run(row, &denied, &row.denied, "denial"); + assert_eq!(denied.state, allow.state, "{name}: denial changed state"); + assert_eq!( + denied.grab, allow.grab, + "{name}: denial changed the grab and freeze state" + ); + let mut moved_seen = 0; + for got in &denied.clients { + let allowed = allow + .clients + .iter() + .find(|c| c.client == got.client) + .expect("allow-all stream for the client"); + let allowed_frames: Vec<(Kind, u32, &[u8])> = split_frames(&allowed.bytes, allowed.order) + .into_iter() + .filter_map(|frame| { + decode(frame, allowed.order).map(|(kind, window)| (kind, window, frame)) + }) + .collect(); + for frame in split_frames(&got.bytes, got.order) { + let Some((kind, window)) = decode(frame, got.order) else { + continue; + }; + if let Some((_, _, same)) = allowed_frames + .iter() + .find(|(k, w, _)| *k == kind && *w == window) + { + assert_eq!( + frame, *same, + "{name}: client {} {kind:?} @{window:#x} bytes under denial", + got.client + ); + continue; + } + let moved = row + .moved + .iter() + .find(|m| m.client == got.client && m.window == window && kind == Kind::Core) + .unwrap_or_else(|| { + panic!( + "{name}: client {} {kind:?} @{window:#x} is moved by the denial and has no literal", + got.client + ) + }); + assert_eq!( + frame, + literal_moved(row.drive.pressed(), got.order, got.sequence, moved).as_slice(), + "{name}: client {} moved frame @{window:#x}", + got.client + ); + moved_seen += 1; + } + } + assert_eq!(moved_seen, row.moved.len(), "{name}: moved frames written"); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs index d884e6c63..41413a328 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -18,736 +18,12 @@ //! //! Receive calls are compared per client: `state.clients` is a HashMap, so the //! order across clients is not part of the contract. - -use super::{ - access_notify_support::{DENY, NotifyFixture, dec16, dec32, enc16, enc32, split_frames}, - extensions::{ExtensionHook, RecordedExtensionCheck}, - xi2::xi_select_body, -}; +use super::{access_input_support::*, access_notify_support::NotifyFixture}; use crate::{ - access::{Decision, EventDescription, EventSubject}, - core_loop::{ - InputOrigin, client_io, - key_fanout::{ - RawKeyEvent, key_event_fanout_after_transition, key_event_fanout_to_state, - raw_key_event_to_state, - }, - process_request::RequestOutcome, - }, - host_x11::HostKeyEvent, - nested::XI2_MAJOR_OPCODE, - resources::ROOT_WINDOW, - server::{QueuedInputEvent, Xi1SyncState}, + core_loop::InputOrigin, + server::Xi1SyncState, xinput::{DEVICEID_MASTER_KEYBOARD, DEVICEID_XTEST_KEYBOARD}, }; -use std::{collections::BTreeMap, sync::atomic::Ordering}; -use yserver_protocol::x11::{ClientByteOrder, ClientId, RequestHeader, SequenceNumber}; - -const SEND_CLIENT: u32 = 1; -/// The client that selects on the child window (A in the brief). -const A: u32 = 2; -/// The client that selects on the focus window (B in the brief). -const B: u32 = 3; -const FOCUS: u32 = 0x0061_0001; -const CHILD: u32 = 0x0061_0002; -const POINTER: (i16, i16) = (120, 120); -const KEYCODE: u8 = 38; -const TIME: u32 = 0x5678; -const XI_MAJOR: u8 = 137; -const XI_SELECT_EVENTS: u8 = 46; -const CORE_CHANGE_WINDOW_ATTRIBUTES: u8 = 2; -const CORE_CREATE_WINDOW: u8 = 1; -const CORE_MAP_WINDOW: u8 = 8; -const CORE_SET_INPUT_FOCUS: u8 = 42; -const CW_EVENT_MASK: u32 = 0x800; -const KEY_PRESS: u32 = 1; -const KEY_RELEASE: u32 = 2; -/// XI2 mask word for KeyPress (bit 2) and KeyRelease (bit 3). -const XI_KEY_PRESS: u32 = 1 << 2; -const XI_KEY_RELEASE: u32 = 1 << 3; -const XI_KEY_PRESS_AND_RELEASE: u32 = XI_KEY_PRESS | XI_KEY_RELEASE; -/// XI2 mask word for RawKeyPress (bit 13) and RawKeyRelease (bit 14). -const XI_RAW_KEY_PRESS: u32 = 1 << 13; -/// The grab window of the grab rows: the root is on no walk to FOCUS. -const ROOT: u32 = ROOT_WINDOW.0; - -/// One frame the server writes: (client, what it is, event window). -type Frame = (u32, Kind, u32); -/// One Receive call the server makes: (client, description, subject window). -type Call = (u32, CallKind, u32); - -/// What a key frame is. `Xi2` carries the form's device id. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Kind { - Core, - Xi2(u16), - /// A raw key copy: its device, always on the root. A raw frame has no - /// event window, so the grab-leg copy and the root-fanout copy decode the - /// same; only the Receive trace tells them apart. - Raw(u16), -} - -/// What a Receive check names. An XI2 check names the description, not the -/// form, so it carries no device. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum CallKind { - Core, - Xi2, - Raw, -} - -#[derive(Clone, Copy)] -enum Drive { - /// `key_event_fanout_to_state`: the transition-checked entry. - Entry { origin: InputOrigin, pressed: bool }, - /// `key_event_fanout_after_transition` with explicit master and synthetic flags. - After { - origin: InputOrigin, - pressed: bool, - master: bool, - synthetic: bool, - }, - /// `raw_key_event_to_state`: the XI2 raw copies of one device key. - Raw { origin: InputOrigin, pressed: bool }, -} - -impl Drive { - fn pressed(self) -> bool { - match self { - Drive::Entry { pressed, .. } - | Drive::After { pressed, .. } - | Drive::Raw { pressed, .. } => pressed, - } - } -} - -struct Expect { - frames: &'static [Frame], - calls: &'static [Call], -} - -/// A frame the denial moves to another window: the literal bytes the row pins. -/// Core KeyPress/KeyRelease only; the event is the key's, so only its window, -/// child and coordinates vary. -#[derive(Clone, Copy)] -struct Moved { - client: u32, - window: u32, - child: u32, - event: (i16, i16), -} - -struct Row { - name: &'static str, - setup: fn(&mut NotifyFixture), - drive: Drive, - /// (client, check, window) Receive calls to deny. - deny: &'static [Call], - /// Frames only the denied run writes, pinned in full. - moved: &'static [Moved], - allow: Expect, - denied: Expect, -} - -// ---- request helpers ----------------------------------------------------- - -/// Sends one request from `client` with the next sequence number of that -/// client, checks it was handled with no writer failure, and returns the bytes -/// the requester was sent (a reply, or nothing). -fn send_with_reply( - f: &mut NotifyFixture, - client: u32, - opcode: u8, - data: u8, - body: &[u8], -) -> Vec { - let sequence = { - let state = &f.state.clients[&client]; - let next = state.last_sequence.load(Ordering::Relaxed).wrapping_add(1); - state.last_sequence.store(next, Ordering::Relaxed); - next - }; - let header = RequestHeader { - opcode, - data, - length_units: u32::try_from((4 + body.len()) / 4).expect("request length"), - }; - let outcome = f - .request(ClientId(client), SequenceNumber(sequence), header, body) - .expect("request through process_request"); - assert!( - matches!(outcome, RequestOutcome::Handled), - "request handled" - ); - assert!( - client_io::failed_writers(&f.state.clients).is_empty(), - "request queued a disconnect" - ); - f.drain(ClientId(client)) -} - -/// `send_with_reply` for a request that has no reply and no error. -fn send(f: &mut NotifyFixture, client: u32, opcode: u8, data: u8, body: &[u8]) { - assert!( - send_with_reply(f, client, opcode, data, body).is_empty(), - "requester got bytes" - ); -} - -/// Two windows: FOCUS (100,100) 200x200 and CHILD inside it at (10,10), both -/// mapped. Focus is FOCUS, the pointer is inside CHILD. -fn tree(f: &mut NotifyFixture) { - for (client, base) in [(SEND_CLIENT, 0x0100), (A, 0x0200), (B, 0x0300)] { - f.state.clients[&client] - .last_sequence - .store(base, Ordering::Relaxed); - } - for (window, parent, x, y, size) in [ - (FOCUS, ROOT_WINDOW.0, 100, 100, 200), - (CHILD, FOCUS, 10, 10, 50), - ] { - let mut body = Vec::with_capacity(32); - body.extend_from_slice(&window.to_le_bytes()); - body.extend_from_slice(&parent.to_le_bytes()); - body.extend_from_slice(&(x as i16).to_le_bytes()); - body.extend_from_slice(&(y as i16).to_le_bytes()); - body.extend_from_slice(&(size as u16).to_le_bytes()); - body.extend_from_slice(&(size as u16).to_le_bytes()); - body.extend_from_slice(&0_u16.to_le_bytes()); // border - body.extend_from_slice(&1_u16.to_le_bytes()); // InputOutput - body.extend_from_slice(&crate::resources::ROOT_VISUAL.0.to_le_bytes()); - body.extend_from_slice(&0_u32.to_le_bytes()); // value mask - send(f, SEND_CLIENT, CORE_CREATE_WINDOW, 24, &body); - send(f, SEND_CLIENT, CORE_MAP_WINDOW, 0, &window.to_le_bytes()); - } - send( - f, - SEND_CLIENT, - CORE_SET_INPUT_FOCUS, - 0, - &[FOCUS.to_le_bytes(), 0_u32.to_le_bytes()].concat(), - ); - f.state.pointer_root = POINTER; -} - -/// Core KeyPress/KeyRelease selection on `window` for `client`. -fn select_core(f: &mut NotifyFixture, client: u32, window: u32, mask: u32) { - let body = [ - window.to_le_bytes(), - CW_EVENT_MASK.to_le_bytes(), - mask.to_le_bytes(), - ] - .concat(); - send(f, client, CORE_CHANGE_WINDOW_ATTRIBUTES, 0, &body); -} - -/// XI2 key selection of one device on `window` for `client`. -fn select_xi2(f: &mut NotifyFixture, client: u32, window: u32, device: u16, mask: u32) { - let body = xi_select_body(window, &[(device, &[mask])]); - send(f, client, XI_MAJOR, XI_SELECT_EVENTS, &body); -} - -/// Detectable autorepeat for `client`: XkbPerClientFlags with -/// `XkbPCF_DetectableAutoRepeatMask`, after XkbUseExtension. Both go through the -/// XKB request dispatcher (`handle_xkb_request`), as the XKB tests drive them. -fn set_detectable_repeat(f: &mut NotifyFixture, client: u32) { - const XKB_MAJOR: u8 = 136; - const XKB_USE_EXTENSION: u8 = 0; - const XKB_PER_CLIENT_FLAGS: u8 = 21; - const DETECTABLE_AUTO_REPEAT: u32 = 1; - xkb_request(f, client, XKB_MAJOR, XKB_USE_EXTENSION, &[1, 0, 0, 0]); - let mut body = vec![0_u8; 24]; - body[0..2].copy_from_slice(&0x0100_u16.to_le_bytes()); // XkbUseCoreKbd - body[4..8].copy_from_slice(&DETECTABLE_AUTO_REPEAT.to_le_bytes()); // change - body[8..12].copy_from_slice(&DETECTABLE_AUTO_REPEAT.to_le_bytes()); // value - xkb_request(f, client, XKB_MAJOR, XKB_PER_CLIENT_FLAGS, &body); - let flags = f - .state - .xkb_clients - .get(&client) - .copied() - .unwrap_or_default(); - assert!( - flags.wants_detectable_auto_repeat(), - "XkbPerClientFlags set detectable repeat" - ); -} - -/// One XKB request through `handle_xkb_request`, with its reply drained. -fn xkb_request(f: &mut NotifyFixture, client: u32, opcode: u8, minor: u8, body: &[u8]) { - let sequence = { - let state = &f.state.clients[&client]; - let next = state.last_sequence.load(Ordering::Relaxed).wrapping_add(1); - state.last_sequence.store(next, Ordering::Relaxed); - next - }; - crate::core_loop::process_request::xkb::handle_xkb_request( - &mut f.state, - &mut f.backend, - None, - ClientId(client), - SequenceNumber(sequence), - RequestHeader { - opcode, - data: minor, - length_units: u32::try_from(1 + body.len().div_ceil(4)).expect("request length"), - }, - body, - ) - .expect("XKB request through handle_xkb_request"); - f.drain(ClientId(client)); -} - -/// The slave keyboard's exact XI2 grab owned by `owner` on `grab_window`, made -/// with XIGrabDevice (asynchronous, not owner-events, KeyPress mask). -fn grab_slave_keyboard(f: &mut NotifyFixture, owner: u32, grab_window: u32) { - grab_keyboard_device( - f, - owner, - DEVICEID_XTEST_KEYBOARD, - grab_window, - false, - XI_KEY_PRESS, - ); -} - -/// XIGrabDevice of `device` by `owner` on `grab_window` with the given -/// owner_events and one mask word. A master keyboard grab is the -/// `active_keyboard_grab` the raw master leg reads; a slave grab is per device. -fn grab_keyboard_device( - f: &mut NotifyFixture, - owner: u32, - device: u16, - grab_window: u32, - owner_events: bool, - mask: u32, -) { - const XI_GRAB_DEVICE: u8 = 51; - let mut body = Vec::with_capacity(28); - body.extend_from_slice(&grab_window.to_le_bytes()); - body.extend_from_slice(&[0; 8]); // CurrentTime, no cursor - body.extend_from_slice(&device.to_le_bytes()); - body.extend_from_slice(&[1, 1, u8::from(owner_events), 0]); // async modes - body.extend_from_slice(&1_u16.to_le_bytes()); // one mask word - body.extend_from_slice(&mask.to_le_bytes()); - let bytes = send_with_reply(f, owner, XI_MAJOR, XI_GRAB_DEVICE, &body); - let reply = &bytes[bytes.len() - 32..]; - assert_eq!((reply[0], reply[8]), (1, 0), "XIGrabDevice replies Success"); -} - -/// SetInputFocus(PointerRoot) from the requester. -fn set_focus_pointer_root(f: &mut NotifyFixture) { - send( - f, - SEND_CLIENT, - CORE_SET_INPUT_FOCUS, - 0, - &[1_u32.to_le_bytes(), 0_u32.to_le_bytes()].concat(), - ); -} - -/// The core GrabKeyboard request by `owner` on `window`, asynchronous pointer -/// mode, with `owner_events`. The reply must be Success. -fn grab_keyboard(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: bool) { - const CORE_GRAB_KEYBOARD: u8 = 31; - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&window.to_le_bytes()); - body.extend_from_slice(&[0; 4]); // CurrentTime - body.extend_from_slice(&[1, 1, 0, 0]); // async pointer, async keyboard - let bytes = send_with_reply(f, owner, CORE_GRAB_KEYBOARD, u8::from(owner_events), &body); - let reply = &bytes[bytes.len() - 32..]; - assert_eq!((reply[0], reply[1]), (1, 0), "GrabKeyboard replies Success"); -} - -/// The core GrabKey request by `owner` on `window` for `KEYCODE` with no -/// modifiers, asynchronous pointer mode and the given keyboard mode. -fn grab_key( - f: &mut NotifyFixture, - owner: u32, - window: u32, - owner_events: bool, - keyboard_sync: bool, -) { - const CORE_GRAB_KEY: u8 = 33; - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&window.to_le_bytes()); - body.extend_from_slice(&0_u16.to_le_bytes()); // modifiers - body.push(KEYCODE); - body.push(1); // pointer async - body.push(u8::from(!keyboard_sync)); // keyboard: 0 sync, 1 async - body.extend_from_slice(&[0; 3]); - send(f, owner, CORE_GRAB_KEY, u8::from(owner_events), &body); -} - -// ---- run and decode ------------------------------------------------------ - -fn key_event(origin: InputOrigin, pressed: bool) -> HostKeyEvent { - HostKeyEvent { - origin, - pressed, - keycode: KEYCODE, - time: TIME, - root_x: POINTER.0, - root_y: POINTER.1, - event_x: 0, - event_y: 0, - state: 0, - } -} - -fn drive(f: &mut NotifyFixture, drive: Drive) { - let dropped = match drive { - Drive::Entry { origin, pressed } => { - key_event_fanout_to_state(&mut f.state, &mut f.backend, key_event(origin, pressed)) - } - Drive::After { - origin, - pressed, - master, - synthetic, - } => key_event_fanout_after_transition( - &mut f.state, - &mut f.backend, - key_event(origin, pressed), - master, - synthetic, - ), - Drive::Raw { origin, pressed } => raw_key_event_to_state( - &mut f.state, - RawKeyEvent { - origin, - keycode: KEYCODE, - pressed, - time: TIME, - }, - false, - false, - ), - }; - assert!(dropped.is_empty(), "delivery queued a disconnect"); -} - -/// The key-related description a Receive call names, or `None` for other events. -fn key_call(description: &EventDescription) -> Option<(CallKind, bool)> { - match description.extension { - None if description.type_code == 2 || description.type_code == 3 => { - Some((CallKind::Core, description.type_code == 2)) - } - Some(extension) - if description.type_code == 35 && extension.major_opcode == XI2_MAJOR_OPCODE => - { - match extension.event_type { - 2 | 3 => Some((CallKind::Xi2, extension.event_type == 2)), - 13 | 14 => Some((CallKind::Raw, extension.event_type == 13)), - _ => None, - } - } - _ => None, - } -} - -/// Denies exactly the listed (client, kind, window) Receive checks, matched by -/// hook, subject and description. -fn decide(denied: &[Call], pressed: bool, call: &RecordedExtensionCheck) -> Decision { - if call.hook != ExtensionHook::Receive { - return Decision::Allow; - } - let (Some(EventSubject::Window(window)), Some(events)) = (call.receive, call.events.as_deref()) - else { - return Decision::Allow; - }; - let [description] = events else { - return Decision::Allow; - }; - let Some((kind, press)) = key_call(description) else { - return Decision::Allow; - }; - if press != pressed { - return Decision::Allow; - } - if denied.contains(&(call.client.0, kind, window.0)) { - DENY - } else { - Decision::Allow - } -} - -/// Decodes a frame the key walk writes: a core KeyPress/KeyRelease (event -/// window at byte 12), an XI2 key GenericEvent (device at byte 10, event -/// window at byte 24) or a raw key GenericEvent (device at byte 10, always the -/// root). `None` for any other frame. -fn decode(frame: &[u8], order: ClientByteOrder) -> Option<(Kind, u32)> { - match frame[0] & 0x7f { - 2 | 3 => Some((Kind::Core, dec32(&frame[12..16], order))), - 35 if frame[1] == XI2_MAJOR_OPCODE => match dec16(&frame[8..10], order) { - 2 | 3 => Some(( - Kind::Xi2(dec16(&frame[10..12], order)), - dec32(&frame[24..28], order), - )), - 13 | 14 => Some((Kind::Raw(dec16(&frame[10..12], order)), ROOT)), - _ => None, - }, - _ => None, - } -} - -struct ClientBytes { - client: u32, - order: ClientByteOrder, - sequence: u16, - bytes: Vec, -} - -/// The keyboard grab and the master XI1 freeze after a run: whether an active -/// keyboard grab exists, and the master freeze state with the stored press. -#[derive(Debug, PartialEq, Eq)] -struct GrabState { - active: bool, - freeze: Option<(Xi1SyncState, Option<(bool, u8)>)>, -} - -struct Run { - clients: Vec, - calls: Vec, - state: String, - grab: GrabState, -} - -fn run(row: &Row, policy: Option<&'static [Call]>) -> Run { - let mut f = NotifyFixture::new(); - (row.setup)(&mut f); - f.state.clients.get_mut(&A).expect("client A").byte_order = ClientByteOrder::BigEndian; - for client in [SEND_CLIENT, A, B] { - f.drain(ClientId(client)); - } - let calls = policy.map(|denied| { - let pressed = row.drive.pressed(); - f.install_policy(move |_, call| decide(denied, pressed, call)) - }); - drive(&mut f, row.drive); - assert!( - client_io::failed_writers(&f.state.clients).is_empty(), - "{}: delivery queued a disconnect", - row.name - ); - let clients = [SEND_CLIENT, A, B] - .into_iter() - .map(|client| { - let state = &f.state.clients[&client]; - ClientBytes { - client, - order: state.byte_order, - sequence: state.last_sequence.load(Ordering::Relaxed), - bytes: f.drain(ClientId(client)), - } - }) - .collect(); - let calls = calls - .map(|calls| { - calls - .lock() - .unwrap() - .iter() - .filter(|call| call.hook == ExtensionHook::Receive) - .filter_map(|call| { - let subject = match call.receive? { - EventSubject::Window(window) => window.0, - other => panic!("{}: key Receive subject {other:?}", row.name), - }; - let [description] = call.events.as_deref()? else { - return None; - }; - let (kind, pressed) = key_call(description)?; - assert_eq!( - pressed, - row.drive.pressed(), - "{}: Receive names the other key event", - row.name - ); - Some((call.client.0, kind, subject)) - }) - .collect() - }) - .unwrap_or_default(); - let state = format!("{:?}", (f.state.core_focus.raw, f.state.keys_down)); - let grab = GrabState { - active: f.state.active_keyboard_grab.is_some(), - freeze: f - .state - .xi1_frozen - .get(&DEVICEID_MASTER_KEYBOARD) - .map(|freeze| { - let stored = match &freeze.stored { - Some(QueuedInputEvent::HostKeyTransition(event, _, _)) => { - Some((event.pressed, event.keycode)) - } - _ => None, - }; - (freeze.state, stored) - }), - }; - Run { - clients, - calls, - state, - grab, - } -} - -fn grouped(items: impl IntoIterator) -> BTreeMap> { - let mut out: BTreeMap> = BTreeMap::new(); - for (client, item) in items { - out.entry(client).or_default().push(item); - } - out -} - -/// The key frames a run wrote, with the client byte order and sequence checked. -fn delivered(name: &str, run: &Run) -> Vec { - let mut frames = Vec::new(); - for client in &run.clients { - for frame in split_frames(&client.bytes, client.order) { - if let Some((kind, window)) = decode(frame, client.order) { - let sequence = match client.order { - ClientByteOrder::LittleEndian => client.sequence.to_le_bytes(), - ClientByteOrder::BigEndian => client.sequence.to_be_bytes(), - }; - assert_eq!( - &frame[2..4], - sequence.as_slice(), - "{name}: client {} frame sequence", - client.client - ); - let keycode = match kind { - Kind::Core => u32::from(frame[1]), - Kind::Xi2(_) | Kind::Raw(_) => dec32(&frame[16..20], client.order), - }; - assert_eq!(keycode, u32::from(KEYCODE), "{name}: frame keycode"); - frames.push((client.client, kind, window)); - } - } - } - frames -} - -fn check_run(row: &Row, run: &Run, expect: &Expect, mode: &str) { - let name = row.name; - assert_eq!( - grouped(run.calls.iter().map(|&(c, kind, w)| (c, (kind, w)))), - grouped(expect.calls.iter().map(|&(c, kind, w)| (c, (kind, w)))), - "{name} [{mode}]: Receive calls per client" - ); - assert_eq!( - grouped( - delivered(name, run) - .into_iter() - .map(|(c, k, w)| (c, (k, w))) - ), - grouped(expect.frames.iter().map(|&(c, k, w)| (c, (k, w)))), - "{name} [{mode}]: frames per client" - ); -} - -/// The full 32 bytes of a core key frame the denial moved, with the row's -/// press flag, the frame's sequence and the recipient's byte order. -fn literal_moved(pressed: bool, order: ClientByteOrder, sequence: u16, moved: &Moved) -> Vec { - let mut bytes = vec![if pressed { 2 } else { 3 }, KEYCODE]; - bytes.extend(enc16(order, sequence)); - bytes.extend(enc32(order, TIME)); - bytes.extend(enc32(order, ROOT_WINDOW.0)); - bytes.extend(enc32(order, moved.window)); - bytes.extend(enc32(order, moved.child)); - bytes.extend(enc16(order, POINTER.0 as u16)); - bytes.extend(enc16(order, POINTER.1 as u16)); - bytes.extend(enc16(order, moved.event.0 as u16)); - bytes.extend(enc16(order, moved.event.1 as u16)); - bytes.extend(enc16(order, 0)); // state - bytes.extend([1, 0]); // same-screen, pad - assert_eq!(bytes.len(), 32); - bytes -} - -/// Runs one row under the three modes and checks it: literal frames and Receive -/// calls per run, byte identity of no-policy and allow-all, identical bytes for -/// a frame both allow-all and denied write, and literal bytes for each frame -/// only the denied run writes. -fn check_row(row: &Row) { - let name = row.name; - let plain = run(row, None); - let allow = run(row, Some(&[])); - assert_eq!( - allow.clients.iter().map(|c| &c.bytes).collect::>(), - plain.clients.iter().map(|c| &c.bytes).collect::>(), - "{name}: allow-all changed the bytes" - ); - assert_eq!(allow.state, plain.state, "{name}: allow-all changed state"); - check_run( - row, - &plain, - &Expect { - frames: row.allow.frames, - calls: &[], - }, - "no policy", - ); - check_run(row, &allow, &row.allow, "allow-all"); - - let denied = run(row, Some(row.deny)); - check_run(row, &denied, &row.denied, "denial"); - assert_eq!(denied.state, allow.state, "{name}: denial changed state"); - assert_eq!( - denied.grab, allow.grab, - "{name}: denial changed the grab and freeze state" - ); - let mut moved_seen = 0; - for got in &denied.clients { - let allowed = allow - .clients - .iter() - .find(|c| c.client == got.client) - .expect("allow-all stream for the client"); - let allowed_frames: Vec<(Kind, u32, &[u8])> = split_frames(&allowed.bytes, allowed.order) - .into_iter() - .filter_map(|frame| { - decode(frame, allowed.order).map(|(kind, window)| (kind, window, frame)) - }) - .collect(); - for frame in split_frames(&got.bytes, got.order) { - let Some((kind, window)) = decode(frame, got.order) else { - continue; - }; - if let Some((_, _, same)) = allowed_frames - .iter() - .find(|(k, w, _)| *k == kind && *w == window) - { - assert_eq!( - frame, *same, - "{name}: client {} {kind:?} @{window:#x} bytes under denial", - got.client - ); - continue; - } - let moved = row - .moved - .iter() - .find(|m| m.client == got.client && m.window == window && kind == Kind::Core) - .unwrap_or_else(|| { - panic!( - "{name}: client {} {kind:?} @{window:#x} is moved by the denial and has no literal", - got.client - ) - }); - assert_eq!( - frame, - literal_moved(row.drive.pressed(), got.order, got.sequence, moved).as_slice(), - "{name}: client {} moved frame @{window:#x}", - got.client - ); - moved_seen += 1; - } - } - assert_eq!(moved_seen, row.moved.len(), "{name}: moved frames written"); -} // ---- rows ---------------------------------------------------------------- diff --git a/crates/yserver-core/src/core_loop/process_request/tests/mod.rs b/crates/yserver-core/src/core_loop/process_request/tests/mod.rs index 7ac3a9b66..c059f6568 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/mod.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/mod.rs @@ -7,6 +7,7 @@ mod access_gc_font; mod access_glx; mod access_grabs; mod access_input; +mod access_input_support; mod access_key_input; mod access_notify_egress; mod access_notify_exemptions; From d59964f5816553dfb2e5162170dee43b4047e1c6 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 19:06:18 -0300 Subject: [PATCH 23/72] test(access): generalise the input harness for pointer and XI1 batches The shared harness now matches whole batches (every description of a call must name the same event), names core, XI2, raw and XI1 device calls by event type, and drives pointer events through pointer_event_fanout_to_state. Each row can state the grab state of its denied run (pointer grab added); by default it is the allow-all state. The no-policy and allow-all runs must now also share their grab state. Frame decoding covers core and XI2 button and motion events. XI1 device frames are not decoded yet. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Haiku 5.5 --- .../tests/access_input_support.rs | 224 ++++++++++++++---- .../process_request/tests/access_key_input.rs | 30 +++ 2 files changed, 204 insertions(+), 50 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index c0722e9c2..479046720 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -16,9 +16,10 @@ use crate::{ RawKeyEvent, key_event_fanout_after_transition, key_event_fanout_to_state, raw_key_event_to_state, }, + pointer_fanout::pointer_event_fanout_to_state, process_request::RequestOutcome, }, - host_x11::HostKeyEvent, + host_x11::{HostKeyEvent, HostPointerEvent, HostXidMap, PointerEventKind}, nested::XI2_MAJOR_OPCODE, resources::ROOT_WINDOW, server::{QueuedInputEvent, Xi1SyncState}, @@ -78,6 +79,8 @@ pub(super) enum CallKind { Core, Xi2, Raw, + /// An XI1 device event (or batch), named by its offset from the XI base. + Xi1, } #[derive(Clone, Copy)] @@ -93,14 +96,55 @@ pub(super) enum Drive { }, /// `raw_key_event_to_state`: the XI2 raw copies of one device key. Raw { origin: InputOrigin, pressed: bool }, + /// `pointer_event_fanout_to_state` with `handle_grabs` and `!is_replay`. + /// `button` is the detail of a button event and is ignored for motion. + #[allow(dead_code)] // constructed by the pointer scenarios (next commit) + Pointer { + origin: InputOrigin, + kind: PointerEventKind, + button: u8, + }, } impl Drive { - fn pressed(self) -> bool { + /// The event type the drive produces, in the numbering core and XI2 share: + /// 2/3 key press/release, 4/5/6 button press/release and motion, 13/14 raw key. + pub(super) fn ev(self) -> u16 { + match self { + Drive::Entry { pressed, .. } | Drive::After { pressed, .. } => { + if pressed { + 2 + } else { + 3 + } + } + Drive::Raw { pressed, .. } => { + if pressed { + 13 + } else { + 14 + } + } + Drive::Pointer { kind, .. } => match kind { + PointerEventKind::ButtonPress => 4, + PointerEventKind::ButtonRelease => 5, + PointerEventKind::MotionNotify => 6, + other => panic!("pointer drive of {other:?} is not a natural walk"), + }, + } + } + + /// The detail byte every frame of this drive carries: the keycode for key + /// events, the button for button events, zero for motion. + pub(super) fn detail(self) -> u32 { match self { - Drive::Entry { pressed, .. } - | Drive::After { pressed, .. } - | Drive::Raw { pressed, .. } => pressed, + Drive::Entry { .. } | Drive::After { .. } | Drive::Raw { .. } => u32::from(KEYCODE), + Drive::Pointer { kind, button, .. } => match kind { + PointerEventKind::ButtonPress | PointerEventKind::ButtonRelease => { + u32::from(button) + } + _ => 0, + }, } } } @@ -128,6 +172,9 @@ pub(super) struct Row { /// (client, check, window) Receive calls to deny. pub(super) deny: &'static [Call], /// Frames only the denied run writes, pinned in full. + /// The denied run's grab state when it differs from allow-all; `None` means + /// the same as allow-all. + pub(super) denied_grab: Option, pub(super) moved: &'static [Moved], pub(super) allow: Expect, pub(super) denied: Expect, @@ -396,6 +443,35 @@ pub(super) fn drive(f: &mut NotifyFixture, drive: Drive) { master, synthetic, ), + Drive::Pointer { + origin, + kind, + button, + } => pointer_event_fanout_to_state( + &mut f.state, + &mut f.backend, + &HostXidMap::new(), + HostPointerEvent { + origin, + kind, + host_xid: 0, + detail: button, + time: TIME, + root_x: POINTER.0, + root_y: POINTER.1, + event_x: POINTER.0, + event_y: POINTER.1, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + device_axes: None, + tree_change: false, + }, + true, + false, + ), Drive::Raw { origin, pressed } => raw_key_event_to_state( &mut f.state, RawKeyEvent { @@ -411,28 +487,42 @@ pub(super) fn drive(f: &mut NotifyFixture, drive: Drive) { assert!(dropped.is_empty(), "delivery queued a disconnect"); } -/// The key-related description a Receive call names, or `None` for other events. -pub(super) fn key_call(description: &EventDescription) -> Option<(CallKind, bool)> { +/// The (kind, event type) one description names: core 2..=6, XI2 2..=6 and +/// 13/14 raw, and XI1 device events by offset. `None` for anything else. +fn describe(description: &EventDescription) -> Option<(CallKind, u16)> { match description.extension { - None if description.type_code == 2 || description.type_code == 3 => { - Some((CallKind::Core, description.type_code == 2)) + None if (2..=6).contains(&description.type_code) => { + Some((CallKind::Core, u16::from(description.type_code))) } Some(extension) if description.type_code == 35 && extension.major_opcode == XI2_MAJOR_OPCODE => { match extension.event_type { - 2 | 3 => Some((CallKind::Xi2, extension.event_type == 2)), - 13 | 14 => Some((CallKind::Raw, extension.event_type == 13)), + 2..=6 => Some((CallKind::Xi2, extension.event_type)), + 13 | 14 => Some((CallKind::Raw, extension.event_type)), _ => None, } } + Some(extension) if extension.major_opcode == XI2_MAJOR_OPCODE => { + Some((CallKind::Xi1, extension.event_type)) + } _ => None, } } +/// The (kind, event type) of a whole batch: every description must name the +/// same one, so a batch is matched and denied as a unit. `None` otherwise. +pub(super) fn event_call(events: &[EventDescription]) -> Option<(CallKind, u16)> { + let (first, rest) = events.split_first()?; + let named = describe(first)?; + rest.iter() + .all(|description| describe(description) == Some(named)) + .then_some(named) +} + /// Denies exactly the listed (client, kind, window) Receive checks, matched by -/// hook, subject and description. -pub(super) fn decide(denied: &[Call], pressed: bool, call: &RecordedExtensionCheck) -> Decision { +/// hook, subject and batch. `ev` is the event type the row drives. +pub(super) fn decide(denied: &[Call], ev: u16, call: &RecordedExtensionCheck) -> Decision { if call.hook != ExtensionHook::Receive { return Decision::Allow; } @@ -440,13 +530,10 @@ pub(super) fn decide(denied: &[Call], pressed: bool, call: &RecordedExtensionChe else { return Decision::Allow; }; - let [description] = events else { + let Some((kind, named)) = event_call(events) else { return Decision::Allow; }; - let Some((kind, press)) = key_call(description) else { - return Decision::Allow; - }; - if press != pressed { + if named != ev { return Decision::Allow; } if denied.contains(&(call.client.0, kind, window.0)) { @@ -456,15 +543,15 @@ pub(super) fn decide(denied: &[Call], pressed: bool, call: &RecordedExtensionChe } } -/// Decodes a frame the key walk writes: a core KeyPress/KeyRelease (event -/// window at byte 12), an XI2 key GenericEvent (device at byte 10, event -/// window at byte 24) or a raw key GenericEvent (device at byte 10, always the -/// root). `None` for any other frame. +/// Decodes a frame the walks write: a core key, button or motion event (event +/// window at byte 12), an XI2 key, button or motion GenericEvent (device at +/// byte 10, event window at byte 24) or a raw key GenericEvent (device at byte +/// 10, always the root). `None` for any other frame. pub(super) fn decode(frame: &[u8], order: ClientByteOrder) -> Option<(Kind, u32)> { match frame[0] & 0x7f { - 2 | 3 => Some((Kind::Core, dec32(&frame[12..16], order))), + 2..=6 => Some((Kind::Core, dec32(&frame[12..16], order))), 35 if frame[1] == XI2_MAJOR_OPCODE => match dec16(&frame[8..10], order) { - 2 | 3 => Some(( + 2..=6 => Some(( Kind::Xi2(dec16(&frame[10..12], order)), dec32(&frame[24..28], order), )), @@ -488,6 +575,17 @@ pub(super) struct ClientBytes { pub(super) struct GrabState { pub(super) active: bool, pub(super) freeze: Option<(Xi1SyncState, Option<(bool, u8)>)>, + pub(super) pointer: Option, +} + +/// The active pointer grab: its owner, grab window, and the implicit and +/// passive flags. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct PointerGrab { + pub(super) owner: u32, + pub(super) window: u32, + pub(super) implicit: bool, + pub(super) passive: bool, } pub(super) struct Run { @@ -505,8 +603,8 @@ pub(super) fn run(row: &Row, policy: Option<&'static [Call]>) -> Run { f.drain(ClientId(client)); } let calls = policy.map(|denied| { - let pressed = row.drive.pressed(); - f.install_policy(move |_, call| decide(denied, pressed, call)) + let ev = row.drive.ev(); + f.install_policy(move |_, call| decide(denied, ev, call)) }); drive(&mut f, row.drive); assert!( @@ -538,16 +636,15 @@ pub(super) fn run(row: &Row, policy: Option<&'static [Call]>) -> Run { EventSubject::Window(window) => window.0, other => panic!("{}: key Receive subject {other:?}", row.name), }; - let [description] = call.events.as_deref()? else { - return None; - }; - let (kind, pressed) = key_call(description)?; - assert_eq!( - pressed, - row.drive.pressed(), - "{}: Receive names the other key event", - row.name - ); + let (kind, named) = event_call(call.events.as_deref()?)?; + if kind != CallKind::Xi1 { + assert_eq!( + named, + row.drive.ev(), + "{}: Receive names another event", + row.name + ); + } Some((call.client.0, kind, subject)) }) .collect() @@ -555,6 +652,16 @@ pub(super) fn run(row: &Row, policy: Option<&'static [Call]>) -> Run { .unwrap_or_default(); let state = format!("{:?}", (f.state.core_focus.raw, f.state.keys_down)); let grab = GrabState { + pointer: f + .state + .active_pointer_grab + .as_ref() + .map(|grab| PointerGrab { + owner: grab.owner.0, + window: grab.grab_window.0, + implicit: grab.implicit, + passive: grab.passive, + }), active: f.state.active_keyboard_grab.is_some(), freeze: f .state @@ -589,7 +696,7 @@ pub(super) fn grouped( } /// The key frames a run wrote, with the client byte order and sequence checked. -pub(super) fn delivered(name: &str, run: &Run) -> Vec { +pub(super) fn delivered(name: &str, run: &Run, detail: u32) -> Vec { let mut frames = Vec::new(); for client in &run.clients { for frame in split_frames(&client.bytes, client.order) { @@ -608,7 +715,7 @@ pub(super) fn delivered(name: &str, run: &Run) -> Vec { Kind::Core => u32::from(frame[1]), Kind::Xi2(_) | Kind::Raw(_) => dec32(&frame[16..20], client.order), }; - assert_eq!(keycode, u32::from(KEYCODE), "{name}: frame keycode"); + assert_eq!(keycode, detail, "{name}: frame detail"); frames.push((client.client, kind, window)); } } @@ -625,7 +732,7 @@ pub(super) fn check_run(row: &Row, run: &Run, expect: &Expect, mode: &str) { ); assert_eq!( grouped( - delivered(name, run) + delivered(name, run, row.drive.detail()) .into_iter() .map(|(c, k, w)| (c, (k, w))) ), @@ -637,12 +744,13 @@ pub(super) fn check_run(row: &Row, run: &Run, expect: &Expect, mode: &str) { /// The full 32 bytes of a core key frame the denial moved, with the row's /// press flag, the frame's sequence and the recipient's byte order. pub(super) fn literal_moved( - pressed: bool, + ev: u16, + detail: u32, order: ClientByteOrder, sequence: u16, moved: &Moved, ) -> Vec { - let mut bytes = vec![if pressed { 2 } else { 3 }, KEYCODE]; + let mut bytes = vec![ev as u8, detail as u8]; bytes.extend(enc16(order, sequence)); bytes.extend(enc32(order, TIME)); bytes.extend(enc32(order, ROOT_WINDOW.0)); @@ -672,6 +780,10 @@ pub(super) fn check_row(row: &Row) { "{name}: allow-all changed the bytes" ); assert_eq!(allow.state, plain.state, "{name}: allow-all changed state"); + assert_eq!( + allow.grab, plain.grab, + "{name}: allow-all changed the grab and freeze state" + ); check_run( row, &plain, @@ -687,8 +799,9 @@ pub(super) fn check_row(row: &Row) { check_run(row, &denied, &row.denied, "denial"); assert_eq!(denied.state, allow.state, "{name}: denial changed state"); assert_eq!( - denied.grab, allow.grab, - "{name}: denial changed the grab and freeze state" + denied.grab, + *row.denied_grab.as_ref().unwrap_or(&allow.grab), + "{name}: denied grab and freeze state" ); let mut moved_seen = 0; for got in &denied.clients { @@ -718,22 +831,33 @@ pub(super) fn check_row(row: &Row) { ); continue; } + // A core frame is pinned in full; an XI2 or raw frame is matched + // by client and window only (its literal is not encoded here). let moved = row .moved .iter() - .find(|m| m.client == got.client && m.window == window && kind == Kind::Core) + .find(|m| m.client == got.client && m.window == window) .unwrap_or_else(|| { panic!( "{name}: client {} {kind:?} @{window:#x} is moved by the denial and has no literal", got.client ) }); - assert_eq!( - frame, - literal_moved(row.drive.pressed(), got.order, got.sequence, moved).as_slice(), - "{name}: client {} moved frame @{window:#x}", - got.client - ); + if kind == Kind::Core { + assert_eq!( + frame, + literal_moved( + row.drive.ev(), + row.drive.detail(), + got.order, + got.sequence, + moved + ) + .as_slice(), + "{name}: client {} moved frame @{window:#x}", + got.client + ); + } moved_seen += 1; } } diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs index 41413a328..056bdacbb 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -49,6 +49,7 @@ const K1: Row = Row { frames: &[(B, Kind::Core, FOCUS)], calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, FOCUS)], }, + denied_grab: None, moved: &[Moved { client: B, window: FOCUS, @@ -80,6 +81,7 @@ const K2: Row = Row { frames: &[(B, Kind::Core, CHILD)], calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, CHILD)], }, + denied_grab: None, moved: &[], }; @@ -107,6 +109,7 @@ const K3_XI2_DENIED: Row = Row { frames: &[(A, Kind::Core, CHILD)], calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], }, + denied_grab: None, moved: &[Moved { client: A, window: CHILD, @@ -135,6 +138,7 @@ const K3_BOTH_DENIED: Row = Row { (B, CallKind::Core, FOCUS), ], }, + denied_grab: None, moved: &[Moved { client: B, window: FOCUS, @@ -185,6 +189,7 @@ const K4_ALLOWED: Row = Row { ], calls: &[(A, CallKind::Xi2, CHILD)], }, + denied_grab: None, moved: &[], }; @@ -207,6 +212,7 @@ const K4_XI2_DENIED: Row = Row { frames: &[(A, Kind::Core, CHILD)], calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], }, + denied_grab: None, moved: &[Moved { client: A, window: CHILD, @@ -240,6 +246,7 @@ const K5_XI2_SUPPRESSED: Row = Row { frames: &[], calls: &[], }, + denied_grab: None, moved: &[], }; @@ -269,6 +276,7 @@ const K5_DETECTABLE_SUPPRESSED: Row = Row { frames: &[], calls: &[], }, + denied_grab: None, moved: &[], }; @@ -299,6 +307,7 @@ const K5B_EXCLUDED_FORM_STILL_STOPS: Row = Row { frames: &[], calls: &[(A, CallKind::Xi2, CHILD)], }, + denied_grab: None, moved: &[], }; @@ -321,6 +330,7 @@ const K5B_EXCLUDED_MASTER_FORM_STILL_STOPS: Row = Row { synthetic: false, }, deny: &[(A, CallKind::Xi2, CHILD)], + denied_grab: None, moved: &[], allow: Expect { frames: &[], @@ -356,6 +366,7 @@ const K5C_SLAVE_GRAB_OWNER: Row = Row { frames: &[], calls: &[(A, CallKind::Xi2, FOCUS)], }, + denied_grab: None, moved: &[], }; @@ -383,6 +394,7 @@ const K5C_SLAVE_FOCUS_PATH: Row = Row { frames: &[], calls: &[(A, CallKind::Xi2, CHILD)], }, + denied_grab: None, moved: &[], }; @@ -414,6 +426,7 @@ const K6A_ALL_DENIED_LANDS_ON_FOCUS: Row = Row { (B, CallKind::Core, FOCUS), ], }, + denied_grab: None, moved: &[Moved { client: B, window: FOCUS, @@ -445,6 +458,7 @@ const K6B_ATTEMPT_LANDS_ON_FOCUS: Row = Row { frames: &[], calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], }, + denied_grab: None, moved: &[], }; @@ -475,6 +489,7 @@ const K7_OWNER_DENIED_ON_POINTER_WINDOW: Row = Row { frames: &[(A, Kind::Core, FOCUS)], calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], }, + denied_grab: None, moved: &[Moved { client: A, window: FOCUS, @@ -513,6 +528,7 @@ const K8_ALLOWED_FOREIGN_FALLS_BACK: Row = Row { (A, CallKind::Core, ROOT), ], }, + denied_grab: None, moved: &[Moved { client: A, window: ROOT, @@ -546,6 +562,7 @@ const K9_DENIED_FOREIGN_DOES_NOT_REJECT: Row = Row { frames: &[(A, Kind::Core, FOCUS)], calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], }, + denied_grab: None, moved: &[Moved { client: A, window: FOCUS, @@ -579,6 +596,7 @@ const K9_OWNER_QUALIFIES_FIRST: Row = Row { frames: &[(A, Kind::Core, CHILD)], calls: &[(A, CallKind::Core, CHILD)], }, + denied_grab: None, moved: &[], }; @@ -610,6 +628,7 @@ const K10_SUPPRESSED_FOREIGN_STILL_REJECTS: Row = Row { frames: &[(A, Kind::Core, ROOT)], calls: &[(A, CallKind::Core, ROOT)], }, + denied_grab: None, moved: &[], }; @@ -637,6 +656,7 @@ const K11_GRAB_WINDOW_DENIAL_DELIVERS: Row = Row { frames: &[], calls: &[(A, CallKind::Core, ROOT)], }, + denied_grab: None, moved: &[], }; @@ -665,6 +685,7 @@ const K12_ACTIVATING_DENIAL_ACTIVATES: Row = Row { frames: &[], calls: &[(A, CallKind::Core, ROOT)], }, + denied_grab: None, moved: &[], }; @@ -689,6 +710,7 @@ const K13_SYNTHETIC_XI2_RELEASE_SUPPRESSED: Row = Row { frames: &[], calls: &[], }, + denied_grab: None, moved: &[], }; @@ -719,6 +741,7 @@ const K13_DETECTABLE_CORE_RELEASE_SUPPRESSED: Row = Row { frames: &[], calls: &[], }, + denied_grab: None, moved: &[], }; @@ -754,6 +777,7 @@ const K9B_EVERY_FOREIGN_SELECTOR_IS_CHECKED: Row = Row { (A, CallKind::Core, ROOT), ], }, + denied_grab: None, moved: &[Moved { client: A, window: ROOT, @@ -793,6 +817,7 @@ const K13_SUPPRESSED_OWNER_QUALIFIES_ON_THE_NATURAL_WALK: Row = Row { frames: &[], calls: &[], }, + denied_grab: None, moved: &[], }; @@ -915,6 +940,7 @@ fn k12_denied_activating_press_still_activates_and_freezes() { denied.grab, GrabState { active: true, + pointer: None, freeze: Some((Xi1SyncState::FrozenWithEvent, Some((true, KEYCODE)))), }, "the denied activating press activates the grab and freezes with the press stored" @@ -991,6 +1017,7 @@ const K13_RAW_ROOT_COPY_DENIAL: Row = Row { (B, CallKind::Raw, ROOT), ], }, + denied_grab: None, moved: &[], }; @@ -1042,6 +1069,7 @@ const K14_RAW_OWNER_FALLS_BACK_TO_GRAB_WINDOW: Row = Row { (A, CallKind::Raw, ROOT), ], }, + denied_grab: None, moved: &[], }; @@ -1071,6 +1099,7 @@ const K14_NO_RAW_BIT_NO_FALLBACK: Row = Row { frames: &[], calls: &[(A, CallKind::Raw, ROOT), (A, CallKind::Raw, ROOT)], }, + denied_grab: None, moved: &[], }; @@ -1103,6 +1132,7 @@ const K15_ALLOWED_NATURAL_SKIPS_GRAB_WINDOW: Row = Row { ], calls: &[(A, CallKind::Raw, ROOT), (A, CallKind::Raw, ROOT)], }, + denied_grab: None, moved: &[], }; From e996e210f9b497859b55e4ffee22d0182b05ab36 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 19:11:33 -0300 Subject: [PATCH 24/72] test(access): pointer natural-walk scenarios (red) Adds access_pointer_input.rs with p1 to p7: denied core and XI2 selectors in the natural walk, the shared check of slave and master forms, core shadowing and its reopening, a deferred core copy, and a form that is not written. Rows state the target allow-all Receive calls and the denied outcome. Eight tests are ignored until the routing change lands; p7 is a guard and passes today. Today natural pointer walks ask Receive for no copy, so a denial changes nothing (the ignored tests fail on their allow-all calls). Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Haiku 5.5 --- .../tests/access_input_support.rs | 19 +- .../tests/access_pointer_input.rs | 576 ++++++++++++++++++ .../core_loop/process_request/tests/mod.rs | 1 + 3 files changed, 589 insertions(+), 7 deletions(-) create mode 100644 crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index 479046720..60361031e 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -98,11 +98,14 @@ pub(super) enum Drive { Raw { origin: InputOrigin, pressed: bool }, /// `pointer_event_fanout_to_state` with `handle_grabs` and `!is_replay`. /// `button` is the detail of a button event and is ignored for motion. - #[allow(dead_code)] // constructed by the pointer scenarios (next commit) Pointer { origin: InputOrigin, kind: PointerEventKind, button: u8, + /// Root position of the event; the pointer sits at `POINTER` before it. + to: (i16, i16), + /// Relative motion the device reports (zero for a button event). + delta: (i32, i32), }, } @@ -447,6 +450,8 @@ pub(super) fn drive(f: &mut NotifyFixture, drive: Drive) { origin, kind, button, + to, + delta, } => pointer_event_fanout_to_state( &mut f.state, &mut f.backend, @@ -457,15 +462,15 @@ pub(super) fn drive(f: &mut NotifyFixture, drive: Drive) { host_xid: 0, detail: button, time: TIME, - root_x: POINTER.0, - root_y: POINTER.1, - event_x: POINTER.0, - event_y: POINTER.1, + root_x: to.0, + root_y: to.1, + event_x: to.0, + event_y: to.1, state: 0, crossing_mode: 0, child: 0, - raw_dx: 0, - raw_dy: 0, + raw_dx: delta.0, + raw_dy: delta.1, device_axes: None, tree_change: false, }, diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs new file mode 100644 index 000000000..a64dff312 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -0,0 +1,576 @@ +//! Natural pointer walks under a Receive denial (PR 4c part 2, plan 2, task 1a). +//! +//! The tree is root > P (FOCUS) > C (CHILD), with the pointer over C. Rows use +//! the master pointer origin `XTest(2)` and ButtonPress unless they state +//! otherwise. Each row runs the no-policy, allow-all and denied modes through +//! `check_row`, so the literal frames and Receive calls per client are pinned. +//! The mutation each test must kill is named in its comment. + +use super::{access_input_support::*, access_notify_support::NotifyFixture}; +use crate::{ + core_loop::{DeviceInfo, InputOrigin, pointer_fanout::pointer_event_fanout_to_state}, + host_x11::{HostPointerEvent, HostXidMap, PointerEventKind}, + server::ServerState, + xinput::{DEVICEID_MASTER_POINTER, DEVICEID_XTEST_POINTER, InputCapabilities, InputSourceId}, +}; + +/// Core ButtonPressMask and MotionNotify mask bits. +const CORE_BUTTON_PRESS: u32 = 1 << 2; +const CORE_MOTION: u32 = 1 << 6; +/// XI2 mask bits, one per event type: ButtonPress (4) and Motion (6). +const XI_BUTTON_PRESS: u32 = 1 << 4; +const XI_MOTION: u32 = 1 << 6; +/// XIAllDevices, the device id that selects every device. +const XI_ALL_DEVICES: u16 = 0; +/// The source id of the physical pointer in the Physical-origin row. +const PHYSICAL_SOURCE: u64 = 0xA75_400; + +const XTEST_MASTER: InputOrigin = InputOrigin::XTest(DEVICEID_MASTER_POINTER); +const XTEST_SLAVE: InputOrigin = InputOrigin::XTest(DEVICEID_XTEST_POINTER); + +const fn press(origin: InputOrigin) -> Drive { + Drive::Pointer { + origin, + kind: PointerEventKind::ButtonPress, + button: 1, + to: POINTER, + delta: (0, 0), + } +} + +/// A move from the pointer's place to (125, 125), still over C. +const fn motion(origin: InputOrigin) -> Drive { + Drive::Pointer { + origin, + kind: PointerEventKind::MotionNotify, + button: 0, + to: (125, 125), + delta: (5, 5), + } +} + +/// A pointer grab with the given owner and window and no keyboard grab. +const fn pointer_grab(owner: u32, window: u32, implicit: bool) -> Option { + Some(GrabState { + active: false, + freeze: None, + pointer: Some(PointerGrab { + owner, + window, + implicit, + passive: false, + }), + }) +} + +/// The event P (FOCUS) gives a copy of the pointer at root (120, 120). +const P_EVENT: (i16, i16) = (20, 20); +/// The event C (CHILD) gives a copy of the pointer at root (120, 120). +const C_EVENT: (i16, i16) = (10, 10); + +/// Registers a physical pointer source with the XI registry. +fn register_physical_pointer(state: &mut ServerState) { + let info = DeviceInfo { + source_id: InputSourceId(PHYSICAL_SOURCE), + enabled: true, + resume_key: None, + capabilities: InputCapabilities { + keyboard: false, + pointer: true, + touch: false, + }, + name: format!("pointer source {PHYSICAL_SOURCE}"), + device_node: format!("/dev/input/event{PHYSICAL_SOURCE}"), + sysname: format!("event{PHYSICAL_SOURCE}"), + vendor_id: 1, + product_id: PHYSICAL_SOURCE as u32, + is_touchpad: false, + config: crate::core_loop::message::LibinputConfigSnapshot::default(), + }; + let _ = state.xi_register_source(&info); +} + +/// Moves the sprite onto the pointer's place before the row's event, so the +/// slave pass starts from C as it does in a session (Xorg delivers slave motion +/// to the window the sprite left). Nothing is selected yet, so nothing is sent. +fn park_pointer(f: &mut NotifyFixture) { + let dropped = pointer_event_fanout_to_state( + &mut f.state, + &mut f.backend, + &HostXidMap::new(), + HostPointerEvent { + origin: XTEST_MASTER, + kind: PointerEventKind::MotionNotify, + host_xid: 0, + detail: 0, + time: TIME, + root_x: POINTER.0, + root_y: POINTER.1, + event_x: POINTER.0, + event_y: POINTER.1, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + device_axes: None, + tree_change: false, + }, + true, + false, + ); + assert!( + dropped.is_empty(), + "parking the pointer queued a disconnect" + ); +} + +// ---- P1 ------------------------------------------------------------------ + +fn setup_p1(f: &mut NotifyFixture) { + tree(f); + select_core(f, B, CHILD, CORE_BUTTON_PRESS); + select_core(f, A, FOCUS, CORE_BUTTON_PRESS); +} + +const P1: Row = Row { + name: "p1_denied_core_selector_does_not_stop_the_core_walk", + setup: setup_p1, + drive: press(XTEST_MASTER), + deny: &[(B, CallKind::Core, CHILD)], + denied_grab: pointer_grab(A, FOCUS, true), + moved: &[Moved { + client: A, + window: FOCUS, + child: CHILD, + event: P_EVENT, + }], + allow: Expect { + frames: &[(B, Kind::Core, CHILD)], + calls: &[(B, CallKind::Core, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Core, FOCUS)], + calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + }, +}; + +/// Mutation: the core walk stops at any window with a core selector, without +/// asking Receive (selection-only stop). A then never sees the press. +#[test] +#[ignore = "red until Task 1b: Receive decides the natural pointer walks"] +fn p1_denied_core_selector_does_not_stop_the_core_walk() { + check_row(&P1); +} + +// ---- P2 ------------------------------------------------------------------ + +fn setup_p2(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + select_core(f, A, FOCUS, CORE_BUTTON_PRESS); +} + +const P2: Row = Row { + name: "p2_denied_xi2_selector_does_not_absorb_core", + setup: setup_p2, + drive: press(XTEST_MASTER), + deny: &[(B, CallKind::Xi2, CHILD)], + denied_grab: pointer_grab(A, FOCUS, true), + moved: &[Moved { + client: A, + window: FOCUS, + child: CHILD, + event: P_EVENT, + }], + allow: Expect { + frames: &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(B, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Core, FOCUS)], + calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Core, FOCUS)], + }, +}; + +/// Mutation: an XI2 selection absorbs the walk whether or not its copy is +/// allowed (selection-only absorption), or the denied XI2 copy is checked twice. +#[test] +#[ignore = "red until Task 1b: Receive decides the natural pointer walks"] +fn p2_denied_xi2_selector_does_not_absorb_core() { + check_row(&P2); +} + +// ---- P3 ------------------------------------------------------------------ + +fn setup_p3(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + select_xi2(f, A, FOCUS, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); +} + +const P3: Row = Row { + name: "p3_xi2_walk_skips_a_denied_window", + setup: setup_p3, + drive: press(XTEST_MASTER), + deny: &[(B, CallKind::Xi2, CHILD)], + denied_grab: pointer_grab(A, FOCUS, true), + moved: &[Moved { + client: A, + window: FOCUS, + child: CHILD, + event: P_EVENT, + }], + allow: Expect { + frames: &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(B, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], + calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], + }, +}; + +/// Mutation: the XI2 route window is the first window with a selection rather +/// than the first with an allowed one, so the denied copy at C ends the walk. +#[test] +#[ignore = "red until Task 1b: Receive decides the natural pointer walks"] +fn p3_xi2_walk_skips_a_denied_window() { + check_row(&P3); +} + +// ---- P4 ------------------------------------------------------------------ + +fn setup_p4(f: &mut NotifyFixture) { + tree(f); + park_pointer(f); + select_xi2(f, B, CHILD, XI_ALL_DEVICES, XI_MOTION); + select_xi2(f, A, FOCUS, DEVICEID_MASTER_POINTER, XI_MOTION); +} + +/// Allow-all: B's slave and master forms at C come from one check. +const P4_ALLOWED: Row = Row { + name: "p4_slave_and_master_forms_share_one_check", + setup: setup_p4, + drive: motion(XTEST_SLAVE), + deny: &[], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[ + (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), + (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + calls: &[(B, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[ + (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), + (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + calls: &[(B, CallKind::Xi2, CHILD)], + }, +}; + +/// Denied: B's one check covers both forms, so B gets neither and A's master +/// form at P is the only copy. +const P4_DENIED: Row = Row { + name: "p4_slave_and_master_forms_share_one_check", + setup: setup_p4, + drive: motion(XTEST_SLAVE), + deny: &[(B, CallKind::Xi2, CHILD)], + denied_grab: None, + moved: &[Moved { + client: A, + window: FOCUS, + child: CHILD, + event: P_EVENT, + }], + allow: Expect { + frames: &[ + (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), + (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + calls: &[(B, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], + calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], + }, +}; + +/// Mutation: the slave and master forms each ask Receive (two calls for B), +/// or the master form is checked at the slave pass's window. +#[test] +#[ignore = "red until Task 1b: Receive decides the natural pointer walks"] +fn p4_slave_and_master_forms_share_one_check() { + check_row(&P4_ALLOWED); + check_row(&P4_DENIED); +} + +// ---- P5 ------------------------------------------------------------------ + +fn setup_p5(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + select_core(f, A, CHILD, CORE_BUTTON_PRESS); +} + +/// Allow-all: A's master XI2 copy shadows its core copy at C. +const P5_ALLOWED: Row = Row { + name: "p5_denied_xi2_reopens_that_clients_core", + setup: setup_p5, + drive: press(XTEST_MASTER), + deny: &[], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + }, +}; + +/// Denied: A's XI2 copy is refused, so its core copy at C is delivered. +const P5_DENIED: Row = Row { + name: "p5_denied_xi2_reopens_that_clients_core", + setup: setup_p5, + drive: press(XTEST_MASTER), + deny: &[(A, CallKind::Xi2, CHILD)], + denied_grab: None, + moved: &[Moved { + client: A, + window: CHILD, + child: 0, + event: C_EVENT, + }], + allow: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], + }, +}; + +/// Mutation: A's core copy is shadowed by its XI2 selection, not by the copy +/// that is allowed, so the denied XI2 still hides the core copy at C. +#[test] +#[ignore = "red until Task 1b: Receive decides the natural pointer walks"] +fn p5_denied_xi2_reopens_that_clients_core() { + check_row(&P5_ALLOWED); + check_row(&P5_DENIED); +} + +// ---- P5b ----------------------------------------------------------------- + +fn setup_p5b(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, CHILD, CORE_BUTTON_PRESS); + select_xi2(f, A, FOCUS, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + select_core(f, B, FOCUS, CORE_BUTTON_PRESS); +} + +/// Denying A's core copy at C changes nothing: a shadowed core copy is not +/// checked, and the walk stops at C as it does with allow-all. +const P5B_CORE_DENIED: Row = Row { + name: "p5b_shadow_follows_the_master_copy_anywhere", + setup: setup_p5b, + drive: press(XTEST_MASTER), + deny: &[(A, CallKind::Core, CHILD)], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], + calls: &[(A, CallKind::Xi2, FOCUS)], + }, + denied: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], + calls: &[(A, CallKind::Xi2, FOCUS)], + }, +}; + +/// Denying A's master XI2 copy at P reopens A's core copy at C, and the walk +/// stops there, so B at P gets nothing. +const P5B_XI2_DENIED: Row = Row { + name: "p5b_shadow_follows_the_master_copy_anywhere", + setup: setup_p5b, + drive: press(XTEST_MASTER), + deny: &[(A, CallKind::Xi2, FOCUS)], + denied_grab: None, + moved: &[Moved { + client: A, + window: CHILD, + child: 0, + event: C_EVENT, + }], + allow: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], + calls: &[(A, CallKind::Xi2, FOCUS)], + }, + denied: Expect { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Xi2, FOCUS), (A, CallKind::Core, CHILD)], + }, +}; + +/// Mutation: a shadow that only applies at the same window (the core copy at C +/// is checked and then deduplicated), or a shadowed core copy that is still +/// checked before the walk stops. +#[test] +#[ignore = "red until Task 1b: Receive decides the natural pointer walks"] +fn p5b_shadow_follows_the_master_copy_anywhere() { + check_row(&P5B_CORE_DENIED); + check_row(&P5B_XI2_DENIED); +} + +// ---- P5c ----------------------------------------------------------------- + +fn setup_p5c(f: &mut NotifyFixture) { + tree(f); + park_pointer(f); + select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_MOTION); + select_core(f, A, CHILD, CORE_MOTION); + select_xi2(f, A, FOCUS, DEVICEID_MASTER_POINTER, XI_MOTION); + select_xi2(f, A, FOCUS, DEVICEID_XTEST_POINTER, XI_MOTION); +} + +/// Denied: the master route is P (A's master copy), so A's core copy at C is +/// shadowed and A gets its slave and master forms at P, with no core copy. +const P5C_DENIED: Row = Row { + name: "p5c_shadow_uses_the_allowed_master_route", + setup: setup_p5c, + drive: motion(XTEST_SLAVE), + deny: &[(B, CallKind::Xi2, CHILD)], + denied_grab: None, + moved: &[Moved { + client: A, + window: FOCUS, + child: CHILD, + event: P_EVENT, + }], + allow: Expect { + frames: &[ + (A, Kind::Xi2(DEVICEID_XTEST_POINTER), FOCUS), + (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], + }, + denied: Expect { + frames: &[ + (A, Kind::Xi2(DEVICEID_XTEST_POINTER), FOCUS), + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS), + ], + calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], + }, +}; + +/// Mutation: the shadow uses the selection-only master route, which ends at C +/// (B's selection); A then keeps its core copy at C and gets no XI2 at P. +#[test] +#[ignore = "red until Task 1b: Receive decides the natural pointer walks"] +fn p5c_shadow_uses_the_allowed_master_route() { + check_row(&P5C_DENIED); +} + +// ---- P6 ------------------------------------------------------------------ + +fn setup_p6(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, CHILD, DEVICEID_XTEST_POINTER, XI_BUTTON_PRESS); + select_core(f, A, CHILD, CORE_BUTTON_PRESS); +} + +/// A slave press: A's core copy is deferred behind the slave pass. Denying it +/// drops that copy at admission, after the slave XI2 copy was written. +const P6_DENIED: Row = Row { + name: "p6_deferred_core_copy_is_checked_at_admission", + setup: setup_p6, + drive: press(XTEST_SLAVE), + deny: &[(A, CallKind::Core, CHILD)], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[ + (A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), + (A, Kind::Core, CHILD), + ], + calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], + }, +}; + +/// Mutation: the deferred core copy is checked again at the flush (two calls), +/// or never checked (the copy is written with no call). +#[test] +#[ignore = "red until Task 1b: Receive decides the natural pointer walks"] +fn p6_deferred_core_copy_is_checked_at_admission() { + check_row(&P6_DENIED); +} + +// ---- P7 ------------------------------------------------------------------ + +/// A physical pointer holds button 1; the XTest slave then presses button 1, +/// so the master form is not written and B's master XI2 copy is never checked. +fn setup_p7(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + register_physical_pointer(&mut f.state); + let dropped = pointer_event_fanout_to_state( + &mut f.state, + &mut f.backend, + &HostXidMap::new(), + HostPointerEvent { + origin: InputOrigin::Physical(InputSourceId(PHYSICAL_SOURCE)), + kind: PointerEventKind::ButtonPress, + host_xid: 0, + detail: 1, + time: TIME, + root_x: POINTER.0, + root_y: POINTER.1, + event_x: POINTER.0, + event_y: POINTER.1, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: 0, + raw_dy: 0, + device_axes: None, + tree_change: false, + }, + true, + false, + ); + assert!(dropped.is_empty(), "physical press queued a disconnect"); +} + +const P7: Row = Row { + name: "p7_no_check_for_a_form_not_emitted", + setup: setup_p7, + drive: press(XTEST_SLAVE), + deny: &[(B, CallKind::Xi2, CHILD)], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[], + calls: &[], + }, + denied: Expect { + frames: &[], + calls: &[], + }, +}; + +/// Guard: a master form that is not written asks nothing, so denying B's copy +/// changes nothing. Passes today. +#[test] +fn p7_no_check_for_a_form_not_emitted() { + check_row(&P7); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/mod.rs b/crates/yserver-core/src/core_loop/process_request/tests/mod.rs index c059f6568..0f6b43970 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/mod.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/mod.rs @@ -16,6 +16,7 @@ mod access_notify_objects; mod access_notify_selection; mod access_notify_support; mod access_notify_windows; +mod access_pointer_input; mod access_present; mod access_properties; mod access_randr; From f1f44b2fd2cfe1b46afe3f486c36c9a05e606fc6 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 19:20:24 -0300 Subject: [PATCH 25/72] test(access): review round 1 for the pointer harness Harness and scenario fixes from the task 1a review, tests only: - p6 denied row: no master pointer grab, the slave XI2 grab stays, and the call order is core admission then the XI2 form. - p5b and p5 denied rows state the core implicit grab (via_xi2 false). - Pointer grab facts carry via_xi2; the grab state is a list of facts (keyboard, master pointer, slave pointer, XI1, keyboard and pointer freezes) compared in full between no-policy and allow-all. - XI2 moved frames assert child and event_x/event_y as well as the window. - A Receive call is traced and denied as an ordered list of descriptions, each in its own numbering (XI1 offsets are not compared with XI2 types). - p7 presses physically before the XI2 selection and pins its grab state. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Haiku 5.5 --- .../tests/access_input_support.rs | 290 +++++++++++++----- .../process_request/tests/access_key_input.rs | 26 +- .../tests/access_pointer_input.rs | 104 ++++--- 3 files changed, 288 insertions(+), 132 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index 60361031e..b5bb1142f 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -22,8 +22,8 @@ use crate::{ host_x11::{HostKeyEvent, HostPointerEvent, HostXidMap, PointerEventKind}, nested::XI2_MAJOR_OPCODE, resources::ROOT_WINDOW, - server::{QueuedInputEvent, Xi1SyncState}, - xinput::{DEVICEID_MASTER_KEYBOARD, DEVICEID_XTEST_KEYBOARD}, + server::{QueuedInputEvent, ServerState, Xi1SyncState}, + xinput::{DEVICEID_MASTER_KEYBOARD, DEVICEID_MASTER_POINTER, DEVICEID_XTEST_KEYBOARD}, }; use std::{collections::BTreeMap, sync::atomic::Ordering}; use yserver_protocol::x11::{ClientByteOrder, ClientId, RequestHeader, SequenceNumber}; @@ -76,11 +76,48 @@ pub(super) enum Kind { /// form, so it carries no device. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum CallKind { + /// One core description; its number is the row's event type. Core, + /// One XI2 description; its number is the row's event type. Xi2, + /// One raw key description; its number is the row's event type. Raw, - /// An XI1 device event (or batch), named by its offset from the XI base. - Xi1, + /// An ordered list of descriptions, each with its own numbering. A batch + /// is denied or traced as one call. + Batch(&'static [Named]), +} + +/// One event description in its own numbering: core type, XI2 or raw event +/// type, or the XI1 offset from the XI base (XI1 numbering is not XI2's). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Named { + Core(u16), + Xi2(u16), + Raw(u16), + Xi1(u16), +} + +/// A Receive call as traced: (client, ordered descriptions, subject window). +pub(super) type Seen = (u32, Vec, u32); + +/// The traced form of an expected call. The shorthand kinds name one +/// description with the row's event type. +fn expected_call(call: &Call, ev: u16) -> Seen { + let (client, kind, window) = *call; + let names = match kind { + CallKind::Core => vec![Named::Core(ev)], + CallKind::Xi2 => vec![Named::Xi2(ev)], + CallKind::Raw => vec![Named::Raw(ev)], + CallKind::Batch(list) => list.to_vec(), + }; + (client, names, window) +} + +/// The number a named description carries, for the shorthand check. +fn number(named: Named) -> u16 { + match named { + Named::Core(n) | Named::Xi2(n) | Named::Raw(n) | Named::Xi1(n) => n, + } } #[derive(Clone, Copy)] @@ -175,9 +212,9 @@ pub(super) struct Row { /// (client, check, window) Receive calls to deny. pub(super) deny: &'static [Call], /// Frames only the denied run writes, pinned in full. - /// The denied run's grab state when it differs from allow-all; `None` means + /// The denied run's grab facts when they differ from allow-all; `None` means /// the same as allow-all. - pub(super) denied_grab: Option, + pub(super) denied_grab: Option<&'static [Grab]>, pub(super) moved: &'static [Moved], pub(super) allow: Expect, pub(super) denied: Expect, @@ -492,41 +529,37 @@ pub(super) fn drive(f: &mut NotifyFixture, drive: Drive) { assert!(dropped.is_empty(), "delivery queued a disconnect"); } -/// The (kind, event type) one description names: core 2..=6, XI2 2..=6 and -/// 13/14 raw, and XI1 device events by offset. `None` for anything else. -fn describe(description: &EventDescription) -> Option<(CallKind, u16)> { +/// The traced name of one description: core 2..=6, XI2 2..=6, raw 13/14, and +/// XI1 device events by offset. `None` for anything else. +fn name_of(description: &EventDescription) -> Option { match description.extension { None if (2..=6).contains(&description.type_code) => { - Some((CallKind::Core, u16::from(description.type_code))) + Some(Named::Core(u16::from(description.type_code))) } Some(extension) if description.type_code == 35 && extension.major_opcode == XI2_MAJOR_OPCODE => { match extension.event_type { - 2..=6 => Some((CallKind::Xi2, extension.event_type)), - 13 | 14 => Some((CallKind::Raw, extension.event_type)), + 2..=6 => Some(Named::Xi2(extension.event_type)), + 13 | 14 => Some(Named::Raw(extension.event_type)), _ => None, } } Some(extension) if extension.major_opcode == XI2_MAJOR_OPCODE => { - Some((CallKind::Xi1, extension.event_type)) + Some(Named::Xi1(extension.event_type)) } _ => None, } } -/// The (kind, event type) of a whole batch: every description must name the -/// same one, so a batch is matched and denied as a unit. `None` otherwise. -pub(super) fn event_call(events: &[EventDescription]) -> Option<(CallKind, u16)> { - let (first, rest) = events.split_first()?; - let named = describe(first)?; - rest.iter() - .all(|description| describe(description) == Some(named)) - .then_some(named) +/// The ordered names of a batch, or `None` when any description is unnamed. +fn names_of(events: &[EventDescription]) -> Option> { + events.iter().map(name_of).collect() } -/// Denies exactly the listed (client, kind, window) Receive checks, matched by -/// hook, subject and batch. `ev` is the event type the row drives. +/// Denies the listed (client, batch, window) Receive checks: a call is denied +/// when some entry names its whole ordered list and subject. `ev` is the event +/// type the row drives, used by the shorthand entries. pub(super) fn decide(denied: &[Call], ev: u16, call: &RecordedExtensionCheck) -> Decision { if call.hook != ExtensionHook::Receive { return Decision::Allow; @@ -535,17 +568,14 @@ pub(super) fn decide(denied: &[Call], ev: u16, call: &RecordedExtensionCheck) -> else { return Decision::Allow; }; - let Some((kind, named)) = event_call(events) else { + let Some(names) = names_of(events) else { return Decision::Allow; }; - if named != ev { - return Decision::Allow; - } - if denied.contains(&(call.client.0, kind, window.0)) { - DENY - } else { - Decision::Allow - } + let hit = denied.iter().any(|entry| { + let (client, expected, subject) = expected_call(entry, ev); + client == call.client.0 && subject == window.0 && expected == names + }); + if hit { DENY } else { Decision::Allow } } /// Decodes a frame the walks write: a core key, button or motion event (event @@ -574,30 +604,47 @@ pub(super) struct ClientBytes { pub(super) bytes: Vec, } -/// The keyboard grab and the master XI1 freeze after a run: whether an active -/// keyboard grab exists, and the master freeze state with the stored press. -#[derive(Debug, PartialEq, Eq)] -pub(super) struct GrabState { - pub(super) active: bool, - pub(super) freeze: Option<(Xi1SyncState, Option<(bool, u8)>)>, - pub(super) pointer: Option, +/// One fact of the grab state after a run. A row states the facts its denied +/// run must have; the no-policy and allow-all runs must have the same list. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Grab { + /// The active keyboard grab: owner and grab window. + Keyboard { owner: u32, window: u32 }, + /// The active master pointer grab. + Pointer(PointerGrab), + /// A slave pointer's XI2 grab, keyed by the slave's device id. + SlavePointer { device: u16, grab: PointerGrab }, + /// An XI1 device grab (implicit or explicit), keyed by device id. + Xi1 { + device: u16, + owner: u32, + window: u32, + }, + /// The master keyboard's XI1 freeze and whether it holds a stored press. + KeyboardFreeze { + state: Xi1SyncState, + stored: Option<(bool, u8)>, + }, + /// The master pointer's XI1 freeze and whether it holds a stored event. + PointerFreeze { state: Xi1SyncState, stored: bool }, } -/// The active pointer grab: its owner, grab window, and the implicit and -/// passive flags. +/// The active pointer grab: its owner, grab window, the implicit and passive +/// flags, and whether it was established through XI2 (`via_xi2`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct PointerGrab { pub(super) owner: u32, pub(super) window: u32, pub(super) implicit: bool, pub(super) passive: bool, + pub(super) via_xi2: bool, } pub(super) struct Run { pub(super) clients: Vec, - pub(super) calls: Vec, + pub(super) calls: Vec, pub(super) state: String, - pub(super) grab: GrabState, + pub(super) grab: Vec, } pub(super) fn run(row: &Row, policy: Option<&'static [Call]>) -> Run { @@ -641,47 +688,24 @@ pub(super) fn run(row: &Row, policy: Option<&'static [Call]>) -> Run { EventSubject::Window(window) => window.0, other => panic!("{}: key Receive subject {other:?}", row.name), }; - let (kind, named) = event_call(call.events.as_deref()?)?; - if kind != CallKind::Xi1 { + let names = names_of(call.events.as_deref()?)?; + if let [single] = names.as_slice() + && !matches!(single, Named::Xi1(_)) + { assert_eq!( - named, + number(*single), row.drive.ev(), "{}: Receive names another event", row.name ); } - Some((call.client.0, kind, subject)) + Some((call.client.0, names, subject)) }) .collect() }) .unwrap_or_default(); let state = format!("{:?}", (f.state.core_focus.raw, f.state.keys_down)); - let grab = GrabState { - pointer: f - .state - .active_pointer_grab - .as_ref() - .map(|grab| PointerGrab { - owner: grab.owner.0, - window: grab.grab_window.0, - implicit: grab.implicit, - passive: grab.passive, - }), - active: f.state.active_keyboard_grab.is_some(), - freeze: f - .state - .xi1_frozen - .get(&DEVICEID_MASTER_KEYBOARD) - .map(|freeze| { - let stored = match &freeze.stored { - Some(QueuedInputEvent::HostKeyTransition(event, _, _)) => { - Some((event.pressed, event.keycode)) - } - _ => None, - }; - (freeze.state, stored) - }), - }; + let grab = grab_facts(&f.state); Run { clients, calls, @@ -690,6 +714,65 @@ pub(super) fn run(row: &Row, policy: Option<&'static [Call]>) -> Run { } } +/// The grab facts of a server state, in a fixed order: keyboard grab, master +/// pointer grab, slave pointer grabs by device, XI1 grabs by device, then the +/// master keyboard and pointer freezes. +fn grab_facts(state: &ServerState) -> Vec { + let pointer = |grab: &crate::server::ActivePointerGrab| PointerGrab { + owner: grab.owner.0, + window: grab.grab_window.0, + implicit: grab.implicit, + passive: grab.passive, + via_xi2: grab.via_xi2, + }; + let mut facts = Vec::new(); + if let Some(grab) = state.active_keyboard_grab.as_ref() { + facts.push(Grab::Keyboard { + owner: grab.owner.0, + window: grab.grab_window.0, + }); + } + if let Some(grab) = state.active_pointer_grab.as_ref() { + facts.push(Grab::Pointer(pointer(grab))); + } + let mut slaves: Vec<_> = state.xi2_pointer_grabs.iter().collect(); + slaves.sort_by_key(|(device, _)| **device); + for (device, grab) in slaves { + facts.push(Grab::SlavePointer { + device: *device, + grab: pointer(grab), + }); + } + let mut xi1: Vec<_> = state.xi1_active_grabs.iter().collect(); + xi1.sort_by_key(|(device, _)| **device); + for (device, grab) in xi1 { + facts.push(Grab::Xi1 { + device: *device, + owner: grab.owner.0, + window: grab.grab_window.0, + }); + } + if let Some(freeze) = state.xi1_frozen.get(&DEVICEID_MASTER_KEYBOARD) { + let stored = match &freeze.stored { + Some(QueuedInputEvent::HostKeyTransition(event, _, _)) => { + Some((event.pressed, event.keycode)) + } + _ => None, + }; + facts.push(Grab::KeyboardFreeze { + state: freeze.state, + stored, + }); + } + if let Some(freeze) = state.xi1_frozen.get(&DEVICEID_MASTER_POINTER) { + facts.push(Grab::PointerFreeze { + state: freeze.state, + stored: freeze.stored.is_some(), + }); + } + facts +} + pub(super) fn grouped( items: impl IntoIterator, ) -> BTreeMap> { @@ -731,8 +814,15 @@ pub(super) fn delivered(name: &str, run: &Run, detail: u32) -> Vec { pub(super) fn check_run(row: &Row, run: &Run, expect: &Expect, mode: &str) { let name = row.name; assert_eq!( - grouped(run.calls.iter().map(|&(c, kind, w)| (c, (kind, w)))), - grouped(expect.calls.iter().map(|&(c, kind, w)| (c, (kind, w)))), + grouped( + run.calls + .iter() + .map(|(c, names, w)| (*c, (names.clone(), *w))) + ), + grouped(expect.calls.iter().map(|call| { + let (c, names, w) = expected_call(call, row.drive.ev()); + (c, (names, w)) + })), "{name} [{mode}]: Receive calls per client" ); assert_eq!( @@ -803,9 +893,12 @@ pub(super) fn check_row(row: &Row) { let denied = run(row, Some(row.deny)); check_run(row, &denied, &row.denied, "denial"); assert_eq!(denied.state, allow.state, "{name}: denial changed state"); + let expected_grab: Vec = match row.denied_grab { + Some(facts) => facts.to_vec(), + None => allow.grab.clone(), + }; assert_eq!( - denied.grab, - *row.denied_grab.as_ref().unwrap_or(&allow.grab), + denied.grab, expected_grab, "{name}: denied grab and freeze state" ); let mut moved_seen = 0; @@ -848,6 +941,23 @@ pub(super) fn check_row(row: &Row) { got.client ) }); + if let Kind::Xi2(_) = kind { + // The XI2 device event: child (byte 28), event_x and event_y + // as FP16.16 at bytes 40 and 44 (the event window is byte 24). + let child = dec32(&frame[28..32], got.order); + let event_x = dec32(&frame[40..44], got.order) as i32 >> 16; + let event_y = dec32(&frame[44..48], got.order) as i32 >> 16; + assert_eq!( + (child, event_x, event_y), + ( + moved.child, + i32::from(moved.event.0), + i32::from(moved.event.1) + ), + "{name}: client {} moved XI2 frame @{window:#x}", + got.client + ); + } if kind == Kind::Core { assert_eq!( frame, @@ -868,3 +978,29 @@ pub(super) fn check_row(row: &Row) { } assert_eq!(moved_seen, row.moved.len(), "{name}: moved frames written"); } + +#[cfg(test)] +mod batch_naming { + use super::*; + + /// Mutation: a batch is traced by its first description, or the shorthand + /// names a description with another event type than the row drives. The + /// list order and each description's own numbering are what decide and the + /// trace compare. + #[test] + fn a_batch_call_is_traced_as_its_ordered_list() { + const SMOOTH_STOP: &[Named] = &[Named::Xi2(6), Named::Xi2(6)]; + let batch: Call = (A, CallKind::Batch(SMOOTH_STOP), CHILD); + assert_eq!( + expected_call(&batch, 4), + (A, vec![Named::Xi2(6), Named::Xi2(6)], CHILD) + ); + let shorthand: Call = (A, CallKind::Xi2, CHILD); + assert_eq!( + expected_call(&shorthand, 6), + (A, vec![Named::Xi2(6)], CHILD) + ); + let xi1: Call = (B, CallKind::Batch(&[Named::Xi1(6)]), FOCUS); + assert_eq!(expected_call(&xi1, 4), (B, vec![Named::Xi1(6)], FOCUS)); + } +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs index 056bdacbb..3ac493a76 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -924,7 +924,10 @@ fn k11_denied_grab_window_copy_is_delivered() { Some(K11_GRAB_WINDOW_DENIAL_DELIVERS.deny), ); assert!( - matches!(denied.grab, GrabState { active: true, .. }), + denied + .grab + .iter() + .any(|fact| matches!(fact, Grab::Keyboard { .. })), "the denied grab-window copy leaves the keyboard grab active" ); } @@ -936,14 +939,19 @@ fn k12_denied_activating_press_still_activates_and_freezes() { &K12_ACTIVATING_DENIAL_ACTIVATES, Some(K12_ACTIVATING_DENIAL_ACTIVATES.deny), ); - assert_eq!( - denied.grab, - GrabState { - active: true, - pointer: None, - freeze: Some((Xi1SyncState::FrozenWithEvent, Some((true, KEYCODE)))), - }, - "the denied activating press activates the grab and freezes with the press stored" + assert!( + denied + .grab + .iter() + .any(|fact| matches!(fact, Grab::Keyboard { .. })), + "the denied activating press activates the keyboard grab" + ); + assert!( + denied.grab.contains(&Grab::KeyboardFreeze { + state: Xi1SyncState::FrozenWithEvent, + stored: Some((true, KEYCODE)), + }), + "the denied activating press freezes with the press stored" ); } diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index a64dff312..421f5f7be 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -49,20 +49,6 @@ const fn motion(origin: InputOrigin) -> Drive { } } -/// A pointer grab with the given owner and window and no keyboard grab. -const fn pointer_grab(owner: u32, window: u32, implicit: bool) -> Option { - Some(GrabState { - active: false, - freeze: None, - pointer: Some(PointerGrab { - owner, - window, - implicit, - passive: false, - }), - }) -} - /// The event P (FOCUS) gives a copy of the pointer at root (120, 120). const P_EVENT: (i16, i16) = (20, 20); /// The event C (CHILD) gives a copy of the pointer at root (120, 120). @@ -138,7 +124,13 @@ const P1: Row = Row { setup: setup_p1, drive: press(XTEST_MASTER), deny: &[(B, CallKind::Core, CHILD)], - denied_grab: pointer_grab(A, FOCUS, true), + denied_grab: Some(&[Grab::Pointer(PointerGrab { + owner: A, + window: FOCUS, + implicit: true, + passive: false, + via_xi2: false, + })]), moved: &[Moved { client: A, window: FOCUS, @@ -176,7 +168,13 @@ const P2: Row = Row { setup: setup_p2, drive: press(XTEST_MASTER), deny: &[(B, CallKind::Xi2, CHILD)], - denied_grab: pointer_grab(A, FOCUS, true), + denied_grab: Some(&[Grab::Pointer(PointerGrab { + owner: A, + window: FOCUS, + implicit: true, + passive: false, + via_xi2: false, + })]), moved: &[Moved { client: A, window: FOCUS, @@ -214,7 +212,13 @@ const P3: Row = Row { setup: setup_p3, drive: press(XTEST_MASTER), deny: &[(B, CallKind::Xi2, CHILD)], - denied_grab: pointer_grab(A, FOCUS, true), + denied_grab: Some(&[Grab::Pointer(PointerGrab { + owner: A, + window: FOCUS, + implicit: true, + passive: false, + via_xi2: true, + })]), moved: &[Moved { client: A, window: FOCUS, @@ -340,7 +344,13 @@ const P5_DENIED: Row = Row { setup: setup_p5, drive: press(XTEST_MASTER), deny: &[(A, CallKind::Xi2, CHILD)], - denied_grab: None, + denied_grab: Some(&[Grab::Pointer(PointerGrab { + owner: A, + window: CHILD, + implicit: true, + passive: false, + via_xi2: false, + })]), moved: &[Moved { client: A, window: CHILD, @@ -401,7 +411,13 @@ const P5B_XI2_DENIED: Row = Row { setup: setup_p5b, drive: press(XTEST_MASTER), deny: &[(A, CallKind::Xi2, FOCUS)], - denied_grab: None, + denied_grab: Some(&[Grab::Pointer(PointerGrab { + owner: A, + window: CHILD, + implicit: true, + passive: false, + via_xi2: false, + })]), moved: &[Moved { client: A, window: CHILD, @@ -492,18 +508,27 @@ const P6_DENIED: Row = Row { setup: setup_p6, drive: press(XTEST_SLAVE), deny: &[(A, CallKind::Core, CHILD)], - denied_grab: None, + denied_grab: Some(&[Grab::SlavePointer { + device: DEVICEID_XTEST_POINTER, + grab: PointerGrab { + owner: A, + window: CHILD, + implicit: true, + passive: false, + via_xi2: true, + }, + }]), moved: &[], allow: Expect { frames: &[ (A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), (A, Kind::Core, CHILD), ], - calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Xi2, CHILD)], }, denied: Expect { frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Xi2, CHILD)], }, }; @@ -519,36 +544,23 @@ fn p6_deferred_core_copy_is_checked_at_admission() { /// A physical pointer holds button 1; the XTest slave then presses button 1, /// so the master form is not written and B's master XI2 copy is never checked. +/// The physical press runs first, before B selects, so no grab exists when the +/// second press routes: the master form's `master_accepted` is the only thing +/// that keeps the natural call from happening. fn setup_p7(f: &mut NotifyFixture) { tree(f); - select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); register_physical_pointer(&mut f.state); - let dropped = pointer_event_fanout_to_state( - &mut f.state, - &mut f.backend, - &HostXidMap::new(), - HostPointerEvent { + drive( + f, + Drive::Pointer { origin: InputOrigin::Physical(InputSourceId(PHYSICAL_SOURCE)), kind: PointerEventKind::ButtonPress, - host_xid: 0, - detail: 1, - time: TIME, - root_x: POINTER.0, - root_y: POINTER.1, - event_x: POINTER.0, - event_y: POINTER.1, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - device_axes: None, - tree_change: false, + button: 1, + to: POINTER, + delta: (0, 0), }, - true, - false, ); - assert!(dropped.is_empty(), "physical press queued a disconnect"); + select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); } const P7: Row = Row { @@ -556,7 +568,7 @@ const P7: Row = Row { setup: setup_p7, drive: press(XTEST_SLAVE), deny: &[(B, CallKind::Xi2, CHILD)], - denied_grab: None, + denied_grab: Some(&[]), moved: &[], allow: Expect { frames: &[], From fdbb3262243633c3e7d78f8370153021acf1095b Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 19:24:06 -0300 Subject: [PATCH 26/72] test(access): review round 2 for the pointer harness The moved XI2 literals for the motion rows (p4 denied, p5c) now derive their event coordinates from the motion target (MOTION_TO) at P's origin, (25, 25), not from the press position. Press-row literals derive from POINTER and each window's origin. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Haiku 5.5 --- .../tests/access_pointer_input.rs | 25 +++++++++++++------ 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index 421f5f7be..3cbb41c42 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -38,21 +38,30 @@ const fn press(origin: InputOrigin) -> Drive { } } -/// A move from the pointer's place to (125, 125), still over C. +/// The root position of the motion rows: still over C. +const MOTION_TO: (i16, i16) = (125, 125); + +/// A move from the pointer's place to `MOTION_TO`. const fn motion(origin: InputOrigin) -> Drive { Drive::Pointer { origin, kind: PointerEventKind::MotionNotify, button: 0, - to: (125, 125), + to: MOTION_TO, delta: (5, 5), } } -/// The event P (FOCUS) gives a copy of the pointer at root (120, 120). -const P_EVENT: (i16, i16) = (20, 20); -/// The event C (CHILD) gives a copy of the pointer at root (120, 120). -const C_EVENT: (i16, i16) = (10, 10); +/// The root origins of P (FOCUS) and C (CHILD) in the tree. +const P_ORIGIN: (i16, i16) = (100, 100); +const C_ORIGIN: (i16, i16) = (110, 110); + +/// The event P gives a copy of the pointer at the press position (`POINTER`). +const P_EVENT: (i16, i16) = (POINTER.0 - P_ORIGIN.0, POINTER.1 - P_ORIGIN.1); +/// The event C gives a copy of the pointer at the press position (`POINTER`). +const C_EVENT: (i16, i16) = (POINTER.0 - C_ORIGIN.0, POINTER.1 - C_ORIGIN.1); +/// The event P gives a copy of the pointer at the motion target (`MOTION_TO`). +const MOTION_EVENT_AT_P: (i16, i16) = (MOTION_TO.0 - P_ORIGIN.0, MOTION_TO.1 - P_ORIGIN.1); /// Registers a physical pointer source with the XI registry. fn register_physical_pointer(state: &mut ServerState) { @@ -288,7 +297,7 @@ const P4_DENIED: Row = Row { client: A, window: FOCUS, child: CHILD, - event: P_EVENT, + event: MOTION_EVENT_AT_P, }], allow: Expect { frames: &[ @@ -467,7 +476,7 @@ const P5C_DENIED: Row = Row { client: A, window: FOCUS, child: CHILD, - event: P_EVENT, + event: MOTION_EVENT_AT_P, }], allow: Expect { frames: &[ From 10f26b9b6004678e863290abfbfdc13f6a2dc9dd Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 19:34:58 -0300 Subject: [PATCH 27/72] feat(access): Receive decides the natural pointer walks A per-dispatch ReceiveMemo gives each (client, subject, batch) one Receive result, shared by the routing decision and the write. The core walk, the XI2 route windows and recipients, the core shadow and the deferred core copies now take a denial as a non-delivery: it does not stop or absorb a walk, shadow the client's core copy, or become an implicit-grab candidate. The master route resolves before the core walk; a client's core copy is shadowed when the client is among the master form's allowed recipients. Forms the dispatch does not write, or a grab decides, route by selection only. Fixed grab-window copies and the slave press route are checked at the write. xi2_stamp_deviceid_for_source has no caller left and is removed with its test. Four access_crossing_notify tests still pin the old rule that cooked pointer copies are never checked; they need the controller's ruling. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Sonnet 5.5 --- crates/yserver-core/src/core_loop/fanout.rs | 106 ++- .../src/core_loop/pointer_fanout.rs | 617 +++++++++++------- .../core_loop/pointer_fanout/owner_events.rs | 15 +- .../src/core_loop/pointer_fanout/tests.rs | 86 +-- .../tests/access_pointer_input.rs | 8 - 5 files changed, 503 insertions(+), 329 deletions(-) diff --git a/crates/yserver-core/src/core_loop/fanout.rs b/crates/yserver-core/src/core_loop/fanout.rs index 88bd39235..6053c0bc3 100644 --- a/crates/yserver-core/src/core_loop/fanout.rs +++ b/crates/yserver-core/src/core_loop/fanout.rs @@ -197,13 +197,14 @@ fn xi2_pointer_selected_on(state: &ServerState, window: ResourceId, evtype: u16) /// instead). Without an accurate `child`, fvwm3's `Mouse 1 R A Menu` /// binding fires on every click anywhere in the screen. #[must_use] -pub fn pointer_propagation_target_by_id( +pub(crate) fn pointer_propagation_target_by_id( state: &ServerState, start: ResourceId, start_x: i16, start_y: i16, mask_bits: u32, xi2_evtype: Option, + mut walk: Option>, ) -> Option<(ResourceId, i16, i16, Vec, ResourceId)> { let mut current = start; let mut x = start_x; @@ -217,14 +218,44 @@ pub fn pointer_propagation_target_by_id( // frame, handing the WM a press Xorg never sends. That armed // OpenBox's drag state, so a later bare MotionNotify started a // Move/Resize with no button held (#141). - if let Some(evtype) = xi2_evtype - && xi2_pointer_selected_on(state, current, evtype) - { - return None; + // + // Under Receive the absorbing window is the master form's route + // window, the first window whose XI2 copy is allowed. + if let Some(evtype) = xi2_evtype { + let absorbs = match &walk { + Some(walk) => walk.absorbing_window == Some(current), + None => xi2_pointer_selected_on(state, current, evtype), + }; + if absorbs { + return None; + } } let subs = subscribers_by_id(state, current, mask_bits); if !subs.is_empty() { - return Some((current, x, y, subs, child.unwrap_or(ResourceId(0)))); + let Some(walk) = walk.as_mut() else { + return Some((current, x, y, subs, child.unwrap_or(ResourceId(0)))); + }; + // A shadowed subscriber stops the walk with no check. The others + // are checked; an allowed one stops the walk too, and a denied + // copy is a non-delivery that lets it continue. + let description = EventDescription::core(walk.event_type); + let batch = EventBatch::new(std::slice::from_ref(&description)); + let mut stops = false; + let mut recipients = Vec::with_capacity(subs.len()); + for sub in subs { + if walk.shadowed.contains(&sub) { + stops = true; + } else if walk + .memo + .allows(state, sub, EventSubject::Window(current), &batch) + { + stops = true; + recipients.push(sub); + } + } + if stops { + return Some((current, x, y, recipients, child.unwrap_or(ResourceId(0)))); + } } let window = state.resources.window(current)?; if window.parent == current { @@ -306,6 +337,63 @@ pub(crate) fn receive_allows( ) } +/// The Receive results of one input dispatch, one per (client, subject, +/// batch). A routing decision and the write that follows it share the result, +/// so a client is asked once per attempt. With no policy installed nothing is +/// asked and nothing is stored. +/// +/// The access types derive `Eq` but not `Hash`, so the entries are a small +/// `Vec` compared by equality. +pub(crate) struct ReceiveMemo { + entries: Vec<(ClientId, EventSubject, Vec, bool)>, +} + +impl ReceiveMemo { + pub(crate) fn new() -> Self { + Self { + entries: Vec::new(), + } + } + + /// First call per (client, subject, batch) asks `receive_allows`; later + /// calls return the stored result without asking. + pub(crate) fn allows( + &mut self, + state: &ServerState, + client: ClientId, + subject: EventSubject, + events: &EventBatch<'_>, + ) -> bool { + if !state.policies_installed() { + return true; + } + if let Some((.., allowed)) = self + .entries + .iter() + .find(|(c, s, e, _)| *c == client && *s == subject && e.as_slice() == events.events()) + { + return *allowed; + } + let allowed = receive_allows(state, client, subject, events); + self.entries + .push((client, subject, events.events().to_vec(), allowed)); + allowed + } +} + +/// How the core propagation walk of one pointer dispatch uses Receive. +pub(crate) struct CoreWalk<'a> { + pub(crate) memo: &'a mut ReceiveMemo, + /// The master XI2 form's route window: the one window where an XI2 + /// selection absorbs the core copy. + pub(crate) absorbing_window: Option, + /// Clients whose core copy the allowed master XI2 copy shadows. + pub(crate) shadowed: &'a [ClientId], + /// The core event code of the copy (ButtonPress 4, ButtonRelease 5, + /// MotionNotify 6). + pub(crate) event_type: u8, +} + fn fanout_event_to_clients_inner( state: &mut ServerState, client_ids: &[ClientId], @@ -886,7 +974,8 @@ mod tests { 5, 5, 0x0000_0004, - Some(XI_BUTTON_PRESS) + Some(XI_BUTTON_PRESS), + None, ) .is_none(), "an XI2 master-device selection must absorb the core press, \ @@ -902,6 +991,7 @@ mod tests { 5, 0x0000_0004, Some(XI_BUTTON_PRESS), + None, ) .expect("a slave-device XI2 selection must not absorb the core press"); assert_eq!(win, FRAME); @@ -911,7 +1001,7 @@ mod tests { // unchanged: Enter/Leave are not routed by the flavour-ordered loop. let state = build(1); let (win, _, _, _, _) = - pointer_propagation_target_by_id(&state, CHILD, 5, 5, 0x0000_0004, None) + pointer_propagation_target_by_id(&state, CHILD, 5, 5, 0x0000_0004, None, None) .expect("without an absorbing evtype the walk still finds the frame"); assert_eq!(win, FRAME); } diff --git a/crates/yserver-core/src/core_loop/pointer_fanout.rs b/crates/yserver-core/src/core_loop/pointer_fanout.rs index 2f23d0583..aa1883755 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout.rs @@ -32,8 +32,8 @@ use yserver_protocol::x11::{self, ClientId, ResourceId, SequenceNumber}; use crate::{ access::{EventBatch, EventDescription, EventSubject}, core_loop::fanout::{ - client_target_id, fanout_event_to_clients, fanout_event_to_clients_with_receive, - pointer_propagation_target_by_id, + CoreWalk, ReceiveMemo, client_target_id, fanout_event_to_clients, + fanout_event_to_clients_with_receive, pointer_propagation_target_by_id, receive_allows, }, host_x11::{HostPointerEvent, HostXidMap, PointerEventKind}, nested::XI2_MAJOR_OPCODE, @@ -1023,6 +1023,9 @@ fn pointer_event_fanout_to_state_inner( } let mut dropped = Vec::new(); + // Every Receive result of this dispatch: a routing decision and the write + // that follows it share one. Nothing is stored when no policy is installed. + let mut receive = ReceiveMemo::new(); // Step 1 — translate host-screen coords to ynest-root coords. let event = translate_host_event(state, xid_map, event); @@ -1379,6 +1382,7 @@ fn pointer_event_fanout_to_state_inner( target_y, mask_bit, xi2_absorbing_evtype(event.kind), + None, ) .map(|(_, _, _, c, _)| c) .unwrap_or_default(); @@ -1390,6 +1394,7 @@ fn pointer_event_fanout_to_state_inner( xi2_evt, xi_source.slave_deviceid, None, + None, ); let label_clients = |cs: &[ClientId]| -> String { if cs.is_empty() { @@ -1485,6 +1490,7 @@ fn pointer_event_fanout_to_state_inner( target, top_level_id_opt.unwrap_or(ROOT_WINDOW), is_replay, + true, ); merge_dropped(&mut dropped, extras); handled_core_via_grab = true; @@ -1516,6 +1522,7 @@ fn pointer_event_fanout_to_state_inner( target, top_level_id_opt.unwrap_or(ROOT_WINDOW), is_replay, + true, ); merge_dropped(&mut dropped, extras); } @@ -1546,6 +1553,7 @@ fn pointer_event_fanout_to_state_inner( target, top_level_id_opt.unwrap_or(ROOT_WINDOW), is_replay, + true, ); merge_dropped(&mut dropped, extras); } @@ -1711,6 +1719,7 @@ fn pointer_event_fanout_to_state_inner( target, top_level_id_opt.unwrap_or(ROOT_WINDOW), is_replay, + true, ); merge_dropped(&mut dropped, extras); delivered = true; @@ -1794,14 +1803,83 @@ fn pointer_event_fanout_to_state_inner( } else { (target, target_x, target_y) }; - let (nested_id, event_x, event_y, mut core_targets, propagation_child) = if is_crossing { - ( - cross_start, - cross_x, - cross_y, - core_crossing_targets(state, cross_start, mask_bit), - ResourceId(0), - ) + // The master XI2 form of this dispatch decides two things about the + // core copy: the one window where an XI2 selection absorbs it, and + // which clients it shadows. yserver shadows the core form per client + // when that client also gets the master XI2 copy. For crossings this is + // a yserver rule: Xorg dispatches core and XI2 separately + // (`dix/enterleave.c:596-607`). Other pointer kinds mirror + // `deliver_key_to_window`; without this, clients selecting both forms + // process clicks and motion twice. Skip the shadow on replay because the + // XI2 fanout below is skipped as well. + // + // Only the MASTER-pointer XI2 form duplicates the core event, so shadow + // core only for those clients (Chromium's Ozone X11 selects core + XI2 + // on the master -> it must NOT get both). A client whose XI2 selection + // is a specific SLAVE device receives a distinct per-device event (Xorg + // delivers both core AND the slave XI2), so it must KEEP the core form. + // Enlightenment selects core ButtonPress on its canvas AND XI2 on the + // slave pointer; deduping it out of core left only the slave event (EFL + // routes that to its multi/touch handler as button 0), so no click ever + // registered on the e desktop. + // + // The master route resolves before the core walk. When the dispatch + // writes the master form (`master_form_written`, and no grab decides + // it), a selection counts only if its copy is allowed, so a denied XI2 + // copy neither absorbs nor shadows. Crossings and a form that is not + // written keep the selection-only recipients. + let xi2_evt = xi2_evtype(event.kind); + // Dedup against the SAME window the core form is delivered to. For + // crossings that is the per-window `cross_start` (the XI2 fanout below + // also resolves crossings to that window); using the live deepest hit + // would compute the set for the wrong window and leak a double + // (core + XI2) crossing to a client selecting both on the window being + // left/entered. + let (dedup_target, _dedup_top_level) = if is_crossing { + (cross_start, state.top_level_for_target(cross_start)) + } else { + (target, top_level_id) + }; + let master_form_written = !is_crossing + && !is_replay + && replay_has_master_form + && (replay.is_some() + || xi_source.slave_deviceid.is_none() + || xi_source.attached_master == Some(XI2_MASTER_POINTER_DEVICE_ID)) + && !master_form_decided_by_grab( + state, + xi_source, + replay, + pointer_xi2_grab_delivery(state, handle_grabs, event.kind, xi_source), + ); + let (master_route_window, shadowed) = if xi2_evt == 0 { + (None, Vec::new()) + } else { + let window = xi2_route_window_for_source( + state, + dedup_target, + Xi2PointerForm::Master, + xi2_evt, + xi_source.slave_deviceid, + master_form_written.then_some(&mut receive), + ); + let recipients = match window { + Some(window) if !is_replay => xi2_form_targets_for_source( + state, + window, + Xi2PointerForm::Master, + xi2_evt, + xi_source.slave_deviceid, + master_form_written.then_some(&mut receive), + ), + _ => Vec::new(), + }; + (window, recipients) + }; + let (nested_id, event_x, event_y, core_targets, propagation_child) = if is_crossing { + let mut core_targets = core_crossing_targets(state, cross_start, mask_bit); + core_targets.retain(|client| !shadowed.contains(client)); + (cross_start, cross_x, cross_y, core_targets, ResourceId(0)) } else { pointer_propagation_target_by_id( state, @@ -1810,66 +1888,16 @@ fn pointer_event_fanout_to_state_inner( cross_y, mask_bit, xi2_absorbing_evtype(event.kind), + Some(CoreWalk { + memo: &mut receive, + absorbing_window: master_route_window, + shadowed: &shadowed, + event_type: core_pointer_event_type(event.kind), + }), ) .unwrap_or((cross_start, cross_x, cross_y, Vec::new(), ResourceId(0))) }; - // yserver shadows the core form per client when that client also gets - // XI2 on the same window. For crossings this is a yserver rule: Xorg - // dispatches core and XI2 separately (`dix/enterleave.c:596-607`). - // Other pointer kinds mirror `deliver_key_to_window`; without this, - // clients selecting both forms process clicks and motion twice. Skip - // on replay because the XI2 fanout below is skipped as well. - if !is_replay { - let xi2_evt = xi2_evtype(event.kind); - if xi2_evt != 0 { - // Dedup against the SAME window the core form was just - // delivered to. For crossings that is the per-window - // `cross_start` (the XI2 fanout below also resolves - // crossings to that window); using the live deepest hit - // here would compute the dedup set for the wrong window and - // leak a double (core + XI2) crossing to a client selecting - // both on the window being left/entered. - let (dedup_target, dedup_top_level) = if is_crossing { - (cross_start, state.top_level_for_target(cross_start)) - } else { - (target, top_level_id) - }; - let xi2_dedup = compute_xi2_targets_for_source( - state, - dedup_target, - dedup_top_level, - xi2_evt, - xi_source.slave_deviceid, - None, - ); - // Only the MASTER-pointer XI2 form duplicates the core - // event, so shadow core only for those clients (Chromium's - // Ozone X11 selects core + XI2 on the master → it must NOT - // get both). A client whose XI2 selection is a specific - // SLAVE device receives a distinct per-device event (Xorg - // delivers both core AND the slave XI2), so it must KEEP - // the core form. Enlightenment selects core ButtonPress on - // its canvas AND XI2 on the slave pointer; deduping it out - // of core left only the slave event (EFL routes that to its - // multi/touch handler as button 0), so no click ever - // registered on the e desktop. - core_targets.retain(|c| { - !xi2_dedup.contains(c) - || xi_source.slave_deviceid.is_some_and(|slave_deviceid| { - xi2_stamp_deviceid_for_source( - state, - *c, - dedup_target, - dedup_top_level, - xi2_evt, - Some(slave_deviceid), - ) == slave_deviceid - }) - }); - } - } - if matches!( event.kind, PointerEventKind::ButtonPress | PointerEventKind::ButtonRelease @@ -1908,6 +1936,7 @@ fn pointer_event_fanout_to_state_inner( target, top_level_id, is_replay, + false, ); // Capture the core candidate. The final resolver compares it with // XI2 using Xorg's deepest-window, XI2-before-core ordering. @@ -1976,13 +2005,7 @@ fn pointer_event_fanout_to_state_inner( _ => None, }; let active_source_grab = active_grab_for_source(state, xi_source); - let xi2_grab_delivery = handle_grabs - && event.kind == PointerEventKind::ButtonPress - && active_source_grab.is_some_and(|grab| grab.passive) - && state - .xi1_frozen - .get(&source_device_id) - .is_some_and(|freeze| freeze.stored.is_some()); + let xi2_grab_delivery = pointer_xi2_grab_delivery(state, handle_grabs, event.kind, xi_source); let owner_events_slave_route = if xi2_grab_delivery && let Some(grab) = grab_for_form(state, xi_source, Xi2PointerForm::Slave, replay) && grab.passive @@ -2129,6 +2152,30 @@ fn pointer_event_fanout_to_state_inner( // every path window that selected it. Coalesce-safe: for the common // case the producer's window IS the deepest hit, so this is a no-op. // Clients reached only through the slave's earlier window. + // + // Which forms this dispatch writes through a memo-decided route. A form + // that is not written, or whose delivery a grab owns or redirects (its + // owner's copy is a fixed recipient, checked at the write), routes its + // natural selectors by selection only. The slave press route is converted + // in a later task, so its copies are checked at the write as well. + let xi2_crossing = matches!( + event.kind, + PointerEventKind::EnterNotify | PointerEventKind::LeaveNotify + ); + let slave_form_checked = !xi2_crossing + && xi_source.slave_deviceid.is_some() + && replay_has_slave_form + && button_transition.source_accepted + && owner_events_slave_route.is_none() + && slave_press_delivery.is_none() + && !xi2_grab_delivery; + let master_form_checked = !xi2_crossing + && replay_has_master_form + && button_transition.master_accepted + && (replay.is_some() + || xi_source.slave_deviceid.is_none() + || xi_source.attached_master == Some(XI2_MASTER_POINTER_DEVICE_ID)) + && !master_form_decided_by_grab(state, xi_source, replay, xi2_grab_delivery); let mut xi2_slave_only_targets: Vec = Vec::new(); let mut xi2_targets = if matches!( event.kind, @@ -2152,9 +2199,16 @@ fn pointer_event_fanout_to_state_inner( xi2_evtype, xi_source.slave_deviceid, slave_press_delivery.as_ref(), + Some(FormChecks { + memo: &mut receive, + slave: slave_form_checked, + master: master_form_checked, + }), ); if slave_pass_target != target { // The slave's form is routed from the sprite's previous window. + // The master's copies were decided at the live target, so only the + // slave form uses the memo here. let earlier = compute_xi2_targets_for_source( state, slave_pass_target, @@ -2162,6 +2216,11 @@ fn pointer_event_fanout_to_state_inner( xi2_evtype, xi_source.slave_deviceid, slave_press_delivery.as_ref(), + Some(FormChecks { + memo: &mut receive, + slave: slave_form_checked, + master: false, + }), ); xi2_slave_only_targets = earlier .iter() @@ -2515,6 +2574,11 @@ fn pointer_event_fanout_to_state_inner( xi2_evtype, xi_source.slave_deviceid, slave_press_delivery.as_ref(), + Some(FormChecks { + memo: &mut receive, + slave: slave_form_checked, + master: master_form_checked, + }), ); let wants_slave_at_target = wants_slave; if slave_pass_target != target { @@ -2526,9 +2590,19 @@ fn pointer_event_fanout_to_state_inner( xi2_evtype, xi_source.slave_deviceid, slave_press_delivery.as_ref(), + Some(FormChecks { + memo: &mut receive, + slave: slave_form_checked, + master: false, + }), ) .1; } + // The selection-decided answers, before a grab adds its owner: a copy + // is decided by the memo only when its form is checked and this + // client's selection made it a recipient. + let slave_copy_decided = slave_form_checked && wants_slave; + let master_copy_decided = master_form_checked && wants_master; // Exact slave grabs use their XI2 mask/device identity without a // separate XISelectEvents selection; detached sources have no master // cooked-event fallback. @@ -2678,6 +2752,7 @@ fn pointer_event_fanout_to_state_inner( form, xi2_evtype, xi_source.slave_deviceid, + slave_copy_decided.then_some(&mut receive), ) .unwrap_or(target), } @@ -2688,6 +2763,7 @@ fn pointer_event_fanout_to_state_inner( form, xi2_evtype, xi_source.slave_deviceid, + master_copy_decided.then_some(&mut receive), ) .unwrap_or(target) }; @@ -2788,20 +2864,39 @@ fn pointer_event_fanout_to_state_inner( } } }; - let extras = if is_crossing_evt { - let description = crate::xinput::xi2_event_description(xi2_evtype); - let events = EventBatch::new(std::slice::from_ref(&description)); - fanout_event_to_clients_with_receive( - state, - std::slice::from_ref(cid), - EventSubject::Window(ev_win), - &events, - encode, + // A copy the memo decided is written as it stands. Any other copy + // (a grab owner's, a slave press route's, one a form's selection + // did not give this client) is checked here, once, at its window. + let description = crate::xinput::xi2_event_description(xi2_evtype); + let events = EventBatch::new(std::slice::from_ref(&description)); + let copy_decided = match form { + Xi2PointerForm::Slave => slave_copy_decided, + Xi2PointerForm::Master => master_copy_decided, + }; + let (allowed, extras) = if is_crossing_evt { + ( + true, + fanout_event_to_clients_with_receive( + state, + std::slice::from_ref(cid), + EventSubject::Window(ev_win), + &events, + encode, + ), ) } else { - fanout_event_to_clients(state, std::slice::from_ref(cid), encode) + // `scroll_motion_only_grab` writes no bytes, so it asks nothing. + let allowed = copy_decided + || scroll_motion_only_grab + || receive_allows(state, *cid, EventSubject::Window(ev_win), &events); + let extras = if allowed { + fanout_event_to_clients(state, std::slice::from_ref(cid), encode) + } else { + Vec::new() + }; + (allowed, extras) }; - let delivered = !extras.contains(cid); + let delivered = allowed && !extras.contains(cid); merge_dropped(&mut dropped, extras); if event.kind == PointerEventKind::ButtonPress && button_want @@ -3371,6 +3466,7 @@ fn resolve_slave_press_delivery( Xi2PointerForm::Slave, xi2_evtype(PointerEventKind::ButtonPress), Some(deviceid), + None, ); if !xi2_recipients.is_empty() { return SlavePressDelivery::Xi2 { @@ -4006,6 +4102,39 @@ fn active_pointer_grab_target( )) } +/// The activating press of a passive grab whose event is stored: the grab +/// owner's copy is delivered on the grab window, whatever the selections say. +fn pointer_xi2_grab_delivery( + state: &ServerState, + handle_grabs: bool, + kind: PointerEventKind, + xi_source: PointerXiSource, +) -> bool { + let source_device_id = xi_source.slave_deviceid.unwrap_or(xi_source.sourceid); + handle_grabs + && kind == PointerEventKind::ButtonPress + && active_grab_for_source(state, xi_source).is_some_and(|grab| grab.passive) + && state + .xi1_frozen + .get(&source_device_id) + .is_some_and(|freeze| freeze.stored.is_some()) +} + +/// Whether a grab decides the master form's recipients, so its natural +/// selectors are not checked: an XI2 grab delivery, or a master grab with a +/// live owner. +fn master_form_decided_by_grab( + state: &ServerState, + xi_source: PointerXiSource, + replay: Option, + xi2_grab_delivery: bool, +) -> bool { + xi2_grab_delivery + || grab_for_form(state, xi_source, Xi2PointerForm::Master, replay) + .and_then(|grab| active_pointer_grab_target(state, grab)) + .is_some() +} + struct DeferredCorePointerEvent { target: ClientId, window: ResourceId, @@ -4054,6 +4183,7 @@ fn fanout_core_pointer_event_ordered( natural_target: ResourceId, top_level: ResourceId, is_replay: bool, + fresh_check: bool, ) -> Vec { let defer_slave_form = !is_replay && source.slave_deviceid.is_some() @@ -4061,6 +4191,12 @@ fn fanout_core_pointer_event_ordered( event.kind, PointerEventKind::EnterNotify | PointerEventKind::LeaveNotify ); + // `fresh_check`: `targets` are fixed recipients (a grab owner), so this + // write is the attempt Receive is asked about. Otherwise a walk decided + // them and asked already. A copy deferred behind the slave pass is checked + // here, when it is admitted; the flush writes it unchecked. + let description = EventDescription::core(core_pointer_event_type(event.kind)); + let events = EventBatch::new(std::slice::from_ref(&description)); let mut immediate = Vec::with_capacity(targets.len()); for target in targets { let has_slave_form = defer_slave_form @@ -4073,20 +4209,24 @@ fn fanout_core_pointer_event_ordered( xi2_evtype(event.kind), Some(slave_deviceid), None, + None, ) .1 }); if has_slave_form { - defer_core_pointer_event( - deferred, - std::slice::from_ref(target), - window, - child, - event, - event_x, - event_y, - focus, - ); + if !fresh_check || receive_allows(state, *target, EventSubject::Window(window), &events) + { + defer_core_pointer_event( + deferred, + std::slice::from_ref(target), + window, + child, + event, + event_x, + event_y, + focus, + ); + } } else { immediate.push(*target); } @@ -4107,13 +4247,13 @@ fn fanout_core_pointer_event_ordered( focus, ); }; - let event_type = match event.kind { - PointerEventKind::EnterNotify => 7, - PointerEventKind::LeaveNotify => 8, - _ => return fanout_event_to_clients(state, &immediate, encode), - }; - let description = EventDescription::core(event_type); - let events = EventBatch::new(std::slice::from_ref(&description)); + let is_crossing = matches!( + event.kind, + PointerEventKind::EnterNotify | PointerEventKind::LeaveNotify + ); + if !is_crossing && !fresh_check { + return fanout_event_to_clients(state, &immediate, encode); + } fanout_event_to_clients_with_receive( state, &immediate, @@ -4123,6 +4263,17 @@ fn fanout_core_pointer_event_ordered( ) } +/// The core event code of a pointer event. +fn core_pointer_event_type(kind: PointerEventKind) -> u8 { + match kind { + PointerEventKind::ButtonPress => 4, + PointerEventKind::ButtonRelease => 5, + PointerEventKind::MotionNotify => 6, + PointerEventKind::EnterNotify => 7, + PointerEventKind::LeaveNotify => 8, + } +} + fn fanout_deferred_core_pointer_event( state: &mut ServerState, delivery: DeferredCorePointerEvent, @@ -4505,19 +4656,33 @@ fn xi2_form_selected_on_for_source( /// Route one XI2 device form using Xorg's `DeliverDeviceEvents` rule: walk /// leaf-to-root and stop at the first window with a matching selection. /// Every selector on that window receives the form; selectors on higher -/// ancestors do not receive duplicate copies. +/// ancestors do not receive duplicate copies. With a memo, a selection counts +/// only if its copy is allowed. fn xi2_route_window_for_source( state: &ServerState, target: ResourceId, form: Xi2PointerForm, evtype: u16, slave_deviceid: Option, + mut receive: Option<&mut ReceiveMemo>, ) -> Option { let mut window = target; for _ in 0..256 { - if state.clients.values().any(|client| { - xi2_form_selected_on_for_source(client, window, form, evtype, slave_deviceid) - }) { + let selected = match receive.as_deref_mut() { + Some(memo) => !xi2_form_targets_for_source( + state, + window, + form, + evtype, + slave_deviceid, + Some(memo), + ) + .is_empty(), + None => state.clients.values().any(|client| { + xi2_form_selected_on_for_source(client, window, form, evtype, slave_deviceid) + }), + }; + if selected { return Some(window); } if window == ROOT_WINDOW { @@ -4528,21 +4693,49 @@ fn xi2_route_window_for_source( None } +/// The clients that selected `form` of `evtype` on `window`. With a memo, only +/// those whose copy at `window` is allowed (the form's description is the one +/// XI2 description for both forms, so a client's slave and master forms at +/// one window share one check). fn xi2_form_targets_for_source( state: &ServerState, window: ResourceId, form: Xi2PointerForm, evtype: u16, slave_deviceid: Option, + mut receive: Option<&mut ReceiveMemo>, ) -> Vec { - state - .clients - .iter() - .filter_map(|(id, client)| { - xi2_form_selected_on_for_source(client, window, form, evtype, slave_deviceid) - .then_some(ClientId(*id)) - }) - .collect() + let description = crate::xinput::xi2_event_description(evtype); + let batch = EventBatch::new(std::slice::from_ref(&description)); + let mut targets = Vec::new(); + for (id, client) in &state.clients { + if xi2_form_selected_on_for_source(client, window, form, evtype, slave_deviceid) + && receive.as_deref_mut().is_none_or(|memo| { + memo.allows(state, ClientId(*id), EventSubject::Window(window), &batch) + }) + { + targets.push(ClientId(*id)); + } + } + targets +} + +/// A memo and which XI2 forms of one call are checked through it. An unchecked +/// form, like no memo at all, routes by selection only. +pub(super) struct FormChecks<'a> { + pub(super) memo: &'a mut ReceiveMemo, + pub(super) slave: bool, + pub(super) master: bool, +} + +impl FormChecks<'_> { + fn memo_for(&mut self, form: Xi2PointerForm) -> Option<&mut ReceiveMemo> { + let checked = match form { + Xi2PointerForm::Slave => self.slave, + Xi2PointerForm::Master => self.master, + }; + checked.then_some(&mut *self.memo) + } } /// The one XI2 form a crossing is delivered in. Xorg computes Enter/Leave @@ -4577,7 +4770,7 @@ fn xi2_crossing_targets_for_source( .collect(), _ => { let (form, _) = xi2_crossing_form(xi_source); - xi2_form_targets_for_source(state, window, form, evtype, xi_source.slave_deviceid) + xi2_form_targets_for_source(state, window, form, evtype, xi_source.slave_deviceid, None) } } } @@ -4588,9 +4781,10 @@ pub(crate) fn xi2_master_selectors( window: ResourceId, evtype: u16, ) -> Vec { - xi2_form_targets_for_source(state, window, Xi2PointerForm::Master, evtype, None) + xi2_form_targets_for_source(state, window, Xi2PointerForm::Master, evtype, None, None) } +#[allow(clippy::too_many_arguments)] fn compute_xi2_targets_for_source( state: &ServerState, target: yserver_protocol::x11::ResourceId, @@ -4598,6 +4792,7 @@ fn compute_xi2_targets_for_source( xi2_evtype: u16, slave_deviceid: Option, slave_press_delivery: Option<&SlavePressDelivery>, + mut receive: Option>, ) -> Vec { let mut xi2_targets: Vec = Vec::new(); if xi2_evtype == 0 { @@ -4609,43 +4804,37 @@ fn compute_xi2_targets_for_source( [None, Some(Xi2PointerForm::Master)] }; for form in forms.into_iter().flatten() { - let route = if form == Xi2PointerForm::Slave { - match slave_press_delivery { - Some(SlavePressDelivery::Xi2 { window, recipients }) => { + let route = if form == Xi2PointerForm::Slave + && let Some(delivery) = slave_press_delivery + { + match delivery { + SlavePressDelivery::Xi2 { window, recipients } => { Some((*window, recipients.clone())) } - Some(SlavePressDelivery::Xi1 { .. } | SlavePressDelivery::None) => None, - None => { - xi2_route_window_for_source(state, target, form, xi2_evtype, slave_deviceid) - .map(|window| { - ( - window, - xi2_form_targets_for_source( - state, - window, - form, - xi2_evtype, - slave_deviceid, - ), - ) - }) - } + SlavePressDelivery::Xi1 { .. } | SlavePressDelivery::None => None, } } else { - xi2_route_window_for_source(state, target, form, xi2_evtype, slave_deviceid).map( - |window| { - ( - window, - xi2_form_targets_for_source( - state, - window, - form, - xi2_evtype, - slave_deviceid, - ), - ) - }, + xi2_route_window_for_source( + state, + target, + form, + xi2_evtype, + slave_deviceid, + receive.as_mut().and_then(|checks| checks.memo_for(form)), ) + .map(|window| { + ( + window, + xi2_form_targets_for_source( + state, + window, + form, + xi2_evtype, + slave_deviceid, + receive.as_mut().and_then(|checks| checks.memo_for(form)), + ), + ) + }) }; if let Some((_window, recipients)) = route { for cid in recipients { @@ -4692,67 +4881,6 @@ fn compute_xi2_raw_targets( (slave_targets, master_targets) } -/// The XI2 `deviceid` an event delivered to `cid` carries, given the -/// device that client selected on for this `(target, top_level)` pair. -/// A specific-slave selection yields the slave id; a master / -/// `XIAllMasterDevices` / `XIAllDevices` selection yields the master id. -/// Mirrors `xi2_mask_for_client`'s window/device precedence. -/// -/// Two uses: it picks the deviceid stamped on the delivered XI2 event, -/// and it decides whether that XI2 event *duplicates* the core event -/// (only the master form does) and must therefore shadow core delivery. -fn xi2_stamp_deviceid_for_source( - state: &ServerState, - cid: ClientId, - target: ResourceId, - _top_level: ResourceId, - evtype: u16, - slave_deviceid: Option, -) -> u16 { - let Some(client) = state.clients.get(&cid.0) else { - return XI2_MASTER_POINTER_DEVICE_ID; - }; - if xi2_route_window_for_source( - state, - target, - Xi2PointerForm::Master, - evtype, - slave_deviceid, - ) - .is_some_and(|window| { - xi2_form_selected_on_for_source( - client, - window, - Xi2PointerForm::Master, - evtype, - slave_deviceid, - ) - }) { - return XI2_MASTER_POINTER_DEVICE_ID; - } - if let Some(slave_deviceid) = slave_deviceid - && xi2_route_window_for_source( - state, - target, - Xi2PointerForm::Slave, - evtype, - Some(slave_deviceid), - ) - .is_some_and(|window| { - xi2_form_selected_on_for_source( - client, - window, - Xi2PointerForm::Slave, - evtype, - Some(slave_deviceid), - ) - }) - { - return slave_deviceid; - } - XI2_MASTER_POINTER_DEVICE_ID -} - /// Which stamped forms of a pointer XI2 event `cid` should receive for /// `evtype`, mirroring Xorg's per-device delivery: the MASTER form if it /// selected under the concrete master pointer, `XIAllMasterDevices(1)`, @@ -4772,47 +4900,52 @@ fn xi2_pointer_forms_for_source( evtype: u16, slave_deviceid: Option, slave_press_delivery: Option<&SlavePressDelivery>, + mut receive: Option>, ) -> (bool, bool) { let Some(client) = state.clients.get(&cid.0) else { return (false, false); }; - let master = xi2_route_window_for_source( - state, - target, - Xi2PointerForm::Master, - evtype, - slave_deviceid, - ) - .is_some_and(|window| { - xi2_form_selected_on_for_source( - client, - window, - Xi2PointerForm::Master, - evtype, - slave_deviceid, - ) - }); + // A checked form counts the client only when its copy at the route window + // is allowed. The route walk asked every selector of that window already, + // so this reads the memo. + let mut selected_at_route = |form: Xi2PointerForm, slave_deviceid: Option| { + let memo = receive.as_mut().and_then(|checks| checks.memo_for(form)); + let (window, memo) = match memo { + Some(memo) => ( + xi2_route_window_for_source( + state, + target, + form, + evtype, + slave_deviceid, + Some(&mut *memo), + ), + Some(memo), + ), + None => ( + xi2_route_window_for_source(state, target, form, evtype, slave_deviceid, None), + None, + ), + }; + window.is_some_and(|window| { + xi2_form_selected_on_for_source(client, window, form, evtype, slave_deviceid) + && memo.is_none_or(|memo| { + let description = crate::xinput::xi2_event_description(evtype); + memo.allows( + state, + cid, + EventSubject::Window(window), + &EventBatch::new(std::slice::from_ref(&description)), + ) + }) + }) + }; + let master = selected_at_route(Xi2PointerForm::Master, slave_deviceid); let slave = match slave_press_delivery { Some(SlavePressDelivery::Xi2 { recipients, .. }) => recipients.contains(&cid), Some(SlavePressDelivery::Xi1 { .. } | SlavePressDelivery::None) => false, - None => slave_deviceid.is_some_and(|device_id| { - xi2_route_window_for_source( - state, - target, - Xi2PointerForm::Slave, - evtype, - Some(device_id), - ) - .is_some_and(|window| { - xi2_form_selected_on_for_source( - client, - window, - Xi2PointerForm::Slave, - evtype, - Some(device_id), - ) - }) - }), + None => slave_deviceid + .is_some_and(|device_id| selected_at_route(Xi2PointerForm::Slave, Some(device_id))), }; (master, slave) } diff --git a/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs b/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs index 8dea61249..1783158d2 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs @@ -183,9 +183,14 @@ pub(super) fn xi2_motion_targets_for_source( continue; } - let Some(window) = - xi2_route_window_for_source(state, target, form, XI_MOTION, source.slave_deviceid) - else { + let Some(window) = xi2_route_window_for_source( + state, + target, + form, + XI_MOTION, + source.slave_deviceid, + None, + ) else { continue; }; let child = xi2_child_toward(state, window, target); @@ -199,7 +204,7 @@ pub(super) fn xi2_motion_targets_for_source( ) }; for client in - xi2_form_targets_for_source(state, window, form, XI_MOTION, source.slave_deviceid) + xi2_form_targets_for_source(state, window, form, XI_MOTION, source.slave_deviceid, None) { targets.push(Xi2MotionTarget { client, @@ -401,7 +406,7 @@ pub(super) fn owner_events_route( let mut rejected = false; if let Some(evtype) = xi2_evtype { let subscribers = - xi2_form_targets_for_source(state, current, form, evtype, slave_deviceid); + xi2_form_targets_for_source(state, current, form, evtype, slave_deviceid, None); if !subscribers.is_empty() { if subscribers.contains(&grab_client) { return OwnerEventsRoute::Natural { diff --git a/crates/yserver-core/src/core_loop/pointer_fanout/tests.rs b/crates/yserver-core/src/core_loop/pointer_fanout/tests.rs index 121288d0a..5f3df068f 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout/tests.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout/tests.rs @@ -4497,64 +4497,6 @@ fn pointer_event_fires_neg_transition_alarm_on_per_device_idletime_vcp() { ); } -/// Regression (e27 clicks dead): the device classification that gates -/// both the core/XI2 dedup and the XI2 `deviceid` stamp. A client -/// selecting on the SLAVE pointer must classify as slave (so the dedup -/// leaves its CORE ButtonPress intact — Enlightenment needs the core -/// click); a client selecting the MASTER, `XIAllMasterDevices`, or -/// `XIAllDevices` must classify as master (so it is still deduped, -/// preserving Chromium's no-double-ButtonPress fix). HW-confirmed on -/// both e27 (clicks work) and Chrome (no double-click) 2026-06-25. -#[test] -fn xi2_stamp_deviceid_classifies_slave_vs_master_selectors() { - let mut state = ServerState::new(); - let _p1 = install_client(&mut state, 1); - let _p2 = install_client(&mut state, 2); - let _p3 = install_client(&mut state, 3); - let _p4 = install_client(&mut state, 4); - let win = ResourceId(0x10_0009); - const XI_BUTTON_PRESS_MASK: u32 = 1 << 4; - // client 1: slave-pointer selection (Enlightenment's pattern). - state.clients.get_mut(&1).unwrap().xi2_masks.insert( - (win, XI2_XTEST_POINTER_DEVICE_ID), - u64::from(XI_BUTTON_PRESS_MASK), - ); - // client 2: master-pointer selection (Chromium's pattern). - state.clients.get_mut(&2).unwrap().xi2_masks.insert( - (win, XI2_MASTER_POINTER_DEVICE_ID), - u64::from(XI_BUTTON_PRESS_MASK), - ); - // client 3: XIAllMasterDevices (1) wildcard. - state - .clients - .get_mut(&3) - .unwrap() - .xi2_masks - .insert((win, 1), u64::from(XI_BUTTON_PRESS_MASK)); - // client 4: no XI2 selection at all. - - assert_eq!( - xi2_stamp_deviceid_for_source(&state, ClientId(1), win, win, 4, Some(4)), - XI2_XTEST_POINTER_DEVICE_ID, - "slave-device selector must stay slave (keeps core delivery)" - ); - assert_eq!( - xi2_stamp_deviceid_for_source(&state, ClientId(2), win, win, 4, Some(4)), - XI2_MASTER_POINTER_DEVICE_ID, - "master-device selector must be master (stays deduped)" - ); - assert_eq!( - xi2_stamp_deviceid_for_source(&state, ClientId(3), win, win, 4, Some(4)), - XI2_MASTER_POINTER_DEVICE_ID, - "XIAllMasterDevices selector classifies as master" - ); - assert_eq!( - xi2_stamp_deviceid_for_source(&state, ClientId(4), win, win, 4, Some(4)), - XI2_MASTER_POINTER_DEVICE_ID, - "no XI2 selection defaults to master" - ); -} - /// Issue #72: lite-xl (SDL2) got NO mouse interactions because it /// splits its XI2 selection across device-id wildcards on the SAME /// window — Motion/Touch/Gesture under `XIAllMasterDevices(1)` but @@ -4589,7 +4531,8 @@ fn xi2_split_device_wildcards_deliver_button_press_issue_72() { // XI_ButtonPress (4) is selected ONLY under XIAllDevices(0). Under // the old first-match semantics device 1 matched first and had no // button bit -> empty targets -> the click reached no client. - let press_targets = compute_xi2_targets_for_source(&state, window, window, 4, Some(4), None); + let press_targets = + compute_xi2_targets_for_source(&state, window, window, 4, Some(4), None, None); assert!( press_targets.contains(&ClientId(11)), "issue #72: XI_ButtonPress selected under XIAllDevices(0) must be \ @@ -4597,7 +4540,8 @@ fn xi2_split_device_wildcards_deliver_button_press_issue_72() { ); // XI_ButtonRelease (5) is likewise only under XIAllDevices(0). - let release_targets = compute_xi2_targets_for_source(&state, window, window, 5, Some(4), None); + let release_targets = + compute_xi2_targets_for_source(&state, window, window, 5, Some(4), None, None); assert!( release_targets.contains(&ClientId(11)), "issue #72: XI_ButtonRelease under XIAllDevices(0) must be delivered" @@ -4605,7 +4549,8 @@ fn xi2_split_device_wildcards_deliver_button_press_issue_72() { // Sanity: XI_Motion (6) — selected under BOTH wildcards — still // reaches the client (this arm passed even under first-match). - let motion_targets = compute_xi2_targets_for_source(&state, window, window, 6, Some(4), None); + let motion_targets = + compute_xi2_targets_for_source(&state, window, window, 6, Some(4), None, None); assert!( motion_targets.contains(&ClientId(11)), "XI_Motion must continue to be delivered" @@ -4644,13 +4589,22 @@ fn xi2_pointer_forms_all_devices_selector_gets_both_forms_issue_72() { // core issue-#72 fix: it was false under master-only bucketing. set_masks(&mut state, &[(1u16, 0x381c_00c0u32), (0u16, 0x19f2u32)]); assert_eq!( - xi2_pointer_forms_for_source(&state, ClientId(11), win, win, MOTION, Some(4), None), + xi2_pointer_forms_for_source(&state, ClientId(11), win, win, MOTION, Some(4), None, None), (true, true), "issue #72: an XIAllDevices(0) selector must get BOTH forms for \ Motion so SDL3 can parse smooth scroll off the slave-stamped motion" ); assert_eq!( - xi2_pointer_forms_for_source(&state, ClientId(11), win, win, BUTTON_PRESS, Some(4), None), + xi2_pointer_forms_for_source( + &state, + ClientId(11), + win, + win, + BUTTON_PRESS, + Some(4), + None, + None + ), (true, true), "ButtonPress selected under XIAllDevices(0) must also yield BOTH forms" ); @@ -4659,7 +4613,7 @@ fn xi2_pointer_forms_all_devices_selector_gets_both_forms_issue_72() { // covers master devices only, so master form yes, slave form no. set_masks(&mut state, &[(1u16, 0x0000_0040u32)]); assert_eq!( - xi2_pointer_forms_for_source(&state, ClientId(11), win, win, MOTION, Some(4), None), + xi2_pointer_forms_for_source(&state, ClientId(11), win, win, MOTION, Some(4), None, None), (true, false), "XIAllMasterDevices(1) covers master devices only: master form, NO slave form" ); @@ -4668,7 +4622,7 @@ fn xi2_pointer_forms_all_devices_selector_gets_both_forms_issue_72() { // slave form yes, master form no; preserves core delivery. set_masks(&mut state, &[(XI2_XTEST_POINTER_DEVICE_ID, 0x0000_0040u32)]); assert_eq!( - xi2_pointer_forms_for_source(&state, ClientId(11), win, win, MOTION, Some(4), None), + xi2_pointer_forms_for_source(&state, ClientId(11), win, win, MOTION, Some(4), None, None), (false, true), "a concrete slave-pointer selector gets the slave form only" ); @@ -4677,7 +4631,7 @@ fn xi2_pointer_forms_all_devices_selector_gets_both_forms_issue_72() { // slave, so both forms. set_masks(&mut state, &[(0u16, 0x0000_0040u32)]); assert_eq!( - xi2_pointer_forms_for_source(&state, ClientId(11), win, win, MOTION, Some(4), None), + xi2_pointer_forms_for_source(&state, ClientId(11), win, win, MOTION, Some(4), None, None), (true, true), "XIAllDevices(0) matches both master and slave: BOTH forms" ); diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index 3cbb41c42..5e42ea7be 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -159,7 +159,6 @@ const P1: Row = Row { /// Mutation: the core walk stops at any window with a core selector, without /// asking Receive (selection-only stop). A then never sees the press. #[test] -#[ignore = "red until Task 1b: Receive decides the natural pointer walks"] fn p1_denied_core_selector_does_not_stop_the_core_walk() { check_row(&P1); } @@ -203,7 +202,6 @@ const P2: Row = Row { /// Mutation: an XI2 selection absorbs the walk whether or not its copy is /// allowed (selection-only absorption), or the denied XI2 copy is checked twice. #[test] -#[ignore = "red until Task 1b: Receive decides the natural pointer walks"] fn p2_denied_xi2_selector_does_not_absorb_core() { check_row(&P2); } @@ -247,7 +245,6 @@ const P3: Row = Row { /// Mutation: the XI2 route window is the first window with a selection rather /// than the first with an allowed one, so the denied copy at C ends the walk. #[test] -#[ignore = "red until Task 1b: Receive decides the natural pointer walks"] fn p3_xi2_walk_skips_a_denied_window() { check_row(&P3); } @@ -315,7 +312,6 @@ const P4_DENIED: Row = Row { /// Mutation: the slave and master forms each ask Receive (two calls for B), /// or the master form is checked at the slave pass's window. #[test] -#[ignore = "red until Task 1b: Receive decides the natural pointer walks"] fn p4_slave_and_master_forms_share_one_check() { check_row(&P4_ALLOWED); check_row(&P4_DENIED); @@ -379,7 +375,6 @@ const P5_DENIED: Row = Row { /// Mutation: A's core copy is shadowed by its XI2 selection, not by the copy /// that is allowed, so the denied XI2 still hides the core copy at C. #[test] -#[ignore = "red until Task 1b: Receive decides the natural pointer walks"] fn p5_denied_xi2_reopens_that_clients_core() { check_row(&P5_ALLOWED); check_row(&P5_DENIED); @@ -447,7 +442,6 @@ const P5B_XI2_DENIED: Row = Row { /// is checked and then deduplicated), or a shadowed core copy that is still /// checked before the walk stops. #[test] -#[ignore = "red until Task 1b: Receive decides the natural pointer walks"] fn p5b_shadow_follows_the_master_copy_anywhere() { check_row(&P5B_CORE_DENIED); check_row(&P5B_XI2_DENIED); @@ -497,7 +491,6 @@ const P5C_DENIED: Row = Row { /// Mutation: the shadow uses the selection-only master route, which ends at C /// (B's selection); A then keeps its core copy at C and gets no XI2 at P. #[test] -#[ignore = "red until Task 1b: Receive decides the natural pointer walks"] fn p5c_shadow_uses_the_allowed_master_route() { check_row(&P5C_DENIED); } @@ -544,7 +537,6 @@ const P6_DENIED: Row = Row { /// Mutation: the deferred core copy is checked again at the flush (two calls), /// or never checked (the copy is written with no call). #[test] -#[ignore = "red until Task 1b: Receive decides the natural pointer walks"] fn p6_deferred_core_copy_is_checked_at_admission() { check_row(&P6_DENIED); } From 209fc06f91c3fb42752016ad167107f03dc114be Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 19:39:02 -0300 Subject: [PATCH 28/72] test(access): pointer copies are now checked Four access_crossing_notify tests pinned that natural pointer copies were never asked. Natural copies now ask Receive once each. - cooked pointer copies: DENIED's copies are not written and each is asked once with the child as subject; ALLOWED's ButtonPress frame is unchanged, and it gains the core motion DENIED's refused master motion no longer absorbs. - XI2 grab-window ButtonPress: asked once, fresh; a denial writes nothing and the grab stays active. - barrier rows (B1 and the owner denial) pin only the barrier calls; the drive's core motion copies are checked but not pinned there. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Sonnet 5.5 --- .../tests/access_crossing_notify.rs | 131 +++++++++++++----- .../tests/access_notify_support.rs | 50 +++++-- 2 files changed, 133 insertions(+), 48 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_crossing_notify.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_crossing_notify.rs index 3def27599..b66e159d3 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_crossing_notify.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_crossing_notify.rs @@ -995,6 +995,13 @@ fn barrier_drive(f: &mut NotifyFixture) { assert!(!f.state.pointer_barriers[&BARRIER_XID].hit); } +/// A barrier notification (XI2 BarrierHit 25 or BarrierLeave 26). The drive also moves the +/// pointer, so the natural core motion copies are checked too (plan 2, Task 1b); this row +/// pins only the barrier calls. +fn is_barrier_call(call: &ExpectedReceive) -> bool { + call.events == [xi2_event(25)] || call.events == [xi2_event(26)] +} + const B1_BARRIER_SELECTORS: Row = row!( "B1 BarrierHit and BarrierLeave to the barrier selectors", barrier_setup, @@ -1021,7 +1028,8 @@ const B1_BARRIER_SELECTORS: Row = row!( .collect() }, barrier_effects, -); +) +.only_calls(is_barrier_call); const ROWS: &[Row] = &[ R1_MONITOR_ROOT, @@ -1407,7 +1415,10 @@ fn receive_barrier_grab_owner_denial() { feed_barrier_motion(&mut f, 190, 95, 50); feed_barrier_motion(&mut f, 200, 110, 50); assert!(f.state.pointer_barriers[&BARRIER_XID].hit); - let seen = trace("barrier owner", &calls); + let seen: Vec = trace("barrier owner", &calls) + .into_iter() + .filter(is_barrier_call) + .collect(); let streams = [SENDER, DENIED, ALLOWED].map(|client| f.drain(client)); (f, seen, streams) }; @@ -1611,17 +1622,20 @@ fn receive_xi_keyboard_regrab_orders_focus_out_before_in() { assert_no_writer_failures(&f); } -/// A ButtonPress delivered through the XIGrabDevice mask (not XISelectEvents) arrives -/// unchanged when the owner's synthetic activation is denied, and adds no Receive call. +/// A ButtonPress delivered through the XIGrabDevice mask (not XISelectEvents) is the grab +/// owner's copy on the grab window: a fixed recipient, checked once, fresh, with that window as +/// subject. A denial counts as delivered (spec l.424-429): the owner gets no bytes and the grab +/// stays active. With the check allowed the frame arrives unchanged (evtype 4). #[test] -fn receive_xi_pointer_grab_event_is_unchecked() { - let run = |deny_activation: bool| { +fn receive_xi_pointer_grab_window_copy_is_checked_fresh() { + let run = |deny_press: bool| { let mut f = new_fixture(); grab_setup(&mut f); drain_all(&mut f); - let activation = request_opcodes(XI_MAJOR, 51); - let calls = if deny_activation { - deny_receive(&mut f, DENIED, move |c| c.request == activation) + let calls = if deny_press { + deny_receive(&mut f, DENIED, |c| { + c.events.as_deref() == Some(&[xi2_event(4)][..]) + }) } else { allow_all(&mut f) }; @@ -1644,22 +1658,27 @@ fn receive_xi_pointer_grab_event_is_unchecked() { let stream = f.drain(DENIED); (f, stream, trace("pointer grab mask", &calls)) }; - let (_, allow_stream, _) = run(false); + let (_, allow_stream, allow_seen) = run(false); let (denied_f, denied_stream, seen) = run(true); - assert_eq!( - denied_stream, allow_stream, - "the grab-mask ButtonPress arrives unchanged" - ); - let frames = split_frames(&denied_stream, ClientByteOrder::BigEndian); + let frames = split_frames(&allow_stream, ClientByteOrder::BigEndian); assert_eq!(frames.len(), 1, "one XI2 ButtonPress"); assert_eq!(frames[0][8..10], [0, 4], "evtype 4 (ButtonPress)"); assert!( - seen.iter().all(|call| call.events != vec![xi2_event(4)]), - "no Receive call for the ButtonPress" + denied_stream.is_empty(), + "the denied grab-window ButtonPress is not written" ); + let presses = |seen: &[ExpectedReceive]| -> Vec { + seen.iter() + .filter(|c| c.events == vec![xi2_event(4)]) + .cloned() + .collect() + }; + let press = call(DENIED, None, CROSS_CHILD, xi2_event(4)); + assert_eq!(presses(&allow_seen), vec![press.clone()], "asked once"); + assert_eq!(presses(&seen), vec![press], "asked once, denied"); assert!( denied_f.state.active_pointer_grab.is_some(), - "the button does not end the grab" + "a denial counts as delivered: the grab stays active" ); } @@ -1720,12 +1739,15 @@ fn receive_xi_pointer_grab_chain_details() { assert!(f.state.active_pointer_grab.is_none()); } -/// Cooked pointer events are not checked: motion and ButtonPress, in core and XI2 form (the -/// XI2 ButtonPress on the XTEST pointer, the XI2 motion on the master pointer), arrive -/// unchanged under a deny-all policy, and no Receive call is recorded for them. +/// Natural pointer copies are checked (spec l.381-385: one Receive result per recipient per +/// attempt; plan 2, Task 1b). DENIED selects core motion, the XTEST slave's XI2 ButtonPress and +/// the master's XI2 motion on the child; ALLOWED selects core motion and ButtonPress there. With +/// every Receive call to DENIED refused, DENIED receives none of its copies and each copy is asked +/// once with the child as subject. ALLOWED's ButtonPress frame equals the no-policy run's; +/// DENIED's denied master motion no longer absorbs ALLOWED's core motion, so ALLOWED gains it. #[test] -fn receive_core_cooked_pointer_unchecked() { - let run = |deny_all: bool| { +fn receive_cooked_pointer_copies_are_checked() { + let run = |policy: u8| { let mut f = new_fixture(); crossing_windows(&mut f); rx!(f, ALLOWED) @@ -1741,10 +1763,10 @@ fn receive_core_cooked_pointer_unchecked() { .xi2_masks .insert((CROSS_CHILD, MASTER_POINTER), 1 << 6); drain_all(&mut f); - let calls = if deny_all { - f.install_policy(|_, _| DENY) - } else { - allow_all(&mut f) + let calls = match policy { + 0 => None, + 1 => Some(allow_all(&mut f)), + _ => Some(deny_receive(&mut f, DENIED, |_| true)), }; feed( &mut f, @@ -1761,14 +1783,13 @@ fn receive_core_cooked_pointer_unchecked() { 0x3579, ); let streams = [DENIED, ALLOWED].map(|client| f.drain(client)); - (streams, trace("cooked pointer", &calls)) + (streams, calls.map(|calls| trace("cooked pointer", &calls))) }; - let (plain, _) = run(false); - let (denied, seen) = run(true); - assert_eq!( - denied, plain, - "cooked motion and ButtonPress arrive unchanged" - ); + let (plain, _) = run(0); + let (allowed, allow_seen) = run(1); + let (denied, seen) = run(2); + let (seen, allow_seen) = (seen.unwrap(), allow_seen.unwrap()); + assert_eq!(allowed, plain, "allow-all changes no bytes"); let xi2_types: Vec = split_frames(&plain[0], ClientByteOrder::BigEndian) .into_iter() .filter(|frame| frame[0] == 35) @@ -1777,10 +1798,48 @@ fn receive_core_cooked_pointer_unchecked() { assert_eq!( xi2_types, vec![6, 4], - "DENIED gets the XI2 motion and ButtonPress" + "DENIED gets the XI2 motion and ButtonPress without a policy" ); assert!(!plain[1].is_empty(), "ALLOWED got the core events"); - assert!(seen.is_empty(), "no Receive call for cooked pointer events"); + assert!(denied[0].is_empty(), "DENIED receives none of its copies"); + let denied_frames = split_frames(&denied[1], ClientByteOrder::BigEndian); + assert_eq!( + denied_frames.iter().map(|f| f[0]).collect::>(), + vec![6, 4], + "ALLOWED gains the reopened core motion before its ButtonPress" + ); + assert_eq!( + denied_frames[1], + plain[1].as_slice(), + "ALLOWED's ButtonPress frame is unchanged" + ); + let per_client = |calls: &[ExpectedReceive], client: ClientId| -> Vec { + calls + .iter() + .filter(|c| c.client == client) + .cloned() + .collect() + }; + let motion_xi2 = call(DENIED, None, CROSS_CHILD, xi2_event(6)); + let press_xi2 = call(DENIED, None, CROSS_CHILD, xi2_event(4)); + let core = |client, n| call(client, None, CROSS_CHILD, EventDescription::core(n)); + // Allow-all: DENIED's allowed master motion absorbs the core motion, so ALLOWED's motion + // is never asked; each copy that is written is asked once. + assert_eq!( + per_client(&allow_seen, DENIED), + vec![motion_xi2.clone(), press_xi2.clone()] + ); + assert_eq!(per_client(&allow_seen, ALLOWED), vec![core(ALLOWED, 4)]); + // Denied: the refused master motion neither absorbs nor shadows, so DENIED's own core + // motion and ALLOWED's core motion are asked; the slave XI2 ButtonPress once, at the write. + assert_eq!( + per_client(&seen, DENIED), + vec![motion_xi2, core(DENIED, 6), press_xi2] + ); + assert_eq!( + per_client(&seen, ALLOWED), + vec![core(ALLOWED, 6), core(ALLOWED, 4)] + ); } /// A RRSetScreenSize copy carries its own window: each receiver's three copies name the root, diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_notify_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_notify_support.rs index ee482179e..0dce86e84 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_notify_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_notify_support.rs @@ -275,6 +275,9 @@ pub(super) enum Order { Total, /// Calls grouped by client: order is checked within one client, not across clients. PerClient, + /// As `PerClient`, over the recorded calls the filter keeps. For a row whose drive + /// also makes calls this row does not pin (for example natural pointer copies). + PerClientOnly(fn(&ExpectedReceive) -> bool), } /// `(description, byte offset, bytes)` pins of a row's fields. @@ -298,6 +301,14 @@ pub(super) struct Row { pub(super) effects: fn(&NotifyFixture) -> String, } +impl Row { + /// The row compares only the calls `keep` selects, grouped by client. + pub(super) const fn only_calls(mut self, keep: fn(&ExpectedReceive) -> bool) -> Self { + self.order = Order::PerClientOnly(keep); + self + } +} + /// Splits one client's stream into frames: 32 bytes each, except GenericEvent /// (type 35), whose length in the client's byte order gives `32 + 4 * length`. pub(super) fn split_frames(bytes: &[u8], order: ClientByteOrder) -> Vec<&[u8]> { @@ -376,6 +387,12 @@ fn assert_row_trace( "{} [{mode}]: Receive calls per client", row.name ), + Order::PerClientOnly(_) => assert_eq!( + by_client(actual), + by_client(expected), + "{} [{mode}]: Receive calls per client", + row.name + ), } } @@ -402,7 +419,11 @@ fn run_row( ); let streams = clients.iter().map(|c| (*c, f.drain(*c))).collect(); let trace = calls.map_or_else(Vec::new, |calls| { - receive_trace(row.name, "policy", &calls.lock().unwrap()) + let mut trace = receive_trace(row.name, "policy", &calls.lock().unwrap()); + if let Order::PerClientOnly(keep) = row.order { + trace.retain(keep); + } + trace }); let effects = (row.effects)(&f); (f, streams, trace, effects) @@ -495,17 +516,22 @@ pub(super) fn check_row(row: &Row) { "{name}: denial changed state" ); for ((client, allowed), (_, got)) in streams.iter().zip(&denied) { - let want = if *client == NOTIFY_RECEIVER_DENIED { - let order = allow.state.clients[&client.0].byte_order; - split_frames(allowed, order) - .into_iter() - .filter(|frame| (row.describe)(&allow, order, frame).is_none()) - .flatten() - .copied() - .collect() - } else { - allowed.clone() - }; + let want = + if *client == NOTIFY_RECEIVER_DENIED && matches!(row.order, Order::PerClientOnly(_)) { + // The drive's other copies (not pinned by the row) are checked too, so the + // denied receiver gets nothing at all. + Vec::new() + } else if *client == NOTIFY_RECEIVER_DENIED { + let order = allow.state.clients[&client.0].byte_order; + split_frames(allowed, order) + .into_iter() + .filter(|frame| (row.describe)(&allow, order, frame).is_none()) + .flatten() + .copied() + .collect() + } else { + allowed.clone() + }; assert_eq!(*got, want, "{name}: client {client:?} bytes under denial"); } } From a606997669d734bbecc650dbb68020ddc5a820db Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 19:46:08 -0300 Subject: [PATCH 29/72] fix(access): review round 1 for the natural pointer walks - The slave form's route from the live target no longer goes through the memo when the slave pass starts from an earlier window: no slave copy is written along it, so asking Receive there was a phantom check. - A written copy that is not a grab attempt (the slave press route) resolves through the dispatch memo, so a slave and a master form at one window share one call. Only grab-window and grab-owner copies take a fresh check. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Sonnet 5.5 --- .../src/core_loop/pointer_fanout.rs | 26 +++- .../tests/access_pointer_input.rs | 115 +++++++++++++++++- 2 files changed, 133 insertions(+), 8 deletions(-) diff --git a/crates/yserver-core/src/core_loop/pointer_fanout.rs b/crates/yserver-core/src/core_loop/pointer_fanout.rs index aa1883755..06c9683ee 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout.rs @@ -2169,13 +2169,15 @@ fn pointer_event_fanout_to_state_inner( && owner_events_slave_route.is_none() && slave_press_delivery.is_none() && !xi2_grab_delivery; + let master_grab_decided = + master_form_decided_by_grab(state, xi_source, replay, xi2_grab_delivery); let master_form_checked = !xi2_crossing && replay_has_master_form && button_transition.master_accepted && (replay.is_some() || xi_source.slave_deviceid.is_none() || xi_source.attached_master == Some(XI2_MASTER_POINTER_DEVICE_ID)) - && !master_form_decided_by_grab(state, xi_source, replay, xi2_grab_delivery); + && !master_grab_decided; let mut xi2_slave_only_targets: Vec = Vec::new(); let mut xi2_targets = if matches!( event.kind, @@ -2199,9 +2201,11 @@ fn pointer_event_fanout_to_state_inner( xi2_evtype, xi_source.slave_deviceid, slave_press_delivery.as_ref(), + // The slave form is written along the route from `slave_pass_target`; + // a route from the live target would ask for copies never written. Some(FormChecks { memo: &mut receive, - slave: slave_form_checked, + slave: slave_form_checked && slave_pass_target == target, master: master_form_checked, }), ); @@ -2576,7 +2580,7 @@ fn pointer_event_fanout_to_state_inner( slave_press_delivery.as_ref(), Some(FormChecks { memo: &mut receive, - slave: slave_form_checked, + slave: slave_form_checked && slave_pass_target == target, master: master_form_checked, }), ); @@ -2886,9 +2890,23 @@ fn pointer_event_fanout_to_state_inner( ) } else { // `scroll_motion_only_grab` writes no bytes, so it asks nothing. + // A grab attempt (fixed window, grab owner) is a fresh check. Any other + // copy is the natural attempt, so it reuses a decision the memo holds + // for this client, window and description (a slave and a master form + // at one window share one call). + let grab_attempt = fixed_geometry.is_some() + || xi2_grab_delivery + || match form { + Xi2PointerForm::Slave => owner_events_slave_route.is_some(), + Xi2PointerForm::Master => master_grab_decided, + }; let allowed = copy_decided || scroll_motion_only_grab - || receive_allows(state, *cid, EventSubject::Window(ev_win), &events); + || if grab_attempt { + receive_allows(state, *cid, EventSubject::Window(ev_win), &events) + } else { + receive.allows(state, *cid, EventSubject::Window(ev_win), &events) + }; let extras = if allowed { fanout_event_to_clients(state, std::slice::from_ref(cid), encode) } else { diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index 5e42ea7be..d915dfdf5 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -89,6 +89,11 @@ fn register_physical_pointer(state: &mut ServerState) { /// slave pass starts from C as it does in a session (Xorg delivers slave motion /// to the window the sprite left). Nothing is selected yet, so nothing is sent. fn park_pointer(f: &mut NotifyFixture) { + park_pointer_at(f, POINTER); +} + +/// As `park_pointer`, at the root position `at`. +fn park_pointer_at(f: &mut NotifyFixture, at: (i16, i16)) { let dropped = pointer_event_fanout_to_state( &mut f.state, &mut f.backend, @@ -99,10 +104,10 @@ fn park_pointer(f: &mut NotifyFixture) { host_xid: 0, detail: 0, time: TIME, - root_x: POINTER.0, - root_y: POINTER.1, - event_x: POINTER.0, - event_y: POINTER.1, + root_x: at.0, + root_y: at.1, + event_x: at.0, + event_y: at.1, state: 0, crossing_mode: 0, child: 0, @@ -317,6 +322,108 @@ fn p4_slave_and_master_forms_share_one_check() { check_row(&P4_DENIED); } +// ---- P4b ----------------------------------------------------------------- + +/// The pointer sits on P outside C, so the slave pass starts from P while the +/// live target is C. +const OUTSIDE_C: (i16, i16) = (105, 105); + +fn setup_p4b(f: &mut NotifyFixture) { + tree(f); + park_pointer_at(f, OUTSIDE_C); + select_xi2(f, B, CHILD, DEVICEID_XTEST_POINTER, XI_MOTION); +} + +/// A slave motion moves the sprite from P into C. B selects the slave form on C +/// only, so the slave form (routed from P) has no recipient and B gets nothing, +/// in every mode. The route from the live target C writes no slave copy, so it +/// asks nothing. +const P4B: Row = Row { + name: "p4b_no_check_for_the_slave_route_from_the_live_target", + setup: setup_p4b, + drive: motion(XTEST_SLAVE), + deny: &[(B, CallKind::Xi2, CHILD)], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[], + calls: &[], + }, + denied: Expect { + frames: &[], + calls: &[], + }, +}; + +/// Mutation: the slave form's route from the live target (not the earlier +/// window) goes through the memo (`slave_form_checked` there), so B's selection +/// on C is asked although no copy of it is ever written. +#[test] +fn p4b_no_check_for_the_slave_route_from_the_live_target() { + check_row(&P4B); +} + +// ---- P4c ----------------------------------------------------------------- + +fn setup_p4c(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, B, CHILD, XI_ALL_DEVICES, XI_BUTTON_PRESS); +} + +/// Allow-all: B's slave press copy (routed by the slave press route) and its +/// master copy at C share the one check the master route made. +const P4C_ALLOWED: Row = Row { + name: "p4c_slave_press_and_master_forms_share_one_check", + setup: setup_p4c, + drive: press(XTEST_SLAVE), + deny: &[], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[ + (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), + (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + calls: &[(B, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[ + (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), + (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + calls: &[(B, CallKind::Xi2, CHILD)], + }, +}; + +/// Denied: neither form is written, and the one call is not repeated. +const P4C_DENIED: Row = Row { + name: "p4c_slave_press_and_master_forms_share_one_check", + setup: setup_p4c, + drive: press(XTEST_SLAVE), + deny: &[(B, CallKind::Xi2, CHILD)], + denied_grab: Some(&[]), + moved: &[], + allow: Expect { + frames: &[ + (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), + (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + calls: &[(B, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[], + calls: &[(B, CallKind::Xi2, CHILD)], + }, +}; + +/// Mutation: the slave press copy (not a grab attempt) takes a fresh +/// `receive_allows` instead of the dispatch memo, so B is asked twice. +#[test] +fn p4c_slave_press_and_master_forms_share_one_check() { + check_row(&P4C_ALLOWED); + check_row(&P4C_DENIED); +} + // ---- P5 ------------------------------------------------------------------ fn setup_p5(f: &mut NotifyFixture) { From bdd0d7539102c72c3105627183d13b3e2c9073a0 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 19:57:03 -0300 Subject: [PATCH 30/72] feat(access): Receive decides grabbed pointer delivery An owner-events grab's natural walk now qualifies the owner through the first protocol (XI2, XI1, core) whose copy Receive allows, and only an owner that qualifies in none lets an allowed foreign selector of any protocol reject the walk. The owner's natural copy reuses the dispatch memo; each grab-window attempt (core fallback, owner_events false, the XI2 master and slave fallbacks) is one fresh check in the grab's protocol, made before the grab mask and the via_xi2 guard, and a denial counts as delivered (dix/events.c:4388-4398). Passive activation, sync freezing and the stored press are unchanged under a denied activating copy. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Sonnet 5.5 --- .../src/core_loop/pointer_fanout.rs | 153 ++++- .../core_loop/pointer_fanout/owner_events.rs | 136 ++-- .../tests/access_pointer_input.rs | 618 +++++++++++++++++- 3 files changed, 825 insertions(+), 82 deletions(-) diff --git a/crates/yserver-core/src/core_loop/pointer_fanout.rs b/crates/yserver-core/src/core_loop/pointer_fanout.rs index 06c9683ee..430ccce31 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout.rs @@ -1464,6 +1464,7 @@ fn pointer_event_fanout_to_state_inner( mask_bit, Some(xi2_evtype(event.kind)), None, + Some(&mut receive), ) }); if let Some(route) = natural_route { @@ -1490,7 +1491,8 @@ fn pointer_event_fanout_to_state_inner( target, top_level_id_opt.unwrap_or(ROOT_WINDOW), is_replay, - true, + // The route asked Receive for this copy: the write reuses it. + false, ); merge_dropped(&mut dropped, extras); handled_core_via_grab = true; @@ -1501,7 +1503,10 @@ fn pointer_event_fanout_to_state_inner( handled_core_via_grab = true; } OwnerEventsRoute::Fallback => { - if !via_xi2 && grab_event_mask & mask_bit != 0 { + if !via_xi2 + && core_grab_window_allows(state, grab_client, grab_window, event.kind) + && grab_event_mask & mask_bit != 0 + { let event_x = clamp_grab_coord(event.root_x, gx); let event_y = clamp_grab_coord(event.root_y, gy); let focus = state.crossing_has_focus(grab_window); @@ -1522,7 +1527,7 @@ fn pointer_event_fanout_to_state_inner( target, top_level_id_opt.unwrap_or(ROOT_WINDOW), is_replay, - true, + false, ); merge_dropped(&mut dropped, extras); } @@ -1534,7 +1539,10 @@ fn pointer_event_fanout_to_state_inner( PointerEventKind::EnterNotify | PointerEventKind::LeaveNotify ) { // owner_events=false goes directly to the grab window. - if !via_xi2 && grab_event_mask & mask_bit != 0 { + if !via_xi2 + && core_grab_window_allows(state, grab_client, grab_window, event.kind) + && grab_event_mask & mask_bit != 0 + { let event_x = clamp_grab_coord(event.root_x, gx); let event_y = clamp_grab_coord(event.root_y, gy); let focus = state.crossing_has_focus(grab_window); @@ -1553,7 +1561,7 @@ fn pointer_event_fanout_to_state_inner( target, top_level_id_opt.unwrap_or(ROOT_WINDOW), is_replay, - true, + false, ); merge_dropped(&mut dropped, extras); } @@ -2040,6 +2048,7 @@ fn pointer_event_fanout_to_state_inner( pointer_mask_bit(event.kind, event.state), Some(xi2_evtype(event.kind)), xi1_class, + Some(&mut receive), ) } else { OwnerEventsRoute::Fallback @@ -2258,6 +2267,11 @@ fn pointer_event_fanout_to_state_inner( OwnerEventsRoute, )> = None; let mut xi2_slave_grab_window_target: Option<(ClientId, ResourceId, i16, i16)> = None; + // The grab-window attempts' fresh Receive results, made before the grab + // mask (`dix/events.c:4388-4398`); the writer reuses them. + let mut xi2_grab_window_allowed = true; + let mut xi2_slave_grab_window_allowed = true; + let xi2_grab_description = crate::xinput::xi2_event_description(xi2_evtype); // Physical wheel input arrives as button 4–7 transitions, then this // fanout adds the XI2 Motion carrying the scroll valuator. Xorg turns a @@ -2306,6 +2320,7 @@ fn pointer_event_fanout_to_state_inner( pointer_mask_bit(event.kind, event.state), Some(xi2_evtype), None, + Some(&mut receive), ) } else { OwnerEventsRoute::Fallback @@ -2320,18 +2335,27 @@ fn pointer_event_fanout_to_state_inner( xi2_targets.push(grab_client); } } - OwnerEventsRoute::Fallback if via_xi2 && xi2_grab_accepts_event(grab.xi2_mask) => { - if !xi2_targets.contains(&grab_client) { - xi2_targets.push(grab_client); - } - xi2_scroll_master_grab_motion_only = - xi2_scroll_button_press && grab.xi2_mask & (1_u64 << xi2_evtype) == 0; - xi2_grab_window_target = Some(( + OwnerEventsRoute::Fallback if via_xi2 => { + // The grab window's attempt: one fresh check before the mask. + xi2_grab_window_allowed = receive_allows( + state, grab_client, - grab_window, - clamp_grab_coord(event.root_x, gx), - clamp_grab_coord(event.root_y, gy), - )); + EventSubject::Window(grab_window), + &EventBatch::new(std::slice::from_ref(&xi2_grab_description)), + ); + if xi2_grab_accepts_event(grab.xi2_mask) { + if !xi2_targets.contains(&grab_client) { + xi2_targets.push(grab_client); + } + xi2_scroll_master_grab_motion_only = + xi2_scroll_button_press && grab.xi2_mask & (1_u64 << xi2_evtype) == 0; + xi2_grab_window_target = Some(( + grab_client, + grab_window, + clamp_grab_coord(event.root_x, gx), + clamp_grab_coord(event.root_y, gy), + )); + } } _ => {} } @@ -2350,21 +2374,30 @@ fn pointer_event_fanout_to_state_inner( xi2_targets.push(grab.owner); } } - OwnerEventsRoute::Fallback if grab.via_xi2 && xi2_grab_accepts_event(grab.xi2_mask) => { - if !xi2_targets.contains(&grab.owner) { - xi2_targets.push(grab.owner); - } + OwnerEventsRoute::Fallback if grab.via_xi2 => { let (grab_window, grab_client, gx, gy, ..) = active_pointer_grab_target(state, grab) .expect("resolved slave grab keeps its owner and window"); - xi2_slave_grab_window_target = Some(( + // The grab window's attempt: one fresh check before the mask. + xi2_slave_grab_window_allowed = receive_allows( + state, grab_client, - grab_window, - clamp_grab_coord(event.root_x, gx), - clamp_grab_coord(event.root_y, gy), - )); - xi2_scroll_slave_grab_motion_only = - xi2_scroll_button_press && grab.xi2_mask & (1_u64 << xi2_evtype) == 0; + EventSubject::Window(grab_window), + &EventBatch::new(std::slice::from_ref(&xi2_grab_description)), + ); + if xi2_grab_accepts_event(grab.xi2_mask) { + if !xi2_targets.contains(&grab.owner) { + xi2_targets.push(grab.owner); + } + xi2_slave_grab_window_target = Some(( + grab_client, + grab_window, + clamp_grab_coord(event.root_x, gx), + clamp_grab_coord(event.root_y, gy), + )); + xi2_scroll_slave_grab_motion_only = + xi2_scroll_button_press && grab.xi2_mask & (1_u64 << xi2_evtype) == 0; + } } _ => {} } @@ -2894,15 +2927,43 @@ fn pointer_event_fanout_to_state_inner( // copy is the natural attempt, so it reuses a decision the memo holds // for this client, window and description (a slave and a master form // at one window share one call). - let grab_attempt = fixed_geometry.is_some() - || xi2_grab_delivery - || match form { - Xi2PointerForm::Slave => owner_events_slave_route.is_some(), - Xi2PointerForm::Master => master_grab_decided, - }; + // The owner's natural copy is the route's decision (the memo), and the + // grab-window fallback was checked fresh where the route resolved. + let owner_route = match form { + Xi2PointerForm::Slave => owner_events_slave_route, + Xi2PointerForm::Master => owner_events_master_route, + } + .filter(|(grab, _)| grab.owner == *cid); + let natural_owner_copy = matches!( + owner_route, + Some(( + _, + OwnerEventsRoute::Natural { + protocol: OwnerProtocol::Xi2, + .. + } + )) + ); + let grab_window_result = match form { + Xi2PointerForm::Slave => xi2_slave_grab_window_target + .filter(|(owner, ..)| owner == cid) + .map(|_| xi2_slave_grab_window_allowed), + Xi2PointerForm::Master => xi2_grab_window_target + .filter(|(owner, ..)| owner == cid) + .map(|_| xi2_grab_window_allowed), + }; + let grab_attempt = !natural_owner_copy + && (fixed_geometry.is_some() + || xi2_grab_delivery + || match form { + Xi2PointerForm::Slave => owner_events_slave_route.is_some(), + Xi2PointerForm::Master => master_grab_decided, + }); let allowed = copy_decided || scroll_motion_only_grab - || if grab_attempt { + || if let Some(result) = grab_window_result { + result + } else if grab_attempt { receive_allows(state, *cid, EventSubject::Window(ev_win), &events) } else { receive.allows(state, *cid, EventSubject::Window(ev_win), &events) @@ -4153,6 +4214,30 @@ fn master_form_decided_by_grab( .is_some() } +/// A core grab's grab-window attempt: one fresh Receive check for the grab +/// owner's core copy, made before the grab mask and the `via_xi2` guard +/// (`dix/events.c:4388-4398`). A denial counts as delivered: the caller still +/// consumes the event, and the write that follows an allowed result is +/// unchecked. A grab owner that is gone is not asked and gets nothing. +fn core_grab_window_allows( + state: &ServerState, + owner: ClientId, + grab_window: ResourceId, + kind: PointerEventKind, +) -> bool { + if !state.policies_installed() { + return true; + } + let description = EventDescription::core(core_pointer_event_type(kind)); + state.clients.contains_key(&owner.0) + && receive_allows( + state, + owner, + EventSubject::Window(grab_window), + &EventBatch::new(std::slice::from_ref(&description)), + ) +} + struct DeferredCorePointerEvent { target: ClientId, window: ResourceId, diff --git a/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs b/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs index 1783158d2..dcca985b0 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs @@ -1,7 +1,7 @@ //! Grab-owner selection, XI1 selection order, and fallback routing. use super::{ - ClientId, PointerReplay, PointerXiSource, ResourceId, ServerState, + ClientId, PointerReplay, PointerXiSource, ReceiveMemo, ResourceId, ServerState, XI2_MASTER_POINTER_DEVICE_ID, Xi2PointerForm, clamp_grab_coord, xi2_child_toward, xi2_form_targets_for_source, xi2_route_window_for_source, }; @@ -139,6 +139,7 @@ pub(super) fn xi2_motion_targets_for_source( 0, Some(XI_MOTION), None, + None, ) } else { OwnerEventsRoute::Fallback @@ -262,6 +263,7 @@ pub(super) fn xi1_selection_filter_for_slave_grab( 0, Some(evtype), Some(class), + None, ) } else { OwnerEventsRoute::Fallback @@ -382,10 +384,39 @@ pub(super) enum OwnerEventsRoute { Fallback, } +/// The XI1 copy of one device event as Receive sees it: its description, and +/// for `DeviceMotionNotify` the `DeviceValuator` continuation, one batch +/// (`dix/eventconvert.c:369`). `evcode` is the absolute XI1 event code. +pub(super) fn xi1_batch(evcode: u8) -> Vec { + let offset = evcode.saturating_sub(crate::server::XI_FIRST_EVENT); + let mut batch = vec![crate::xinput::xi1_event_description(offset)]; + if offset == crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET { + batch.push(crate::xinput::xi1_event_description( + crate::xinput::XI_DEVICE_VALUATOR_OFFSET, + )); + } + batch +} + +/// One protocol's selectors at a window, with the batch their copy is checked as. +struct RouteLeg { + protocol: OwnerProtocol, + selectors: Vec, + batch: Vec, +} + /// Resolve one owner-events attempt at each window in Xorg's protocol /// order: XI2, XI1, then core (`../xserver/dix/events.c:2279-2313, /// 2895-2930`). A rejected selector blocks propagation only after all /// protocols have had an attempt on that window. +/// +/// With a memo, a selection counts only if its copy is allowed. At each +/// window the owner qualifies through the first protocol it selected whose +/// copy is allowed; only if it qualifies in none are the foreign selectors of +/// every protocol evaluated (no short-circuit), and any allowed one rejects +/// the walk. A denied copy is a non-delivery: it neither qualifies the owner +/// nor rejects. The core copy's event code is the XI2 event type (4, 5, 6 are +/// shared); a caller with no `xi2_evtype` has no core leg to check. pub(super) fn owner_events_route( state: &ServerState, form: Xi2PointerForm, @@ -397,64 +428,77 @@ pub(super) fn owner_events_route( core_mask: u32, xi2_evtype: Option, xi1_mask: Option, + mut receive: Option<&mut ReceiveMemo>, ) -> OwnerEventsRoute { let mut current = start; let mut x = start_x; let mut y = start_y; let mut child: Option = None; for _ in 0..256 { - let mut rejected = false; + let mut legs: Vec = Vec::with_capacity(3); if let Some(evtype) = xi2_evtype { - let subscribers = - xi2_form_targets_for_source(state, current, form, evtype, slave_deviceid, None); - if !subscribers.is_empty() { - if subscribers.contains(&grab_client) { - return OwnerEventsRoute::Natural { - window: current, - x, - y, - child: child.unwrap_or(ResourceId(0)), - protocol: OwnerProtocol::Xi2, - }; - } - rejected = true; - } + legs.push(RouteLeg { + protocol: OwnerProtocol::Xi2, + selectors: xi2_form_targets_for_source( + state, + current, + form, + evtype, + slave_deviceid, + None, + ), + batch: vec![crate::xinput::xi2_event_description(evtype)], + }); } if form == Xi2PointerForm::Slave && let (Some(device_id), Some(class)) = (slave_deviceid, xi1_mask) + && (class >> 8) as u16 == device_id { - let class_device = (class >> 8) as u16; - if class_device == device_id { - let subscribers = - xi1_window_selectors(state, current, (class & 0xff) as u8, device_id); - if !subscribers.is_empty() { - if subscribers.contains(&grab_client) { - return OwnerEventsRoute::Natural { - window: current, - x, - y, - child: child.unwrap_or(ResourceId(0)), - protocol: OwnerProtocol::Xi1, - }; - } - rejected = true; - } - } + let evcode = (class & 0xff) as u8; + legs.push(RouteLeg { + protocol: OwnerProtocol::Xi1, + selectors: xi1_window_selectors(state, current, evcode, device_id), + batch: xi1_batch(evcode), + }); } if form == Xi2PointerForm::Master && core_mask != 0 { - let subscribers = - crate::core_loop::fanout::subscribers_by_id(state, current, core_mask); - if !subscribers.is_empty() { - if subscribers.contains(&grab_client) { - return OwnerEventsRoute::Natural { - window: current, - x, - y, - child: child.unwrap_or(ResourceId(0)), - protocol: OwnerProtocol::Core, - }; - } - rejected = true; + legs.push(RouteLeg { + protocol: OwnerProtocol::Core, + selectors: crate::core_loop::fanout::subscribers_by_id(state, current, core_mask), + batch: xi2_evtype + .and_then(|evtype| u8::try_from(evtype).ok()) + .map(crate::access::EventDescription::core) + .into_iter() + .collect(), + }); + } + let mut allowed = + |client: ClientId, batch: &[crate::access::EventDescription]| match receive + .as_deref_mut() + { + Some(memo) if !batch.is_empty() => memo.allows( + state, + client, + crate::access::EventSubject::Window(current), + &crate::access::EventBatch::new(batch), + ), + _ => true, + }; + for leg in &legs { + if leg.selectors.contains(&grab_client) && allowed(grab_client, &leg.batch) { + return OwnerEventsRoute::Natural { + window: current, + x, + y, + child: child.unwrap_or(ResourceId(0)), + protocol: leg.protocol, + }; + } + } + let mut rejected = false; + for leg in &legs { + for client in leg.selectors.iter().filter(|c| **c != grab_client) { + rejected |= allowed(*client, &leg.batch); } } if rejected { diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index d915dfdf5..5bcd025eb 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -6,13 +6,19 @@ //! `check_row`, so the literal frames and Receive calls per client are pinned. //! The mutation each test must kill is named in its comment. -use super::{access_input_support::*, access_notify_support::NotifyFixture}; +use super::{ + access_input_support::*, + access_notify_support::{DENY, NotifyFixture}, + extensions::ExtensionHook, +}; use crate::{ + access::{Decision, EventSubject}, core_loop::{DeviceInfo, InputOrigin, pointer_fanout::pointer_event_fanout_to_state}, host_x11::{HostPointerEvent, HostXidMap, PointerEventKind}, - server::ServerState, + server::{QueuedInputEvent, ServerState, Xi1SyncState}, xinput::{DEVICEID_MASTER_POINTER, DEVICEID_XTEST_POINTER, InputCapabilities, InputSourceId}, }; +use yserver_protocol::x11::{ClientId, ResourceId}; /// Core ButtonPressMask and MotionNotify mask bits. const CORE_BUTTON_PRESS: u32 = 1 << 2; @@ -694,3 +700,611 @@ const P7: Row = Row { fn p7_no_check_for_a_form_not_emitted() { check_row(&P7); } + +// ---- Task 2: grabs and passive activation --------------------------------- +// +// O is client A, the foreign selector F is client B. Core grabs go through +// `GrabPointer`/`GrabButton`, XI2 grabs through `XIGrabDevice`/ +// `XIPassiveGrabDevice`. The grab window G is the root unless a row says +// otherwise: it is on no selection of the rows below. + +const CORE_GRAB_POINTER: u8 = 26; +const CORE_GRAB_BUTTON: u8 = 28; +const XI_PASSIVE_GRAB_DEVICE: u8 = 54; + +/// `GrabPointer` by `owner` on `window`, asynchronous, with the core event mask. +fn grab_pointer(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: bool, mask: u32) { + let mut body = Vec::with_capacity(20); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&(mask as u16).to_le_bytes()); + body.extend_from_slice(&[1, 1]); // async pointer, async keyboard + body.extend_from_slice(&[0; 12]); // no confinement, no cursor, CurrentTime + let bytes = send_with_reply(f, owner, CORE_GRAB_POINTER, u8::from(owner_events), &body); + let reply = &bytes[bytes.len() - 32..]; + assert_eq!((reply[0], reply[1]), (1, 0), "GrabPointer replies Success"); +} + +/// `GrabButton` of button 1 by `owner` on `window` for ButtonPress|Release, +/// with any modifier and the given pointer mode (0 = sync). +fn grab_button(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: bool, sync: bool) { + let mut body = Vec::with_capacity(20); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&0x000c_u16.to_le_bytes()); + body.extend_from_slice(&[u8::from(!sync), 1]); // pointer mode (0 sync), async keyboard + body.extend_from_slice(&[0; 8]); // no confinement, no cursor + body.extend_from_slice(&[1, 0]); // button 1, pad + body.extend_from_slice(&0x8000_u16.to_le_bytes()); // AnyModifier + send(f, owner, CORE_GRAB_BUTTON, u8::from(owner_events), &body); +} + +/// `XIGrabDevice` of the master pointer by `owner` on `window`. +fn xi_grab_master_pointer( + f: &mut NotifyFixture, + owner: u32, + window: u32, + owner_events: bool, + mask: u32, +) { + grab_keyboard_device( + f, + owner, + DEVICEID_MASTER_POINTER, + window, + owner_events, + mask, + ); +} + +/// `XIPassiveGrabDevice` of button 1 on `device` by `owner` on `window`, any +/// modifier, with the XI2 event mask and the given mode (0 = sync). +fn xi_passive_grab_button( + f: &mut NotifyFixture, + owner: u32, + device: u16, + window: u32, + sync: bool, + mask: u32, +) { + let mut body = Vec::with_capacity(36); + body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&0_u32.to_le_bytes()); // no cursor + body.extend_from_slice(&1_u32.to_le_bytes()); // button 1 + body.extend_from_slice(&device.to_le_bytes()); + body.extend_from_slice(&1_u16.to_le_bytes()); // one modifier + body.extend_from_slice(&1_u16.to_le_bytes()); // one mask word + body.extend_from_slice(&[0, u8::from(!sync), 1, 0]); // Button, mode, async paired, not owner_events + body.extend_from_slice(&0_u16.to_le_bytes()); // pad + body.extend_from_slice(&mask.to_le_bytes()); + body.extend_from_slice(&0x8000_0000_u32.to_le_bytes()); // XIAnyModifier + send_with_reply(f, owner, XI_MAJOR, XI_PASSIVE_GRAB_DEVICE, &body); +} + +/// The literal frame the grab-window fallback writes to A: event window the +/// root, child its child toward the pointer (P), coordinates the root's. +const AT_ROOT: Moved = Moved { + client: A, + window: ROOT, + child: FOCUS, + event: POINTER, +}; + +// ---- P8 ------------------------------------------------------------------ + +fn setup_p8(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, CHILD, CORE_BUTTON_PRESS); + select_core(f, A, FOCUS, CORE_BUTTON_PRESS); + grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); +} + +const P8: Row = Row { + name: "p8_denied_owner_copy_continues_the_natural_walk", + setup: setup_p8, + drive: press(XTEST_MASTER), + deny: &[(A, CallKind::Core, CHILD)], + denied_grab: None, + moved: &[Moved { + client: A, + window: FOCUS, + child: CHILD, + event: P_EVENT, + }], + allow: Expect { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Core, FOCUS)], + calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + }, +}; + +/// Mutation: the owner qualifies by selection (the route returns C although the +/// copy there is denied, so nothing is written), or the natural core write asks +/// again (a second call for A at C when allowed). +#[test] +fn p8_denied_owner_copy_continues_the_natural_walk() { + check_row(&P8); +} + +// ---- P9 ------------------------------------------------------------------ + +/// O selects the master XI2 press on C, F selects the core press on C (a core +/// ButtonPress selection is exclusive per window, so the two cannot both be core). +fn setup_p9(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + // A also selects on P: a walk the denial did not reject would end there. + select_xi2(f, A, FOCUS, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + select_core(f, B, CHILD, CORE_BUTTON_PRESS); + grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); +} + +const P9: Row = Row { + name: "p9_denied_owner_with_allowed_foreign_falls_back", + setup: setup_p9, + drive: press(XTEST_MASTER), + deny: &[(A, CallKind::Xi2, CHILD)], + denied_grab: None, + moved: &[AT_ROOT], + allow: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Core, ROOT)], + calls: &[ + (A, CallKind::Xi2, CHILD), + (B, CallKind::Core, CHILD), + (A, CallKind::Core, ROOT), + ], + }, +}; + +/// Mutation: the denied owner keeps walking (or is dropped) although an allowed +/// foreign selector rejects the walk, so the grab window gets no copy. +#[test] +fn p9_denied_owner_with_allowed_foreign_falls_back() { + check_row(&P9); +} + +// ---- P10 ----------------------------------------------------------------- + +fn setup_p10(f: &mut NotifyFixture) { + tree(f); + select_core(f, B, CHILD, CORE_BUTTON_PRESS); + select_core(f, A, FOCUS, CORE_BUTTON_PRESS); + grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); +} + +const P10: Row = Row { + name: "p10_denied_foreign_selector_does_not_reject", + setup: setup_p10, + drive: press(XTEST_MASTER), + deny: &[(B, CallKind::Core, CHILD)], + denied_grab: None, + moved: &[Moved { + client: A, + window: FOCUS, + child: CHILD, + event: P_EVENT, + }], + allow: Expect { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, ROOT)], + }, + denied: Expect { + frames: &[(A, Kind::Core, FOCUS)], + calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + }, +}; + +/// Mutation: a foreign selector rejects the walk by selection (the denied +/// selector at C sends A to the grab window instead of on to P). +#[test] +fn p10_denied_foreign_selector_does_not_reject() { + check_row(&P10); +} + +// ---- P11 ----------------------------------------------------------------- + +fn setup_p11(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + select_core(f, A, CHILD, CORE_BUTTON_PRESS); + grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); +} + +const P11: Row = Row { + name: "p11_owner_qualifies_in_a_later_protocol", + setup: setup_p11, + drive: press(XTEST_MASTER), + deny: &[(A, CallKind::Core, CHILD)], + denied_grab: None, + moved: &[AT_ROOT], + allow: Expect { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Core, ROOT)], + calls: &[ + (A, CallKind::Core, CHILD), + (B, CallKind::Xi2, CHILD), + (A, CallKind::Core, ROOT), + ], + }, +}; + +/// A selects the master XI2 press (denied) and the core press (allowed) on C: +/// it qualifies through the later protocol. +fn setup_p11_own_protocols(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + select_core(f, A, CHILD, CORE_BUTTON_PRESS); + grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); +} + +const P11_OWN_PROTOCOLS: Row = Row { + name: "p11_owner_qualifies_in_a_later_protocol", + setup: setup_p11_own_protocols, + drive: press(XTEST_MASTER), + deny: &[(A, CallKind::Xi2, CHILD)], + denied_grab: None, + moved: &[Moved { + client: A, + window: CHILD, + child: 0, + event: C_EVENT, + }], + allow: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], + }, +}; + +/// Mutation: the foreign selectors are evaluated before the owner (an extra +/// call for B when A qualifies), F's master XI2 copy is asked under the +/// grab-owned master form (a call for B in the allowed run), or the owner +/// qualifies only through the first protocol it selected (the second row falls +/// back to the grab window). +#[test] +fn p11_owner_qualifies_in_a_later_protocol() { + check_row(&P11); + check_row(&P11_OWN_PROTOCOLS); +} + +// ---- P12 ----------------------------------------------------------------- + +fn setup_p12(f: &mut NotifyFixture) { + tree(f); + select_core(f, B, CHILD, CORE_BUTTON_PRESS); + grab_pointer(f, A, ROOT, false, CORE_BUTTON_PRESS); +} + +const P12: Row = Row { + name: "p12_grab_window_denial_counts_as_delivered", + setup: setup_p12, + drive: press(XTEST_MASTER), + deny: &[(A, CallKind::Core, ROOT)], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(A, CallKind::Core, ROOT)], + }, + denied: Expect { + frames: &[], + calls: &[(A, CallKind::Core, ROOT)], + }, +}; + +/// The grab mask lacks ButtonPress: no frame in any mode, but the check still +/// comes first, so the trace has the call at G. +fn setup_p12_mask(f: &mut NotifyFixture) { + tree(f); + select_core(f, B, CHILD, CORE_BUTTON_PRESS); + grab_pointer(f, A, ROOT, false, CORE_MOTION); +} + +const P12_MASK: Row = Row { + name: "p12_grab_window_denial_counts_as_delivered", + setup: setup_p12_mask, + drive: press(XTEST_MASTER), + deny: &[(A, CallKind::Core, ROOT)], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[], + calls: &[(A, CallKind::Core, ROOT)], + }, + denied: Expect { + frames: &[], + calls: &[(A, CallKind::Core, ROOT)], + }, +}; + +/// An XI2 master grab with owner_events false: the grab-window copy is the +/// only call; F's master XI2 selector on C is never asked. +fn setup_p12_xi2(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + xi_grab_master_pointer(f, A, ROOT, false, XI_BUTTON_PRESS); +} + +const P12_XI2: Row = Row { + name: "p12_grab_window_denial_counts_as_delivered", + setup: setup_p12_xi2, + drive: press(XTEST_MASTER), + deny: &[(A, CallKind::Xi2, ROOT)], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], + calls: &[(A, CallKind::Xi2, ROOT)], + }, + denied: Expect { + frames: &[], + calls: &[(A, CallKind::Xi2, ROOT)], + }, +}; + +/// Mutation: the check moves behind the grab mask (second row has no call), the +/// denial is not a delivery (C's selectors get the press), or the XI2 grab asks +/// F's selector (a call for B). +#[test] +fn p12_grab_window_denial_counts_as_delivered() { + check_row(&P12); + check_row(&P12_MASK); + check_row(&P12_XI2); +} + +// ---- P13 ----------------------------------------------------------------- + +fn setup_p13(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + xi_grab_master_pointer(f, A, ROOT, true, XI_BUTTON_PRESS); +} + +const P13: Row = Row { + name: "p13_xi2_owner_events_fallback_is_fresh", + setup: setup_p13, + drive: press(XTEST_MASTER), + deny: &[(A, CallKind::Xi2, CHILD)], + denied_grab: None, + moved: &[AT_ROOT], + allow: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], + calls: &[ + (A, CallKind::Xi2, CHILD), + (B, CallKind::Xi2, CHILD), + (A, CallKind::Xi2, ROOT), + ], + }, +}; + +/// The grab window is C itself: the fallback is a distinct attempt, so A is +/// asked a second time at C (and denied again), not served from the memo. +fn setup_p13_same_window(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + xi_grab_master_pointer(f, A, CHILD, true, XI_BUTTON_PRESS); +} + +const P13_SAME_WINDOW: Row = Row { + name: "p13_xi2_owner_events_fallback_is_fresh", + setup: setup_p13_same_window, + drive: press(XTEST_MASTER), + deny: &[(A, CallKind::Xi2, CHILD)], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[], + calls: &[ + (A, CallKind::Xi2, CHILD), + (B, CallKind::Xi2, CHILD), + (A, CallKind::Xi2, CHILD), + ], + }, +}; + +/// Mutation: the XI2 owner qualifies by selection (nothing is written at C), +/// the natural XI2 write asks again (two calls for A at C when allowed), or the +/// fallback reuses the memo for G (one call for A at C in the same-window row). +#[test] +fn p13_xi2_owner_events_fallback_is_fresh() { + check_row(&P13); + check_row(&P13_SAME_WINDOW); +} + +// ---- P14 ----------------------------------------------------------------- + +/// What one denied activating press left behind: the Receive calls +/// (client, event window, XI2 or core), the bytes each client got, and the +/// fixture to inspect the grab, freeze and queue. +struct Activation { + f: NotifyFixture, + calls: Vec<(u32, u32, bool)>, +} + +/// Runs the activating press of `origin` with every Receive call of `client` +/// at `window` denied, after `setup`. +fn activate_denied( + setup: fn(&mut NotifyFixture), + origin: InputOrigin, + client: u32, + window: u32, +) -> Activation { + let mut f = NotifyFixture::new(); + setup(&mut f); + for id in [SEND_CLIENT, A, B] { + f.drain(ClientId(id)); + } + let seen = f.install_policy(move |_, call| { + let denied = call.hook == ExtensionHook::Receive + && call.client.0 == client + && call.receive == Some(EventSubject::Window(ResourceId(window))); + if denied { DENY } else { Decision::Allow } + }); + drive(&mut f, press(origin)); + let calls = seen + .lock() + .unwrap() + .iter() + .filter(|call| call.hook == ExtensionHook::Receive) + .map(|call| { + let Some(EventSubject::Window(subject)) = call.receive else { + panic!("pointer Receive subject {:?}", call.receive); + }; + let events = call.events.as_deref().expect("Receive batch"); + (call.client.0, subject.0, events[0].extension.is_some()) + }) + .collect(); + Activation { f, calls } +} + +impl Activation { + /// No client was sent a byte, in particular nobody got the denied press. + fn assert_no_bytes(&mut self) { + for id in [SEND_CLIENT, A, B] { + assert_eq!(self.f.drain(ClientId(id)), Vec::::new(), "client {id}"); + } + } + + /// The sync freeze of `device` holds the press: state and stored event. + fn assert_frozen_with_press(&self, device: u16) { + let freeze = self.f.state.xi1_frozen.get(&device).expect("freeze entry"); + assert_eq!(freeze.state, Xi1SyncState::FrozenWithEvent); + assert!( + matches!(&freeze.stored, Some(QueuedInputEvent::HostPointer(event)) + if event.kind == PointerEventKind::ButtonPress), + "the press is stored: {:?}", + freeze.stored + ); + } + + /// The devices and shape of the queued events, in order. + fn queued(&self) -> Vec<(u16, &'static str)> { + self.f + .state + .sync_pending + .iter() + .map(|pending| { + let shape = match &pending.event { + QueuedInputEvent::HostPointer(_) => "HostPointer", + QueuedInputEvent::HostPointerMaster(..) => "HostPointerMaster", + _ => "other", + }; + (pending.device, shape) + }) + .collect() + } +} + +fn setup_p14_core(f: &mut NotifyFixture) { + tree(f); + grab_button(f, A, ROOT, false, true); +} + +/// A sync `GrabButton` on G: the activating press is denied to its owner, and +/// the grab still activates, freezes and stores the press. Mutation (all three +/// p14 tests): the denial skips the activation, the freeze or the stored press +/// (a `delivered` gate on the freeze), or a second owner call is made, or the +/// unchecked owner write under `xi2_grab_delivery` delivers the denied copy. +#[test] +fn p14_denied_activating_press_still_activates_and_freezes() { + let mut run = activate_denied(setup_p14_core, XTEST_MASTER, A, ROOT); + assert_eq!(run.calls, vec![(A, ROOT, false)], "one fresh check at G"); + run.assert_no_bytes(); + let grab = run.f.state.active_pointer_grab.expect("the grab activated"); + assert_eq!( + (grab.owner.0, grab.grab_window.0, grab.passive), + (A, ROOT, true) + ); + run.assert_frozen_with_press(DEVICEID_MASTER_POINTER); + follow_with_motion(&mut run, XTEST_MASTER); + assert_eq!(run.queued(), vec![(DEVICEID_MASTER_POINTER, "HostPointer")]); +} + +fn setup_p14_xi2_master_from_slave(f: &mut NotifyFixture) { + tree(f); + xi_passive_grab_button(f, A, DEVICEID_MASTER_POINTER, ROOT, true, XI_BUTTON_PRESS); +} + +fn setup_p14_xi2_master_origin(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + xi_passive_grab_button(f, A, DEVICEID_MASTER_POINTER, ROOT, true, XI_BUTTON_PRESS); +} + +/// The motion that follows the activating press, from `origin`. +fn follow_with_motion(run: &mut Activation, origin: InputOrigin) { + drive( + &mut run.f, + Drive::Pointer { + origin, + kind: PointerEventKind::MotionNotify, + button: 0, + to: MOTION_TO, + delta: (5, 5), + }, + ); + run.assert_no_bytes(); +} + +/// A sync `XIPassiveGrabDevice` on the master from an attached slave origin: +/// A's copy on G is denied, nobody else gets the press, and the grab still +/// freezes with the press stored. The next motion delivers its slave part and +/// defers the master part behind the freeze. +#[test] +fn p14_denied_xi2_activating_press_still_freezes_from_a_slave_origin() { + let mut run = activate_denied(setup_p14_xi2_master_from_slave, XTEST_SLAVE, A, ROOT); + assert_eq!(run.calls, vec![(A, ROOT, true)], "one fresh XI2 check at G"); + run.assert_no_bytes(); + let grab = run.f.state.active_pointer_grab.expect("the grab activated"); + assert_eq!( + (grab.owner.0, grab.grab_window.0, grab.passive, grab.via_xi2), + (A, ROOT, true, true) + ); + run.assert_frozen_with_press(DEVICEID_MASTER_POINTER); + follow_with_motion(&mut run, XTEST_SLAVE); + assert_eq!( + run.queued(), + vec![(DEVICEID_MASTER_POINTER, "HostPointerMaster")] + ); +} + +/// The same grab from a master origin (`xi2_grab_delivery`): A also selects the +/// master XI2 press on C, which is the window its copy is routed to. Denying +/// that copy writes nothing, asks once, and still freezes with the press stored. +#[test] +fn p14_denied_xi2_activating_press_from_a_master_origin_still_freezes() { + let mut run = activate_denied(setup_p14_xi2_master_origin, XTEST_MASTER, A, CHILD); + assert_eq!(run.calls, vec![(A, CHILD, true)], "one XI2 check, at C"); + run.assert_no_bytes(); + assert!( + run.f + .state + .active_pointer_grab + .is_some_and(|grab| grab.passive) + ); + run.assert_frozen_with_press(DEVICEID_MASTER_POINTER); + follow_with_motion(&mut run, XTEST_MASTER); + assert_eq!(run.queued(), vec![(DEVICEID_MASTER_POINTER, "HostPointer")]); +} From 573717630d3f664cf2ba20b4656183415def8605 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 20:08:35 -0300 Subject: [PATCH 31/72] fix(access): review round 1 for grabbed pointer delivery The master and slave emitted-form predicates are computed once and gate the XI2 route memo and the grab-window fallback check, replacing the duplicated master_form_written/master_form_checked predicate. The XI2 route in an activation dispatch leaves the core leg selection-only, since the core grab block did not route it. One grab_window_allows helper serves the core and XI2 grab-window checks. Tests cover the deferred master part, the async activation, and the core same-window fallback. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Sonnet 5.5 --- .../src/core_loop/pointer_fanout.rs | 95 +++++---- .../core_loop/pointer_fanout/owner_events.rs | 9 +- .../tests/access_pointer_input.rs | 194 ++++++++++++++++-- 3 files changed, 237 insertions(+), 61 deletions(-) diff --git a/crates/yserver-core/src/core_loop/pointer_fanout.rs b/crates/yserver-core/src/core_loop/pointer_fanout.rs index 430ccce31..8227ad687 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout.rs @@ -1421,6 +1421,10 @@ fn pointer_event_fanout_to_state_inner( // ── Core fanout ───────────────────────────────────────────────── let mut handled_core_via_grab = false; + // Whether the core grab block routed this dispatch's core copy (its + // `owner_events_route` asked for the core copies). An activation dispatch + // is not routed there, so its XI2 route must not ask for core copies. + let mut core_grab_routed = false; let mut deferred_core_events = Vec::new(); // Step 2 — active-grab redirection (core events only). @@ -1437,6 +1441,7 @@ fn pointer_event_fanout_to_state_inner( && let Some((grab_window, grab_client, gx, gy, owner_events, via_xi2, grab_event_mask)) = active_pointer_grab_target(state, grab) { + core_grab_routed = true; // Xorg DeliverGrabbedEvent's owner_events=true rule is NOT // "the immediate hit window is owned by the grab client". // It is "the event would normally be reported to the grab @@ -1465,6 +1470,7 @@ fn pointer_event_fanout_to_state_inner( Some(xi2_evtype(event.kind)), None, Some(&mut receive), + true, ) }); if let Some(route) = natural_route { @@ -1776,6 +1782,20 @@ fn pointer_event_fanout_to_state_inner( event.kind, PointerEventKind::EnterNotify | PointerEventKind::LeaveNotify ); + // The forms this dispatch writes, decided once. Receive is asked about a + // form's copies (route, grab-window fallback) only if the form is emitted; + // a grab that decides the master form is a further condition of the + // natural selectors, not of the form. + let master_form_emitted = !is_crossing + && replay_has_master_form + && button_transition.master_accepted + && (replay.is_some() + || xi_source.slave_deviceid.is_none() + || xi_source.attached_master == Some(XI2_MASTER_POINTER_DEVICE_ID)); + let slave_form_emitted = !is_crossing + && xi_source.slave_deviceid.is_some() + && replay_has_slave_form + && button_transition.source_accepted; if !handled_core_via_grab && button_transition.master_accepted && (top_level_id_opt.is_some() || is_crossing) @@ -1848,12 +1868,8 @@ fn pointer_event_fanout_to_state_inner( } else { (target, top_level_id) }; - let master_form_written = !is_crossing + let master_form_written = master_form_emitted && !is_replay - && replay_has_master_form - && (replay.is_some() - || xi_source.slave_deviceid.is_none() - || xi_source.attached_master == Some(XI2_MASTER_POINTER_DEVICE_ID)) && !master_form_decided_by_grab( state, xi_source, @@ -2048,7 +2064,8 @@ fn pointer_event_fanout_to_state_inner( pointer_mask_bit(event.kind, event.state), Some(xi2_evtype(event.kind)), xi1_class, - Some(&mut receive), + slave_form_emitted.then_some(&mut receive), + false, ) } else { OwnerEventsRoute::Fallback @@ -2167,26 +2184,13 @@ fn pointer_event_fanout_to_state_inner( // owner's copy is a fixed recipient, checked at the write), routes its // natural selectors by selection only. The slave press route is converted // in a later task, so its copies are checked at the write as well. - let xi2_crossing = matches!( - event.kind, - PointerEventKind::EnterNotify | PointerEventKind::LeaveNotify - ); - let slave_form_checked = !xi2_crossing - && xi_source.slave_deviceid.is_some() - && replay_has_slave_form - && button_transition.source_accepted + let slave_form_checked = slave_form_emitted && owner_events_slave_route.is_none() && slave_press_delivery.is_none() && !xi2_grab_delivery; let master_grab_decided = master_form_decided_by_grab(state, xi_source, replay, xi2_grab_delivery); - let master_form_checked = !xi2_crossing - && replay_has_master_form - && button_transition.master_accepted - && (replay.is_some() - || xi_source.slave_deviceid.is_none() - || xi_source.attached_master == Some(XI2_MASTER_POINTER_DEVICE_ID)) - && !master_grab_decided; + let master_form_checked = master_form_emitted && !master_grab_decided; let mut xi2_slave_only_targets: Vec = Vec::new(); let mut xi2_targets = if matches!( event.kind, @@ -2320,7 +2324,8 @@ fn pointer_event_fanout_to_state_inner( pointer_mask_bit(event.kind, event.state), Some(xi2_evtype), None, - Some(&mut receive), + master_form_emitted.then_some(&mut receive), + core_grab_routed, ) } else { OwnerEventsRoute::Fallback @@ -2337,12 +2342,8 @@ fn pointer_event_fanout_to_state_inner( } OwnerEventsRoute::Fallback if via_xi2 => { // The grab window's attempt: one fresh check before the mask. - xi2_grab_window_allowed = receive_allows( - state, - grab_client, - EventSubject::Window(grab_window), - &EventBatch::new(std::slice::from_ref(&xi2_grab_description)), - ); + xi2_grab_window_allowed = !master_form_emitted + || grab_window_allows(state, grab_client, grab_window, &xi2_grab_description); if xi2_grab_accepts_event(grab.xi2_mask) { if !xi2_targets.contains(&grab_client) { xi2_targets.push(grab_client); @@ -2379,12 +2380,8 @@ fn pointer_event_fanout_to_state_inner( active_pointer_grab_target(state, grab) .expect("resolved slave grab keeps its owner and window"); // The grab window's attempt: one fresh check before the mask. - xi2_slave_grab_window_allowed = receive_allows( - state, - grab_client, - EventSubject::Window(grab_window), - &EventBatch::new(std::slice::from_ref(&xi2_grab_description)), - ); + xi2_slave_grab_window_allowed = !slave_form_emitted + || grab_window_allows(state, grab_client, grab_window, &xi2_grab_description); if xi2_grab_accepts_event(grab.xi2_mask) { if !xi2_targets.contains(&grab.owner) { xi2_targets.push(grab.owner); @@ -2922,7 +2919,9 @@ fn pointer_event_fanout_to_state_inner( ), ) } else { - // `scroll_motion_only_grab` writes no bytes, so it asks nothing. + // `scroll_motion_only_grab` writes no bytes, so this write asks nothing; the grab + // window's fallback attempt was already checked, before the mask, where + // the route resolved. // A grab attempt (fixed window, grab owner) is a fresh check. Any other // copy is the natural attempt, so it reuses a decision the memo holds // for this client, window and description (a slave and a master form @@ -4214,30 +4213,44 @@ fn master_form_decided_by_grab( .is_some() } -/// A core grab's grab-window attempt: one fresh Receive check for the grab -/// owner's core copy, made before the grab mask and the `via_xi2` guard +/// A grab-window attempt: one fresh Receive check for the grab owner's copy +/// of `description`, made before the grab mask and the core interference guard /// (`dix/events.c:4388-4398`). A denial counts as delivered: the caller still /// consumes the event, and the write that follows an allowed result is /// unchecked. A grab owner that is gone is not asked and gets nothing. -fn core_grab_window_allows( +fn grab_window_allows( state: &ServerState, owner: ClientId, grab_window: ResourceId, - kind: PointerEventKind, + description: &EventDescription, ) -> bool { if !state.policies_installed() { return true; } - let description = EventDescription::core(core_pointer_event_type(kind)); state.clients.contains_key(&owner.0) && receive_allows( state, owner, EventSubject::Window(grab_window), - &EventBatch::new(std::slice::from_ref(&description)), + &EventBatch::new(std::slice::from_ref(description)), ) } +/// `grab_window_allows` for a core grab's core copy of a pointer event. +fn core_grab_window_allows( + state: &ServerState, + owner: ClientId, + grab_window: ResourceId, + kind: PointerEventKind, +) -> bool { + grab_window_allows( + state, + owner, + grab_window, + &EventDescription::core(core_pointer_event_type(kind)), + ) +} + struct DeferredCorePointerEvent { target: ClientId, window: ResourceId, diff --git a/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs b/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs index dcca985b0..2c2612689 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs @@ -140,6 +140,7 @@ pub(super) fn xi2_motion_targets_for_source( Some(XI_MOTION), None, None, + false, ) } else { OwnerEventsRoute::Fallback @@ -264,6 +265,7 @@ pub(super) fn xi1_selection_filter_for_slave_grab( Some(evtype), Some(class), None, + false, ) } else { OwnerEventsRoute::Fallback @@ -415,7 +417,8 @@ struct RouteLeg { /// copy is allowed; only if it qualifies in none are the foreign selectors of /// every protocol evaluated (no short-circuit), and any allowed one rejects /// the walk. A denied copy is a non-delivery: it neither qualifies the owner -/// nor rejects. The core copy's event code is the XI2 event type (4, 5, 6 are +/// nor rejects. `core_checked` says whether the core leg's copies are asked +/// at all. The core copy's event code is the XI2 event type (4, 5, 6 are /// shared); a caller with no `xi2_evtype` has no core leg to check. pub(super) fn owner_events_route( state: &ServerState, @@ -429,6 +432,7 @@ pub(super) fn owner_events_route( xi2_evtype: Option, xi1_mask: Option, mut receive: Option<&mut ReceiveMemo>, + core_checked: bool, ) -> OwnerEventsRoute { let mut current = start; let mut x = start_x; @@ -465,7 +469,10 @@ pub(super) fn owner_events_route( legs.push(RouteLeg { protocol: OwnerProtocol::Core, selectors: crate::core_loop::fanout::subscribers_by_id(state, current, core_mask), + // A dispatch whose core copy was not routed by the core grab + // block (an activation) leaves the core leg selection-only. batch: xi2_evtype + .filter(|_| core_checked) .and_then(|evtype| u8::try_from(evtype).ok()) .map(crate::access::EventDescription::core) .into_iter() diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index 5bcd025eb..610dcdd76 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -711,6 +711,7 @@ fn p7_no_check_for_a_form_not_emitted() { const CORE_GRAB_POINTER: u8 = 26; const CORE_GRAB_BUTTON: u8 = 28; const XI_PASSIVE_GRAB_DEVICE: u8 = 54; +const XI_ALLOW_EVENTS: u8 = 53; /// `GrabPointer` by `owner` on `window`, asynchronous, with the core event mask. fn grab_pointer(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: bool, mask: u32) { @@ -763,6 +764,7 @@ fn xi_passive_grab_button( device: u16, window: u32, sync: bool, + owner_events: bool, mask: u32, ) { let mut body = Vec::with_capacity(36); @@ -773,7 +775,7 @@ fn xi_passive_grab_button( body.extend_from_slice(&device.to_le_bytes()); body.extend_from_slice(&1_u16.to_le_bytes()); // one modifier body.extend_from_slice(&1_u16.to_le_bytes()); // one mask word - body.extend_from_slice(&[0, u8::from(!sync), 1, 0]); // Button, mode, async paired, not owner_events + body.extend_from_slice(&[0, u8::from(!sync), 1, u8::from(owner_events)]); // Button, mode, async paired, owner_events body.extend_from_slice(&0_u16.to_le_bytes()); // pad body.extend_from_slice(&mask.to_le_bytes()); body.extend_from_slice(&0x8000_0000_u32.to_le_bytes()); // XIAnyModifier @@ -862,11 +864,44 @@ const P9: Row = Row { }, }; +/// The core grab window is C itself: O core on C (denied), F master XI2 on C +/// (allowed). The core fallback is a distinct attempt, so O is asked at C again. +fn setup_p9_core_same_window(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, CHILD, CORE_BUTTON_PRESS); + select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + grab_pointer(f, A, CHILD, true, CORE_BUTTON_PRESS); +} + +const P9_CORE_SAME_WINDOW: Row = Row { + name: "p9_denied_owner_with_allowed_foreign_falls_back", + setup: setup_p9_core_same_window, + drive: press(XTEST_MASTER), + deny: &[(A, CallKind::Core, CHILD)], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + }, + denied: Expect { + frames: &[], + calls: &[ + (A, CallKind::Core, CHILD), + (B, CallKind::Xi2, CHILD), + (A, CallKind::Core, CHILD), + ], + }, +}; + /// Mutation: the denied owner keeps walking (or is dropped) although an allowed -/// foreign selector rejects the walk, so the grab window gets no copy. +/// foreign selector rejects the walk, so the grab window gets no copy; or the +/// core fallback takes the memo's result for (O, G, core) instead of a fresh +/// check (the same-window row then has one call for O, not two). #[test] fn p9_denied_owner_with_allowed_foreign_falls_back() { check_row(&P9); + check_row(&P9_CORE_SAME_WINDOW); } // ---- P10 ----------------------------------------------------------------- @@ -1140,6 +1175,7 @@ fn p13_xi2_owner_events_fallback_is_fresh() { /// fixture to inspect the grab, freeze and queue. struct Activation { f: NotifyFixture, + seen: std::sync::Arc>>, calls: Vec<(u32, u32, bool)>, } @@ -1163,23 +1199,33 @@ fn activate_denied( if denied { DENY } else { Decision::Allow } }); drive(&mut f, press(origin)); - let calls = seen - .lock() - .unwrap() - .iter() - .filter(|call| call.hook == ExtensionHook::Receive) - .map(|call| { - let Some(EventSubject::Window(subject)) = call.receive else { - panic!("pointer Receive subject {:?}", call.receive); - }; - let events = call.events.as_deref().expect("Receive batch"); - (call.client.0, subject.0, events[0].extension.is_some()) - }) - .collect(); - Activation { f, calls } + let mut run = Activation { + f, + seen, + calls: Vec::new(), + }; + run.calls = run.receive_calls(); + run } impl Activation { + /// Every Receive call so far: (client, event window, XI2 or core). + fn receive_calls(&self) -> Vec<(u32, u32, bool)> { + self.seen + .lock() + .unwrap() + .iter() + .filter(|call| call.hook == ExtensionHook::Receive) + .map(|call| { + let Some(EventSubject::Window(subject)) = call.receive else { + panic!("pointer Receive subject {:?}", call.receive); + }; + let events = call.events.as_deref().expect("Receive batch"); + (call.client.0, subject.0, events[0].extension.is_some()) + }) + .collect() + } + /// No client was sent a byte, in particular nobody got the denied press. fn assert_no_bytes(&mut self) { for id in [SEND_CLIENT, A, B] { @@ -1244,13 +1290,29 @@ fn p14_denied_activating_press_still_activates_and_freezes() { fn setup_p14_xi2_master_from_slave(f: &mut NotifyFixture) { tree(f); - xi_passive_grab_button(f, A, DEVICEID_MASTER_POINTER, ROOT, true, XI_BUTTON_PRESS); + xi_passive_grab_button( + f, + A, + DEVICEID_MASTER_POINTER, + ROOT, + true, + false, + XI_BUTTON_PRESS, + ); } fn setup_p14_xi2_master_origin(f: &mut NotifyFixture) { tree(f); select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); - xi_passive_grab_button(f, A, DEVICEID_MASTER_POINTER, ROOT, true, XI_BUTTON_PRESS); + xi_passive_grab_button( + f, + A, + DEVICEID_MASTER_POINTER, + ROOT, + true, + false, + XI_BUTTON_PRESS, + ); } /// The motion that follows the activating press, from `origin`. @@ -1271,7 +1333,9 @@ fn follow_with_motion(run: &mut Activation, origin: InputOrigin) { /// A sync `XIPassiveGrabDevice` on the master from an attached slave origin: /// A's copy on G is denied, nobody else gets the press, and the grab still /// freezes with the press stored. The next motion delivers its slave part and -/// defers the master part behind the freeze. +/// defers the master part behind the freeze. Mutation: the XI2 master block asks +/// for the grab window without the emitted-form gate (a phantom call after the +/// motion, and a second one at the thaw). #[test] fn p14_denied_xi2_activating_press_still_freezes_from_a_slave_origin() { let mut run = activate_denied(setup_p14_xi2_master_from_slave, XTEST_SLAVE, A, ROOT); @@ -1288,6 +1352,25 @@ fn p14_denied_xi2_activating_press_still_freezes_from_a_slave_origin() { run.queued(), vec![(DEVICEID_MASTER_POINTER, "HostPointerMaster")] ); + // The deferred master part is not written yet, so nobody is asked for it. + assert_eq!( + run.receive_calls(), + run.calls, + "no call for the deferred master part" + ); + // Thawing runs the master part: that is the one attempt, asked once. + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime + body.extend_from_slice(&DEVICEID_MASTER_POINTER.to_le_bytes()); + body.extend_from_slice(&[0, 0]); // XIAsyncDevice + send(&mut run.f, A, XI_MAJOR, XI_ALLOW_EVENTS, &body); + let mut expected = run.calls.clone(); + expected.push((A, ROOT, true)); + assert_eq!( + run.receive_calls(), + expected, + "one call when the master part runs" + ); } /// The same grab from a master origin (`xi2_grab_delivery`): A also selects the @@ -1308,3 +1391,76 @@ fn p14_denied_xi2_activating_press_from_a_master_origin_still_freezes() { follow_with_motion(&mut run, XTEST_MASTER); assert_eq!(run.queued(), vec![(DEVICEID_MASTER_POINTER, "HostPointer")]); } + +// ---- I2 ------------------------------------------------------------------ + +/// An async `GrabButton` with owner_events on G: the activation dispatch writes +/// only the activating press, on G. O selects core on C and XI2 on P. The core +/// grab block did not route this dispatch, so the XI2 route asks nothing about +/// O's core copy at C, and a denial there changes nothing. +fn setup_activation_owner_events(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, CHILD, CORE_BUTTON_PRESS); + select_xi2(f, A, FOCUS, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + grab_button(f, A, ROOT, true, false); +} + +const ACTIVATION_OWNER_EVENTS: Row = Row { + name: "activation_route_asks_no_core_copy", + setup: setup_activation_owner_events, + drive: press(XTEST_MASTER), + deny: &[(A, CallKind::Core, CHILD)], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(A, CallKind::Core, ROOT)], + }, + denied: Expect { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(A, CallKind::Core, ROOT)], + }, +}; + +/// Mutation: the XI2 block's route asks the core leg in an activation dispatch +/// (`core_checked` true): the denied run then has an O@C core call and walks +/// on to an XI2 press at P. +#[test] +fn activation_route_asks_no_core_copy() { + check_row(&ACTIVATION_OWNER_EVENTS); +} + +fn setup_p14_owner_events_from_slave(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_MOTION); + xi_passive_grab_button( + f, + A, + DEVICEID_MASTER_POINTER, + ROOT, + true, + true, + XI_BUTTON_PRESS | XI_MOTION, + ); +} + +/// The same sync master grab with owner_events, and A selecting the master XI2 +/// motion on C: the follow-up slave motion defers its master part, so the +/// route that would ask A@C for that copy must not ask yet. +/// Mutation: the master block's route takes the memo although the master form +/// is not emitted in this dispatch (a phantom A@C call). +#[test] +fn p14_deferred_master_part_asks_nothing_in_the_route() { + let mut run = activate_denied(setup_p14_owner_events_from_slave, XTEST_SLAVE, A, ROOT); + let before = run.receive_calls(); + follow_with_motion(&mut run, XTEST_SLAVE); + assert_eq!( + run.queued(), + vec![(DEVICEID_MASTER_POINTER, "HostPointerMaster")] + ); + assert_eq!( + run.receive_calls(), + before, + "no call for the deferred master part" + ); +} From 0b7befd1f2a62d5a85fa000a0ed87397c00fed77 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 20:18:20 -0300 Subject: [PATCH 32/72] feat(access): Receive decides the slave press protocol resolve_slave_press_delivery takes the dispatch memo: at each window the allowed slave XI2 selectors, else the allowed XI1 DeviceButtonPress selectors, else the parent. The XI2 leg is asked only when the slave form is routed here, the XI1 leg only when the router reaches its selection walk (device not frozen, no passive grab takes the press). The recipients are decided: the XI2 copies are written as they stand and the XI1 implicit owner is chosen among the XI1 recipients. The passive grab matcher of the router is shared with the route. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Sonnet 5.5 --- .../src/core_loop/pointer_fanout.rs | 91 +++-- .../tests/access_input_support.rs | 25 +- .../tests/access_pointer_input.rs | 363 +++++++++++++++++- 3 files changed, 454 insertions(+), 25 deletions(-) diff --git a/crates/yserver-core/src/core_loop/pointer_fanout.rs b/crates/yserver-core/src/core_loop/pointer_fanout.rs index 8227ad687..620317de8 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout.rs @@ -23,7 +23,7 @@ use buttons::{master_button_transition, pointer_button_transition}; pub(in crate::core_loop) use owner_events::xtest_wire_valuators; use owner_events::{ OwnerEventsRoute, OwnerProtocol, Xi1SelectionFilter, grab_for_form, owner_events_route, - xi1_device_mask_on_window, xi1_event_mask_bit, xi1_selection_filter_for_slave_grab, + xi1_batch, xi1_device_mask_on_window, xi1_event_mask_bit, xi1_selection_filter_for_slave_grab, xi1_window_selectors, xi1_window_selectors_with_grab_class, xi2_motion_targets_for_source, }; @@ -2130,8 +2130,22 @@ fn pointer_event_fanout_to_state_inner( && !state.xi1_active_grabs.contains_key(&deviceid) && !state.xi2_pointer_grabs.contains_key(&deviceid) { + // The slave press route asks Receive for the copies this dispatch + // writes: the XI2 slave form when it is routed here (no grab owns + // or redirects it), and the XI1 form when the router reaches the + // selection walk (not frozen, no passive grab takes the press). + let xi2_routed = + slave_form_emitted && owner_events_slave_route.is_none() && !xi2_grab_delivery; + let xi1_routed = xi2_routed + && !xi1_device_frozen(state, deviceid) + && xi1_matching_passive_grab(state, &q).is_none(); slave_press_delivery = Some(resolve_slave_press_delivery( - state, target, deviceid, q.evcode, + state, + target, + deviceid, + q.evcode, + xi2_routed.then_some(&mut receive), + xi1_routed, )); } let extras = xi1_route_device_event(state, q, true, slave_press_delivery.as_ref()); @@ -2182,12 +2196,10 @@ fn pointer_event_fanout_to_state_inner( // Which forms this dispatch writes through a memo-decided route. A form // that is not written, or whose delivery a grab owns or redirects (its // owner's copy is a fixed recipient, checked at the write), routes its - // natural selectors by selection only. The slave press route is converted - // in a later task, so its copies are checked at the write as well. - let slave_form_checked = slave_form_emitted - && owner_events_slave_route.is_none() - && slave_press_delivery.is_none() - && !xi2_grab_delivery; + // natural selectors by selection only. The slave press route decides its + // XI2 recipients through the same memo, so they are written as they stand. + let slave_form_checked = + slave_form_emitted && owner_events_slave_route.is_none() && !xi2_grab_delivery; let master_grab_decided = master_form_decided_by_grab(state, xi_source, replay, xi2_grab_delivery); let master_form_checked = master_form_emitted && !master_grab_decided; @@ -3363,19 +3375,7 @@ pub(crate) fn xi1_route_device_event( // reprocessing pass skips grabs at or above the released grab's // window — "as though they were not present" (the replay floor). if is_press { - let matched = state - .xi1_passive_grabs - .iter() - .find(|g| { - g.deviceid == q.deviceid - && (g.detail == 0 || g.detail == q.detail) - && (g.modifiers == 0x8000 || g.modifiers == q.state_mask & 0x00ff) - && xi1_window_in_chain(state, q.natural_target, g.grab_window) - && !q - .replay_floor - .is_some_and(|floor| xi1_window_in_chain(state, floor, g.grab_window)) - }) - .copied(); + let matched = xi1_matching_passive_grab(state, &q); if let Some(g) = matched { state.xi1_active_grabs.insert( q.deviceid, @@ -3530,12 +3530,52 @@ fn compute_xi1_route_targets( } } +/// The XI1 passive grab an XI1 press activates, if any (the replay floor +/// hides the grabs at or above the released one). +fn xi1_matching_passive_grab( + state: &ServerState, + q: &crate::server::Xi1QueuedEvent, +) -> Option { + state + .xi1_passive_grabs + .iter() + .find(|g| { + g.deviceid == q.deviceid + && (g.detail == 0 || g.detail == q.detail) + && (g.modifiers == 0x8000 || g.modifiers == q.state_mask & 0x00ff) + && xi1_window_in_chain(state, q.natural_target, g.grab_window) + && !q + .replay_floor + .is_some_and(|floor| xi1_window_in_chain(state, floor, g.grab_window)) + }) + .copied() +} + +/// True when the router queues the device's XI1 events instead of delivering. +fn xi1_device_frozen(state: &ServerState, deviceid: u16) -> bool { + state + .xi1_frozen + .get(&deviceid) + .is_some_and(crate::server::Xi1Freeze::frozen) +} + +/// Chooses the protocol of a slave press: at each window from the target up, +/// the slave XI2 selectors whose copy is allowed, else the XI1 +/// `DeviceButtonPress` selectors whose copy is allowed, else the parent. With a +/// memo, an XI2 selection counts only if its copy is allowed (the same result +/// the write reuses); `xi1_checked` says the router writes the XI1 form, so its +/// selectors are asked too. The XI1 recipients returned are decided: the router +/// writes them as they stand and picks the XI1 implicit owner among them. fn resolve_slave_press_delivery( state: &ServerState, target: ResourceId, deviceid: u16, xi1_evcode: u8, + mut receive: Option<&mut ReceiveMemo>, + xi1_checked: bool, ) -> SlavePressDelivery { + let xi1_description = xi1_batch(xi1_evcode); + let xi1_batch = EventBatch::new(&xi1_description); let mut window = target; for _ in 0..256 { let xi2_recipients = xi2_form_targets_for_source( @@ -3544,7 +3584,7 @@ fn resolve_slave_press_delivery( Xi2PointerForm::Slave, xi2_evtype(PointerEventKind::ButtonPress), Some(deviceid), - None, + receive.as_deref_mut(), ); if !xi2_recipients.is_empty() { return SlavePressDelivery::Xi2 { @@ -3553,7 +3593,12 @@ fn resolve_slave_press_delivery( }; } - let xi1_recipients = xi1_window_selectors(state, window, xi1_evcode, deviceid); + let mut xi1_recipients = xi1_window_selectors(state, window, xi1_evcode, deviceid); + if xi1_checked && let Some(memo) = receive.as_deref_mut() { + xi1_recipients.retain(|client| { + memo.allows(state, *client, EventSubject::Window(window), &xi1_batch) + }); + } if !xi1_recipients.is_empty() { return SlavePressDelivery::Xi1 { window, diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index b5bb1142f..c6431066c 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -66,6 +66,9 @@ type Call = (u32, CallKind, u32); pub(super) enum Kind { Core, Xi2(u16), + /// An XI1 `DeviceButtonPress`: its device. The frame carries the button in + /// its detail byte and the event window at byte 12, as a core frame does. + Xi1(u16), /// A raw key copy: its device, always on the root. A raw frame has no /// event window, so the grab-leg copy and the root-fanout copy decode the /// same; only the Receive trace tells them apart. @@ -312,6 +315,18 @@ pub(super) fn select_core(f: &mut NotifyFixture, client: u32, window: u32, mask: send(f, client, CORE_CHANGE_WINDOW_ATTRIBUTES, 0, &body); } +/// XI1 `SelectExtensionEvent` of `classes` (each `device << 8 | event code or +/// class`) on `window` for `client`. +pub(super) fn select_xi1(f: &mut NotifyFixture, client: u32, window: u32, classes: &[u32]) { + let mut body = window.to_le_bytes().to_vec(); + body.extend_from_slice(&u16::try_from(classes.len()).unwrap().to_le_bytes()); + body.extend_from_slice(&[0, 0]); + for class in classes { + body.extend_from_slice(&class.to_le_bytes()); + } + send(f, client, XI_MAJOR, 6, &body); +} + /// XI2 key selection of one device on `window` for `client`. pub(super) fn select_xi2(f: &mut NotifyFixture, client: u32, window: u32, device: u16, mask: u32) { let body = xi_select_body(window, &[(device, &[mask])]); @@ -585,6 +600,14 @@ pub(super) fn decide(denied: &[Call], ev: u16, call: &RecordedExtensionCheck) -> pub(super) fn decode(frame: &[u8], order: ClientByteOrder) -> Option<(Kind, u32)> { match frame[0] & 0x7f { 2..=6 => Some((Kind::Core, dec32(&frame[12..16], order))), + code if code + == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET => + { + Some(( + Kind::Xi1(u16::from(frame[31] & 0x7f)), + dec32(&frame[12..16], order), + )) + } 35 if frame[1] == XI2_MAJOR_OPCODE => match dec16(&frame[8..10], order) { 2..=6 => Some(( Kind::Xi2(dec16(&frame[10..12], order)), @@ -800,7 +823,7 @@ pub(super) fn delivered(name: &str, run: &Run, detail: u32) -> Vec { client.client ); let keycode = match kind { - Kind::Core => u32::from(frame[1]), + Kind::Core | Kind::Xi1(_) => u32::from(frame[1]), Kind::Xi2(_) | Kind::Raw(_) => dec32(&frame[16..20], client.order), }; assert_eq!(keycode, detail, "{name}: frame detail"); diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index 610dcdd76..b58220d5d 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -8,7 +8,7 @@ use super::{ access_input_support::*, - access_notify_support::{DENY, NotifyFixture}, + access_notify_support::{DENY, NotifyFixture, split_frames}, extensions::ExtensionHook, }; use crate::{ @@ -23,6 +23,7 @@ use yserver_protocol::x11::{ClientId, ResourceId}; /// Core ButtonPressMask and MotionNotify mask bits. const CORE_BUTTON_PRESS: u32 = 1 << 2; const CORE_MOTION: u32 = 1 << 6; +const CORE_BUTTON_RELEASE: u32 = 1 << 3; /// XI2 mask bits, one per event type: ButtonPress (4) and Motion (6). const XI_BUTTON_PRESS: u32 = 1 << 4; const XI_MOTION: u32 = 1 << 6; @@ -1464,3 +1465,363 @@ fn p14_deferred_master_part_asks_nothing_in_the_route() { "no call for the deferred master part" ); } + +// ---- P15-P20: implicit grabs and the slave press protocol ----------------- + +/// The XI1 class a client selects: `device << 8 | evcode`. +const fn xi1_class(device: u16, offset: u8) -> u32 { + ((device as u32) << 8) | (crate::server::XI_FIRST_EVENT + offset) as u32 +} + +/// The class value of an XI1 `DeviceButtonGrab` selection, which the router +/// reads as "this input client selected the button grab" (the low byte is the +/// class code, not an event code). +const fn xi1_grab_class(device: u16) -> u32 { + ((device as u32) << 8) | crate::xinput::XI1_DEVICE_BUTTON_GRAB_CLASS as u32 +} + +const XI1_SLAVE_PRESS: u32 = xi1_class( + DEVICEID_XTEST_POINTER, + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET, +); + +/// The Receive batch of an XI1 `DeviceButtonPress` copy. +const XI1_PRESS_CALL: CallKind = CallKind::Batch(&[Named::Xi1( + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET as u16, +)]); + +/// The grab fact of a core implicit grab. +const fn core_implicit(owner: u32, window: u32) -> Grab { + Grab::Pointer(PointerGrab { + owner, + window, + implicit: true, + passive: false, + via_xi2: false, + }) +} + +const fn xi1_implicit(owner: u32, window: u32) -> Grab { + Grab::Xi1 { + device: DEVICEID_XTEST_POINTER, + owner, + window, + } +} + +fn setup_p15(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, CHILD, CORE_BUTTON_PRESS | CORE_BUTTON_RELEASE); + select_core(f, B, FOCUS, CORE_BUTTON_PRESS | CORE_BUTTON_RELEASE); +} + +const P15: Row = Row { + name: "p15_denied_candidate_is_not_the_implicit_owner", + setup: setup_p15, + drive: press(XTEST_MASTER), + deny: &[(A, CallKind::Core, CHILD)], + denied_grab: Some(&[core_implicit(B, FOCUS)]), + moved: &[Moved { + client: B, + window: FOCUS, + child: CHILD, + event: P_EVENT, + }], + allow: Expect { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + }, + denied: Expect { + frames: &[(B, Kind::Core, FOCUS)], + calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, FOCUS)], + }, +}; + +/// A denied on C: B on P gets the press and owns the implicit grab; the release, +/// with the pointer still over C, goes to B at P. Mutation (task 1's core +/// candidate): the candidate is any walk recipient, denied or not, so A owns the +/// grab and the release goes to A at C. +#[test] +fn p15_denied_candidate_is_not_the_implicit_owner() { + check_row(&P15); + let mut f = NotifyFixture::new(); + setup_p15(&mut f); + for id in [SEND_CLIENT, A, B] { + f.drain(ClientId(id)); + } + f.install_policy(|_, call| { + let denied = call.hook == ExtensionHook::Receive + && call.client.0 == A + && call.receive == Some(EventSubject::Window(ResourceId(CHILD))); + if denied { DENY } else { Decision::Allow } + }); + drive(&mut f, press(XTEST_MASTER)); + for id in [A, B] { + f.drain(ClientId(id)); + } + drive( + &mut f, + Drive::Pointer { + origin: XTEST_MASTER, + kind: PointerEventKind::ButtonRelease, + button: 1, + to: POINTER, + delta: (0, 0), + }, + ); + let mut released = Vec::new(); + for id in [A, B] { + let order = f.state.clients[&id].byte_order; + for frame in split_frames(&f.drain(ClientId(id)), order) { + released.extend(decode(frame, order).map(|seen| (id, seen))); + } + } + assert_eq!(released, vec![(B, (Kind::Core, FOCUS))], "release owner"); +} + +fn setup_p16(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, CHILD, CORE_BUTTON_PRESS); +} + +const P16: Row = Row { + name: "p16_all_denied_no_implicit_grab", + setup: setup_p16, + drive: press(XTEST_MASTER), + deny: &[(A, CallKind::Core, CHILD)], + denied_grab: Some(&[]), + moved: &[], + allow: Expect { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + }, + denied: Expect { + frames: &[], + calls: &[(A, CallKind::Core, CHILD)], + }, +}; + +/// A alone on C, denied: nobody receives the press and no pointer grab is +/// active afterwards. Mutation (task 1's core candidate): the denied recipient +/// still qualifies, so A owns an implicit grab it never received a press for. +#[test] +fn p16_all_denied_no_implicit_grab() { + check_row(&P16); +} + +fn setup_p17(f: &mut NotifyFixture) { + tree(f); + // A owns C, so it is the implicit-grab owner among equal candidates there. + f.state + .resources + .window_mut(ResourceId(CHILD)) + .expect("C") + .owner = ClientId(A); + select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); +} + +const P17: Row = Row { + name: "p17_xi2_owner_preference_among_allowed", + setup: setup_p17, + drive: press(XTEST_MASTER), + deny: &[(A, CallKind::Xi2, CHILD)], + denied_grab: Some(&[Grab::Pointer(PointerGrab { + owner: B, + window: CHILD, + implicit: true, + passive: false, + via_xi2: true, + })]), + moved: &[], + allow: Expect { + frames: &[ + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + calls: &[(A, CallKind::Xi2, CHILD), (B, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD), (B, CallKind::Xi2, CHILD)], + }, +}; + +/// Both select the master pointer's XI2 press on C; A is the window's owner and +/// wins with allow-all, and with A denied B owns the grab. Mutation (task 1's +/// XI2 candidate): a denied copy still enters the owner preference. +#[test] +fn p17_xi2_owner_preference_among_allowed() { + check_row(&P17); + // The allow-all grab fact is A (the owner), not B. + let allow = run(&P17, Some(&[])); + assert_eq!( + allow.grab, + vec![Grab::Pointer(PointerGrab { + owner: A, + window: CHILD, + implicit: true, + passive: false, + via_xi2: true, + })] + ); +} + +fn setup_p18(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, CHILD, DEVICEID_XTEST_POINTER, XI_BUTTON_PRESS); + select_xi1(f, B, CHILD, &[XI1_SLAVE_PRESS]); +} + +const P18: Row = Row { + name: "p18_denied_slave_xi2_falls_to_xi1", + setup: setup_p18, + drive: press(XTEST_SLAVE), + deny: &[(A, CallKind::Xi2, CHILD)], + denied_grab: Some(&[xi1_implicit(B, CHILD)]), + moved: &[Moved { + client: B, + window: CHILD, + child: 0, + event: C_EVENT, + }], + allow: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + }, + denied: Expect { + frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD), (B, XI1_PRESS_CALL, CHILD)], + }, +}; + +/// Slave origin; A selects the slave's XI2 press on C, B its XI1 press on C. A +/// denied: B gets the XI1 form at C and owns the XI1 implicit grab, with one +/// call. Mutation: the protocol is chosen by selection (the XI2 selector wins +/// though denied: B gets nothing); or the XI1 copy is checked a second time. +#[test] +fn p18_denied_slave_xi2_falls_to_xi1() { + check_row(&P18); +} + +fn setup_p19(f: &mut NotifyFixture) { + tree(f); + select_xi1(f, A, CHILD, &[XI1_SLAVE_PRESS]); + select_xi1(f, B, FOCUS, &[XI1_SLAVE_PRESS]); +} + +const P19: Row = Row { + name: "p19_denied_xi1_press_continues", + setup: setup_p19, + drive: press(XTEST_SLAVE), + deny: &[(A, XI1_PRESS_CALL, CHILD)], + denied_grab: Some(&[xi1_implicit(B, FOCUS)]), + moved: &[Moved { + client: B, + window: FOCUS, + child: CHILD, + event: P_EVENT, + }], + allow: Expect { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + calls: &[(A, XI1_PRESS_CALL, CHILD)], + }, + denied: Expect { + frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], + calls: &[(A, XI1_PRESS_CALL, CHILD), (B, XI1_PRESS_CALL, FOCUS)], + }, +}; + +/// A's XI1 press selector on C is denied, B's on P is not: the walk continues +/// and B gets the press at P. Mutation: a denied XI1 selector stops the walk +/// (selection decides the window), so B gets nothing. +#[test] +fn p19_denied_xi1_press_continues() { + check_row(&P19); +} + +fn setup_p20(f: &mut NotifyFixture) { + tree(f); + select_xi1(f, A, CHILD, &[XI1_SLAVE_PRESS]); + select_xi1( + f, + B, + CHILD, + &[XI1_SLAVE_PRESS, xi1_grab_class(DEVICEID_XTEST_POINTER)], + ); +} + +const P20: Row = Row { + name: "p20_xi1_implicit_owner_from_allowed", + setup: setup_p20, + drive: press(XTEST_SLAVE), + deny: &[(B, XI1_PRESS_CALL, CHILD)], + denied_grab: Some(&[xi1_implicit(A, CHILD)]), + moved: &[], + allow: Expect { + frames: &[ + (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + (B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + ], + calls: &[(A, XI1_PRESS_CALL, CHILD), (B, XI1_PRESS_CALL, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + calls: &[(A, XI1_PRESS_CALL, CHILD), (B, XI1_PRESS_CALL, CHILD)], + }, +}; + +/// Two XI1 press selectors on C, the one that also selected the button grab +/// class is denied: the other owns the XI1 implicit grab (allow-all: the grab +/// class holder). Mutation: the owner is chosen among the selectors, not among +/// the allowed recipients, so the denied B owns the grab. +#[test] +fn p20_xi1_implicit_owner_from_allowed() { + check_row(&P20); + let allow = run(&P20, Some(&[])); + assert_eq!(allow.grab, vec![xi1_implicit(B, CHILD)]); +} + +fn setup_p20b(f: &mut NotifyFixture) { + tree(f); + select_xi1(f, A, CHILD, &[XI1_SLAVE_PRESS]); + f.state + .xi1_passive_grabs + .push(crate::server::Xi1PassiveGrab { + owner: ClientId(B), + deviceid: DEVICEID_XTEST_POINTER, + grab_window: ResourceId(FOCUS), + detail: 0, + modifiers: 0x8000, + owner_events: false, + this_mode: 1, + other_mode: 1, + is_key: false, + }); +} + +const P20B: Row = Row { + name: "p20b_xi1_passive_activation_asks_no_selector", + setup: setup_p20b, + drive: press(XTEST_SLAVE), + deny: &[(A, XI1_PRESS_CALL, CHILD)], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], + calls: &[], + }, + denied: Expect { + frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], + calls: &[], + }, +}; + +/// An XI1 passive grab takes the slave press, so the router never reaches the +/// selection walk: A's selector copy is not written and Receive is not asked +/// (the activating write is Task 5's). Mutation: the route asks the XI1 +/// selectors although a passive grab matches (`xi1_routed` ignores it). +#[test] +fn p20b_xi1_passive_activation_asks_no_selector() { + check_row(&P20B); +} From 6ad091b2b4d5541a352eb02898f9ba49d862ccdc Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 20:26:27 -0300 Subject: [PATCH 33/72] fix(access): review round 1 for the slave press protocol The XI2 leg of the slave press route is asked only when the XI2 fanout runs (a top level exists) and no grab owns the form; the XI1 leg depends only on the router reaching its selection walk, so a press the XI2 fanout skips neither asks phantom XI2 copies nor leaves the XI1 recipients unchecked. The route flag is computed once (slave_form_checked) for the route and the write. Tests reuse the existing XI1 select body and class helpers, and the moved-frame check pins moved XI1 frames in full. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Sonnet 5.5 --- .../src/core_loop/pointer_fanout.rs | 35 ++--- .../tests/access_input_support.rs | 27 +++- .../tests/access_pointer_input.rs | 122 +++++++++++++++--- .../process_request/tests/access_xi_notify.rs | 2 +- 4 files changed, 148 insertions(+), 38 deletions(-) diff --git a/crates/yserver-core/src/core_loop/pointer_fanout.rs b/crates/yserver-core/src/core_loop/pointer_fanout.rs index 620317de8..a09dcb752 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout.rs @@ -2096,6 +2096,12 @@ fn pointer_event_fanout_to_state_inner( } else { target }; + // The slave XI2 form is routed through the memo only when the XI2 fanout + // runs (a top level exists) and no grab owns or redirects the form. + let slave_form_checked = slave_form_emitted + && top_level_id_opt.is_some() + && owner_events_slave_route.is_none() + && !xi2_grab_delivery; let mut slave_press_delivery = None; if let Some(offset) = xi1_offset && replay_has_slave_form @@ -2130,21 +2136,19 @@ fn pointer_event_fanout_to_state_inner( && !state.xi1_active_grabs.contains_key(&deviceid) && !state.xi2_pointer_grabs.contains_key(&deviceid) { - // The slave press route asks Receive for the copies this dispatch - // writes: the XI2 slave form when it is routed here (no grab owns - // or redirects it), and the XI1 form when the router reaches the - // selection walk (not frozen, no passive grab takes the press). - let xi2_routed = - slave_form_emitted && owner_events_slave_route.is_none() && !xi2_grab_delivery; - let xi1_routed = xi2_routed - && !xi1_device_frozen(state, deviceid) + // The XI1 selectors are asked exactly when the router reaches its + // selection walk with this delivery (device not frozen, which + // mirrors router step 1, and no passive grab takes the press), + // whatever the XI2 form does. + let xi1_routed = !xi1_device_frozen(state, deviceid) && xi1_matching_passive_grab(state, &q).is_none(); slave_press_delivery = Some(resolve_slave_press_delivery( state, target, deviceid, q.evcode, - xi2_routed.then_some(&mut receive), + &mut receive, + slave_form_checked, xi1_routed, )); } @@ -2198,8 +2202,6 @@ fn pointer_event_fanout_to_state_inner( // owner's copy is a fixed recipient, checked at the write), routes its // natural selectors by selection only. The slave press route decides its // XI2 recipients through the same memo, so they are written as they stand. - let slave_form_checked = - slave_form_emitted && owner_events_slave_route.is_none() && !xi2_grab_delivery; let master_grab_decided = master_form_decided_by_grab(state, xi_source, replay, xi2_grab_delivery); let master_form_checked = master_form_emitted && !master_grab_decided; @@ -3571,11 +3573,12 @@ fn resolve_slave_press_delivery( target: ResourceId, deviceid: u16, xi1_evcode: u8, - mut receive: Option<&mut ReceiveMemo>, + receive: &mut ReceiveMemo, + xi2_checked: bool, xi1_checked: bool, ) -> SlavePressDelivery { let xi1_description = xi1_batch(xi1_evcode); - let xi1_batch = EventBatch::new(&xi1_description); + let xi1_events = EventBatch::new(&xi1_description); let mut window = target; for _ in 0..256 { let xi2_recipients = xi2_form_targets_for_source( @@ -3584,7 +3587,7 @@ fn resolve_slave_press_delivery( Xi2PointerForm::Slave, xi2_evtype(PointerEventKind::ButtonPress), Some(deviceid), - receive.as_deref_mut(), + xi2_checked.then_some(&mut *receive), ); if !xi2_recipients.is_empty() { return SlavePressDelivery::Xi2 { @@ -3594,9 +3597,9 @@ fn resolve_slave_press_delivery( } let mut xi1_recipients = xi1_window_selectors(state, window, xi1_evcode, deviceid); - if xi1_checked && let Some(memo) = receive.as_deref_mut() { + if xi1_checked { xi1_recipients.retain(|client| { - memo.allows(state, *client, EventSubject::Window(window), &xi1_batch) + receive.allows(state, *client, EventSubject::Window(window), &xi1_events) }); } if !xi1_recipients.is_empty() { diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index c6431066c..01dce9ae6 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -318,12 +318,7 @@ pub(super) fn select_core(f: &mut NotifyFixture, client: u32, window: u32, mask: /// XI1 `SelectExtensionEvent` of `classes` (each `device << 8 | event code or /// class`) on `window` for `client`. pub(super) fn select_xi1(f: &mut NotifyFixture, client: u32, window: u32, classes: &[u32]) { - let mut body = window.to_le_bytes().to_vec(); - body.extend_from_slice(&u16::try_from(classes.len()).unwrap().to_le_bytes()); - body.extend_from_slice(&[0, 0]); - for class in classes { - body.extend_from_slice(&class.to_le_bytes()); - } + let body = super::xi1_select_extension_event_body(window, classes); send(f, client, XI_MAJOR, 6, &body); } @@ -981,6 +976,26 @@ pub(super) fn check_row(row: &Row) { got.client ); } + if let Kind::Xi1(device) = kind { + // A DeviceButtonPress has the core ButtonPress layout, except the + // event code and the device id in the last byte. + let mut expected = literal_moved( + row.drive.ev(), + row.drive.detail(), + got.order, + got.sequence, + moved, + ); + expected[0] = + crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET; + expected[31] = device as u8; + assert_eq!( + frame, + expected.as_slice(), + "{name}: client {} moved XI1 frame @{window:#x}", + got.client + ); + } if kind == Kind::Core { assert_eq!( frame, diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index b58220d5d..3befab96d 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -9,6 +9,7 @@ use super::{ access_input_support::*, access_notify_support::{DENY, NotifyFixture, split_frames}, + access_xi_notify::xi1_class, extensions::ExtensionHook, }; use crate::{ @@ -1468,11 +1469,6 @@ fn p14_deferred_master_part_asks_nothing_in_the_route() { // ---- P15-P20: implicit grabs and the slave press protocol ----------------- -/// The XI1 class a client selects: `device << 8 | evcode`. -const fn xi1_class(device: u16, offset: u8) -> u32 { - ((device as u32) << 8) | (crate::server::XI_FIRST_EVENT + offset) as u32 -} - /// The class value of an XI1 `DeviceButtonGrab` selection, which the router /// reads as "this input client selected the button grab" (the low byte is the /// class code, not an event code). @@ -1480,10 +1476,13 @@ const fn xi1_grab_class(device: u16) -> u32 { ((device as u32) << 8) | crate::xinput::XI1_DEVICE_BUTTON_GRAB_CLASS as u32 } -const XI1_SLAVE_PRESS: u32 = xi1_class( - DEVICEID_XTEST_POINTER, - crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET, -); +/// The XI1 class of the slave's `DeviceButtonPress`. +fn xi1_slave_press() -> u32 { + xi1_class( + DEVICEID_XTEST_POINTER, + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET, + ) +} /// The Receive batch of an XI1 `DeviceButtonPress` copy. const XI1_PRESS_CALL: CallKind = CallKind::Batch(&[Named::Xi1( @@ -1670,7 +1669,7 @@ fn p17_xi2_owner_preference_among_allowed() { fn setup_p18(f: &mut NotifyFixture) { tree(f); select_xi2(f, A, CHILD, DEVICEID_XTEST_POINTER, XI_BUTTON_PRESS); - select_xi1(f, B, CHILD, &[XI1_SLAVE_PRESS]); + select_xi1(f, B, CHILD, &[xi1_slave_press()]); } const P18: Row = Row { @@ -1706,8 +1705,8 @@ fn p18_denied_slave_xi2_falls_to_xi1() { fn setup_p19(f: &mut NotifyFixture) { tree(f); - select_xi1(f, A, CHILD, &[XI1_SLAVE_PRESS]); - select_xi1(f, B, FOCUS, &[XI1_SLAVE_PRESS]); + select_xi1(f, A, CHILD, &[xi1_slave_press()]); + select_xi1(f, B, FOCUS, &[xi1_slave_press()]); } const P19: Row = Row { @@ -1742,12 +1741,12 @@ fn p19_denied_xi1_press_continues() { fn setup_p20(f: &mut NotifyFixture) { tree(f); - select_xi1(f, A, CHILD, &[XI1_SLAVE_PRESS]); + select_xi1(f, A, CHILD, &[xi1_slave_press()]); select_xi1( f, B, CHILD, - &[XI1_SLAVE_PRESS, xi1_grab_class(DEVICEID_XTEST_POINTER)], + &[xi1_slave_press(), xi1_grab_class(DEVICEID_XTEST_POINTER)], ); } @@ -1784,7 +1783,7 @@ fn p20_xi1_implicit_owner_from_allowed() { fn setup_p20b(f: &mut NotifyFixture) { tree(f); - select_xi1(f, A, CHILD, &[XI1_SLAVE_PRESS]); + select_xi1(f, A, CHILD, &[xi1_slave_press()]); f.state .xi1_passive_grabs .push(crate::server::Xi1PassiveGrab { @@ -1825,3 +1824,96 @@ const P20B: Row = Row { fn p20b_xi1_passive_activation_asks_no_selector() { check_row(&P20B); } + +/// The press over a root that nothing can hit (unmapped, as `unhit_root` +/// makes it): there is no top level, so the XI2 fanout does not run while the +/// XI1 router still does. +const BARE_ROOT: (i16, i16) = (10, 10); + +fn unhit_root(f: &mut NotifyFixture) { + f.state + .resources + .window_mut(ResourceId(ROOT)) + .expect("root") + .map_state = crate::resources::MapState::Unmapped; +} + +const fn press_at_bare_root(origin: InputOrigin) -> Drive { + Drive::Pointer { + origin, + kind: PointerEventKind::ButtonPress, + button: 1, + to: BARE_ROOT, + delta: (0, 0), + } +} + +fn setup_i1a(f: &mut NotifyFixture) { + tree(f); + park_pointer_at(f, BARE_ROOT); + unhit_root(f); + select_xi2(f, A, ROOT, DEVICEID_XTEST_POINTER, XI_BUTTON_PRESS); + select_xi1(f, B, ROOT, &[xi1_slave_press()]); +} + +const I1A: Row = Row { + name: "i1a_bare_root_slave_xi2_is_not_asked", + setup: setup_i1a, + drive: press_at_bare_root(XTEST_SLAVE), + deny: &[(A, CallKind::Xi2, ROOT)], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[], + calls: &[], + }, + denied: Expect { + frames: &[], + calls: &[], + }, +}; + +/// A selects the slave's XI2 press on the root, B its XI1 press, and the press +/// is over the bare root: no XI2 copy is written, so Receive is not asked for +/// A's, and a denial must not hand the press to B (nor give B an XI1 grab). +/// Mutation: the XI2 leg is asked without the top-level condition. +#[test] +fn i1a_bare_root_slave_xi2_is_not_asked() { + check_row(&I1A); +} + +fn setup_i1b(f: &mut NotifyFixture) { + tree(f); + park_pointer_at(f, BARE_ROOT); + unhit_root(f); + select_xi1(f, A, ROOT, &[xi1_slave_press()]); + select_xi1(f, B, ROOT, &[xi1_slave_press()]); +} + +const I1B: Row = Row { + name: "i1b_bare_root_xi1_selectors_are_checked", + setup: setup_i1b, + drive: press_at_bare_root(XTEST_SLAVE), + deny: &[(A, XI1_PRESS_CALL, ROOT)], + denied_grab: Some(&[xi1_implicit(B, ROOT)]), + moved: &[], + allow: Expect { + frames: &[ + (A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT), + (B, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT), + ], + calls: &[(A, XI1_PRESS_CALL, ROOT), (B, XI1_PRESS_CALL, ROOT)], + }, + denied: Expect { + frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT)], + calls: &[(A, XI1_PRESS_CALL, ROOT), (B, XI1_PRESS_CALL, ROOT)], + }, +}; + +/// Only XI1 selectors on the root, the press over the bare root: the router +/// writes the XI1 form, so each selector is asked once and the denied one gets +/// nothing. Mutation: the XI1 check is gated on the XI2 flag (here false). +#[test] +fn i1b_bare_root_xi1_selectors_are_checked() { + check_row(&I1B); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_xi_notify.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_xi_notify.rs index 5c01dd97d..d6c791015 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_xi_notify.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_xi_notify.rs @@ -221,7 +221,7 @@ fn select_pair(f: &mut NotifyFixture, select: Select) { } /// Label-free XI1 selection of one event class on `device`. -fn xi1_class(device_id: u16, event_offset: u8) -> u32 { +pub(super) fn xi1_class(device_id: u16, event_offset: u8) -> u32 { (u32::from(device_id) << 8) | u32::from(crate::server::XI_FIRST_EVENT + event_offset) } From 8ead2ac67de2c12e54c4433192a1759d4d71af11 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 20:34:49 -0300 Subject: [PATCH 34/72] feat(access): Receive checks raw pointer and scroll copies Raw root copies are checked one by one with the root as subject. The smooth-scroll Motion of a wheel press follows the ordinary walk through the dispatch memo, and its XI2 grab-window copy takes its own fresh check. The scroll stop keeps today's routing and is checked once per recipient and window with the two-Motion batch. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Sonnet 5.5 --- .../src/core_loop/pointer_fanout.rs | 71 +++-- .../core_loop/pointer_fanout/owner_events.rs | 26 +- .../tests/access_input_support.rs | 62 ++++- .../tests/access_pointer_input.rs | 262 ++++++++++++++++++ 4 files changed, 389 insertions(+), 32 deletions(-) diff --git a/crates/yserver-core/src/core_loop/pointer_fanout.rs b/crates/yserver-core/src/core_loop/pointer_fanout.rs index a09dcb752..91d418d26 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout.rs @@ -2446,9 +2446,18 @@ fn pointer_event_fanout_to_state_inner( // master by rewriting deviceid and retaining sourceid. Keep that // order for clients selecting both forms. Master-only origins have // no slave event to copy. + // Each copy to a root selector is checked on its own, with the root as + // its subject; a denial drops only that copy (`dix/events.c:2515-2517`, + // `:2291`). + let raw_description = crate::xinput::xi2_event_description(raw_evtype); + let raw_events = EventBatch::new(std::slice::from_ref(&raw_description)); if let Some(deviceid) = xi_source.slave_deviceid { - let extras = - fanout_event_to_clients(state, &xi2_raw_slave_targets, |buf, seq, order| { + let extras = fanout_event_to_clients_with_receive( + state, + &xi2_raw_slave_targets, + EventSubject::Window(ROOT_WINDOW), + &raw_events, + |buf, seq, order| { x11::encode_xi2_raw_event( buf, order, @@ -2462,24 +2471,31 @@ fn pointer_event_fanout_to_state_inner( event.raw_dx, event.raw_dy, ); - }); + }, + ); merge_dropped(&mut dropped, extras); } - let extras = fanout_event_to_clients(state, &xi2_raw_master_targets, |buf, seq, order| { - x11::encode_xi2_raw_event( - buf, - order, - seq, - XI2_MAJOR_OPCODE, - raw_evtype, - XI2_MASTER_POINTER_DEVICE_ID, - event.time, - u32::from(event.detail), - xi_source.sourceid, - event.raw_dx, - event.raw_dy, - ); - }); + let extras = fanout_event_to_clients_with_receive( + state, + &xi2_raw_master_targets, + EventSubject::Window(ROOT_WINDOW), + &raw_events, + |buf, seq, order| { + x11::encode_xi2_raw_event( + buf, + order, + seq, + XI2_MAJOR_OPCODE, + raw_evtype, + XI2_MASTER_POINTER_DEVICE_ID, + event.time, + u32::from(event.detail), + xi_source.sourceid, + event.raw_dx, + event.raw_dy, + ); + }, + ); merge_dropped(&mut dropped, extras); } @@ -2530,6 +2546,7 @@ fn pointer_event_fanout_to_state_inner( button_transition.source_accepted, scroll_master_accepted, replay, + Some(&mut receive), ) { let extras = fanout_event_to_clients( state, @@ -3179,9 +3196,25 @@ pub fn emit_scroll_stop_to_state( .unwrap_or(ROOT_WINDOW); let (target, event_x, event_y) = root_hit.unwrap_or((top_level_id, root_x, root_y)); + // The stop goes to the window it resolves today (no Receive in the route, + // so a denial never resumes the walk). Each recipient is asked once per + // window with the two-Motion batch; a client whose slave and master forms + // resolve to one window shares that call. + let stop_description = crate::xinput::xi2_event_description(6); + let stop_descriptions = [stop_description, stop_description]; + let stop_batch = EventBatch::new(&stop_descriptions); + let mut stop_memo = ReceiveMemo::new(); for route in xi2_motion_targets_for_source( - state, xi_source, target, target, event_x, event_y, root_x, root_y, true, true, None, + state, xi_source, target, target, event_x, event_y, root_x, root_y, true, true, None, None, ) { + if !stop_memo.allows( + state, + route.client, + EventSubject::Window(route.window), + &stop_batch, + ) { + continue; + } let scroll = if route.form == Xi2PointerForm::Slave { state .xi_devices diff --git a/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs b/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs index 2c2612689..e2c8a40d6 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs @@ -98,6 +98,7 @@ pub(super) fn xi2_motion_targets_for_source( source_accepted: bool, master_accepted: bool, replay: Option, + mut receive: Option<&mut ReceiveMemo>, ) -> Vec { const XI_MOTION: u16 = 6; if !source_accepted && !master_accepted { @@ -139,7 +140,7 @@ pub(super) fn xi2_motion_targets_for_source( 0, Some(XI_MOTION), None, - None, + receive.as_deref_mut(), false, ) } else { @@ -168,6 +169,16 @@ pub(super) fn xi2_motion_targets_for_source( && grab.xi2_mask & (1_u64 << XI_MOTION) != 0 && let Some((grab_window, _, gx, gy, ..)) = super::active_pointer_grab_target(state, grab) + // The grab window's copy is its own attempt: one fresh check + // for this Motion, before anything else decides it + // (`dix/events.c:4388-4398`). A denial counts as delivered. + && (receive.is_none() + || super::grab_window_allows( + state, + grab.owner, + grab_window, + &crate::xinput::xi2_event_description(XI_MOTION), + )) { let child = xi2_child_toward(state, grab_window, target); targets.push(Xi2MotionTarget { @@ -191,7 +202,7 @@ pub(super) fn xi2_motion_targets_for_source( form, XI_MOTION, source.slave_deviceid, - None, + receive.as_deref_mut(), ) else { continue; }; @@ -205,9 +216,14 @@ pub(super) fn xi2_motion_targets_for_source( clamp_grab_coord(root_y, window_y), ) }; - for client in - xi2_form_targets_for_source(state, window, form, XI_MOTION, source.slave_deviceid, None) - { + for client in xi2_form_targets_for_source( + state, + window, + form, + XI_MOTION, + source.slave_deviceid, + receive.as_deref_mut(), + ) { targets.push(Xi2MotionTarget { client, form, diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index 01dce9ae6..9fd854e73 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -16,7 +16,7 @@ use crate::{ RawKeyEvent, key_event_fanout_after_transition, key_event_fanout_to_state, raw_key_event_to_state, }, - pointer_fanout::pointer_event_fanout_to_state, + pointer_fanout::{emit_scroll_stop_to_state, pointer_event_fanout_to_state}, process_request::RequestOutcome, }, host_x11::{HostKeyEvent, HostPointerEvent, HostXidMap, PointerEventKind}, @@ -147,6 +147,9 @@ pub(super) enum Drive { /// Relative motion the device reports (zero for a button event). delta: (i32, i32), }, + /// `emit_scroll_stop_to_state`: the two-Motion smooth-scroll stop, probed + /// from root position `at`. + ScrollStop { origin: InputOrigin, at: (i16, i16) }, } impl Drive { @@ -168,6 +171,7 @@ impl Drive { 14 } } + Drive::ScrollStop { .. } => 6, Drive::Pointer { kind, .. } => match kind { PointerEventKind::ButtonPress => 4, PointerEventKind::ButtonRelease => 5, @@ -188,8 +192,22 @@ impl Drive { } _ => 0, }, + Drive::ScrollStop { .. } => 0, } } + + /// A wheel press (buttons 4..=7): besides its own press events it writes a + /// smooth-scroll Motion, so the calls and frames of a row may name Motion. + pub(super) fn is_wheel_press(self) -> bool { + matches!( + self, + Drive::Pointer { + kind: PointerEventKind::ButtonPress, + button: 4..=7, + .. + } + ) + } } pub(super) struct Expect { @@ -524,6 +542,19 @@ pub(super) fn drive(f: &mut NotifyFixture, drive: Drive) { true, false, ), + Drive::ScrollStop { origin, at } => { + emit_scroll_stop_to_state( + &mut f.state, + &HostXidMap::new(), + origin, + 0, + at.0, + at.1, + 0, + TIME, + ); + Vec::new() + } Drive::Raw { origin, pressed } => raw_key_event_to_state( &mut f.state, RawKeyEvent { @@ -551,7 +582,7 @@ fn name_of(description: &EventDescription) -> Option { { match extension.event_type { 2..=6 => Some(Named::Xi2(extension.event_type)), - 13 | 14 => Some(Named::Raw(extension.event_type)), + 13..=17 => Some(Named::Raw(extension.event_type)), _ => None, } } @@ -608,7 +639,7 @@ pub(super) fn decode(frame: &[u8], order: ClientByteOrder) -> Option<(Kind, u32) Kind::Xi2(dec16(&frame[10..12], order)), dec32(&frame[24..28], order), )), - 13 | 14 => Some((Kind::Raw(dec16(&frame[10..12], order)), ROOT)), + 13..=17 => Some((Kind::Raw(dec16(&frame[10..12], order)), ROOT)), _ => None, }, _ => None, @@ -708,7 +739,8 @@ pub(super) fn run(row: &Row, policy: Option<&'static [Call]>) -> Run { }; let names = names_of(call.events.as_deref()?)?; if let [single] = names.as_slice() - && !matches!(single, Named::Xi1(_)) + && !matches!(single, Named::Xi1(_) | Named::Raw(15..=17)) + && !row.drive.is_wheel_press() { assert_eq!( number(*single), @@ -802,7 +834,7 @@ pub(super) fn grouped( } /// The key frames a run wrote, with the client byte order and sequence checked. -pub(super) fn delivered(name: &str, run: &Run, detail: u32) -> Vec { +pub(super) fn delivered(name: &str, run: &Run, detail: u32, wheel_press: bool) -> Vec { let mut frames = Vec::new(); for client in &run.clients { for frame in split_frames(&client.bytes, client.order) { @@ -821,7 +853,12 @@ pub(super) fn delivered(name: &str, run: &Run, detail: u32) -> Vec { Kind::Core | Kind::Xi1(_) => u32::from(frame[1]), Kind::Xi2(_) | Kind::Raw(_) => dec32(&frame[16..20], client.order), }; - assert_eq!(keycode, detail, "{name}: frame detail"); + // The smooth-scroll Motion of a wheel press carries no button. + let is_scroll_motion = wheel_press + && matches!(kind, Kind::Xi2(_)) + && dec16(&frame[8..10], client.order) == 6; + let expected = if is_scroll_motion { 0 } else { detail }; + assert_eq!(keycode, expected, "{name}: frame detail"); frames.push((client.client, kind, window)); } } @@ -845,7 +882,7 @@ pub(super) fn check_run(row: &Row, run: &Run, expect: &Expect, mode: &str) { ); assert_eq!( grouped( - delivered(name, run, row.drive.detail()) + delivered(name, run, row.drive.detail(), row.drive.is_wheel_press()) .into_iter() .map(|(c, k, w)| (c, (k, w))) ), @@ -932,13 +969,22 @@ pub(super) fn check_row(row: &Row) { decode(frame, allowed.order).map(|(kind, window)| (kind, window, frame)) }) .collect(); + // A frame is paired with the allow-all frame of the same kind and window + // at the same position among those (a stop writes two such frames). + let mut seen_before: Vec<(Kind, u32)> = Vec::new(); for frame in split_frames(&got.bytes, got.order) { let Some((kind, window)) = decode(frame, got.order) else { continue; }; + let nth = seen_before + .iter() + .filter(|(k, w)| *k == kind && *w == window) + .count(); + seen_before.push((kind, window)); if let Some((_, _, same)) = allowed_frames .iter() - .find(|(k, w, _)| *k == kind && *w == window) + .filter(|(k, w, _)| *k == kind && *w == window) + .nth(nth) { assert_eq!( frame, *same, diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index 3befab96d..04bb0d8fd 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -1917,3 +1917,265 @@ const I1B: Row = Row { fn i1b_bare_root_xi1_selectors_are_checked() { check_row(&I1B); } + +// ---- Task 4: raw copies and smooth scroll ----------------------------------- +// +// X is client A, Y is client B, S is the send client. + +/// XI2 raw and Motion selection bits. +const XI_RAW_BUTTON_PRESS: u32 = 1 << 15; +const RAW_BUTTON_PRESS_CALL: CallKind = CallKind::Batch(&[Named::Raw(15)]); + +/// The device id the registry gives the physical pointer of these rows. +const PHYSICAL_DEVICE: u16 = 6; +const PHYSICAL_SOURCE_ORIGIN: InputOrigin = InputOrigin::Physical(InputSourceId(PHYSICAL_SOURCE)); + +fn setup_p21(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, ROOT, DEVICEID_MASTER_POINTER, XI_RAW_BUTTON_PRESS); + select_xi2(f, B, ROOT, DEVICEID_MASTER_POINTER, XI_RAW_BUTTON_PRESS); + select_xi2( + f, + SEND_CLIENT, + ROOT, + DEVICEID_XTEST_POINTER, + XI_RAW_BUTTON_PRESS, + ); +} + +const P21: Row = Row { + name: "p21_denied_raw_root_copy_drops_only_that_copy", + setup: setup_p21, + drive: press(XTEST_SLAVE), + deny: &[(A, RAW_BUTTON_PRESS_CALL, ROOT)], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[ + (SEND_CLIENT, Kind::Raw(DEVICEID_XTEST_POINTER), ROOT), + (A, Kind::Raw(DEVICEID_MASTER_POINTER), ROOT), + (B, Kind::Raw(DEVICEID_MASTER_POINTER), ROOT), + ], + calls: &[ + (SEND_CLIENT, RAW_BUTTON_PRESS_CALL, ROOT), + (A, RAW_BUTTON_PRESS_CALL, ROOT), + (B, RAW_BUTTON_PRESS_CALL, ROOT), + ], + }, + denied: Expect { + frames: &[ + (SEND_CLIENT, Kind::Raw(DEVICEID_XTEST_POINTER), ROOT), + (B, Kind::Raw(DEVICEID_MASTER_POINTER), ROOT), + ], + calls: &[ + (SEND_CLIENT, RAW_BUTTON_PRESS_CALL, ROOT), + (A, RAW_BUTTON_PRESS_CALL, ROOT), + (B, RAW_BUTTON_PRESS_CALL, ROOT), + ], + }, +}; + +/// A and B select the master raw press on the root, S the slave's; A is +/// denied: only A's copy goes, B and S keep theirs, in the same order. +/// Mutation: the raw copies are written unchecked (every denied-run assertion +/// fails), or a denial stops the raw fanout (B or S lose theirs). +#[test] +fn p21_denied_raw_root_copy_drops_only_that_copy() { + check_row(&P21); +} + +/// A physical wheel press (button 4) at C; the master XI2 Motion selectors +/// are X (A) on C and Y (B) on P. +fn setup_scroll_walk(f: &mut NotifyFixture) { + tree(f); + register_physical_pointer(&mut f.state); + select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_MOTION); + select_xi2(f, B, FOCUS, DEVICEID_MASTER_POINTER, XI_MOTION); +} + +const SCROLL_MOTION_CALL: CallKind = CallKind::Batch(&[Named::Xi2(6)]); + +const P22: Row = Row { + name: "p22_scroll_motion_follows_the_walk", + setup: setup_scroll_walk, + drive: Drive::Pointer { + origin: PHYSICAL_SOURCE_ORIGIN, + kind: PointerEventKind::ButtonPress, + button: 4, + to: POINTER, + delta: (0, 0), + }, + deny: &[(A, SCROLL_MOTION_CALL, CHILD)], + denied_grab: None, + moved: &[Moved { + client: B, + window: FOCUS, + child: CHILD, + event: P_EVENT, + }], + allow: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, SCROLL_MOTION_CALL, CHILD)], + }, + denied: Expect { + frames: &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], + calls: &[ + (A, SCROLL_MOTION_CALL, CHILD), + (B, SCROLL_MOTION_CALL, FOCUS), + ], + }, +}; + +/// The scroll Motion of a wheel press follows the ordinary walk: X's denied +/// copy on C does not stop it, and Y at P gets the Motion. +/// Mutation: the scroll Motion routes by selection only (the denied row then +/// writes nothing for Y and asks nothing of Y), or is written unchecked. +#[test] +fn p22_scroll_motion_follows_the_walk() { + check_row(&P22); +} + +const STOP_BATCH: CallKind = CallKind::Batch(&[Named::Xi2(6), Named::Xi2(6)]); + +const fn scroll_stop() -> Drive { + Drive::ScrollStop { + origin: PHYSICAL_SOURCE_ORIGIN, + at: POINTER, + } +} + +const P23_ALLOWED_AND_DENIED: Row = Row { + name: "p23_scroll_stop_is_not_rerouted", + setup: setup_scroll_walk, + drive: scroll_stop(), + deny: &[(A, STOP_BATCH, CHILD)], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[ + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + calls: &[(A, STOP_BATCH, CHILD)], + }, + denied: Expect { + frames: &[], + calls: &[(A, STOP_BATCH, CHILD)], + }, +}; + +fn setup_scroll_stop_two_forms(f: &mut NotifyFixture) { + tree(f); + register_physical_pointer(&mut f.state); + select_xi2(f, A, CHILD, XI_ALL_DEVICES, XI_MOTION); +} + +const P23_TWO_FORMS: Row = Row { + name: "p23_scroll_stop_is_not_rerouted", + setup: setup_scroll_stop_two_forms, + drive: scroll_stop(), + deny: &[], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[ + (A, Kind::Xi2(PHYSICAL_DEVICE), CHILD), + (A, Kind::Xi2(PHYSICAL_DEVICE), CHILD), + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + calls: &[(A, STOP_BATCH, CHILD)], + }, + denied: Expect { + frames: &[ + (A, Kind::Xi2(PHYSICAL_DEVICE), CHILD), + (A, Kind::Xi2(PHYSICAL_DEVICE), CHILD), + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + calls: &[(A, STOP_BATCH, CHILD)], + }, +}; + +const P23_TWO_FORMS_DENIED: Row = Row { + deny: &[(A, STOP_BATCH, CHILD)], + denied: Expect { + frames: &[], + calls: &[(A, STOP_BATCH, CHILD)], + }, + ..P23_TWO_FORMS +}; + +/// The stop routes from its own probe hit, as today. X's denied batch on C +/// drops X's two Motions and the walk does not resume (Y at P gets nothing +/// and is not asked); allowed, X gets both. A client with both device forms on +/// one window is asked once for both forms' four events. +/// Mutations: the stop routes through the memo (Y gets it at P and is asked); +/// one check per event (two calls for X); one check per form (two calls in +/// the two-form row). +#[test] +fn p23_scroll_stop_is_not_rerouted() { + check_row(&P23_ALLOWED_AND_DENIED); + check_row(&P23_TWO_FORMS); + check_row(&P23_TWO_FORMS_DENIED); +} + +/// A's XIGrabDevice on the master pointer at the root, owner_events false, +/// selecting Motion only: a wheel press writes A the scroll Motion at the grab +/// window and no button event. +fn setup_p22_grab(f: &mut NotifyFixture) { + tree(f); + register_physical_pointer(&mut f.state); + xi_grab_master_pointer(f, A, ROOT, false, XI_MOTION); +} + +const P22_GRAB_PRESS_CALL: CallKind = CallKind::Batch(&[Named::Xi2(4)]); + +const P22_GRAB_MOTION_DENIED: Row = Row { + name: "p22_scroll_motion_grab_window_has_its_own_check", + setup: setup_p22_grab, + deny: &[(A, SCROLL_MOTION_CALL, ROOT)], + denied: Expect { + frames: &[], + calls: &[ + (A, P22_GRAB_PRESS_CALL, ROOT), + (A, SCROLL_MOTION_CALL, ROOT), + ], + }, + ..P22_GRAB_PRESS_DENIED +}; + +const P22_GRAB_PRESS_DENIED: Row = Row { + name: "p22_scroll_motion_grab_window_has_its_own_check", + setup: setup_p22_grab, + drive: P22.drive, + deny: &[(A, P22_GRAB_PRESS_CALL, ROOT)], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], + calls: &[ + (A, P22_GRAB_PRESS_CALL, ROOT), + (A, SCROLL_MOTION_CALL, ROOT), + ], + }, + denied: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], + calls: &[ + (A, P22_GRAB_PRESS_CALL, ROOT), + (A, SCROLL_MOTION_CALL, ROOT), + ], + }, +}; + +/// The scroll Motion of an XI2 grab with owner_events false is a grab-window +/// copy of its own: one fresh check, whatever the press's check at that +/// window said. Denying the press check leaves the Motion written; denying the +/// Motion check drops it. +/// Mutation: the Motion reuses the press's grab-window result (the first row +/// then drops the Motion), or is written unchecked (the second row writes it). +#[test] +fn p22_scroll_motion_grab_window_has_its_own_check() { + check_row(&P22_GRAB_PRESS_DENIED); + check_row(&P22_GRAB_MOTION_DENIED); +} From 565cb28f5d7e340d45a259b877ad31ddfeb02d5f Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 20:48:39 -0300 Subject: [PATCH 35/72] feat(access): Receive decides XI1 device event delivery The XI1 router takes the dispatch's ReceiveMemo. A natural walk stops only at a window with an allowed (or no-copy) selector; the XI1 grab, the owner_events route, the XI2 slave grab filter and the passive activating write use the same decision, so route and write agree with one call per copy. Thaw re-entries and the XI1 focused key each get a fresh memo. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Sonnet 5.5 --- .../yserver-core/src/core_loop/key_fanout.rs | 1 + .../src/core_loop/pointer_fanout.rs | 229 ++++++---- .../core_loop/pointer_fanout/owner_events.rs | 9 +- .../tests/access_input_support.rs | 80 +++- .../process_request/tests/access_key_input.rs | 93 ++++ .../tests/access_pointer_input.rs | 401 +++++++++++++++++- .../process_request/xi/dispatch/grabs.rs | 8 +- 7 files changed, 736 insertions(+), 85 deletions(-) diff --git a/crates/yserver-core/src/core_loop/key_fanout.rs b/crates/yserver-core/src/core_loop/key_fanout.rs index f8ca7af00..f3415f51f 100644 --- a/crates/yserver-core/src/core_loop/key_fanout.rs +++ b/crates/yserver-core/src/core_loop/key_fanout.rs @@ -1758,6 +1758,7 @@ fn deliver_xi1_focused_key( }, true, None, + &mut crate::core_loop::fanout::ReceiveMemo::new(), ) } diff --git a/crates/yserver-core/src/core_loop/pointer_fanout.rs b/crates/yserver-core/src/core_loop/pointer_fanout.rs index 91d418d26..ac85d0beb 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout.rs @@ -2152,7 +2152,8 @@ fn pointer_event_fanout_to_state_inner( xi1_routed, )); } - let extras = xi1_route_device_event(state, q, true, slave_press_delivery.as_ref()); + let extras = + xi1_route_device_event(state, q, true, slave_press_delivery.as_ref(), &mut receive); merge_dropped(&mut dropped, extras); } @@ -3286,6 +3287,7 @@ pub(crate) fn xi1_route_device_event( q: crate::server::Xi1QueuedEvent, allow_freeze: bool, slave_press_delivery: Option<&SlavePressDelivery>, + receive: &mut ReceiveMemo, ) -> Vec { use crate::xinput::{ XI_DEVICE_BUTTON_PRESS_OFFSET, XI_DEVICE_BUTTON_RELEASE_OFFSET, XI_DEVICE_KEY_PRESS_OFFSET, @@ -3364,15 +3366,20 @@ pub(crate) fn xi1_route_device_event( // 2. Active grab. if let Some(grab) = state.xi1_active_grabs.get(&q.deviceid).copied() { - // owner_events: natural delivery when the natural target's - // selection walk would report to the grab owner anyway. - let natural = compute_xi1_route_targets(state, &q); - let (targets, event_window) = match natural { - Some((clients, w)) if grab.owner_events && clients.contains(&grab.owner) => { - (vec![grab.owner], w) - } - _ => (vec![grab.owner], grab.grab_window), + // owner_events: natural delivery at the first window whose copy the + // owner receives, unless a foreign allowed copy comes first. The + // grab-window copy is its own attempt with one fresh check, made before + // the implicit device-mask gate (`dix/events.c:4388-4398`); a denial + // counts as delivered. + let natural_window = if grab.owner_events { + xi1_owner_events_window(state, &q, grab.owner, receive) + } else { + None }; + let event_window = natural_window.unwrap_or(grab.grab_window); + let copy_allowed = natural_window.is_some() + || xi1_grab_window_copy_allowed(state, &q, grab.owner, grab.grab_window); + let targets = vec![grab.owner]; log::debug!( "xi1_route: evcode={} GRAB owner={} window=0x{:x} detail={}", q.evcode, @@ -3380,7 +3387,8 @@ pub(crate) fn xi1_route_device_event( event_window.0, q.detail, ); - let deliver = !grab.implicit || grab.device_mask & xi1_event_mask_bit(q.evcode) != 0; + let deliver = copy_allowed + && (!grab.implicit || grab.device_mask & xi1_event_mask_bit(q.evcode) != 0); let dropped = if deliver { xi1_fan_device_event(state, &targets, event_window, &q) } else { @@ -3440,7 +3448,13 @@ pub(crate) fn xi1_route_device_event( g.other_mode == 0, ); } - let dropped = xi1_fan_device_event(state, &[g.owner], g.grab_window, &q); + // The activating write is a grab-window copy: one fresh check; a + // denial still activates and freezes with the stored press. + let dropped = if xi1_grab_window_copy_allowed(state, &q, g.owner, g.grab_window) { + xi1_fan_device_event(state, &[g.owner], g.grab_window, &q) + } else { + Vec::new() + }; if allow_freeze { let sync = state.xi1_frozen.entry(q.deviceid).or_default(); if sync.state == crate::server::Xi1SyncState::FrozenNoEvent { @@ -3455,7 +3469,8 @@ pub(crate) fn xi1_route_device_event( // 4. Selection delivery, gated by the device-focus route // (DeliverFocusedEvent for keyboard devices; plain walk for // pointer devices). - let (selection_filter, _direct_grab_route) = xi1_selection_filter_for_slave_grab(state, &q); + let (selection_filter, _direct_grab_route) = + xi1_selection_filter_for_slave_grab(state, &q, receive); let mut dropped = Vec::new(); let hit = if is_button_press && let Some(delivery) = slave_press_delivery @@ -3468,12 +3483,10 @@ pub(crate) fn xi1_route_device_event( } else { match selection_filter { Xi1SelectionFilter::Suppress => None, - Xi1SelectionFilter::Unrestricted => compute_xi1_route_targets(state, &q), - Xi1SelectionFilter::Client(client) => { - compute_xi1_route_targets(state, &q).and_then(|(targets, window)| { - targets.contains(&client).then_some((vec![client], window)) - }) - } + Xi1SelectionFilter::Unrestricted => compute_xi1_route_targets(state, &q, Some(receive)), + // The XI2 route already decided this owner copy with the dispatch + // memo: write it at that window, no second walk. + Xi1SelectionFilter::Client(client, window) => Some((vec![client], window)), } }; let xi1_implicit_press = is_button_press @@ -3538,31 +3551,126 @@ pub(crate) fn xi1_route_device_event( dropped } +/// The windows the XI1 selection walk visits, in order: unbounded walk, +/// walk bounded at the focus window, focus-window-only, or none. +fn xi1_route_windows(state: &ServerState, q: &crate::server::Xi1QueuedEvent) -> Vec { + let stop_at = match q.focus_route { + crate::server::Xi1FocusRoute::Walk => None, + crate::server::Xi1FocusRoute::WalkUpTo(stop) => Some(stop), + crate::server::Xi1FocusRoute::WindowOnly(w) => return vec![w], + crate::server::Xi1FocusRoute::Drop => return Vec::new(), + }; + let mut windows = Vec::new(); + let mut window = q.natural_target; + loop { + windows.push(window); + if window == ROOT_WINDOW || stop_at == Some(window) { + break; + } + match state.resources.window(window).map(|w| w.parent) { + Some(parent) if parent != window => window = parent, + _ => break, + } + } + windows +} + +/// True when `client` selected this event but gets no copy of it: a synthetic +/// repeat release to a detectable-repeat client. Receive is not asked for it. +fn xi1_gets_no_copy( + state: &ServerState, + q: &crate::server::Xi1QueuedEvent, + client: ClientId, +) -> bool { + q.synthetic_repeat + && q.evcode == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET + && state + .xkb_clients + .get(&client.0) + .is_some_and(|flags| flags.wants_detectable_auto_repeat()) +} + +/// The selectors at `window` that stop the walk there: those whose copy is +/// allowed, plus the no-copy ones (they stop it with no call). With no memo +/// every selector counts (today's selection-only walk). +fn xi1_allowed_selectors( + state: &ServerState, + window: ResourceId, + q: &crate::server::Xi1QueuedEvent, + receive: Option<&mut ReceiveMemo>, +) -> Vec { + let mut selectors = xi1_window_selectors(state, window, q.evcode, q.deviceid); + if let Some(memo) = receive { + let batch = xi1_batch(q.evcode); + let events = EventBatch::new(&batch); + selectors.retain(|client| { + xi1_gets_no_copy(state, q, *client) + || memo.allows(state, *client, EventSubject::Window(window), &events) + }); + } + selectors +} + /// Apply the event's [`Xi1FocusRoute`] to find selection-delivery /// targets — the XI1 analogue of Xorg `DeliverFocusedEvent` -/// (dix/events.c:4202): unbounded walk, walk bounded at the focus -/// window, focus-window-only, or none (focus = None). +/// (dix/events.c:4202). A window with no allowed selector does not stop the +/// walk (a denied copy is a non-delivery); with `WindowOnly` it ends it. fn compute_xi1_route_targets( state: &ServerState, q: &crate::server::Xi1QueuedEvent, + mut receive: Option<&mut ReceiveMemo>, ) -> Option<(Vec, ResourceId)> { - match q.focus_route { - crate::server::Xi1FocusRoute::Walk => { - compute_xi1_targets_bounded(state, q.natural_target, q.evcode, q.deviceid, None) + xi1_route_windows(state, q).into_iter().find_map(|window| { + let targets = xi1_allowed_selectors(state, window, q, receive.as_deref_mut()); + (!targets.is_empty()).then_some((targets, window)) + }) +} + +/// owner_events grab: the window whose copy the grab owner receives naturally. +/// At each window the owner qualifies first (its copy allowed, or no copy); +/// only if it does not are the foreign selectors evaluated (no short-circuit), +/// and an allowed one sends the event to the grab window. `None` = grab window. +fn xi1_owner_events_window( + state: &ServerState, + q: &crate::server::Xi1QueuedEvent, + owner: ClientId, + receive: &mut ReceiveMemo, +) -> Option { + let batch = xi1_batch(q.evcode); + let events = EventBatch::new(&batch); + for window in xi1_route_windows(state, q) { + let selectors = xi1_window_selectors(state, window, q.evcode, q.deviceid); + if selectors.is_empty() { + continue; } - crate::server::Xi1FocusRoute::WalkUpTo(stop) => { - compute_xi1_targets_bounded(state, q.natural_target, q.evcode, q.deviceid, Some(stop)) + let mut copy_allowed = |client: ClientId| { + xi1_gets_no_copy(state, q, client) + || receive.allows(state, client, EventSubject::Window(window), &events) + }; + if selectors.contains(&owner) && copy_allowed(owner) { + return Some(window); } - crate::server::Xi1FocusRoute::WindowOnly(w) => { - let targets = xi1_window_selectors(state, w, q.evcode, q.deviceid); - if targets.is_empty() { - None - } else { - Some((targets, w)) - } + let mut rejected = false; + for client in selectors.iter().filter(|c| **c != owner) { + rejected |= copy_allowed(*client); + } + if rejected { + return None; } - crate::server::Xi1FocusRoute::Drop => None, } + None +} + +/// The grab-window copy of an XI1 event is its own attempt: one fresh check in +/// the XI1 form. An owner that gets no copy is not asked. +fn xi1_grab_window_copy_allowed( + state: &ServerState, + q: &crate::server::Xi1QueuedEvent, + owner: ClientId, + grab_window: ResourceId, +) -> bool { + !xi1_gets_no_copy(state, q, owner) + && grab_window_allows_batch(state, owner, grab_window, &xi1_batch(q.evcode)) } /// The XI1 passive grab an XI1 press activates, if any (the replay floor @@ -3699,12 +3807,7 @@ fn xi1_fan_device_event( targets .iter() .copied() - .filter(|client| { - !state - .xkb_clients - .get(&client.0) - .is_some_and(|flags| flags.wants_detectable_auto_repeat()) - }) + .filter(|client| !xi1_gets_no_copy(state, q, *client)) .collect() } else { targets.to_vec() @@ -3862,7 +3965,7 @@ pub(crate) fn xi1_compute_freezes( ); } crate::server::QueuedInputEvent::Xi1Routed(event) => { - let _ = xi1_route_device_event(state, event, true, None); + let _ = xi1_route_device_event(state, event, true, None, &mut ReceiveMemo::new()); } crate::server::QueuedInputEvent::RawKey(event) => { let _ = crate::core_loop::key_fanout::deliver_raw_key_master(state, event); @@ -4103,40 +4206,6 @@ pub(crate) fn xi1_device_grab_owner(state: &ServerState, deviceid: u16) -> Optio } } -/// Find the clients receiving an XI 1.x device input event: starting -/// at the hit target, walk up the ancestor chain; the first window -/// where at least one client selected `(deviceid << 8) | evcode` -/// becomes the event window, and all clients selecting there receive -/// it. Mirrors core propagation (Xorg dix DeliverDeviceEvents); the -/// XI1 dont-propagate list is not honoured yet. -/// -/// `stop_at` is the last window checked (inclusive) — Xorg -/// `DeliverDeviceEvents`'s `stopAt` argument, used when a focus window -/// caps the walk (dix/events.c:4220). -fn compute_xi1_targets_bounded( - state: &ServerState, - target: ResourceId, - evcode: u8, - deviceid: u16, - stop_at: Option, -) -> Option<(Vec, ResourceId)> { - let mut window = target; - loop { - let targets = xi1_window_selectors(state, window, evcode, deviceid); - if !targets.is_empty() { - return Some((targets, window)); - } - if window == ROOT_WINDOW || stop_at == Some(window) { - return None; - } - let parent = state.resources.window(window).map(|w| w.parent)?; - if parent == window { - return None; - } - window = parent; - } -} - fn translate_host_event( state: &ServerState, xid_map: &HostXidMap, @@ -4304,6 +4373,16 @@ fn grab_window_allows( owner: ClientId, grab_window: ResourceId, description: &EventDescription, +) -> bool { + grab_window_allows_batch(state, owner, grab_window, std::slice::from_ref(description)) +} + +/// `grab_window_allows` for a copy that is a batch of descriptions. +fn grab_window_allows_batch( + state: &ServerState, + owner: ClientId, + grab_window: ResourceId, + descriptions: &[EventDescription], ) -> bool { if !state.policies_installed() { return true; @@ -4313,7 +4392,7 @@ fn grab_window_allows( state, owner, EventSubject::Window(grab_window), - &EventBatch::new(std::slice::from_ref(description)), + &EventBatch::new(descriptions), ) } diff --git a/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs b/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs index e2c8a40d6..f86ea40ad 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs @@ -242,13 +242,15 @@ pub(super) fn xi2_motion_targets_for_source( #[derive(Clone, Copy)] pub(super) enum Xi1SelectionFilter { Unrestricted, - Client(ClientId), + /// The grab owner's XI1 copy, decided at this window by the XI2 route. + Client(ClientId, ResourceId), Suppress, } pub(super) fn xi1_selection_filter_for_slave_grab( state: &ServerState, q: &crate::server::Xi1QueuedEvent, + receive: &mut ReceiveMemo, ) -> ( Xi1SelectionFilter, Option<(crate::server::ActivePointerGrab, OwnerEventsRoute)>, @@ -280,7 +282,7 @@ pub(super) fn xi1_selection_filter_for_slave_grab( 0, Some(evtype), Some(class), - None, + Some(receive), false, ) } else { @@ -292,8 +294,9 @@ pub(super) fn xi1_selection_filter_for_slave_grab( match route { OwnerEventsRoute::Natural { protocol: OwnerProtocol::Xi1, + window, .. - } => Xi1SelectionFilter::Client(grab.owner), + } => Xi1SelectionFilter::Client(grab.owner, window), OwnerEventsRoute::Natural { .. } | OwnerEventsRoute::Fallback => { Xi1SelectionFilter::Suppress } diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index 9fd854e73..776436075 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -69,6 +69,14 @@ pub(super) enum Kind { /// An XI1 `DeviceButtonPress`: its device. The frame carries the button in /// its detail byte and the event window at byte 12, as a core frame does. Xi1(u16), + /// An XI1 `DeviceKeyPress` or `DeviceKeyRelease`: its device. + Xi1Key(u16), + /// An XI1 `DeviceMotionNotify` (the leading frame of a motion batch): its + /// device. + Xi1Motion(u16), + /// The `DeviceValuator` continuation of a motion batch: its device. It has + /// no event window; it decodes with window 0. + Xi1Valuator(u16), /// A raw key copy: its device, always on the root. A raw frame has no /// event window, so the grab-leg copy and the root-fanout copy decode the /// same; only the Receive trace tells them apart. @@ -634,6 +642,29 @@ pub(super) fn decode(frame: &[u8], order: ClientByteOrder) -> Option<(Kind, u32) dec32(&frame[12..16], order), )) } + code if code + == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET + || code + == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET => + { + Some(( + Kind::Xi1Key(u16::from(frame[31] & 0x7f)), + dec32(&frame[12..16], order), + )) + } + code if code + == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET => + { + Some(( + Kind::Xi1Motion(u16::from(frame[31] & 0x7f)), + dec32(&frame[12..16], order), + )) + } + code if code + == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_VALUATOR_OFFSET => + { + Some((Kind::Xi1Valuator(u16::from(frame[1])), 0)) + } 35 if frame[1] == XI2_MAJOR_OPCODE => match dec16(&frame[8..10], order) { 2..=6 => Some(( Kind::Xi2(dec16(&frame[10..12], order)), @@ -767,7 +798,7 @@ pub(super) fn run(row: &Row, policy: Option<&'static [Call]>) -> Run { /// The grab facts of a server state, in a fixed order: keyboard grab, master /// pointer grab, slave pointer grabs by device, XI1 grabs by device, then the /// master keyboard and pointer freezes. -fn grab_facts(state: &ServerState) -> Vec { +pub(super) fn grab_facts(state: &ServerState) -> Vec { let pointer = |grab: &crate::server::ActivePointerGrab| PointerGrab { owner: grab.owner.0, window: grab.grab_window.0, @@ -850,7 +881,12 @@ pub(super) fn delivered(name: &str, run: &Run, detail: u32, wheel_press: bool) - client.client ); let keycode = match kind { - Kind::Core | Kind::Xi1(_) => u32::from(frame[1]), + Kind::Core | Kind::Xi1(_) | Kind::Xi1Key(_) | Kind::Xi1Motion(_) => { + u32::from(frame[1]) + } + // The valuator continuation has no detail byte (byte 1 is + // the device). + Kind::Xi1Valuator(_) => detail, Kind::Xi2(_) | Kind::Raw(_) => dec32(&frame[16..20], client.order), }; // The smooth-scroll Motion of a wheel press carries no button. @@ -995,6 +1031,12 @@ pub(super) fn check_row(row: &Row) { } // A core frame is pinned in full; an XI2 or raw frame is matched // by client and window only (its literal is not encoded here). + // The valuator continuation rides on its motion frame, which is the + // one the row pins. + if let Kind::Xi1Valuator(device) = kind { + assert_eq!(u16::from(frame[1]), device, "{name}: valuator device"); + continue; + } let moved = row .moved .iter() @@ -1042,6 +1084,40 @@ pub(super) fn check_row(row: &Row) { got.client ); } + if let Kind::Xi1Key(device) | Kind::Xi1Motion(device) = kind { + // The core key or motion layout, with the XI1 event code and + // the device id (motion also carries MORE_EVENTS) at byte 31. + let (offset, last) = match kind { + Kind::Xi1Motion(_) => ( + crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET, + device as u8 | crate::xinput::XI1_MORE_EVENTS, + ), + _ if row.drive.ev() == 3 => { + (crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET, device as u8) + } + _ => (crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET, device as u8), + }; + let mut expected = literal_moved( + row.drive.ev(), + row.drive.detail(), + got.order, + got.sequence, + moved, + ); + expected[0] = crate::server::XI_FIRST_EVENT + offset; + expected[31] = last; + if let Drive::Pointer { to, .. } = row.drive { + // The root position of the event (bytes 20..24). + expected[20..22].copy_from_slice(&enc16(got.order, to.0 as u16)); + expected[22..24].copy_from_slice(&enc16(got.order, to.1 as u16)); + } + assert_eq!( + frame, + expected.as_slice(), + "{name}: client {} moved XI1 frame @{window:#x}", + got.client + ); + } if kind == Kind::Core { assert_eq!( frame, diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs index 3ac493a76..606205103 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -1148,3 +1148,96 @@ const K15_ALLOWED_NATURAL_SKIPS_GRAB_WINDOW: Row = Row { fn k15_allowed_natural_raw_leg_skips_the_grab_window_check() { check_row(&K15_ALLOWED_NATURAL_SKIPS_GRAB_WINDOW); } + +// ---- XI1 router (plan 2, task 5) ------------------------------------------- + +const XI1_KEY_PRESS_CALL: CallKind = + CallKind::Batch(&[Named::Xi1(crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET as u16)]); +const XI1_KEY_RELEASE_CALL: CallKind = CallKind::Batch(&[Named::Xi1( + crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET as u16, +)]); + +fn xi1_key_class(offset: u8) -> u32 { + (u32::from(DEVICEID_XTEST_KEYBOARD) << 8) | u32::from(crate::server::XI_FIRST_EVENT + offset) +} + +fn setup_k16(f: &mut NotifyFixture) { + tree(f); + let class = xi1_key_class(crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET); + select_xi1(f, A, CHILD, &[class]); + select_xi1(f, B, FOCUS, &[class]); +} + +const K16: Row = Row { + name: "k16_xi1_focused_key_denial_advances_the_focus_walk", + setup: setup_k16, + drive: Drive::Entry { + origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), + pressed: true, + }, + deny: &[(A, XI1_KEY_PRESS_CALL, CHILD)], + allow: Expect { + frames: &[(A, Kind::Xi1Key(DEVICEID_XTEST_KEYBOARD), CHILD)], + calls: &[(A, XI1_KEY_PRESS_CALL, CHILD)], + }, + denied: Expect { + frames: &[(B, Kind::Xi1Key(DEVICEID_XTEST_KEYBOARD), FOCUS)], + calls: &[ + (A, XI1_KEY_PRESS_CALL, CHILD), + (B, XI1_KEY_PRESS_CALL, FOCUS), + ], + }, + denied_grab: None, + moved: &[Moved { + client: B, + window: FOCUS, + child: CHILD, + event: (20, 20), + }], +}; + +/// XTEST keyboard origin; X selects the XI1 `DeviceKeyPress` on C (the pointer +/// window, under focus F), Y on F. X's copy denied: the focus walk goes on and +/// Y gets it at F. Mutation: a denied XI1 selector stops the walk. +#[test] +fn k16_xi1_focused_key_denial_advances_the_focus_walk() { + check_row(&K16); +} + +fn setup_k17(f: &mut NotifyFixture) { + tree(f); + let class = xi1_key_class(crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET); + select_xi1(f, A, CHILD, &[class]); + select_xi1(f, B, FOCUS, &[class]); + set_detectable_repeat(f, A); +} + +const K17: Row = Row { + name: "k17_xi1_detectable_repeat_release_stops_without_a_check", + setup: setup_k17, + drive: Drive::After { + origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), + pressed: false, + master: false, + synthetic: true, + }, + deny: &[(A, XI1_KEY_RELEASE_CALL, CHILD)], + allow: Expect { + frames: &[], + calls: &[], + }, + denied: Expect { + frames: &[], + calls: &[], + }, + denied_grab: None, + moved: &[], +}; + +/// A synthetic repeat release to a detectable-repeat client gets no copy but +/// stops the walk: nothing is written, X is not asked, Y is not reached. +/// Mutation: X is asked (a call) or the walk goes past it (Y gets a frame). +#[test] +fn k17_xi1_detectable_repeat_release_stops_without_a_check() { + check_row(&K17); +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index 04bb0d8fd..e2141ba53 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -1808,21 +1808,32 @@ const P20B: Row = Row { moved: &[], allow: Expect { frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], - calls: &[], + calls: &[(B, XI1_PRESS_CALL, FOCUS)], }, denied: Expect { frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], - calls: &[], + calls: &[(B, XI1_PRESS_CALL, FOCUS)], }, }; /// An XI1 passive grab takes the slave press, so the router never reaches the /// selection walk: A's selector copy is not written and Receive is not asked -/// (the activating write is Task 5's). Mutation: the route asks the XI1 -/// selectors although a passive grab matches (`xi1_routed` ignores it). +/// (the activating write is the grab owner's one fresh check). Mutation: the +/// route asks the XI1 selectors although a passive grab matches (`xi1_routed` +/// ignores it). With the owner denied the grab still activates and nobody gets +/// the press; mutation: the activating write is unchecked. #[test] fn p20b_xi1_passive_activation_asks_no_selector() { check_row(&P20B); + check_row(&Row { + name: "p20b_xi1_passive_activation_owner_denied", + deny: &[(B, XI1_PRESS_CALL, FOCUS)], + denied: Expect { + frames: &[], + calls: &[(B, XI1_PRESS_CALL, FOCUS)], + }, + ..P20B + }); } /// The press over a root that nothing can hit (unmapped, as `unhit_root` @@ -2179,3 +2190,385 @@ fn p22_scroll_motion_grab_window_has_its_own_check() { check_row(&P22_GRAB_PRESS_DENIED); check_row(&P22_GRAB_MOTION_DENIED); } + +// ---- P24-P28: the XI1 router ---------------------------------------------- + +/// The XI1 class of the slave's `DeviceMotionNotify`. +fn xi1_slave_motion() -> u32 { + xi1_class( + DEVICEID_XTEST_POINTER, + crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET, + ) +} + +/// The Receive batch of an XI1 `DeviceMotionNotify` copy: the motion event and +/// its `DeviceValuator` continuation are one batch (`dix/eventconvert.c:369`). +const XI1_MOTION_CALL: CallKind = CallKind::Batch(&[ + Named::Xi1(crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET as u16), + Named::Xi1(crate::xinput::XI_DEVICE_VALUATOR_OFFSET as u16), +]); + +fn setup_p24(f: &mut NotifyFixture) { + tree(f); + park_pointer(f); + select_xi1(f, A, CHILD, &[xi1_slave_motion()]); + select_xi1(f, B, FOCUS, &[xi1_slave_motion()]); +} + +const P24: Row = Row { + name: "p24_denied_xi1_selector_advances_the_walk", + setup: setup_p24, + drive: motion(XTEST_SLAVE), + deny: &[(A, XI1_MOTION_CALL, CHILD)], + denied_grab: None, + moved: &[Moved { + client: B, + window: FOCUS, + child: CHILD, + event: MOTION_EVENT_AT_P, + }], + allow: Expect { + frames: &[ + (A, Kind::Xi1Motion(DEVICEID_XTEST_POINTER), CHILD), + (A, Kind::Xi1Valuator(DEVICEID_XTEST_POINTER), 0), + ], + calls: &[(A, XI1_MOTION_CALL, CHILD)], + }, + denied: Expect { + frames: &[ + (B, Kind::Xi1Motion(DEVICEID_XTEST_POINTER), FOCUS), + (B, Kind::Xi1Valuator(DEVICEID_XTEST_POINTER), 0), + ], + calls: &[(A, XI1_MOTION_CALL, CHILD), (B, XI1_MOTION_CALL, FOCUS)], + }, +}; + +/// Slave motion over C: A selects XI1 `DeviceMotionNotify` on C, B on P. A's +/// copy denied: the walk goes on and B gets it at P. Mutation: a denied XI1 +/// selector stops the walk (selection decides the window), so B gets nothing. +#[test] +fn p24_denied_xi1_selector_advances_the_walk() { + check_row(&P24); +} + +fn setup_p25(f: &mut NotifyFixture) { + tree(f); + park_pointer(f); + select_xi1(f, A, CHILD, &[xi1_slave_motion()]); +} + +const P25: Row = Row { + name: "p25_device_motion_and_valuator_are_one_batch", + setup: setup_p25, + drive: motion(XTEST_SLAVE), + deny: &[(A, XI1_MOTION_CALL, CHILD)], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[ + (A, Kind::Xi1Motion(DEVICEID_XTEST_POINTER), CHILD), + (A, Kind::Xi1Valuator(DEVICEID_XTEST_POINTER), 0), + ], + calls: &[(A, XI1_MOTION_CALL, CHILD)], + }, + denied: Expect { + frames: &[], + calls: &[(A, XI1_MOTION_CALL, CHILD)], + }, +}; + +/// The motion event and its valuator continuation are decided by one call with +/// the two-description batch: denied writes neither frame. Mutation: the route +/// or the write checks per event (two calls; the denied batch never matches +/// either single-description call, so both frames are written). +#[test] +fn p25_device_motion_and_valuator_are_one_batch() { + check_row(&P25); +} + +/// The XI1 `GrabDevice` of the slave pointer by `owner` on `window`. +fn xi1_grab_device(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: bool) { + const XI_GRAB_DEVICE_XI1: u8 = 13; + let mut body = Vec::with_capacity(16); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime + body.extend_from_slice(&0_u16.to_le_bytes()); // no event classes + body.extend_from_slice(&[1, 1, u8::from(owner_events)]); // async modes + body.push(DEVICEID_XTEST_POINTER as u8); + body.extend_from_slice(&[0, 0]); + let bytes = send_with_reply(f, owner, XI_MAJOR, XI_GRAB_DEVICE_XI1, &body); + let reply = &bytes[bytes.len() - 32..]; + assert_eq!((reply[0], reply[8]), (1, 0), "GrabDevice replies Success"); +} + +fn setup_p26_owner_events(f: &mut NotifyFixture) { + tree(f); + select_xi1(f, A, CHILD, &[xi1_slave_press()]); + select_xi1(f, B, CHILD, &[xi1_slave_press()]); + xi1_grab_device(f, A, ROOT, true); +} + +fn xi1_grab_fact(window: u32) -> Grab { + Grab::Xi1 { + device: DEVICEID_XTEST_POINTER, + owner: A, + window, + } +} + +const P26_OWNER_DENIED: Row = Row { + name: "p26_xi1_grab_owner_denied_falls_to_the_grab_window", + setup: setup_p26_owner_events, + drive: press(XTEST_SLAVE), + deny: &[(A, XI1_PRESS_CALL, CHILD)], + denied_grab: None, + moved: &[Moved { + client: A, + window: ROOT, + child: FOCUS, + event: POINTER, + }], + allow: Expect { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + calls: &[(A, XI1_PRESS_CALL, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT)], + calls: &[ + (A, XI1_PRESS_CALL, CHILD), + (B, XI1_PRESS_CALL, CHILD), + (A, XI1_PRESS_CALL, ROOT), + ], + }, +}; + +fn setup_p26_not_owner_events(f: &mut NotifyFixture) { + tree(f); + select_xi1(f, A, CHILD, &[xi1_slave_press()]); + select_xi1(f, B, CHILD, &[xi1_slave_press()]); + xi1_grab_device(f, A, ROOT, false); +} + +const P26_NO_OWNER_EVENTS: Row = Row { + name: "p26_xi1_grab_without_owner_events_asks_only_the_grab_window", + setup: setup_p26_not_owner_events, + drive: press(XTEST_SLAVE), + deny: &[(A, XI1_PRESS_CALL, ROOT)], + denied_grab: None, + moved: &[], + allow: Expect { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT)], + calls: &[(A, XI1_PRESS_CALL, ROOT)], + }, + denied: Expect { + frames: &[], + calls: &[(A, XI1_PRESS_CALL, ROOT)], + }, +}; + +const P26_OWNER_ALLOWED: Row = Row { + name: "p26_xi1_grab_owner_allowed_asks_no_foreign_selector", + setup: setup_p26_owner_events, + deny: &[], + moved: &[], + denied: Expect { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + calls: &[(A, XI1_PRESS_CALL, CHILD)], + }, + ..P26_OWNER_DENIED +}; + +/// Slave origin, XI1 `GrabDevice` by A on G (the root). With `owner_events` +/// and A's own copy on C allowed A gets it at C and the foreign selector B is +/// not asked. With A denied, B (allowed) sends the event to G: A gets one fresh +/// check there. Without `owner_events` the natural walk is not checked at all: +/// only A's copy at G, and a denial there is a delivery (grab stays). +/// Mutations: the owner copy is not checked in the route (selection decides); +/// the foreign selector is asked before the owner; the grab-window copy is +/// written unchecked or the natural walk is asked without `owner_events`. +#[test] +fn p26_xi1_grab() { + check_row(&P26_OWNER_DENIED); + check_row(&P26_OWNER_ALLOWED); + check_row(&P26_NO_OWNER_EVENTS); + for row in [&P26_OWNER_DENIED, &P26_NO_OWNER_EVENTS] { + assert_eq!(run(row, Some(row.deny)).grab, vec![xi1_grab_fact(ROOT)]); + } +} + +fn setup_p27(f: &mut NotifyFixture) { + tree(f); + select_xi1(f, A, CHILD, &[xi1_slave_press()]); + grab_keyboard_device(f, A, DEVICEID_XTEST_POINTER, ROOT, true, XI_BUTTON_PRESS); +} + +const P27: Row = Row { + name: "p27_xi1_slave_grab_filter_agrees_with_the_xi2_route", + setup: setup_p27, + drive: press(XTEST_SLAVE), + deny: &[(A, XI1_PRESS_CALL, CHILD)], + denied_grab: None, + moved: &[Moved { + client: A, + window: ROOT, + child: FOCUS, + event: POINTER, + }], + allow: Expect { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + calls: &[(A, XI1_PRESS_CALL, CHILD)], + }, + denied: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], + calls: &[(A, XI1_PRESS_CALL, CHILD), (A, CallKind::Xi2, ROOT)], + }, +}; + +/// An XIGrabDevice on the slave with `owner_events` and ButtonPress in its +/// mask; A selects the XI1 press on C. A's XI1 copy denied: the XI2 route +/// falls back to the grab window and the XI1 selection path delivers nothing +/// to A (one XI1 call, one XI2 grab-window call). Mutation: the filter is +/// selection-only (A also gets the XI1 copy at C: double delivery), or the +/// router asks again. +#[test] +fn p27_xi1_slave_grab_filter_agrees_with_the_xi2_route() { + check_row(&P27); +} + +/// Drains every client and appends the frames the walks write. +fn collect_frames(f: &mut NotifyFixture, frames: &mut Vec<(u32, Kind, u32)>) { + for id in [SEND_CLIENT, A, B] { + let order = f.state.clients[&id].byte_order; + let bytes = f.drain(ClientId(id)); + for frame in split_frames(&bytes, order) { + if let Some((kind, window)) = decode(frame, order) { + frames.push((id, kind, window)); + } + } + } +} + +/// What the thaw replay of p28 left: Receive calls and frames per client. +struct Replay { + calls: Vec<(u32, u32)>, + frames: Vec<(u32, Kind, u32)>, + grab: Vec, +} + +fn setup_p28(f: &mut NotifyFixture) { + tree(f); + select_xi1(f, A, CHILD, &[xi1_slave_press()]); + select_xi1( + f, + B, + CHILD, + &[xi1_slave_press(), xi1_grab_class(DEVICEID_XTEST_POINTER)], + ); + // A sync `GrabDeviceButton` by the requester on P, any button and modifier. + f.state + .xi1_passive_grabs + .push(crate::server::Xi1PassiveGrab { + owner: ClientId(SEND_CLIENT), + deviceid: DEVICEID_XTEST_POINTER, + grab_window: ResourceId(FOCUS), + detail: 0, + modifiers: 0x8000, + owner_events: false, + this_mode: 0, + other_mode: 1, + is_key: false, + }); +} + +/// Runs p28: the press activates the sync grab and is stored, then the owner's +/// `AllowDeviceEvents(ReplayThisDevice)` re-routes it. `denied` denies B's XI1 +/// press copy at C. +fn replay_p28(denied: bool) -> Replay { + const XI_ALLOW_DEVICE_EVENTS_XI1: u8 = 19; + let mut f = NotifyFixture::new(); + setup_p28(&mut f); + for id in [SEND_CLIENT, A, B] { + f.drain(ClientId(id)); + } + let seen = f.install_policy(move |_, call| { + let hit = denied + && call.hook == ExtensionHook::Receive + && call.client.0 == B + && call.receive == Some(EventSubject::Window(ResourceId(CHILD))); + if hit { DENY } else { Decision::Allow } + }); + drive(&mut f, press(XTEST_SLAVE)); + let freeze = f + .state + .xi1_frozen + .get(&DEVICEID_XTEST_POINTER) + .expect("the sync grab froze the slave"); + assert_eq!(freeze.state, Xi1SyncState::FrozenWithEvent); + let activation_calls = seen.lock().unwrap().len(); + assert_eq!(activation_calls, 1, "the activating write: one fresh check"); + let mut frames = Vec::new(); + collect_frames(&mut f, &mut frames); + let mut body = Vec::new(); + body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime + body.extend_from_slice(&[2, DEVICEID_XTEST_POINTER as u8, 0, 0]); // ReplayThisDevice + send( + &mut f, + SEND_CLIENT, + XI_MAJOR, + XI_ALLOW_DEVICE_EVENTS_XI1, + &body, + ); + let calls = seen + .lock() + .unwrap() + .iter() + .filter(|call| call.hook == ExtensionHook::Receive) + .map(|call| { + let Some(EventSubject::Window(window)) = call.receive else { + panic!("Receive subject {:?}", call.receive); + }; + (call.client.0, window.0) + }) + .collect(); + collect_frames(&mut f, &mut frames); + Replay { + calls, + frames, + grab: grab_facts(&f.state), + } +} + +/// A sync `GrabDeviceButton` by the requester on P activates on the press and +/// stores it; its `AllowDeviceEvents(ReplayThisDevice)` re-routes the press +/// through the thaw with no decided delivery. Two XI1 press selectors on C; the +/// one that also selected the grab class (B) is denied: the other (A) owns the +/// XI1 implicit grab. Allow-all: B, the grab class holder. Mutation: the +/// implicit owner is chosen among the selectors (the denied B owns the grab), +/// or the replay walk is unchecked (B gets the copy). +#[test] +fn p28_thawed_xi1_press_picks_the_owner_from_allowed() { + let xi1 = |client| (client, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD); + let owner = |client| { + vec![Grab::Xi1 { + device: DEVICEID_XTEST_POINTER, + owner: client, + window: CHILD, + }] + }; + let allow = replay_p28(false); + // The activating write first, then one call per selector (their order is + // the selection order, not part of the contract). + assert_eq!(allow.calls[0], (SEND_CLIENT, FOCUS)); + let mut replay_calls = allow.calls[1..].to_vec(); + replay_calls.sort_unstable(); + assert_eq!(replay_calls, vec![(A, CHILD), (B, CHILD)]); + assert!(allow.frames.contains(&xi1(A)) && allow.frames.contains(&xi1(B))); + assert_eq!(allow.grab, owner(B)); + let denied = replay_p28(true); + assert_eq!( + denied.calls, allow.calls, + "one call per recipient per attempt" + ); + assert!(denied.frames.contains(&xi1(A)) && !denied.frames.contains(&xi1(B))); + assert_eq!(denied.grab, owner(A)); +} diff --git a/crates/yserver-core/src/core_loop/process_request/xi/dispatch/grabs.rs b/crates/yserver-core/src/core_loop/process_request/xi/dispatch/grabs.rs index 43988ff1d..560a5588a 100644 --- a/crates/yserver-core/src/core_loop/process_request/xi/dispatch/grabs.rs +++ b/crates/yserver-core/src/core_loop/process_request/xi/dispatch/grabs.rs @@ -1955,7 +1955,13 @@ pub(super) fn handle_xi1_allow_device_events( match stored { crate::server::QueuedInputEvent::Xi1Routed(mut q) => { q.replay_floor = replay_floor; - let _ = xi1_route_device_event(state, q, true, None); + let _ = xi1_route_device_event( + state, + q, + true, + None, + &mut crate::core_loop::fanout::ReceiveMemo::new(), + ); } crate::server::QueuedInputEvent::HostPointer(event) => { let xid_map = backend.xid_map().clone(); From d707d62183d605d89cbe7883aa94e01a804c265b Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 20:51:56 -0300 Subject: [PATCH 36/72] test(access): XI1 grab foreign rejection and filter route window Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Sonnet 5.5 --- .../tests/access_pointer_input.rs | 66 ++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index e2141ba53..7a297b1f0 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -2378,6 +2378,26 @@ const P26_OWNER_ALLOWED: Row = Row { ..P26_OWNER_DENIED }; +fn setup_p26_foreign_rejects(f: &mut NotifyFixture) { + tree(f); + select_xi1(f, A, CHILD, &[xi1_slave_press()]); + select_xi1(f, A, FOCUS, &[xi1_slave_press()]); + select_xi1(f, B, CHILD, &[xi1_slave_press()]); + xi1_grab_device(f, A, ROOT, true); +} + +/// O denied on C, F allowed on C: F's copy rejects the walk, so O does not +/// reach its own selector on P: it gets the event at G. +const P26_FOREIGN_REJECTS: Row = Row { + name: "p26_xi1_grab_foreign_copy_rejects_the_walk", + setup: setup_p26_foreign_rejects, + allow: Expect { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + calls: &[(A, XI1_PRESS_CALL, CHILD)], + }, + ..P26_OWNER_DENIED +}; + /// Slave origin, XI1 `GrabDevice` by A on G (the root). With `owner_events` /// and A's own copy on C allowed A gets it at C and the foreign selector B is /// not asked. With A denied, B (allowed) sends the event to G: A gets one fresh @@ -2391,7 +2411,12 @@ fn p26_xi1_grab() { check_row(&P26_OWNER_DENIED); check_row(&P26_OWNER_ALLOWED); check_row(&P26_NO_OWNER_EVENTS); - for row in [&P26_OWNER_DENIED, &P26_NO_OWNER_EVENTS] { + check_row(&P26_FOREIGN_REJECTS); + for row in [ + &P26_OWNER_DENIED, + &P26_NO_OWNER_EVENTS, + &P26_FOREIGN_REJECTS, + ] { assert_eq!(run(row, Some(row.deny)).grab, vec![xi1_grab_fact(ROOT)]); } } @@ -2448,6 +2473,45 @@ fn collect_frames(f: &mut NotifyFixture, frames: &mut Vec<(u32, Kind, u32)>) { } } +fn setup_p27_later_window(f: &mut NotifyFixture) { + tree(f); + select_xi1(f, B, CHILD, &[xi1_slave_press()]); + select_xi1(f, A, FOCUS, &[xi1_slave_press()]); + grab_keyboard_device(f, A, DEVICEID_XTEST_POINTER, ROOT, true, XI_BUTTON_PRESS); +} + +/// B's foreign XI1 copy on C is denied, A's own is on P. Allow-all: B's copy +/// rejects the walk, A gets the XI2 grab-window copy. Denied: the route reaches +/// A's selector on P and the router writes it there, though a selection-only +/// walk would stop at B's selector on C and give A nothing. Mutation: the +/// router walks the selectors again without the memo. +const P27_LATER_WINDOW: Row = Row { + name: "p27_xi1_slave_grab_filter_writes_at_the_route_window", + setup: setup_p27_later_window, + drive: press(XTEST_SLAVE), + deny: &[(B, XI1_PRESS_CALL, CHILD)], + denied_grab: None, + moved: &[Moved { + client: A, + window: FOCUS, + child: CHILD, + event: P_EVENT, + }], + allow: Expect { + frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], + calls: &[(B, XI1_PRESS_CALL, CHILD), (A, CallKind::Xi2, ROOT)], + }, + denied: Expect { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], + calls: &[(B, XI1_PRESS_CALL, CHILD), (A, XI1_PRESS_CALL, FOCUS)], + }, +}; + +#[test] +fn p27_xi1_slave_grab_filter_writes_at_the_route_window() { + check_row(&P27_LATER_WINDOW); +} + /// What the thaw replay of p28 left: Receive calls and frames per client. struct Replay { calls: Vec<(u32, u32)>, From 44f7dfb372fbb6817083dd12b1d9a633f6288bbf Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Tue, 1 Dec 2026 23:24:46 -0300 Subject: [PATCH 37/72] refactor(access): final review clean-ups for pointer delivery Compute the master-form grab predicate once and share it between the core shadow and the XI2 writer, drop the dead dedup top-level binding and the unreachable XI2 evtype branch, correct the scroll Motion grab-window comment, move a misplaced field doc, document the unmapped-root rows, and reword test comments that referred to plan structure. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Sonnet 5.5 --- .../src/core_loop/pointer_fanout.rs | 28 ++++++------------- .../core_loop/pointer_fanout/owner_events.rs | 6 ++-- .../tests/access_crossing_notify.rs | 6 ++-- .../tests/access_input_support.rs | 6 ++-- .../process_request/tests/access_key_input.rs | 4 +-- .../tests/access_pointer_input.rs | 16 ++++++----- 6 files changed, 30 insertions(+), 36 deletions(-) diff --git a/crates/yserver-core/src/core_loop/pointer_fanout.rs b/crates/yserver-core/src/core_loop/pointer_fanout.rs index ac85d0beb..a8d64625f 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout.rs @@ -1792,6 +1792,12 @@ fn pointer_event_fanout_to_state_inner( && (replay.is_some() || xi_source.slave_deviceid.is_none() || xi_source.attached_master == Some(XI2_MASTER_POINTER_DEVICE_ID)); + // Whether an XI2 grab owns delivery, and whether a grab decides the master + // form's recipients, asked once so the core shadow and the XI2 writer + // cannot disagree. + let xi2_grab_delivery = pointer_xi2_grab_delivery(state, handle_grabs, event.kind, xi_source); + let master_grab_decided = + master_form_decided_by_grab(state, xi_source, replay, xi2_grab_delivery); let slave_form_emitted = !is_crossing && xi_source.slave_deviceid.is_some() && replay_has_slave_form @@ -1863,22 +1869,9 @@ fn pointer_event_fanout_to_state_inner( // would compute the set for the wrong window and leak a double // (core + XI2) crossing to a client selecting both on the window being // left/entered. - let (dedup_target, _dedup_top_level) = if is_crossing { - (cross_start, state.top_level_for_target(cross_start)) - } else { - (target, top_level_id) - }; - let master_form_written = master_form_emitted - && !is_replay - && !master_form_decided_by_grab( - state, - xi_source, - replay, - pointer_xi2_grab_delivery(state, handle_grabs, event.kind, xi_source), - ); - let (master_route_window, shadowed) = if xi2_evt == 0 { - (None, Vec::new()) - } else { + let dedup_target = if is_crossing { cross_start } else { target }; + let master_form_written = master_form_emitted && !is_replay && !master_grab_decided; + let (master_route_window, shadowed) = { let window = xi2_route_window_for_source( state, dedup_target, @@ -2029,7 +2022,6 @@ fn pointer_event_fanout_to_state_inner( _ => None, }; let active_source_grab = active_grab_for_source(state, xi_source); - let xi2_grab_delivery = pointer_xi2_grab_delivery(state, handle_grabs, event.kind, xi_source); let owner_events_slave_route = if xi2_grab_delivery && let Some(grab) = grab_for_form(state, xi_source, Xi2PointerForm::Slave, replay) && grab.passive @@ -2203,8 +2195,6 @@ fn pointer_event_fanout_to_state_inner( // owner's copy is a fixed recipient, checked at the write), routes its // natural selectors by selection only. The slave press route decides its // XI2 recipients through the same memo, so they are written as they stand. - let master_grab_decided = - master_form_decided_by_grab(state, xi_source, replay, xi2_grab_delivery); let master_form_checked = master_form_emitted && !master_grab_decided; let mut xi2_slave_only_targets: Vec = Vec::new(); let mut xi2_targets = if matches!( diff --git a/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs b/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs index f86ea40ad..7a4b55935 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs @@ -170,8 +170,10 @@ pub(super) fn xi2_motion_targets_for_source( && let Some((grab_window, _, gx, gy, ..)) = super::active_pointer_grab_target(state, grab) // The grab window's copy is its own attempt: one fresh check - // for this Motion, before anything else decides it - // (`dix/events.c:4388-4398`). A denial counts as delivered. + // for this Motion (`dix/events.c:4388-4398`), asked only when + // this grab writes the Motion (its mask selects it and the + // owner is live), so no delivery count depends on it. A denial + // counts as delivered. && (receive.is_none() || super::grab_window_allows( state, diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_crossing_notify.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_crossing_notify.rs index b66e159d3..4d3a34325 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_crossing_notify.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_crossing_notify.rs @@ -1,5 +1,5 @@ //! Receive checks on crossing, focus, barrier and ConfigureNotify sites (PR 4c -//! plan 2: R1–R4, C1–C5, F1–F2, B1). +//! pointer: R1–R4, C1–C5, F1–F2, B1). //! //! Each row drives one site through its production entry under the shared runner //! (`access_notify_support::check_row`): the Receive trace, the frames, the pinned @@ -996,7 +996,7 @@ fn barrier_drive(f: &mut NotifyFixture) { } /// A barrier notification (XI2 BarrierHit 25 or BarrierLeave 26). The drive also moves the -/// pointer, so the natural core motion copies are checked too (plan 2, Task 1b); this row +/// pointer, so the natural core motion copies are checked too; this row /// pins only the barrier calls. fn is_barrier_call(call: &ExpectedReceive) -> bool { call.events == [xi2_event(25)] || call.events == [xi2_event(26)] @@ -1740,7 +1740,7 @@ fn receive_xi_pointer_grab_chain_details() { } /// Natural pointer copies are checked (spec l.381-385: one Receive result per recipient per -/// attempt; plan 2, Task 1b). DENIED selects core motion, the XTEST slave's XI2 ButtonPress and +/// attempt). DENIED selects core motion, the XTEST slave's XI2 ButtonPress and /// the master's XI2 motion on the child; ALLOWED selects core motion and ButtonPress there. With /// every Receive call to DENIED refused, DENIED receives none of its copies and each copy is asked /// once with the child as subject. ALLOWED's ButtonPress frame equals the no-policy run's; diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index 776436075..0757e697a 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -29,9 +29,9 @@ use std::{collections::BTreeMap, sync::atomic::Ordering}; use yserver_protocol::x11::{ClientByteOrder, ClientId, RequestHeader, SequenceNumber}; pub(super) const SEND_CLIENT: u32 = 1; -/// The client that selects on the child window (A in the brief). +/// The client that selects on the child window (A). pub(super) const A: u32 = 2; -/// The client that selects on the focus window (B in the brief). +/// The client that selects on the focus window (B). pub(super) const B: u32 = 3; pub(super) const FOCUS: u32 = 0x0061_0001; pub(super) const CHILD: u32 = 0x0061_0002; @@ -240,10 +240,10 @@ pub(super) struct Row { pub(super) drive: Drive, /// (client, check, window) Receive calls to deny. pub(super) deny: &'static [Call], - /// Frames only the denied run writes, pinned in full. /// The denied run's grab facts when they differ from allow-all; `None` means /// the same as allow-all. pub(super) denied_grab: Option<&'static [Grab]>, + /// Frames only the denied run writes, pinned in full. pub(super) moved: &'static [Moved], pub(super) allow: Expect, pub(super) denied: Expect, diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs index 606205103..d15b1ee45 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -1,5 +1,5 @@ //! Receive decisions in the focused key walk and XI2-over-core shadowing -//! (PR 4c part 2, plan 1, task 2). +//! (PR 4c part 2, keyboard). //! //! Each row builds its windows, selections, detectable repeat and slave grab //! through requests, pins the pointer and focus, drives one host key through a @@ -1149,7 +1149,7 @@ fn k15_allowed_natural_raw_leg_skips_the_grab_window_check() { check_row(&K15_ALLOWED_NATURAL_SKIPS_GRAB_WINDOW); } -// ---- XI1 router (plan 2, task 5) ------------------------------------------- +// ---- XI1 router ------------------------------------------- const XI1_KEY_PRESS_CALL: CallKind = CallKind::Batch(&[Named::Xi1(crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET as u16)]); diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index 7a297b1f0..e143f6ccb 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -1,4 +1,4 @@ -//! Natural pointer walks under a Receive denial (PR 4c part 2, plan 2, task 1a). +//! Natural pointer walks under a Receive denial (PR 4c part 2, pointer and XI1). //! //! The tree is root > P (FOCUS) > C (CHILD), with the pointer over C. Rows use //! the master pointer origin `XTest(2)` and ButtonPress unless they state @@ -703,7 +703,7 @@ fn p7_no_check_for_a_form_not_emitted() { check_row(&P7); } -// ---- Task 2: grabs and passive activation --------------------------------- +// ---- grabs and passive activation --------------------------------- // // O is client A, the foreign selector F is client B. Core grabs go through // `GrabPointer`/`GrabButton`, XI2 grabs through `XIGrabDevice`/ @@ -1537,7 +1537,7 @@ const P15: Row = Row { }; /// A denied on C: B on P gets the press and owns the implicit grab; the release, -/// with the pointer still over C, goes to B at P. Mutation (task 1's core +/// with the pointer still over C, goes to B at P. Mutation (the core /// candidate): the candidate is any walk recipient, denied or not, so A owns the /// grab and the release goes to A at C. #[test] @@ -1601,7 +1601,7 @@ const P16: Row = Row { }; /// A alone on C, denied: nobody receives the press and no pointer grab is -/// active afterwards. Mutation (task 1's core candidate): the denied recipient +/// active afterwards. Mutation (the core candidate): the denied recipient /// still qualifies, so A owns an implicit grab it never received a press for. #[test] fn p16_all_denied_no_implicit_grab() { @@ -1647,7 +1647,7 @@ const P17: Row = Row { }; /// Both select the master pointer's XI2 press on C; A is the window's owner and -/// wins with allow-all, and with A denied B owns the grab. Mutation (task 1's +/// wins with allow-all, and with A denied B owns the grab. Mutation (the /// XI2 candidate): a denied copy still enters the owner preference. #[test] fn p17_xi2_owner_preference_among_allowed() { @@ -1838,7 +1838,9 @@ fn p20b_xi1_passive_activation_asks_no_selector() { /// The press over a root that nothing can hit (unmapped, as `unhit_root` /// makes it): there is no top level, so the XI2 fanout does not run while the -/// XI1 router still does. +/// XI1 router still does. A real server always has a mapped root, so this +/// state cannot occur there; the rows pin the ask/write rule (XI2 not asked +/// without a top level, XI1 selectors checked) for the code path that would see it. const BARE_ROOT: (i16, i16) = (10, 10); fn unhit_root(f: &mut NotifyFixture) { @@ -1929,7 +1931,7 @@ fn i1b_bare_root_xi1_selectors_are_checked() { check_row(&I1B); } -// ---- Task 4: raw copies and smooth scroll ----------------------------------- +// ---- raw copies and smooth scroll ----------------------------------- // // X is client A, Y is client B, S is the send client. From a7d795d727520094adb2a06226bed5f2a585c8cf Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 09:45:43 -0300 Subject: [PATCH 38/72] docs(plan): compact the input Receive tests Co-Authored-By: Claude Opus 5.5 --- ...6-12-02-access-control-pr4c-input-tests.md | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md diff --git a/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md b/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md new file mode 100644 index 000000000..640f65b9c --- /dev/null +++ b/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md @@ -0,0 +1,58 @@ +# Access control PR 4c part 2, plan 2b: input tests in the reviewed shape + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Bring the key and pointer Receive tests of plans 1 and 2 to the shape the maintainer asked for in #389 (round 2), keeping what they prove, before plan 3 adds replay/thaw tests on top. + +**Architecture:** No production change. The input tests keep one runner, rewritten so a scenario is a setup plus a few short rows, and the harness reuses `access_notify_support.rs` instead of duplicating it. Coverage is measured by mutation, not test count: every production mutation the current tests name is replayed before and after, one at a time, and must still be caught. + +**Tech Stack:** Rust, yserver-core tests (`core_loop/process_request/tests/`). + +**Spec:** `docs/superpowers/specs/2026-10-30-access-control-layer-design.md` §"Input delivery under denial" (l.353–527). The maintainer's test-shape request, #389 review round 2: prove the shared fanout's denial behaviour once; per site a table row (client, request, subject, descriptions); focused tests only where the caller has its own logic around the check; do not repeat wire bytes other tests pin; assert only the fields a site sets, with dynamic values from the fixture. + +**Baseline (at `44f7dfb3`):** `access_pointer_input.rs` 2640 lines (41 tests, 51 rows), `access_key_input.rs` 1243 (31 tests), `access_input_support.rs` 1166. Row literals are 1761 of those lines, setups 552. + +## Global Constraints + +- No production change. `git diff 44f7dfb3 -- ':!crates/yserver-core/src/core_loop/process_request/tests' ':!docs'` stays empty. +- Every test named in plans 1 and 2 keeps its name (p1–p28 incl. p4b, p4c, p5b, p5c, p20b, i1a, i1b, k1–k17 and the rewritten `access_crossing_notify` tests), so plan reviews and the PR body still point at something. +- Coverage by mutation: each production mutation named in a test comment of the three files (and in the task reports under `/data/Projects/claude-scratch/access-control/pr4c-input/sdd-p1/` and `sdd-p2/`) is caught by the same test before and after migration. A probe that the old tests did not catch is listed, not fixed here. +- What the runner still asserts for every row: the Receive trace (client, subject window, ordered description batch), per call order as the row states; for each client which frames arrive (kind, device, event window; child and event coordinates only for frames the denial moves); the grab/freeze state of the denied run; allow-all equal to no policy in bytes and grab state. That last comparison costs no row lines and pins the plan 2 memo under an allow-all policy, so it stays. +- No literal frame encoders in the input tests except where a frame's content is the point (moved frames: child and coordinates); dynamic values (atoms, sequence) from the fixture. +- One shared helper per job: no second copy of `split_frames`, `enc16/dec16`, request senders, or a second `Row`/`check_row` pair with the same purpose. Helpers live in `access_notify_support.rs` (shared) or `access_input_support.rs` (input-only). +- Target size: the three files together at or below 2500 lines. If a test can only be shortened by dropping an assertion that catches a probe, keep it and report the number. +- Commits signed (`-S`), blank line before trailers `Co-Authored-By: Claude Opus 5.5 ` and `Implemented-By: Claude 5.5`; no URLs. Gate per task: `cargo +nightly fmt --all`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test -p yserver-core --lib`. + +## Review Focus + +1. A row that becomes shorter by losing the denied run's frames or grab state (a weaker test with the same name). +2. A probe caught before only by the allow-all-vs-no-policy comparison, now silently uncaught. +3. Per-client call order turned into a multiset where a test relied on order (p6: Core before XI2). +4. Shared-helper merge changing `access_crossing_notify`/`access_xi_notify`/`access_xkb_notify` assertions. + +--- + +### Task 1: mutation baseline and the compact runner + +**Files:** +- Create: `/data/Projects/claude-scratch/access-control/pr4c-input/sdd-p2b/probes.md` (outside the repo) +- Modify: `crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs`, `access_notify_support.rs` + +**Interfaces:** +- Produces: the probe list and its baseline (probe → catching test(s) at `44f7dfb3`); a scenario/row form where a row states only what differs between its allow-all and denied runs (deny list, denied frames, denied calls, denied grab when it differs) and the allow-all expectation is stated once per scenario; the runner keeps the checks listed in Global Constraints. + +- [ ] **Step 1:** Collect every named production mutation (test comments in the three files, sdd-p1/sdd-p2 reports and mutate scripts) into `probes.md` as: id, file:line, the edit, the test(s) expected to catch it. Replay each at `44f7dfb3` one at a time (`cargo test -p yserver-core --lib access_`), record caught/uncaught and by which test, restore by re-applying the exact original text and `cmp` against a saved copy. Commit nothing for this step. +- [ ] **Step 2:** Rewrite the runner and row types into the compact form; remove helpers duplicated with `access_notify_support.rs` (or move shared ones there). Port `access_key_input.rs` onto it (31 tests). +- [ ] **Step 3:** Replay the probes that `access_key_input.rs` catches; each must still be caught by the same test. Gate. Commit `test(access): compact input runner and key scenarios`. + +### Task 2: pointer scenarios + +**Files:** +- Modify: `crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs` (and `access_input_support.rs` only for input-only helpers it needs) + +**Interfaces:** +- Consumes: the runner and row form from Task 1. + +- [ ] **Step 1:** Port p1–p28 (with every row and variant) to the compact form. Drop rows that repeat another row's runs with identical expectations (plan 2 ledger: `P4_ALLOWED`, `P5_ALLOWED`); fold scenarios sharing a setup into one test only when the test name list above is kept. +- [ ] **Step 2:** Replay every probe; each is caught by the same test as at baseline. Record before/after in `probes.md` and the line counts of the three files. +- [ ] **Step 3:** Gate, plus `cargo test --workspace --features xdmcp`. Commit `test(access): compact pointer scenarios`. From 0f4e0e36a0abff42ae7a66424cd56d6b7eb6eb7c Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 09:51:02 -0300 Subject: [PATCH 39/72] docs(plan): input tests plan review round 1 Co-Authored-By: Claude Opus 5.5 --- ...6-12-02-access-control-pr4c-input-tests.md | 84 +++++++++++-------- 1 file changed, 48 insertions(+), 36 deletions(-) diff --git a/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md b/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md index 640f65b9c..5de583dc5 100644 --- a/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md +++ b/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md @@ -4,55 +4,67 @@ **Goal:** Bring the key and pointer Receive tests of plans 1 and 2 to the shape the maintainer asked for in #389 (round 2), keeping what they prove, before plan 3 adds replay/thaw tests on top. -**Architecture:** No production change. The input tests keep one runner, rewritten so a scenario is a setup plus a few short rows, and the harness reuses `access_notify_support.rs` instead of duplicating it. Coverage is measured by mutation, not test count: every production mutation the current tests name is replayed before and after, one at a time, and must still be caught. +**Architecture:** No production change. Each input test file becomes one `ROWS` table run by one test, plus focused tests only where a scenario needs checkpoints a row cannot state. One input runner drives an ordered list of steps (events and client requests) under the installed policy, so the multi-step harnesses of p14, p15 and p28 fold into it and plan 3 can reuse it for replay and thaw. Coverage is measured by mutation: every named production mutation is replayed before and after, and must still be caught by the same row or test. **Tech Stack:** Rust, yserver-core tests (`core_loop/process_request/tests/`). -**Spec:** `docs/superpowers/specs/2026-10-30-access-control-layer-design.md` §"Input delivery under denial" (l.353–527). The maintainer's test-shape request, #389 review round 2: prove the shared fanout's denial behaviour once; per site a table row (client, request, subject, descriptions); focused tests only where the caller has its own logic around the check; do not repeat wire bytes other tests pin; assert only the fields a site sets, with dynamic values from the fixture. +**Spec:** `docs/superpowers/specs/2026-10-30-access-control-layer-design.md` §"Input delivery under denial" (l.353–527). The maintainer's test-shape request, #389 review round 2: prove the shared fanout's denial behaviour once; per site a table row; focused tests only where the caller has its own logic around the check; do not repeat wire bytes other tests pin; assert only the fields a site sets, dynamic values from the fixture. The accepted result is `access_xkb_notify.rs` / `access_xi_notify.rs`: one `ROWS` table per file, one runner. -**Baseline (at `44f7dfb3`):** `access_pointer_input.rs` 2640 lines (41 tests, 51 rows), `access_key_input.rs` 1243 (31 tests), `access_input_support.rs` 1166. Row literals are 1761 of those lines, setups 552. +**Why a separate input runner** (not `access_notify_support::check_row`): these tests check routing (who receives, at which window, which grab and freeze state follows), driven through `pointer_event_fanout_to_state` / `key_event_fanout_to_state` and grab requests, not one site's description. The notify runner stays as it is; the input runner reuses its fixture and frame helpers. + +**Baseline (at `44f7dfb3`):** `access_pointer_input.rs` 2640 lines (41 tests, 51 rows), `access_key_input.rs` 1243 (31 tests), `access_input_support.rs` 1166. Row literals 1761 lines, setups ~520, probe comments ~390. ## Global Constraints -- No production change. `git diff 44f7dfb3 -- ':!crates/yserver-core/src/core_loop/process_request/tests' ':!docs'` stays empty. -- Every test named in plans 1 and 2 keeps its name (p1–p28 incl. p4b, p4c, p5b, p5c, p20b, i1a, i1b, k1–k17 and the rewritten `access_crossing_notify` tests), so plan reviews and the PR body still point at something. -- Coverage by mutation: each production mutation named in a test comment of the three files (and in the task reports under `/data/Projects/claude-scratch/access-control/pr4c-input/sdd-p1/` and `sdd-p2/`) is caught by the same test before and after migration. A probe that the old tests did not catch is listed, not fixed here. -- What the runner still asserts for every row: the Receive trace (client, subject window, ordered description batch), per call order as the row states; for each client which frames arrive (kind, device, event window; child and event coordinates only for frames the denial moves); the grab/freeze state of the denied run; allow-all equal to no policy in bytes and grab state. That last comparison costs no row lines and pins the plan 2 memo under an allow-all policy, so it stays. -- No literal frame encoders in the input tests except where a frame's content is the point (moved frames: child and coordinates); dynamic values (atoms, sequence) from the fixture. -- One shared helper per job: no second copy of `split_frames`, `enc16/dec16`, request senders, or a second `Row`/`check_row` pair with the same purpose. Helpers live in `access_notify_support.rs` (shared) or `access_input_support.rs` (input-only). -- Target size: the three files together at or below 2500 lines. If a test can only be shortened by dropping an assertion that catches a probe, keep it and report the number. +- No production change: `git diff 44f7dfb3 -- ':!crates/yserver-core/src/core_loop/process_request/tests' ':!docs'` stays empty. `access_notify_support.rs` gets additions only, if any. +- Plan 1/2 test names (p1–p28 incl. p4b, p4c, p5b, p5c, p20b, i1a, i1b, k1–k17) live on as row names (or focused-test names); a failing row's panic message names it. Rows removed as duplicates are listed in the commit message with the row that covers them. +- The runner asserts, for every row: the Receive trace (client, subject window, ordered description batch) in the row's stated order (total, per client, or multiset — p6 keeps Core before XI2); which frames each client gets (kind, device, event window), and for frames the denial moves, the decoded event window, child, event x/y and device; the denied run's grab and freeze state, freeze keyed by device (plan 3 needs every device); allow-all equal to no policy in bytes and grab state (pins the plan 2 memo under an allow-all policy; no row lines). +- The denied expectation is a full outcome compared exactly, per client and in order. It is never derived from the actual allow-all run. +- No literal frame encoders (`literal_moved` and its per-kind patches go). An exception needs a baseline probe that only those bytes catch, named in the code. +- No `rustfmt::skip`, no macro DSL for rows. +- Size budget, counting all four support/test files' change against baseline: rows ≤ 1000, setups ≤ 450, focused tests ≤ 350, harness ≤ 950; total about 3300 (from 5049). Over budget is allowed only with the probe that forces it named in the report. - Commits signed (`-S`), blank line before trailers `Co-Authored-By: Claude Opus 5.5 ` and `Implemented-By: Claude 5.5`; no URLs. Gate per task: `cargo +nightly fmt --all`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test -p yserver-core --lib`. ## Review Focus -1. A row that becomes shorter by losing the denied run's frames or grab state (a weaker test with the same name). -2. A probe caught before only by the allow-all-vs-no-policy comparison, now silently uncaught. -3. Per-client call order turned into a multiset where a test relied on order (p6: Core before XI2). -4. Shared-helper merge changing `access_crossing_notify`/`access_xi_notify`/`access_xkb_notify` assertions. +1. A row shorter because it lost the denied frames, the moved-frame fields or the grab/freeze state. +2. A probe caught at baseline only by the allow-all-vs-no-policy comparison, or only by a full-frame literal, now uncaught. +3. A probe "caught" by a compile error or by a notify test (crossing/XI/XKB) instead of the input row that should catch it. +4. The no-policy run asserting "no calls" without a recorder (proves nothing; drop that assertion or record). --- -### Task 1: mutation baseline and the compact runner - -**Files:** -- Create: `/data/Projects/claude-scratch/access-control/pr4c-input/sdd-p2b/probes.md` (outside the repo) -- Modify: `crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs`, `access_notify_support.rs` - -**Interfaces:** -- Produces: the probe list and its baseline (probe → catching test(s) at `44f7dfb3`); a scenario/row form where a row states only what differs between its allow-all and denied runs (deny list, denied frames, denied calls, denied grab when it differs) and the allow-all expectation is stated once per scenario; the runner keeps the checks listed in Global Constraints. - -- [ ] **Step 1:** Collect every named production mutation (test comments in the three files, sdd-p1/sdd-p2 reports and mutate scripts) into `probes.md` as: id, file:line, the edit, the test(s) expected to catch it. Replay each at `44f7dfb3` one at a time (`cargo test -p yserver-core --lib access_`), record caught/uncaught and by which test, restore by re-applying the exact original text and `cmp` against a saved copy. Commit nothing for this step. -- [ ] **Step 2:** Rewrite the runner and row types into the compact form; remove helpers duplicated with `access_notify_support.rs` (or move shared ones there). Port `access_key_input.rs` onto it (31 tests). -- [ ] **Step 3:** Replay the probes that `access_key_input.rs` catches; each must still be caught by the same test. Gate. Commit `test(access): compact input runner and key scenarios`. - -### Task 2: pointer scenarios +### Task 1: probe baseline, the runner, and the key table **Files:** -- Modify: `crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs` (and `access_input_support.rs` only for input-only helpers it needs) - -**Interfaces:** -- Consumes: the runner and row form from Task 1. - -- [ ] **Step 1:** Port p1–p28 (with every row and variant) to the compact form. Drop rows that repeat another row's runs with identical expectations (plan 2 ledger: `P4_ALLOWED`, `P5_ALLOWED`); fold scenarios sharing a setup into one test only when the test name list above is kept. -- [ ] **Step 2:** Replay every probe; each is caught by the same test as at baseline. Record before/after in `probes.md` and the line counts of the three files. -- [ ] **Step 3:** Gate, plus `cargo test --workspace --features xdmcp`. Commit `test(access): compact pointer scenarios`. +- Create (outside the repo): `/data/Projects/claude-scratch/access-control/pr4c-input/sdd-p2b/probes.md` and one replay script (reuse `sdd-p1/mutate*.py` and `sdd-p2/*mut*.py`) +- Modify: `crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs`, `access_key_input.rs` + +**Interfaces (produces):** +```rust +pub(super) enum Step { Event(Drive), Request(fn(&mut NotifyFixture)) } +pub(super) struct Outcome { + pub(super) frames: &'static [Frame], // (client, Kind, event window [, Moved fields]) + pub(super) calls: &'static [Call], // (client, CallKind/batch, subject window) + pub(super) grab: Option<&'static [Grab]>, // None = as allow-all; freeze facts keyed by device +} +pub(super) struct Scenario { pub(super) setup: fn(&mut NotifyFixture), pub(super) steps: &'static [Step], pub(super) allow: Outcome, pub(super) order: CallOrder } +pub(super) struct InputRow { pub(super) name: &'static str, pub(super) scenario: &'static Scenario, pub(super) deny: &'static [Call], pub(super) denied: Outcome } +pub(super) fn check_rows(rows: &[InputRow]); // runs every row, collects failures, panics once listing each failing row name and its message +``` +Names may differ if they avoid clashing with `access_notify_support`'s `Row`/`check_row`; shapes may gain a field only with a reason in the report. Defaults through a const base and `..BASE`. + +- [ ] **Step 1: probes.** Collect every named production mutation (test comments in the three files; sdd-p1/sdd-p2 reports and scripts) into `probes.md`: id, file, the exact original text (asserted to occur once), its replacement, the row/test expected to catch it. Replay each at `44f7dfb3` one at a time with `cargo test -p yserver-core --lib -- access_key_input access_pointer_input`; record compiled yes/no (a probe that does not compile is invalid, not caught), caught/uncaught, and the catching test/row name taken from the failure output. Restore from a saved copy and `cmp`. Prose-only mutations get an executable edit or are marked "not replayable" with the reason. No commit. +- [ ] **Step 2: runner.** Implement the interfaces above in `access_input_support.rs`; moved frames by decoded fields; drop `literal_moved`; reuse `access_notify_support` helpers (`split_frames`, `enc/dec`, fixture) instead of local copies. +- [ ] **Step 3: key table.** `access_key_input.rs` = setups + one `ROWS` + `#[test] fn key_rows() { check_rows(ROWS) }` + focused tests only where needed. `K4_ALLOWED`-style rows that repeat another row's runs with identical expectations are dropped (named in the commit message). +- [ ] **Step 4:** replay the key probes; each caught by the same row name as at baseline. Gate. Commit `test(access): input rows runner and key table`. + +### Task 2: pointer table + +**Files:** Modify `access_pointer_input.rs` (and input-only helpers in `access_input_support.rs`). + +**Interfaces (consumes):** Task 1's runner. + +- [ ] **Step 1:** Port p1–p28 to `ROWS`; p14, p15 and p28 become step lists (press, follow-up motion, `AllowDeviceEvents`, thaw…) on the shared runner; `Activation`, `activate_denied`, `follow_with_motion`, `Replay`, `replay_p28` and the inline second run in p15 go. Drop `P4_ALLOWED`/`P5_ALLOWED` (named in the commit message). +- [ ] **Step 2:** replay every probe (key and pointer); each caught by the same row/test as at baseline. Record before/after and the per-component line counts in `probes.md` and the report. +- [ ] **Step 3:** Gate, plus `cargo test --workspace --features xdmcp`. Commit `test(access): pointer table`. From 19e6b4d9d0f8876acc6314886eb9fe62defe9bed Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 09:52:36 -0300 Subject: [PATCH 40/72] docs(plan): input tests plan review round 2 Co-Authored-By: Claude Opus 5.5 --- .../2026-12-02-access-control-pr4c-input-tests.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md b/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md index 5de583dc5..381f565c0 100644 --- a/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md +++ b/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md @@ -19,10 +19,11 @@ - No production change: `git diff 44f7dfb3 -- ':!crates/yserver-core/src/core_loop/process_request/tests' ':!docs'` stays empty. `access_notify_support.rs` gets additions only, if any. - Plan 1/2 test names (p1–p28 incl. p4b, p4c, p5b, p5c, p20b, i1a, i1b, k1–k17) live on as row names (or focused-test names); a failing row's panic message names it. Rows removed as duplicates are listed in the commit message with the row that covers them. - The runner asserts, for every row: the Receive trace (client, subject window, ordered description batch) in the row's stated order (total, per client, or multiset — p6 keeps Core before XI2); which frames each client gets (kind, device, event window), and for frames the denial moves, the decoded event window, child, event x/y and device; the denied run's grab and freeze state, freeze keyed by device (plan 3 needs every device); allow-all equal to no policy in bytes and grab state (pins the plan 2 memo under an allow-all policy; no row lines). -- The denied expectation is a full outcome compared exactly, per client and in order. It is never derived from the actual allow-all run. +- The denied expectation is a full outcome compared exactly, per client and in order. It is never derived from the actual allow-all run. The one fallback: `grab: None` in a denied outcome means "as the scenario's stated allow grab"; scenarios whose point is grab ownership or freeze (p6, p14–p20, p26, p28, the key grab rows) state their allow grab explicitly. +- Checkpoints: a row may run only the first k steps of its scenario (`steps_until: Option`); a multi-step test's intermediate assertions (calls after the press, none after the follow-up motion, the freeze right after the press, the queued events) become prefix rows. The state facts include each device's freeze state and its queued events (`sync_pending` shape), so plan 3's replay/thaw checkpoints are rows too. - No literal frame encoders (`literal_moved` and its per-kind patches go). An exception needs a baseline probe that only those bytes catch, named in the code. - No `rustfmt::skip`, no macro DSL for rows. -- Size budget, counting all four support/test files' change against baseline: rows ≤ 1000, setups ≤ 450, focused tests ≤ 350, harness ≤ 950; total about 3300 (from 5049). Over budget is allowed only with the probe that forces it named in the report. +- Size budget, counting all four support/test files' change against baseline: rows ≤ 1500, setups ≤ 450, focused tests ≤ 350, harness ≤ 950; total about 3700 (from 5049). Overage is reported with its cause: a probe that forces it (named), or the row format (with the per-row line count). Never compress rows (DSL-like packing, one-letter names, dropped comments naming probes) to meet the number. - Commits signed (`-S`), blank line before trailers `Co-Authored-By: Claude Opus 5.5 ` and `Implemented-By: Claude 5.5`; no URLs. Gate per task: `cargo +nightly fmt --all`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test -p yserver-core --lib`. ## Review Focus @@ -44,12 +45,13 @@ ```rust pub(super) enum Step { Event(Drive), Request(fn(&mut NotifyFixture)) } pub(super) struct Outcome { - pub(super) frames: &'static [Frame], // (client, Kind, event window [, Moved fields]) + pub(super) frames: &'static [Frame], // (client, Kind, event window) + pub(super) moved: &'static [Moved], // decoded event window, child, event x/y, device of frames the denial moves pub(super) calls: &'static [Call], // (client, CallKind/batch, subject window) - pub(super) grab: Option<&'static [Grab]>, // None = as allow-all; freeze facts keyed by device + pub(super) grab: Option<&'static [Grab]>, // grab, freeze and queued-event facts keyed by device; None in `denied` = as the stated allow grab } pub(super) struct Scenario { pub(super) setup: fn(&mut NotifyFixture), pub(super) steps: &'static [Step], pub(super) allow: Outcome, pub(super) order: CallOrder } -pub(super) struct InputRow { pub(super) name: &'static str, pub(super) scenario: &'static Scenario, pub(super) deny: &'static [Call], pub(super) denied: Outcome } +pub(super) struct InputRow { pub(super) name: &'static str, pub(super) scenario: &'static Scenario, pub(super) steps_until: Option, pub(super) deny: &'static [Call], pub(super) denied: Outcome } pub(super) fn check_rows(rows: &[InputRow]); // runs every row, collects failures, panics once listing each failing row name and its message ``` Names may differ if they avoid clashing with `access_notify_support`'s `Row`/`check_row`; shapes may gain a field only with a reason in the report. Defaults through a const base and `..BASE`. @@ -65,6 +67,6 @@ Names may differ if they avoid clashing with `access_notify_support`'s `Row`/`ch **Interfaces (consumes):** Task 1's runner. -- [ ] **Step 1:** Port p1–p28 to `ROWS`; p14, p15 and p28 become step lists (press, follow-up motion, `AllowDeviceEvents`, thaw…) on the shared runner; `Activation`, `activate_denied`, `follow_with_motion`, `Replay`, `replay_p28` and the inline second run in p15 go. Drop `P4_ALLOWED`/`P5_ALLOWED` (named in the commit message). +- [ ] **Step 1:** Port p1–p28 to `ROWS`; p14, p15 and p28 become step lists (press, follow-up motion, `AllowDeviceEvents`, thaw…) on the shared runner, with every intermediate assertion they make today carried over as a prefix row (`steps_until`); `Activation`, `activate_denied`, `follow_with_motion`, `Replay`, `replay_p28` and the inline second run in p15 go. Drop `P4_ALLOWED`/`P5_ALLOWED` (named in the commit message). - [ ] **Step 2:** replay every probe (key and pointer); each caught by the same row/test as at baseline. Record before/after and the per-component line counts in `probes.md` and the report. - [ ] **Step 3:** Gate, plus `cargo test --workspace --features xdmcp`. Commit `test(access): pointer table`. From 535775a3999dce44f968cb2c58743e562b0ad426 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 09:53:29 -0300 Subject: [PATCH 41/72] docs(plan): input tests plan review round 3 Co-Authored-By: Claude Opus 5.5 --- .../2026-12-02-access-control-pr4c-input-tests.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md b/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md index 381f565c0..e303638a2 100644 --- a/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md +++ b/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md @@ -19,8 +19,9 @@ - No production change: `git diff 44f7dfb3 -- ':!crates/yserver-core/src/core_loop/process_request/tests' ':!docs'` stays empty. `access_notify_support.rs` gets additions only, if any. - Plan 1/2 test names (p1–p28 incl. p4b, p4c, p5b, p5c, p20b, i1a, i1b, k1–k17) live on as row names (or focused-test names); a failing row's panic message names it. Rows removed as duplicates are listed in the commit message with the row that covers them. - The runner asserts, for every row: the Receive trace (client, subject window, ordered description batch) in the row's stated order (total, per client, or multiset — p6 keeps Core before XI2); which frames each client gets (kind, device, event window), and for frames the denial moves, the decoded event window, child, event x/y and device; the denied run's grab and freeze state, freeze keyed by device (plan 3 needs every device); allow-all equal to no policy in bytes and grab state (pins the plan 2 memo under an allow-all policy; no row lines). -- The denied expectation is a full outcome compared exactly, per client and in order. It is never derived from the actual allow-all run. The one fallback: `grab: None` in a denied outcome means "as the scenario's stated allow grab"; scenarios whose point is grab ownership or freeze (p6, p14–p20, p26, p28, the key grab rows) state their allow grab explicitly. -- Checkpoints: a row may run only the first k steps of its scenario (`steps_until: Option`); a multi-step test's intermediate assertions (calls after the press, none after the follow-up motion, the freeze right after the press, the queued events) become prefix rows. The state facts include each device's freeze state and its queued events (`sync_pending` shape), so plan 3's replay/thaw checkpoints are rows too. +- The denied expectation is a full outcome compared exactly, per client and in order. It is never derived from the actual allow-all run. Grab facts: `grab: None` in a denied outcome means "as the scenario's stated allow grab"; scenarios whose point is grab ownership or freeze (p6, p14–p20, p26, p28, the key grab rows) state their allow grab explicitly; a scenario that states none compares the denied facts with the actual allow-all run's facts, as today. +- Checkpoints: a multi-step test's intermediate assertions (calls after the press, none after the follow-up motion, the freeze right after the press, the queued events) become their own `Scenario`s whose `steps` are the prefix, each with its own stated allow outcome; rows are named `@` (e.g. `p14_slave@press`). The state facts include each device's freeze state and its queued events (`sync_pending` shape), so plan 3's replay/thaw checkpoints are rows too. +- The runner also keeps today's `(core_focus, keys_down)` check: allow-all equal to no policy, and denied equal to allow-all. - No literal frame encoders (`literal_moved` and its per-kind patches go). An exception needs a baseline probe that only those bytes catch, named in the code. - No `rustfmt::skip`, no macro DSL for rows. - Size budget, counting all four support/test files' change against baseline: rows ≤ 1500, setups ≤ 450, focused tests ≤ 350, harness ≤ 950; total about 3700 (from 5049). Overage is reported with its cause: a probe that forces it (named), or the row format (with the per-row line count). Never compress rows (DSL-like packing, one-letter names, dropped comments naming probes) to meet the number. @@ -51,7 +52,7 @@ pub(super) struct Outcome { pub(super) grab: Option<&'static [Grab]>, // grab, freeze and queued-event facts keyed by device; None in `denied` = as the stated allow grab } pub(super) struct Scenario { pub(super) setup: fn(&mut NotifyFixture), pub(super) steps: &'static [Step], pub(super) allow: Outcome, pub(super) order: CallOrder } -pub(super) struct InputRow { pub(super) name: &'static str, pub(super) scenario: &'static Scenario, pub(super) steps_until: Option, pub(super) deny: &'static [Call], pub(super) denied: Outcome } +pub(super) struct InputRow { pub(super) name: &'static str, pub(super) scenario: &'static Scenario, pub(super) deny: &'static [Call], pub(super) denied: Outcome } pub(super) fn check_rows(rows: &[InputRow]); // runs every row, collects failures, panics once listing each failing row name and its message ``` Names may differ if they avoid clashing with `access_notify_support`'s `Row`/`check_row`; shapes may gain a field only with a reason in the report. Defaults through a const base and `..BASE`. @@ -67,6 +68,6 @@ Names may differ if they avoid clashing with `access_notify_support`'s `Row`/`ch **Interfaces (consumes):** Task 1's runner. -- [ ] **Step 1:** Port p1–p28 to `ROWS`; p14, p15 and p28 become step lists (press, follow-up motion, `AllowDeviceEvents`, thaw…) on the shared runner, with every intermediate assertion they make today carried over as a prefix row (`steps_until`); `Activation`, `activate_denied`, `follow_with_motion`, `Replay`, `replay_p28` and the inline second run in p15 go. Drop `P4_ALLOWED`/`P5_ALLOWED` (named in the commit message). -- [ ] **Step 2:** replay every probe (key and pointer); each caught by the same row/test as at baseline. Record before/after and the per-component line counts in `probes.md` and the report. +- [ ] **Step 1:** Port p1–p28 to `ROWS`; p14, p15 and p28 become step lists (press, follow-up motion, `AllowDeviceEvents`, thaw…) on the shared runner, with every intermediate assertion they make today carried over as a checkpoint scenario (`@`); `Activation`, `activate_denied`, `follow_with_motion`, `Replay`, `replay_p28` and the inline second run in p15 go. Drop `P4_ALLOWED`/`P5_ALLOWED` (named in the commit message). +- [ ] **Step 2:** replay every probe (key and pointer); each caught by the same row/test as at baseline (`probes.md` maps each baseline catcher to the row or `@step` rows that catch it now). Record before/after and the per-component line counts in `probes.md` and the report. - [ ] **Step 3:** Gate, plus `cargo test --workspace --features xdmcp`. Commit `test(access): pointer table`. From bbf53aefa2d23d2974c2474e7327b57885f02f45 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 09:53:52 -0300 Subject: [PATCH 42/72] docs(plan): input tests plan review round 4 Co-Authored-By: Claude Opus 5.5 --- .../plans/2026-12-02-access-control-pr4c-input-tests.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md b/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md index e303638a2..afd1157d2 100644 --- a/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md +++ b/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md @@ -19,7 +19,7 @@ - No production change: `git diff 44f7dfb3 -- ':!crates/yserver-core/src/core_loop/process_request/tests' ':!docs'` stays empty. `access_notify_support.rs` gets additions only, if any. - Plan 1/2 test names (p1–p28 incl. p4b, p4c, p5b, p5c, p20b, i1a, i1b, k1–k17) live on as row names (or focused-test names); a failing row's panic message names it. Rows removed as duplicates are listed in the commit message with the row that covers them. - The runner asserts, for every row: the Receive trace (client, subject window, ordered description batch) in the row's stated order (total, per client, or multiset — p6 keeps Core before XI2); which frames each client gets (kind, device, event window), and for frames the denial moves, the decoded event window, child, event x/y and device; the denied run's grab and freeze state, freeze keyed by device (plan 3 needs every device); allow-all equal to no policy in bytes and grab state (pins the plan 2 memo under an allow-all policy; no row lines). -- The denied expectation is a full outcome compared exactly, per client and in order. It is never derived from the actual allow-all run. Grab facts: `grab: None` in a denied outcome means "as the scenario's stated allow grab"; scenarios whose point is grab ownership or freeze (p6, p14–p20, p26, p28, the key grab rows) state their allow grab explicitly; a scenario that states none compares the denied facts with the actual allow-all run's facts, as today. +- The denied expectation is a full outcome compared exactly, per client and in order. It is never derived from the actual allow-all run, with one exception, grab facts below. Grab facts: `grab: None` in a denied outcome means "as the scenario's stated allow grab"; scenarios whose point is grab ownership or freeze (p6, p14–p20, p26, p28, the key grab rows) state their allow grab explicitly; a scenario that states none compares the denied facts with the actual allow-all run's facts, as today. - Checkpoints: a multi-step test's intermediate assertions (calls after the press, none after the follow-up motion, the freeze right after the press, the queued events) become their own `Scenario`s whose `steps` are the prefix, each with its own stated allow outcome; rows are named `@` (e.g. `p14_slave@press`). The state facts include each device's freeze state and its queued events (`sync_pending` shape), so plan 3's replay/thaw checkpoints are rows too. - The runner also keeps today's `(core_focus, keys_down)` check: allow-all equal to no policy, and denied equal to allow-all. - No literal frame encoders (`literal_moved` and its per-kind patches go). An exception needs a baseline probe that only those bytes catch, named in the code. @@ -49,7 +49,7 @@ pub(super) struct Outcome { pub(super) frames: &'static [Frame], // (client, Kind, event window) pub(super) moved: &'static [Moved], // decoded event window, child, event x/y, device of frames the denial moves pub(super) calls: &'static [Call], // (client, CallKind/batch, subject window) - pub(super) grab: Option<&'static [Grab]>, // grab, freeze and queued-event facts keyed by device; None in `denied` = as the stated allow grab + pub(super) grab: Option<&'static [Grab]>, // grab, freeze and queued-event facts keyed by device; None in `denied` = as the stated allow grab, or, if the scenario states none, as the actual allow-all facts } pub(super) struct Scenario { pub(super) setup: fn(&mut NotifyFixture), pub(super) steps: &'static [Step], pub(super) allow: Outcome, pub(super) order: CallOrder } pub(super) struct InputRow { pub(super) name: &'static str, pub(super) scenario: &'static Scenario, pub(super) deny: &'static [Call], pub(super) denied: Outcome } From 680660d1deba0278a3b63f498079af3199a1b4c0 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 11:52:05 -0300 Subject: [PATCH 43/72] test(access): input rows runner and key table Adds the InputRow runner to access_input_support.rs (Step lists, Scenario, Outcome, CallOrder, check_rows) and ports the key tests to one ROWS table run by one test. Moved frames are compared by their decoded event window, child, event coordinates and device instead of literal bytes. Grab facts now cover every device's freeze entry and the queued events. The old Row and check_row stay for the pointer file until it is ported. Rows dropped as duplicates: - k4_xi2_forms_share_one_check_allowed: its run is the allow run of k4_xi2_forms_share_one_check_denied_reopens_core. - k15_allowed_natural_raw_leg_skips_the_grab_window_check: its run is the allow run of k14_denied_raw_owner_root_copy_falls_back_to_the_grab_window, which states that the grab window is never asked. The k11 and k12 focused assertions are now the allow grab and freeze facts of their rows. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Sonnet 5.5 --- .../tests/access_input_support.rs | 441 ++++- .../process_request/tests/access_key_input.rs | 1714 +++++++---------- 2 files changed, 1104 insertions(+), 1051 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index 0757e697a..bfd62d2f1 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -1,7 +1,8 @@ //! Shared scenario harness for the key and pointer Receive tests (PR 4c -//! part 2): request helpers, the run/decode/check machinery and the -//! `Row` shape. Scenario rows and tests live in the test modules that -//! import this file. +//! part 2): request helpers, the run/decode machinery, the old `Row` shape +//! (the pointer file, until it is ported) and the `InputRow` runner. A test +//! module holds its scenario setups, one `ROWS` table and one `#[test]` that +//! calls `check_rows`. use super::{ access_notify_support::{DENY, NotifyFixture, dec16, dec32, enc16, enc32, split_frames}, @@ -23,7 +24,7 @@ use crate::{ nested::XI2_MAJOR_OPCODE, resources::ROOT_WINDOW, server::{QueuedInputEvent, ServerState, Xi1SyncState}, - xinput::{DEVICEID_MASTER_KEYBOARD, DEVICEID_MASTER_POINTER, DEVICEID_XTEST_KEYBOARD}, + xinput::DEVICEID_XTEST_KEYBOARD, }; use std::{collections::BTreeMap, sync::atomic::Ordering}; use yserver_protocol::x11::{ClientByteOrder, ClientId, RequestHeader, SequenceNumber}; @@ -100,7 +101,7 @@ pub(super) enum CallKind { /// One event description in its own numbering: core type, XI2 or raw event /// type, or the XI1 offset from the XI base (XI1 numbering is not XI2's). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub(super) enum Named { Core(u16), Xi2(u16), @@ -686,7 +687,7 @@ pub(super) struct ClientBytes { /// One fact of the grab state after a run. A row states the facts its denied /// run must have; the no-policy and allow-all runs must have the same list. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq)] pub(super) enum Grab { /// The active keyboard grab: owner and grab window. Keyboard { owner: u32, window: u32 }, @@ -700,18 +701,53 @@ pub(super) enum Grab { owner: u32, window: u32, }, - /// The master keyboard's XI1 freeze and whether it holds a stored press. - KeyboardFreeze { + /// One device's XI1 freeze entry: its sync state, the client whose grab + /// holds it frozen (`other`) and the event it stores for replay. + Freeze { + device: u16, state: Xi1SyncState, - stored: Option<(bool, u8)>, + other: Option, + stored: Option, }, - /// The master pointer's XI1 freeze and whether it holds a stored event. - PointerFreeze { state: Xi1SyncState, stored: bool }, + /// One withheld event in the global `sync_pending` queue, in order. + Queued { device: u16, held: Held }, +} + +/// A withheld input event, reduced to what the freeze rows state. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Held { + Key { pressed: bool, keycode: u8 }, + Raw { pressed: bool, keycode: u8 }, + Pointer { kind: PointerEventKind, detail: u8 }, + Xi1 { evcode: u8, detail: u8 }, +} + +fn held(event: &QueuedInputEvent) -> Held { + match event { + QueuedInputEvent::HostPointer(e) | QueuedInputEvent::HostPointerMaster(e, _) => { + Held::Pointer { + kind: e.kind, + detail: e.detail, + } + } + QueuedInputEvent::HostKey(e) | QueuedInputEvent::HostKeyTransition(e, ..) => Held::Key { + pressed: e.pressed, + keycode: e.keycode, + }, + QueuedInputEvent::Xi1Routed(q) => Held::Xi1 { + evcode: q.evcode, + detail: q.detail, + }, + QueuedInputEvent::RawKey(e) => Held::Raw { + pressed: e.pressed, + keycode: e.keycode, + }, + } } /// The active pointer grab: its owner, grab window, the implicit and passive /// flags, and whether it was established through XI2 (`via_xi2`). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq)] pub(super) struct PointerGrab { pub(super) owner: u32, pub(super) window: u32, @@ -796,8 +832,8 @@ pub(super) fn run(row: &Row, policy: Option<&'static [Call]>) -> Run { } /// The grab facts of a server state, in a fixed order: keyboard grab, master -/// pointer grab, slave pointer grabs by device, XI1 grabs by device, then the -/// master keyboard and pointer freezes. +/// pointer grab, slave pointer grabs by device, XI1 grabs by device, the freeze +/// of every device by device id, then the withheld events in queue order. pub(super) fn grab_facts(state: &ServerState) -> Vec { let pointer = |grab: &crate::server::ActivePointerGrab| PointerGrab { owner: grab.owner.0, @@ -833,22 +869,25 @@ pub(super) fn grab_facts(state: &ServerState) -> Vec { window: grab.grab_window.0, }); } - if let Some(freeze) = state.xi1_frozen.get(&DEVICEID_MASTER_KEYBOARD) { - let stored = match &freeze.stored { - Some(QueuedInputEvent::HostKeyTransition(event, _, _)) => { - Some((event.pressed, event.keycode)) - } - _ => None, - }; - facts.push(Grab::KeyboardFreeze { + let mut frozen: Vec<_> = state.xi1_frozen.iter().collect(); + frozen.sort_by_key(|(device, _)| **device); + for (device, freeze) in frozen { + // A default entry (thawed, nothing stored) is the same as none. + if freeze.state == Xi1SyncState::Thawed && freeze.other.is_none() && freeze.stored.is_none() + { + continue; + } + facts.push(Grab::Freeze { + device: *device, state: freeze.state, - stored, + other: freeze.other.map(|client| client.0), + stored: freeze.stored.as_ref().map(held), }); } - if let Some(freeze) = state.xi1_frozen.get(&DEVICEID_MASTER_POINTER) { - facts.push(Grab::PointerFreeze { - state: freeze.state, - stored: freeze.stored.is_some(), + for pending in &state.sync_pending { + facts.push(Grab::Queued { + device: pending.device, + held: held(&pending.event), }); } facts @@ -865,7 +904,7 @@ pub(super) fn grouped( } /// The key frames a run wrote, with the client byte order and sequence checked. -pub(super) fn delivered(name: &str, run: &Run, detail: u32, wheel_press: bool) -> Vec { +pub(super) fn delivered(name: &str, run: &Run, details: &[u32], wheel_press: bool) -> Vec { let mut frames = Vec::new(); for client in &run.clients { for frame in split_frames(&client.bytes, client.order) { @@ -886,15 +925,21 @@ pub(super) fn delivered(name: &str, run: &Run, detail: u32, wheel_press: bool) - } // The valuator continuation has no detail byte (byte 1 is // the device). - Kind::Xi1Valuator(_) => detail, + Kind::Xi1Valuator(_) => details[0], Kind::Xi2(_) | Kind::Raw(_) => dec32(&frame[16..20], client.order), }; // The smooth-scroll Motion of a wheel press carries no button. let is_scroll_motion = wheel_press && matches!(kind, Kind::Xi2(_)) && dec16(&frame[8..10], client.order) == 6; - let expected = if is_scroll_motion { 0 } else { detail }; - assert_eq!(keycode, expected, "{name}: frame detail"); + assert!( + if is_scroll_motion { + keycode == 0 + } else { + details.contains(&keycode) + }, + "{name}: frame detail {keycode} not in {details:?}" + ); frames.push((client.client, kind, window)); } } @@ -918,7 +963,7 @@ pub(super) fn check_run(row: &Row, run: &Run, expect: &Expect, mode: &str) { ); assert_eq!( grouped( - delivered(name, run, row.drive.detail(), row.drive.is_wheel_press()) + delivered(name, run, &[row.drive.detail()], row.drive.is_wheel_press()) .into_iter() .map(|(c, k, w)| (c, (k, w))) ), @@ -1139,6 +1184,338 @@ pub(super) fn check_row(row: &Row) { assert_eq!(moved_seen, row.moved.len(), "{name}: moved frames written"); } +// ---- the InputRow runner ------------------------------------------------- + +/// One step of a scenario: an input event the server fans out, or a request +/// (a grab, an `AllowDeviceEvents`, ...) a client sends in between. +#[derive(Clone, Copy)] +pub(super) enum Step { + Event(Drive), + #[expect(dead_code, reason = "first used by the pointer table's step lists")] + Request(fn(&mut NotifyFixture)), +} + +/// How a scenario's Receive trace is compared: in total order, in order per +/// client (`state.clients` is a HashMap, so the order across clients is not a +/// contract), or as a multiset. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum CallOrder { + Total, + PerClient, + #[expect(dead_code, reason = "first used by the pointer table")] + Multiset, +} + +/// A frame the denial moves: the denied run writes it where the allow-all run +/// has none like it. The decoded event window, child and event coordinates (and +/// the kind, which carries the device) are what the row states. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Move { + pub(super) client: u32, + pub(super) kind: Kind, + pub(super) window: u32, + pub(super) child: u32, + pub(super) event: (i16, i16), +} + +/// What one run of a scenario produces. In a denied outcome `grab: None` means +/// the scenario's stated allow grab, or, if it states none, the facts of the +/// actual allow-all run. +#[derive(Clone, Copy)] +pub(super) struct Outcome { + pub(super) frames: &'static [Frame], + pub(super) moved: &'static [Move], + pub(super) calls: &'static [Call], + pub(super) grab: Option<&'static [Grab]>, +} + +/// The empty outcome: the base of `..NOTHING` updates. +pub(super) const NOTHING: Outcome = Outcome { + frames: &[], + moved: &[], + calls: &[], + grab: None, +}; + +/// A setup, the steps run after it, and the allow-all outcome. Rows that share +/// a scenario differ in what they deny. +pub(super) struct Scenario { + pub(super) setup: fn(&mut NotifyFixture), + pub(super) steps: &'static [Step], + pub(super) allow: Outcome, + pub(super) order: CallOrder, +} + +pub(super) struct InputRow { + pub(super) name: &'static str, + pub(super) scenario: &'static Scenario, + /// The (client, check, window) Receive calls to deny. + pub(super) deny: &'static [Call], + pub(super) denied: Outcome, +} + +/// The event type the shorthand calls of a scenario name: its first event. +fn first_event(scenario: &Scenario) -> Drive { + scenario + .steps + .iter() + .find_map(|step| match step { + Step::Event(drive) => Some(*drive), + Step::Request(_) => None, + }) + .expect("a scenario drives at least one event") +} + +/// Runs a scenario from a fresh fixture. `policy` is `None` for no policy, or +/// the calls to deny under a recording policy. +fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run { + let mut f = NotifyFixture::new(); + (scenario.setup)(&mut f); + f.state.clients.get_mut(&A).expect("client A").byte_order = ClientByteOrder::BigEndian; + for client in [SEND_CLIENT, A, B] { + f.drain(ClientId(client)); + } + let ev = first_event(scenario).ev(); + let calls = policy.map(|denied| f.install_policy(move |_, call| decide(denied, ev, call))); + for step in scenario.steps { + match step { + Step::Event(event) => drive(&mut f, *event), + Step::Request(request) => request(&mut f), + } + } + assert!( + client_io::failed_writers(&f.state.clients).is_empty(), + "{name}: delivery queued a disconnect" + ); + let clients = [SEND_CLIENT, A, B] + .into_iter() + .map(|client| { + let state = &f.state.clients[&client]; + ClientBytes { + client, + order: state.byte_order, + sequence: state.last_sequence.load(Ordering::Relaxed), + bytes: f.drain(ClientId(client)), + } + }) + .collect(); + let calls = calls + .map(|calls| { + calls + .lock() + .unwrap() + .iter() + .filter(|call| call.hook == ExtensionHook::Receive) + .filter_map(|call| { + let EventSubject::Window(window) = call.receive? else { + panic!("{name}: Receive subject {:?}", call.receive); + }; + Some((call.client.0, names_of(call.events.as_deref()?)?, window.0)) + }) + .collect() + }) + .unwrap_or_default(); + Run { + clients, + calls, + state: format!("{:?}", (f.state.core_focus.raw, f.state.keys_down)), + grab: grab_facts(&f.state), + } +} + +/// The child window and event coordinates a frame of `kind` carries, decoded. +fn placement(frame: &[u8], kind: Kind, order: ClientByteOrder) -> (u32, (i16, i16)) { + match kind { + Kind::Core | Kind::Xi1(_) | Kind::Xi1Key(_) | Kind::Xi1Motion(_) => ( + dec32(&frame[16..20], order), + ( + dec16(&frame[24..26], order) as i16, + dec16(&frame[26..28], order) as i16, + ), + ), + // XI2: child at 28, event x and y as FP16.16 at 40 and 44. + Kind::Xi2(_) => ( + dec32(&frame[28..32], order), + ( + (dec32(&frame[40..44], order) as i32 >> 16) as i16, + (dec32(&frame[44..48], order) as i32 >> 16) as i16, + ), + ), + Kind::Raw(_) | Kind::Xi1Valuator(_) => (0, (0, 0)), + } +} + +/// The frames the denied run writes that the allow-all run does not: a denied +/// frame is paired with the allow-all frame of the same kind and window at the +/// same position among those, and must equal it byte for byte. An unpaired +/// frame is moved. The valuator continuation rides on its motion frame. +fn moved_frames(name: &str, allow: &Run, denied: &Run) -> Vec<(u32, Move)> { + let mut moved = Vec::new(); + for got in &denied.clients { + let allowed = allow + .clients + .iter() + .find(|c| c.client == got.client) + .expect("allow-all stream for the client"); + let allowed_frames: Vec<_> = split_frames(&allowed.bytes, allowed.order) + .into_iter() + .filter_map(|frame| decode(frame, allowed.order).map(|(k, w)| (k, w, frame))) + .collect(); + let mut seen: Vec<(Kind, u32)> = Vec::new(); + for frame in split_frames(&got.bytes, got.order) { + let Some((kind, window)) = decode(frame, got.order) else { + continue; + }; + let nth = seen.iter().filter(|s| **s == (kind, window)).count(); + seen.push((kind, window)); + let same = allowed_frames + .iter() + .filter(|(k, w, _)| (*k, *w) == (kind, window)) + .nth(nth); + if let Some((.., same)) = same { + assert_eq!( + frame, *same, + "{name}: client {} {kind:?} @{window:#x} bytes under denial", + got.client + ); + } else if !matches!(kind, Kind::Xi1Valuator(_)) { + let (child, event) = placement(frame, kind, got.order); + let client = got.client; + moved.push(( + client, + Move { + client, + kind, + window, + child, + event, + }, + )); + } + } + } + moved +} + +/// The details a scenario's frames may carry: the one of each event step. +fn details_of(scenario: &Scenario) -> (Vec, bool) { + let events = scenario.steps.iter().filter_map(|step| match step { + Step::Event(drive) => Some(*drive), + Step::Request(_) => None, + }); + ( + events.clone().map(Drive::detail).collect(), + events.into_iter().any(Drive::is_wheel_press), + ) +} + +/// Compares a run's frames and Receive trace with a stated outcome. +fn check_outcome(name: &str, mode: &str, scenario: &Scenario, run: &Run, want: &Outcome) { + let ev = first_event(scenario).ev(); + let calls: Vec = want.calls.iter().map(|c| expected_call(c, ev)).collect(); + let calls_match = match scenario.order { + CallOrder::Total => run.calls == calls, + CallOrder::PerClient => { + grouped(run.calls.iter().map(|(c, n, w)| (*c, (n.clone(), *w)))) + == grouped(calls.iter().map(|(c, n, w)| (*c, (n.clone(), *w)))) + } + CallOrder::Multiset => { + let sorted = |mut calls: Vec| { + calls.sort(); + calls + }; + sorted(run.calls.clone()) == sorted(calls.clone()) + } + }; + assert!( + calls_match, + "{name} [{mode}]: Receive calls ({:?}) differ\n got: {:?}\n want: {calls:?}", + scenario.order, run.calls + ); + let (details, wheel) = details_of(scenario); + assert_eq!( + grouped( + delivered(name, run, &details, wheel) + .into_iter() + .map(|(c, k, w)| (c, (k, w))) + ), + grouped(want.frames.iter().map(|&(c, k, w)| (c, (k, w)))), + "{name} [{mode}]: frames per client" + ); +} + +/// Runs one row under no policy, an allow-all policy and the row's denial. +/// Allow-all must equal no policy in bytes, state and grab facts; each run is +/// compared with its stated outcome; the denied run's moved frames, grab and +/// freeze facts are compared exactly. +fn check_input_row(row: &InputRow) { + let (name, scenario) = (row.name, row.scenario); + let plain = play(name, scenario, None); + let allow = play(name, scenario, Some(&[])); + let bytes = |run: &Run| { + run.clients + .iter() + .map(|c| c.bytes.clone()) + .collect::>() + }; + assert_eq!( + bytes(&allow), + bytes(&plain), + "{name}: allow-all changed the bytes" + ); + assert_eq!(allow.state, plain.state, "{name}: allow-all changed state"); + assert_eq!( + allow.grab, plain.grab, + "{name}: allow-all changed the grab and freeze state" + ); + check_outcome(name, "allow-all", scenario, &allow, &scenario.allow); + if let Some(facts) = scenario.allow.grab { + assert_eq!(allow.grab, facts, "{name}: allow-all grab and freeze state"); + } + + let denied = play(name, scenario, Some(row.deny)); + check_outcome(name, "denial", scenario, &denied, &row.denied); + assert_eq!(denied.state, allow.state, "{name}: denial changed state"); + let expected_grab = row + .denied + .grab + .or(scenario.allow.grab) + .map_or_else(|| allow.grab.clone(), <[Grab]>::to_vec); + assert_eq!( + denied.grab, expected_grab, + "{name}: denied grab and freeze state" + ); + assert_eq!( + grouped(moved_frames(name, &allow, &denied)), + grouped(row.denied.moved.iter().map(|m| (m.client, *m))), + "{name}: frames the denial moves" + ); +} + +/// Checks every row and panics once, listing each failing row by name. +pub(super) fn check_rows(rows: &[InputRow]) { + let failures: Vec = rows + .iter() + .filter_map(|row| { + let result = std::panic::catch_unwind(|| check_input_row(row)); + let panic = result.err()?; + let message = panic + .downcast_ref::() + .cloned() + .or_else(|| panic.downcast_ref::<&str>().map(|s| (*s).to_owned())) + .unwrap_or_default(); + Some(format!(" - {}: {message}", row.name)) + }) + .collect(); + assert!( + failures.is_empty(), + "{} of {} rows failed:\n{}", + failures.len(), + rows.len(), + failures.join("\n") + ); +} + #[cfg(test)] mod batch_naming { use super::*; diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs index d15b1ee45..056ce8743 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -1,23 +1,13 @@ //! Receive decisions in the focused key walk and XI2-over-core shadowing //! (PR 4c part 2, keyboard). //! -//! Each row builds its windows, selections, detectable repeat and slave grab -//! through requests, pins the pointer and focus, drives one host key through a -//! production key entry, and checks three runs: no policy, an explicit -//! allow-all policy, and a policy that denies the listed (client, check, -//! window) Receive calls. -//! -//! Every run is checked against literal per-client frames (kind, XI2 device, -//! event window, sequence, keycode) and literal per-client Receive calls. The -//! no-policy and allow-all streams must be byte-identical. A frame that both -//! the allow-all and the denied run write has the same bytes in both. A frame -//! only the denied run writes (a denial moved the walk to another window) is -//! pinned in full by the row's literal `moved` entry: child, event coordinates -//! and state. Every such frame must have a `moved` entry, and every entry must -//! be written. -//! -//! Receive calls are compared per client: `state.clients` is a HashMap, so the -//! order across clients is not part of the contract. +//! Each row names a scenario (windows, selections, detectable repeat and grabs +//! built through requests, then one host key driven through a production key +//! entry) and a denial. `check_rows` runs it three ways: no policy, an explicit +//! allow-all policy, and the denial; every run's frames and Receive trace are +//! compared with the stated outcome, frames only the denial writes are compared +//! by their decoded window, child and event coordinates, and the grab and +//! freeze facts are compared exactly. use super::{access_input_support::*, access_notify_support::NotifyFixture}; use crate::{ core_loop::InputOrigin, @@ -25,39 +15,15 @@ use crate::{ xinput::{DEVICEID_MASTER_KEYBOARD, DEVICEID_XTEST_KEYBOARD}, }; -// ---- rows ---------------------------------------------------------------- +// ---- setups -------------------------------------------------------------- -fn setup_child_core_and_focus_core(f: &mut NotifyFixture) { +/// A selects core on CHILD; B selects core on FOCUS. +fn setup_k1(f: &mut NotifyFixture) { tree(f); select_core(f, A, CHILD, KEY_PRESS); select_core(f, B, FOCUS, KEY_PRESS); } -const K1: Row = Row { - name: "k1_denied_pointer_window_selector_advances_the_focus_walk", - setup: setup_child_core_and_focus_core, - drive: Drive::Entry { - origin: InputOrigin::NestedHost, - pressed: true, - }, - deny: &[(A, CallKind::Core, CHILD)], - allow: Expect { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - }, - denied: Expect { - frames: &[(B, Kind::Core, FOCUS)], - calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, FOCUS)], - }, - denied_grab: None, - moved: &[Moved { - client: B, - window: FOCUS, - child: CHILD, - event: (20, 20), - }], -}; - fn setup_k2(f: &mut NotifyFixture) { tree(f); select_core(f, A, CHILD, KEY_PRESS); @@ -65,26 +31,6 @@ fn setup_k2(f: &mut NotifyFixture) { select_core(f, SEND_CLIENT, FOCUS, KEY_PRESS); } -const K2: Row = Row { - name: "k2_one_allowed_selector_stops_the_walk", - setup: setup_k2, - drive: Drive::Entry { - origin: InputOrigin::NestedHost, - pressed: true, - }, - deny: &[(A, CallKind::Core, CHILD)], - allow: Expect { - frames: &[(A, Kind::Core, CHILD), (B, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, CHILD)], - }, - denied: Expect { - frames: &[(B, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, CHILD)], - }, - denied_grab: None, - moved: &[], -}; - /// A selects XI2 (master) and core on CHILD; B selects core on FOCUS. fn setup_k3(f: &mut NotifyFixture) { tree(f); @@ -93,134 +39,15 @@ fn setup_k3(f: &mut NotifyFixture) { select_core(f, B, FOCUS, KEY_PRESS); } -const K3_XI2_DENIED: Row = Row { - name: "k3_denied_xi2_copy_reopens_core_for_that_client", - setup: setup_k3, - drive: Drive::Entry { - origin: InputOrigin::NestedHost, - pressed: true, - }, - deny: &[(A, CallKind::Xi2, CHILD)], - allow: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], - }, - denied_grab: None, - moved: &[Moved { - client: A, - window: CHILD, - child: 0, - event: (10, 10), - }], -}; - -const K3_BOTH_DENIED: Row = Row { - name: "k3_both_denied_walks_on_to_the_focus", - setup: setup_k3, - drive: Drive::Entry { - origin: InputOrigin::NestedHost, - pressed: true, - }, - deny: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], - allow: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[(B, Kind::Core, FOCUS)], - calls: &[ - (A, CallKind::Xi2, CHILD), - (A, CallKind::Core, CHILD), - (B, CallKind::Core, FOCUS), - ], - }, - denied_grab: None, - moved: &[Moved { - client: B, - window: FOCUS, - child: CHILD, - event: (20, 20), - }], -}; - /// A selects XI2 on the master (3) and slave (5) keyboards and core on CHILD. fn setup_k4(f: &mut NotifyFixture) { tree(f); select_core(f, A, CHILD, KEY_PRESS); - select_xi2( - f, - A, - CHILD, - DEVICEID_MASTER_KEYBOARD, - XI_KEY_PRESS_AND_RELEASE, - ); - select_xi2( - f, - A, - CHILD, - DEVICEID_XTEST_KEYBOARD, - XI_KEY_PRESS_AND_RELEASE, - ); + for device in [DEVICEID_MASTER_KEYBOARD, DEVICEID_XTEST_KEYBOARD] { + select_xi2(f, A, CHILD, device, XI_KEY_PRESS_AND_RELEASE); + } } -const K4_ALLOWED: Row = Row { - name: "k4_xi2_forms_share_one_check_allowed", - setup: setup_k4, - drive: Drive::Entry { - origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), - pressed: true, - }, - deny: &[], - allow: Expect { - frames: &[ - (A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD), - (A, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), CHILD), - ], - calls: &[(A, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[ - (A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD), - (A, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), CHILD), - ], - calls: &[(A, CallKind::Xi2, CHILD)], - }, - denied_grab: None, - moved: &[], -}; - -const K4_XI2_DENIED: Row = Row { - name: "k4_xi2_forms_share_one_check_denied_reopens_core", - setup: setup_k4, - drive: Drive::Entry { - origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), - pressed: true, - }, - deny: &[(A, CallKind::Xi2, CHILD)], - allow: Expect { - frames: &[ - (A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD), - (A, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), CHILD), - ], - calls: &[(A, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], - }, - denied_grab: None, - moved: &[Moved { - client: A, - window: CHILD, - child: 0, - event: (10, 10), - }], -}; - /// Synthetic release: A selects only XI2 KeyRelease on CHILD; B core on FOCUS. fn setup_k5_xi2_release(f: &mut NotifyFixture) { tree(f); @@ -228,28 +55,6 @@ fn setup_k5_xi2_release(f: &mut NotifyFixture) { select_core(f, B, FOCUS, KEY_RELEASE); } -const K5_XI2_SUPPRESSED: Row = Row { - name: "k5_suppressed_xi2_release_stops_without_a_check", - setup: setup_k5_xi2_release, - drive: Drive::After { - origin: InputOrigin::NestedHost, - pressed: false, - master: true, - synthetic: true, - }, - deny: &[(A, CallKind::Xi2, CHILD)], - allow: Expect { - frames: &[], - calls: &[], - }, - denied: Expect { - frames: &[], - calls: &[], - }, - denied_grab: None, - moved: &[], -}; - /// Synthetic release with a detectable-repeat core selector on CHILD. fn setup_k5_detectable(f: &mut NotifyFixture) { tree(f); @@ -258,28 +63,6 @@ fn setup_k5_detectable(f: &mut NotifyFixture) { set_detectable_repeat(f, A); } -const K5_DETECTABLE_SUPPRESSED: Row = Row { - name: "k5_suppressed_detectable_core_release_stops_without_a_check", - setup: setup_k5_detectable, - drive: Drive::After { - origin: InputOrigin::NestedHost, - pressed: false, - master: true, - synthetic: true, - }, - deny: &[(A, CallKind::Core, CHILD)], - allow: Expect { - frames: &[], - calls: &[], - }, - denied: Expect { - frames: &[], - calls: &[], - }, - denied_grab: None, - moved: &[], -}; - /// Slave origin with the master transition rejected: the core form is excluded /// on this path. A selects slave XI2 and core on CHILD; B slave XI2 on FOCUS. fn setup_k5b(f: &mut NotifyFixture) { @@ -289,115 +72,27 @@ fn setup_k5b(f: &mut NotifyFixture) { select_xi2(f, B, FOCUS, DEVICEID_XTEST_KEYBOARD, XI_KEY_PRESS); } -const K5B_EXCLUDED_FORM_STILL_STOPS: Row = Row { - name: "k5b_form_excluded_by_the_include_flags_still_stops", - setup: setup_k5b, - drive: Drive::After { - origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), - pressed: true, - master: false, - synthetic: false, - }, - deny: &[(A, CallKind::Xi2, CHILD)], - allow: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[], - calls: &[(A, CallKind::Xi2, CHILD)], - }, - denied_grab: None, - moved: &[], -}; - -/// Slave origin with the master transition rejected: A also selects the master -/// XI2 form on CHILD, which the include flags exclude, so it stops the walk with -/// no copy and no Receive call. B selects the slave form on FOCUS. +/// Slave origin with the master transition rejected: A selects the master XI2 +/// form on CHILD, which the include flags exclude, so it stops the walk with no +/// copy and no Receive call. B selects the slave form on FOCUS. fn setup_k5b_master(f: &mut NotifyFixture) { tree(f); select_xi2(f, A, CHILD, DEVICEID_MASTER_KEYBOARD, XI_KEY_PRESS); select_xi2(f, B, FOCUS, DEVICEID_XTEST_KEYBOARD, XI_KEY_PRESS); } -const K5B_EXCLUDED_MASTER_FORM_STILL_STOPS: Row = Row { - name: "k5b_excluded_master_form_still_stops", - setup: setup_k5b_master, - drive: Drive::After { - origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), - pressed: true, - master: false, - synthetic: false, - }, - deny: &[(A, CallKind::Xi2, CHILD)], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[], - calls: &[], - }, - denied: Expect { - frames: &[], - calls: &[], - }, -}; - /// The slave origin through its exact XI2 grab: the grab owner gets the copy. fn setup_k5c_grab(f: &mut NotifyFixture) { tree(f); grab_slave_keyboard(f, A, FOCUS); } -const K5C_SLAVE_GRAB_OWNER: Row = Row { - name: "k5c_slave_grab_write_is_checked", - setup: setup_k5c_grab, - drive: Drive::After { - origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), - pressed: true, - master: false, - synthetic: false, - }, - deny: &[(A, CallKind::Xi2, FOCUS)], - allow: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), FOCUS)], - calls: &[(A, CallKind::Xi2, FOCUS)], - }, - denied: Expect { - frames: &[], - calls: &[(A, CallKind::Xi2, FOCUS)], - }, - denied_grab: None, - moved: &[], -}; - /// The slave origin through the slave focus path, with no grab. fn setup_k5c_focus(f: &mut NotifyFixture) { tree(f); select_xi2(f, A, CHILD, DEVICEID_XTEST_KEYBOARD, XI_KEY_PRESS); } -const K5C_SLAVE_FOCUS_PATH: Row = Row { - name: "k5c_slave_focus_path_is_checked", - setup: setup_k5c_focus, - drive: Drive::After { - origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), - pressed: true, - master: false, - synthetic: false, - }, - deny: &[(A, CallKind::Xi2, CHILD)], - allow: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[], - calls: &[(A, CallKind::Xi2, CHILD)], - }, - denied_grab: None, - moved: &[], -}; - /// A selects core on CHILD and FOCUS; B selects core on FOCUS. fn setup_k6a(f: &mut NotifyFixture) { tree(f); @@ -406,63 +101,14 @@ fn setup_k6a(f: &mut NotifyFixture) { select_core(f, B, FOCUS, KEY_PRESS); } -const K6A_ALL_DENIED_LANDS_ON_FOCUS: Row = Row { - name: "k6_all_denied_lands_on_focus_with_a_stopping_focus_selector", - setup: setup_k6a, - drive: Drive::Entry { - origin: InputOrigin::NestedHost, - pressed: true, - }, - deny: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - allow: Expect { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - }, - denied: Expect { - frames: &[(B, Kind::Core, FOCUS)], - calls: &[ - (A, CallKind::Core, CHILD), - (A, CallKind::Core, FOCUS), - (B, CallKind::Core, FOCUS), - ], - }, - denied_grab: None, - moved: &[Moved { - client: B, - window: FOCUS, - child: CHILD, - event: (20, 20), - }], -}; - -/// Only A selects, on CHILD and FOCUS, and A is denied everywhere. +/// Only A selects, on CHILD and FOCUS. fn setup_k6b(f: &mut NotifyFixture) { tree(f); select_core(f, A, CHILD, KEY_PRESS); select_core(f, A, FOCUS, KEY_PRESS); } -const K6B_ATTEMPT_LANDS_ON_FOCUS: Row = Row { - name: "k6_only_selector_denied_lands_on_focus_and_writes_nothing", - setup: setup_k6b, - drive: Drive::Entry { - origin: InputOrigin::NestedHost, - pressed: true, - }, - deny: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - allow: Expect { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - }, - denied: Expect { - frames: &[], - calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - }, - denied_grab: None, - moved: &[], -}; - -// ---- grabbed rows: A is the grab owner (O), B is the foreign selector (F) ---- +// Grabbed rows: A is the grab owner, B the foreign selector. /// A grabs the keyboard with owner_events on the root and selects core presses /// on CHILD (the pointer window) and FOCUS. @@ -473,34 +119,10 @@ fn setup_k7(f: &mut NotifyFixture) { select_core(f, A, FOCUS, KEY_PRESS); } -const K7_OWNER_DENIED_ON_POINTER_WINDOW: Row = Row { - name: "k7_denied_owner_copy_continues_the_natural_walk", - setup: setup_k7, - drive: Drive::Entry { - origin: InputOrigin::NestedHost, - pressed: true, - }, - deny: &[(A, CallKind::Core, CHILD)], - allow: Expect { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Core, FOCUS)], - calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - }, - denied_grab: None, - moved: &[Moved { - client: A, - window: FOCUS, - child: CHILD, - event: (20, 20), - }], -}; - /// A grabs with owner_events on the root and selects core on CHILD; B selects -/// core on CHILD too. A is denied at CHILD, so B's allowed copy is the -/// foreign rejection and the grab window gets the key. +/// core on CHILD too. With A denied at CHILD, B's allowed copy is the foreign +/// rejection and the grab window gets the key (k8); with B denied, A qualifies +/// first and B is not asked (k9, same window). fn setup_k8(f: &mut NotifyFixture) { tree(f); grab_keyboard(f, A, ROOT, true); @@ -508,35 +130,6 @@ fn setup_k8(f: &mut NotifyFixture) { select_core(f, B, CHILD, KEY_PRESS); } -const K8_ALLOWED_FOREIGN_FALLS_BACK: Row = Row { - name: "k8_denied_owner_with_allowed_foreign_falls_back", - setup: setup_k8, - drive: Drive::Entry { - origin: InputOrigin::NestedHost, - pressed: true, - }, - deny: &[(A, CallKind::Core, CHILD)], - allow: Expect { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Core, ROOT)], - calls: &[ - (A, CallKind::Core, CHILD), - (B, CallKind::Core, CHILD), - (A, CallKind::Core, ROOT), - ], - }, - denied_grab: None, - moved: &[Moved { - client: A, - window: ROOT, - child: FOCUS, - event: (120, 120), - }], -}; - /// B alone selects core on CHILD and is denied there, so it does not reject; /// A selects core on FOCUS, which is allowed. fn setup_k9(f: &mut NotifyFixture) { @@ -546,60 +139,17 @@ fn setup_k9(f: &mut NotifyFixture) { select_core(f, A, FOCUS, KEY_PRESS); } -const K9_DENIED_FOREIGN_DOES_NOT_REJECT: Row = Row { - name: "k9_denied_foreign_selector_does_not_reject", - setup: setup_k9, - drive: Drive::Entry { - origin: InputOrigin::NestedHost, - pressed: true, - }, - deny: &[(B, CallKind::Core, CHILD)], - allow: Expect { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, ROOT)], - }, - denied: Expect { - frames: &[(A, Kind::Core, FOCUS)], - calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - }, - denied_grab: None, - moved: &[Moved { - client: A, - window: FOCUS, - child: CHILD, - event: (20, 20), - }], -}; - -/// A and B both select core on CHILD and B is denied. A qualifies first, so the -/// walk stops at CHILD and no check is made for B. -fn setup_k9_same_window(f: &mut NotifyFixture) { +/// A grabs with owner_events on the root. A, B and SEND_CLIENT select core +/// press on CHILD. A is denied there; B and SEND_CLIENT are allowed. Every +/// foreign selector is asked, and A falls back to the root grab window. +fn setup_k9b(f: &mut NotifyFixture) { tree(f); grab_keyboard(f, A, ROOT, true); - select_core(f, A, CHILD, KEY_PRESS); - select_core(f, B, CHILD, KEY_PRESS); + for client in [A, B, SEND_CLIENT] { + select_core(f, client, CHILD, KEY_PRESS); + } } -const K9_OWNER_QUALIFIES_FIRST: Row = Row { - name: "k9_owner_on_the_same_window_qualifies_first", - setup: setup_k9_same_window, - drive: Drive::Entry { - origin: InputOrigin::NestedHost, - pressed: true, - }, - deny: &[(B, CallKind::Core, CHILD)], - allow: Expect { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - }, - denied_grab: None, - moved: &[], -}; - /// A selects core release on FOCUS and grabs with owner_events on the root. B /// selects XI2 release on CHILD: the synthetic release of that form is /// suppressed, so B stops the walk with no copy and no Receive call. @@ -610,187 +160,31 @@ fn setup_k10(f: &mut NotifyFixture) { select_xi2(f, B, CHILD, DEVICEID_MASTER_KEYBOARD, XI_KEY_RELEASE); } -const K10_SUPPRESSED_FOREIGN_STILL_REJECTS: Row = Row { - name: "k10_suppressed_foreign_selector_still_rejects", - setup: setup_k10, - drive: Drive::After { - origin: InputOrigin::NestedHost, - pressed: false, - master: true, - synthetic: true, - }, - deny: &[], - allow: Expect { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(A, CallKind::Core, ROOT)], - }, - denied: Expect { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(A, CallKind::Core, ROOT)], - }, - denied_grab: None, - moved: &[], -}; - /// A grabs with owner_events false on the root; B selects core press on FOCUS. -/// The grab-window copy is denied: no bytes, and B gets nothing. fn setup_k11(f: &mut NotifyFixture) { tree(f); grab_keyboard(f, A, ROOT, false); select_core(f, B, FOCUS, KEY_PRESS); } -const K11_GRAB_WINDOW_DENIAL_DELIVERS: Row = Row { - name: "k11_denied_grab_window_copy_is_delivered", - setup: setup_k11, - drive: Drive::Entry { - origin: InputOrigin::NestedHost, - pressed: true, - }, - deny: &[(A, CallKind::Core, ROOT)], - allow: Expect { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(A, CallKind::Core, ROOT)], - }, - denied: Expect { - frames: &[], - calls: &[(A, CallKind::Core, ROOT)], - }, - denied_grab: None, - moved: &[], -}; - /// A holds a synchronous passive GrabKey on the root (owner_events false) and -/// B selects core press on FOCUS. The activating press is denied to A: the -/// grab still activates and freezes with the press stored. +/// B selects core press on FOCUS. fn setup_k12(f: &mut NotifyFixture) { tree(f); grab_key(f, A, ROOT, false, true); select_core(f, B, FOCUS, KEY_PRESS); } -const K12_ACTIVATING_DENIAL_ACTIVATES: Row = Row { - name: "k12_denied_activating_press_still_activates_and_freezes", - setup: setup_k12, - drive: Drive::Entry { - origin: InputOrigin::NestedHost, - pressed: true, - }, - deny: &[(A, CallKind::Core, ROOT)], - allow: Expect { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(A, CallKind::Core, ROOT)], - }, - denied: Expect { - frames: &[], - calls: &[(A, CallKind::Core, ROOT)], - }, - denied_grab: None, - moved: &[], -}; - -/// A holds the slave keyboard's exact XI2 grab on FOCUS (owner_events false). -/// The synthetic XI2 release is suppressed in the grab's protocol: no bytes and -/// no Receive call. -const K13_SYNTHETIC_XI2_RELEASE_SUPPRESSED: Row = Row { - name: "k13_synthetic_xi2_release_to_a_grab_owner_is_suppressed", - setup: setup_k5c_grab, - drive: Drive::After { - origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), - pressed: false, - master: false, - synthetic: true, - }, - deny: &[], - allow: Expect { - frames: &[], - calls: &[], - }, - denied: Expect { - frames: &[], - calls: &[], - }, - denied_grab: None, - moved: &[], -}; - /// A holds a core keyboard grab on the root (owner_events false) and has -/// detectable repeat. The synthetic core release is suppressed for A: no bytes, -/// no Receive call. +/// detectable repeat. fn setup_k13_detectable(f: &mut NotifyFixture) { tree(f); grab_keyboard(f, A, ROOT, false); set_detectable_repeat(f, A); } -const K13_DETECTABLE_CORE_RELEASE_SUPPRESSED: Row = Row { - name: "k13_synthetic_detectable_core_release_to_a_grab_owner_is_suppressed", - setup: setup_k13_detectable, - drive: Drive::After { - origin: InputOrigin::NestedHost, - pressed: false, - master: true, - synthetic: true, - }, - deny: &[], - allow: Expect { - frames: &[], - calls: &[], - }, - denied: Expect { - frames: &[], - calls: &[], - }, - denied_grab: None, - moved: &[], -}; - -/// A grabs with owner_events on the root. A, B and SEND_CLIENT select core -/// press on CHILD. A is denied there; B and SEND_CLIENT are allowed. Every -/// foreign selector is asked, and A falls back to the root grab window. -fn setup_k9b(f: &mut NotifyFixture) { - tree(f); - grab_keyboard(f, A, ROOT, true); - select_core(f, A, CHILD, KEY_PRESS); - select_core(f, B, CHILD, KEY_PRESS); - select_core(f, SEND_CLIENT, CHILD, KEY_PRESS); -} - -const K9B_EVERY_FOREIGN_SELECTOR_IS_CHECKED: Row = Row { - name: "k9b_every_foreign_selector_is_checked", - setup: setup_k9b, - drive: Drive::Entry { - origin: InputOrigin::NestedHost, - pressed: true, - }, - deny: &[(A, CallKind::Core, CHILD)], - allow: Expect { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Core, ROOT)], - calls: &[ - (A, CallKind::Core, CHILD), - (B, CallKind::Core, CHILD), - (SEND_CLIENT, CallKind::Core, CHILD), - (A, CallKind::Core, ROOT), - ], - }, - denied_grab: None, - moved: &[Moved { - client: A, - window: ROOT, - child: FOCUS, - event: (120, 120), - }], -}; - /// A grabs with owner_events on the root and has detectable repeat. A selects -/// core release on CHILD and B selects core release on FOCUS. A's synthetic -/// release is suppressed in the grab's protocol, so A qualifies at CHILD with -/// no Receive call, the walk stops there, and nothing is written. The denial -/// of A at CHILD changes nothing, because no copy is checked. +/// core release on CHILD and B selects core release on FOCUS. fn setup_k13_natural(f: &mut NotifyFixture) { tree(f); grab_keyboard(f, A, ROOT, true); @@ -799,190 +193,13 @@ fn setup_k13_natural(f: &mut NotifyFixture) { select_core(f, B, FOCUS, KEY_RELEASE); } -const K13_SUPPRESSED_OWNER_QUALIFIES_ON_THE_NATURAL_WALK: Row = Row { - name: "k13_suppressed_owner_qualifies_on_the_natural_walk", - setup: setup_k13_natural, - drive: Drive::After { - origin: InputOrigin::NestedHost, - pressed: false, - master: true, - synthetic: true, - }, - deny: &[(A, CallKind::Core, CHILD)], - allow: Expect { - frames: &[], - calls: &[], - }, - denied: Expect { - frames: &[], - calls: &[], - }, - denied_grab: None, - moved: &[], -}; - -#[test] -fn k1_denied_pointer_window_selector_advances_the_focus_walk() { - check_row(&K1); -} - -#[test] -fn k2_one_allowed_selector_stops_the_walk() { - check_row(&K2); -} - -#[test] -fn k3_denied_xi2_copy_reopens_core_for_that_client() { - check_row(&K3_XI2_DENIED); -} - -#[test] -fn k3_both_denied_walks_on_to_the_focus() { - check_row(&K3_BOTH_DENIED); -} - -#[test] -fn k4_xi2_forms_share_one_check_allowed() { - check_row(&K4_ALLOWED); -} - -#[test] -fn k4_xi2_forms_share_one_check_denied_reopens_core() { - check_row(&K4_XI2_DENIED); -} - -#[test] -fn k5_suppressed_xi2_release_stops_without_a_check() { - check_row(&K5_XI2_SUPPRESSED); -} - -#[test] -fn k5_suppressed_detectable_core_release_stops_without_a_check() { - check_row(&K5_DETECTABLE_SUPPRESSED); -} - -#[test] -fn k5b_form_excluded_by_the_include_flags_still_stops() { - check_row(&K5B_EXCLUDED_FORM_STILL_STOPS); -} - -#[test] -fn k5b_excluded_master_form_still_stops() { - check_row(&K5B_EXCLUDED_MASTER_FORM_STILL_STOPS); -} - -#[test] -fn k5c_slave_grab_write_is_checked() { - check_row(&K5C_SLAVE_GRAB_OWNER); -} - -#[test] -fn k5c_slave_focus_path_is_checked() { - check_row(&K5C_SLAVE_FOCUS_PATH); -} - -#[test] -fn k6_all_denied_lands_on_focus_with_a_stopping_focus_selector() { - check_row(&K6A_ALL_DENIED_LANDS_ON_FOCUS); -} - -#[test] -fn k6_only_selector_denied_lands_on_focus_and_writes_nothing() { - check_row(&K6B_ATTEMPT_LANDS_ON_FOCUS); -} - -#[test] -fn k7_denied_owner_copy_continues_the_natural_walk() { - check_row(&K7_OWNER_DENIED_ON_POINTER_WINDOW); -} - -#[test] -fn k8_denied_owner_with_allowed_foreign_falls_back() { - check_row(&K8_ALLOWED_FOREIGN_FALLS_BACK); -} - -#[test] -fn k9_denied_foreign_selector_does_not_reject() { - check_row(&K9_DENIED_FOREIGN_DOES_NOT_REJECT); -} - -#[test] -fn k9_owner_on_the_same_window_qualifies_first() { - check_row(&K9_OWNER_QUALIFIES_FIRST); -} - -#[test] -fn k10_suppressed_foreign_selector_still_rejects() { - check_row(&K10_SUPPRESSED_FOREIGN_STILL_REJECTS); -} - -#[test] -fn k11_denied_grab_window_copy_is_delivered() { - check_row(&K11_GRAB_WINDOW_DENIAL_DELIVERS); - let denied = run( - &K11_GRAB_WINDOW_DENIAL_DELIVERS, - Some(K11_GRAB_WINDOW_DENIAL_DELIVERS.deny), - ); - assert!( - denied - .grab - .iter() - .any(|fact| matches!(fact, Grab::Keyboard { .. })), - "the denied grab-window copy leaves the keyboard grab active" - ); -} - -#[test] -fn k12_denied_activating_press_still_activates_and_freezes() { - check_row(&K12_ACTIVATING_DENIAL_ACTIVATES); - let denied = run( - &K12_ACTIVATING_DENIAL_ACTIVATES, - Some(K12_ACTIVATING_DENIAL_ACTIVATES.deny), - ); - assert!( - denied - .grab - .iter() - .any(|fact| matches!(fact, Grab::Keyboard { .. })), - "the denied activating press activates the keyboard grab" - ); - assert!( - denied.grab.contains(&Grab::KeyboardFreeze { - state: Xi1SyncState::FrozenWithEvent, - stored: Some((true, KEYCODE)), - }), - "the denied activating press freezes with the press stored" - ); -} - -#[test] -fn k13_synthetic_xi2_release_to_a_grab_owner_is_suppressed() { - check_row(&K13_SYNTHETIC_XI2_RELEASE_SUPPRESSED); -} - -#[test] -fn k13_synthetic_detectable_core_release_to_a_grab_owner_is_suppressed() { - check_row(&K13_DETECTABLE_CORE_RELEASE_SUPPRESSED); -} - -#[test] -fn k9b_every_foreign_selector_is_checked() { - check_row(&K9B_EVERY_FOREIGN_SELECTOR_IS_CHECKED); -} - -#[test] -fn k13_suppressed_owner_qualifies_on_the_natural_walk() { - check_row(&K13_SUPPRESSED_OWNER_QUALIFIES_ON_THE_NATURAL_WALK); -} - -// ---- raw key copies (task 4) --------------------------------------------- - /// A and B select RawKeyPress on the root for the master keyboard. SEND_CLIENT /// (the slave-form selector) selects it for the slave keyboard. fn setup_k13_raw(f: &mut NotifyFixture) { tree(f); - select_xi2(f, A, ROOT, DEVICEID_MASTER_KEYBOARD, XI_RAW_KEY_PRESS); - select_xi2(f, B, ROOT, DEVICEID_MASTER_KEYBOARD, XI_RAW_KEY_PRESS); + for client in [A, B] { + select_xi2(f, client, ROOT, DEVICEID_MASTER_KEYBOARD, XI_RAW_KEY_PRESS); + } select_xi2( f, SEND_CLIENT, @@ -992,48 +209,6 @@ fn setup_k13_raw(f: &mut NotifyFixture) { ); } -/// The slave-form copy goes first (slave pass), then the master copies of A -/// and B. Denying A's master root copy drops only A's copy. -const K13_RAW_ROOT_COPY_DENIAL: Row = Row { - name: "k13_denied_raw_root_copy_drops_only_that_copy", - setup: setup_k13_raw, - drive: Drive::Raw { - origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), - pressed: true, - }, - deny: &[(A, CallKind::Raw, ROOT)], - allow: Expect { - frames: &[ - (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), - (B, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), - (SEND_CLIENT, Kind::Raw(DEVICEID_XTEST_KEYBOARD), ROOT), - ], - calls: &[ - (SEND_CLIENT, CallKind::Raw, ROOT), - (A, CallKind::Raw, ROOT), - (B, CallKind::Raw, ROOT), - ], - }, - denied: Expect { - frames: &[ - (B, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), - (SEND_CLIENT, Kind::Raw(DEVICEID_XTEST_KEYBOARD), ROOT), - ], - calls: &[ - (SEND_CLIENT, CallKind::Raw, ROOT), - (A, CallKind::Raw, ROOT), - (B, CallKind::Raw, ROOT), - ], - }, - denied_grab: None, - moved: &[], -}; - -#[test] -fn k13_denied_raw_root_copy_drops_only_that_copy() { - check_row(&K13_RAW_ROOT_COPY_DENIAL); -} - /// A holds the master keyboard's XI2 grab on CHILD with owner_events, the grab /// mask selects RawKeyPress, and focus is PointerRoot. A selects RawKeyPress on /// the root for the master keyboard, so the natural walk reaches it. @@ -1041,6 +216,11 @@ fn setup_k14(f: &mut NotifyFixture) { setup_k14_with_mask(f, XI_KEY_PRESS | XI_RAW_KEY_PRESS); } +/// The same without RawKeyPress in the grab mask. +fn setup_k14_without_raw_bit(f: &mut NotifyFixture) { + setup_k14_with_mask(f, XI_KEY_PRESS); +} + fn setup_k14_with_mask(f: &mut NotifyFixture, mask: u32) { tree(f); set_focus_pointer_root(f); @@ -1048,196 +228,692 @@ fn setup_k14_with_mask(f: &mut NotifyFixture, mask: u32) { select_xi2(f, A, ROOT, DEVICEID_MASTER_KEYBOARD, XI_RAW_KEY_PRESS); } -fn setup_k14_without_raw_bit(f: &mut NotifyFixture) { - setup_k14_with_mask(f, XI_KEY_PRESS); +const XI1_KEY_PRESS_CALL: CallKind = + CallKind::Batch(&[Named::Xi1(crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET as u16)]); +const XI1_KEY_RELEASE_CALL: CallKind = CallKind::Batch(&[Named::Xi1( + crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET as u16, +)]); + +fn xi1_key_class(offset: u8) -> u32 { + (u32::from(DEVICEID_XTEST_KEYBOARD) << 8) | u32::from(crate::server::XI_FIRST_EVENT + offset) } -/// Denying A's root copy: the natural copy falls back to the grab window (a -/// fresh check with CHILD as subject), and the root fanout is denied too. -const K14_RAW_OWNER_FALLS_BACK_TO_GRAB_WINDOW: Row = Row { - name: "k14_denied_raw_owner_root_copy_falls_back_to_the_grab_window", - setup: setup_k14, - drive: Drive::Raw { - origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), - pressed: true, - }, - deny: &[(A, CallKind::Raw, ROOT)], - allow: Expect { - frames: &[ - (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), - (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), - ], - calls: &[(A, CallKind::Raw, ROOT), (A, CallKind::Raw, ROOT)], - }, - denied: Expect { - frames: &[(A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT)], - calls: &[ - (A, CallKind::Raw, ROOT), - (A, CallKind::Raw, CHILD), - (A, CallKind::Raw, ROOT), - ], - }, - denied_grab: None, - moved: &[], -}; +/// A selects the XI1 `DeviceKeyPress` of the slave keyboard on CHILD, B on FOCUS. +fn setup_k16(f: &mut NotifyFixture) { + tree(f); + let class = xi1_key_class(crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET); + select_xi1(f, A, CHILD, &[class]); + select_xi1(f, B, FOCUS, &[class]); +} -#[test] -fn k14_denied_raw_owner_root_copy_falls_back_to_the_grab_window() { - check_row(&K14_RAW_OWNER_FALLS_BACK_TO_GRAB_WINDOW); +/// The same for `DeviceKeyRelease`, with A on detectable repeat. +fn setup_k17(f: &mut NotifyFixture) { + tree(f); + let class = xi1_key_class(crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET); + select_xi1(f, A, CHILD, &[class]); + select_xi1(f, B, FOCUS, &[class]); + set_detectable_repeat(f, A); } -/// Same as k14 without RawKeyPress in the grab mask: nothing falls back, so -/// the owner gets no copy when its root copy is denied. -const K14_NO_RAW_BIT_NO_FALLBACK: Row = Row { - name: "k14b_denied_raw_owner_without_raw_grab_bit_gets_nothing", - setup: setup_k14_without_raw_bit, - drive: Drive::Raw { - origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), - pressed: true, +// ---- scenarios ----------------------------------------------------------- + +const PRESS: Step = Step::Event(Drive::Entry { + origin: InputOrigin::NestedHost, + pressed: true, +}); +const XTEST_PRESS: Step = Step::Event(Drive::Entry { + origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), + pressed: true, +}); +/// The press of a slave origin whose master transition was rejected. +const SLAVE_PRESS: Step = Step::Event(Drive::After { + origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), + pressed: true, + master: false, + synthetic: false, +}); +/// The synthetic (auto-repeat) release of the master keyboard. +const SYNTH_RELEASE: Step = Step::Event(Drive::After { + origin: InputOrigin::NestedHost, + pressed: false, + master: true, + synthetic: true, +}); +const XTEST_RAW_PRESS: Step = Step::Event(Drive::Raw { + origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), + pressed: true, +}); + +/// The grab facts of an active core keyboard grab by A on the root. +const A_GRABS_ROOT: &[Grab] = &[Grab::Keyboard { + owner: A, + window: ROOT, +}]; + +const fn moved(client: u32, kind: Kind, window: u32, child: u32, event: (i16, i16)) -> Move { + Move { + client, + kind, + window, + child, + event, + } +} + +/// A press delivered by an allow-all policy to A at CHILD by a core selection. +const A_AT_CHILD: Outcome = Outcome { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + ..NOTHING +}; + +const K1_SCENARIO: Scenario = Scenario { + setup: setup_k1, + steps: &[PRESS], + allow: A_AT_CHILD, + order: CallOrder::Total, +}; + +const K3_SCENARIO: Scenario = Scenario { + setup: setup_k3, + steps: &[PRESS], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + ..NOTHING }, - deny: &[(A, CallKind::Raw, ROOT)], - allow: Expect { + order: CallOrder::Total, +}; + +const K4_SCENARIO: Scenario = Scenario { + setup: setup_k4, + steps: &[XTEST_PRESS], + allow: Outcome { frames: &[ - (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), - (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + (A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD), + (A, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), CHILD), ], - calls: &[(A, CallKind::Raw, ROOT), (A, CallKind::Raw, ROOT)], - }, - denied: Expect { - frames: &[], - calls: &[(A, CallKind::Raw, ROOT), (A, CallKind::Raw, ROOT)], + calls: &[(A, CallKind::Xi2, CHILD)], + ..NOTHING }, - denied_grab: None, - moved: &[], + order: CallOrder::Total, }; -#[test] -fn k14b_denied_raw_owner_without_raw_grab_bit_gets_nothing() { - check_row(&K14_NO_RAW_BIT_NO_FALLBACK); -} +/// A selector the walk stops at without a copy or a check: nothing is written +/// or asked, whatever the denial says. +const SUPPRESSED: Scenario = Scenario { + setup: setup_k5_xi2_release, + steps: &[SYNTH_RELEASE], + allow: NOTHING, + order: CallOrder::Total, +}; -/// An allowed natural copy is the only copy from the grab leg: the grab window -/// is never asked. -const K15_ALLOWED_NATURAL_SKIPS_GRAB_WINDOW: Row = Row { - name: "k15_allowed_natural_raw_leg_skips_the_grab_window_check", - setup: setup_k14, - drive: Drive::Raw { - origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), - pressed: true, - }, - deny: &[], - allow: Expect { - frames: &[ - (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), - (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), - ], - calls: &[(A, CallKind::Raw, ROOT), (A, CallKind::Raw, ROOT)], +const K5_DETECTABLE_SCENARIO: Scenario = Scenario { + setup: setup_k5_detectable, + steps: &[SYNTH_RELEASE], + allow: NOTHING, + order: CallOrder::Total, +}; + +const K5B_SCENARIO: Scenario = Scenario { + setup: setup_k5b, + steps: &[SLAVE_PRESS], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + ..NOTHING }, - denied: Expect { - frames: &[ - (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), - (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), - ], - calls: &[(A, CallKind::Raw, ROOT), (A, CallKind::Raw, ROOT)], + order: CallOrder::Total, +}; + +const K5B_MASTER_SCENARIO: Scenario = Scenario { + setup: setup_k5b_master, + steps: &[SLAVE_PRESS], + allow: NOTHING, + order: CallOrder::Total, +}; + +const K5C_GRAB_SCENARIO: Scenario = Scenario { + setup: setup_k5c_grab, + steps: &[SLAVE_PRESS], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), FOCUS)], + calls: &[(A, CallKind::Xi2, FOCUS)], + ..NOTHING }, - denied_grab: None, - moved: &[], + order: CallOrder::Total, }; -#[test] -fn k15_allowed_natural_raw_leg_skips_the_grab_window_check() { - check_row(&K15_ALLOWED_NATURAL_SKIPS_GRAB_WINDOW); -} +const K5C_FOCUS_SCENARIO: Scenario = Scenario { + setup: setup_k5c_focus, + steps: &[SLAVE_PRESS], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, +}; -// ---- XI1 router ------------------------------------------- +const K7_SCENARIO: Scenario = Scenario { + setup: setup_k7, + steps: &[PRESS], + allow: Outcome { + grab: Some(A_GRABS_ROOT), + ..A_AT_CHILD + }, + order: CallOrder::Total, +}; -const XI1_KEY_PRESS_CALL: CallKind = - CallKind::Batch(&[Named::Xi1(crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET as u16)]); -const XI1_KEY_RELEASE_CALL: CallKind = CallKind::Batch(&[Named::Xi1( - crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET as u16, -)]); +const K8_SCENARIO: Scenario = Scenario { + setup: setup_k8, + steps: &[PRESS], + allow: Outcome { + grab: Some(A_GRABS_ROOT), + ..A_AT_CHILD + }, + order: CallOrder::PerClient, +}; -fn xi1_key_class(offset: u8) -> u32 { - (u32::from(DEVICEID_XTEST_KEYBOARD) << 8) | u32::from(crate::server::XI_FIRST_EVENT + offset) -} +const K10_SCENARIO: Scenario = Scenario { + setup: setup_k10, + steps: &[SYNTH_RELEASE], + allow: Outcome { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(A, CallKind::Core, ROOT)], + grab: Some(A_GRABS_ROOT), + ..NOTHING + }, + order: CallOrder::Total, +}; -fn setup_k16(f: &mut NotifyFixture) { - tree(f); - let class = xi1_key_class(crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET); - select_xi1(f, A, CHILD, &[class]); - select_xi1(f, B, FOCUS, &[class]); -} +const A_ROOT_COPY: Outcome = Outcome { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(A, CallKind::Core, ROOT)], + grab: Some(A_GRABS_ROOT), + ..NOTHING +}; -const K16: Row = Row { - name: "k16_xi1_focused_key_denial_advances_the_focus_walk", - setup: setup_k16, - drive: Drive::Entry { - origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), - pressed: true, +/// A holds the activating sync grab: the press freezes the master keyboard +/// with the press stored. +const K12_GRABS: &[Grab] = &[ + Grab::Keyboard { + owner: A, + window: ROOT, }, - deny: &[(A, XI1_KEY_PRESS_CALL, CHILD)], - allow: Expect { - frames: &[(A, Kind::Xi1Key(DEVICEID_XTEST_KEYBOARD), CHILD)], - calls: &[(A, XI1_KEY_PRESS_CALL, CHILD)], + Grab::Freeze { + device: DEVICEID_MASTER_KEYBOARD, + state: Xi1SyncState::FrozenWithEvent, + other: None, + stored: Some(Held::Key { + pressed: true, + keycode: KEYCODE, + }), }, - denied: Expect { - frames: &[(B, Kind::Xi1Key(DEVICEID_XTEST_KEYBOARD), FOCUS)], +]; + +const K13_RAW_SCENARIO: Scenario = Scenario { + setup: setup_k13_raw, + steps: &[XTEST_RAW_PRESS], + allow: Outcome { + frames: &[ + (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + (B, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + (SEND_CLIENT, Kind::Raw(DEVICEID_XTEST_KEYBOARD), ROOT), + ], calls: &[ - (A, XI1_KEY_PRESS_CALL, CHILD), - (B, XI1_KEY_PRESS_CALL, FOCUS), + (SEND_CLIENT, CallKind::Raw, ROOT), + (A, CallKind::Raw, ROOT), + (B, CallKind::Raw, ROOT), ], + ..NOTHING }, - denied_grab: None, - moved: &[Moved { - client: B, - window: FOCUS, - child: CHILD, - event: (20, 20), - }], + order: CallOrder::PerClient, }; -/// XTEST keyboard origin; X selects the XI1 `DeviceKeyPress` on C (the pointer -/// window, under focus F), Y on F. X's copy denied: the focus walk goes on and -/// Y gets it at F. Mutation: a denied XI1 selector stops the walk. -#[test] -fn k16_xi1_focused_key_denial_advances_the_focus_walk() { - check_row(&K16); -} +/// The grab owner's raw copies: the natural copy at the root and the grab +/// leg's copy, which the root fanout repeats. An allowed natural copy is the +/// only grab-leg copy; the grab window is never asked. +const K14_GRABS: &[Grab] = &[Grab::Keyboard { + owner: A, + window: CHILD, +}]; +const K14_ALLOW: Outcome = Outcome { + frames: &[ + (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + ], + calls: &[(A, CallKind::Raw, ROOT), (A, CallKind::Raw, ROOT)], + grab: Some(K14_GRABS), + ..NOTHING +}; -fn setup_k17(f: &mut NotifyFixture) { - tree(f); - let class = xi1_key_class(crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET); - select_xi1(f, A, CHILD, &[class]); - select_xi1(f, B, FOCUS, &[class]); - set_detectable_repeat(f, A); -} +// ---- rows ---------------------------------------------------------------- -const K17: Row = Row { - name: "k17_xi1_detectable_repeat_release_stops_without_a_check", - setup: setup_k17, - drive: Drive::After { - origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), - pressed: false, - master: false, - synthetic: true, - }, - deny: &[(A, XI1_KEY_RELEASE_CALL, CHILD)], - allow: Expect { - frames: &[], - calls: &[], - }, - denied: Expect { - frames: &[], - calls: &[], - }, - denied_grab: None, - moved: &[], -}; +const ROWS: &[InputRow] = &[ + InputRow { + name: "k1_denied_pointer_window_selector_advances_the_focus_walk", + scenario: &K1_SCENARIO, + deny: &[(A, CallKind::Core, CHILD)], + denied: Outcome { + frames: &[(B, Kind::Core, FOCUS)], + moved: &[moved(B, Kind::Core, FOCUS, CHILD, (20, 20))], + calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, FOCUS)], + ..NOTHING + }, + }, + InputRow { + name: "k2_one_allowed_selector_stops_the_walk", + scenario: &Scenario { + setup: setup_k2, + steps: &[PRESS], + allow: Outcome { + frames: &[(A, Kind::Core, CHILD), (B, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, CHILD)], + ..NOTHING + }, + order: CallOrder::PerClient, + }, + deny: &[(A, CallKind::Core, CHILD)], + denied: Outcome { + frames: &[(B, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, CHILD)], + ..NOTHING + }, + }, + InputRow { + name: "k3_denied_xi2_copy_reopens_core_for_that_client", + scenario: &K3_SCENARIO, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Core, CHILD)], + moved: &[moved(A, Kind::Core, CHILD, 0, (10, 10))], + calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], + ..NOTHING + }, + }, + InputRow { + name: "k3_both_denied_walks_on_to_the_focus", + scenario: &K3_SCENARIO, + deny: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], + denied: Outcome { + frames: &[(B, Kind::Core, FOCUS)], + moved: &[moved(B, Kind::Core, FOCUS, CHILD, (20, 20))], + calls: &[ + (A, CallKind::Xi2, CHILD), + (A, CallKind::Core, CHILD), + (B, CallKind::Core, FOCUS), + ], + ..NOTHING + }, + }, + // The XI2 forms of one key share one check. With that check allowed the + // denial list is empty, so the allowed row is this scenario's allow run. + InputRow { + name: "k4_xi2_forms_share_one_check_denied_reopens_core", + scenario: &K4_SCENARIO, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Core, CHILD)], + moved: &[moved(A, Kind::Core, CHILD, 0, (10, 10))], + calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], + ..NOTHING + }, + }, + InputRow { + name: "k5_suppressed_xi2_release_stops_without_a_check", + scenario: &SUPPRESSED, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: NOTHING, + }, + InputRow { + name: "k5_suppressed_detectable_core_release_stops_without_a_check", + scenario: &K5_DETECTABLE_SCENARIO, + deny: &[(A, CallKind::Core, CHILD)], + denied: NOTHING, + }, + InputRow { + name: "k5b_form_excluded_by_the_include_flags_still_stops", + scenario: &K5B_SCENARIO, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: Outcome { + calls: &[(A, CallKind::Xi2, CHILD)], + ..NOTHING + }, + }, + InputRow { + name: "k5b_excluded_master_form_still_stops", + scenario: &K5B_MASTER_SCENARIO, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: NOTHING, + }, + InputRow { + name: "k5c_slave_grab_write_is_checked", + scenario: &K5C_GRAB_SCENARIO, + deny: &[(A, CallKind::Xi2, FOCUS)], + denied: Outcome { + calls: &[(A, CallKind::Xi2, FOCUS)], + ..NOTHING + }, + }, + InputRow { + name: "k5c_slave_focus_path_is_checked", + scenario: &K5C_FOCUS_SCENARIO, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: Outcome { + calls: &[(A, CallKind::Xi2, CHILD)], + ..NOTHING + }, + }, + InputRow { + name: "k6_all_denied_lands_on_focus_with_a_stopping_focus_selector", + scenario: &Scenario { + setup: setup_k6a, + steps: &[PRESS], + allow: A_AT_CHILD, + order: CallOrder::PerClient, + }, + deny: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + denied: Outcome { + frames: &[(B, Kind::Core, FOCUS)], + moved: &[moved(B, Kind::Core, FOCUS, CHILD, (20, 20))], + calls: &[ + (A, CallKind::Core, CHILD), + (A, CallKind::Core, FOCUS), + (B, CallKind::Core, FOCUS), + ], + ..NOTHING + }, + }, + InputRow { + name: "k6_only_selector_denied_lands_on_focus_and_writes_nothing", + scenario: &Scenario { + setup: setup_k6b, + steps: &[PRESS], + allow: A_AT_CHILD, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + denied: Outcome { + calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + ..NOTHING + }, + }, + InputRow { + name: "k7_denied_owner_copy_continues_the_natural_walk", + scenario: &K7_SCENARIO, + deny: &[(A, CallKind::Core, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Core, FOCUS)], + moved: &[moved(A, Kind::Core, FOCUS, CHILD, (20, 20))], + calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + ..NOTHING + }, + }, + InputRow { + name: "k8_denied_owner_with_allowed_foreign_falls_back", + scenario: &K8_SCENARIO, + deny: &[(A, CallKind::Core, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Core, ROOT)], + moved: &[moved(A, Kind::Core, ROOT, FOCUS, (120, 120))], + calls: &[ + (A, CallKind::Core, CHILD), + (B, CallKind::Core, CHILD), + (A, CallKind::Core, ROOT), + ], + ..NOTHING + }, + }, + InputRow { + name: "k9_denied_foreign_selector_does_not_reject", + scenario: &Scenario { + setup: setup_k9, + steps: &[PRESS], + allow: Outcome { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, ROOT)], + grab: Some(A_GRABS_ROOT), + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(B, CallKind::Core, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Core, FOCUS)], + moved: &[moved(A, Kind::Core, FOCUS, CHILD, (20, 20))], + calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + ..NOTHING + }, + }, + // A and B both select on CHILD and B is denied. A qualifies first, so the + // walk stops at CHILD and no check is made for B. + InputRow { + name: "k9_owner_on_the_same_window_qualifies_first", + scenario: &K8_SCENARIO, + deny: &[(B, CallKind::Core, CHILD)], + denied: K8_SCENARIO.allow, + }, + InputRow { + name: "k9b_every_foreign_selector_is_checked", + scenario: &Scenario { + setup: setup_k9b, + steps: &[PRESS], + allow: Outcome { + grab: Some(A_GRABS_ROOT), + ..A_AT_CHILD + }, + order: CallOrder::PerClient, + }, + deny: &[(A, CallKind::Core, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Core, ROOT)], + moved: &[moved(A, Kind::Core, ROOT, FOCUS, (120, 120))], + calls: &[ + (A, CallKind::Core, CHILD), + (B, CallKind::Core, CHILD), + (SEND_CLIENT, CallKind::Core, CHILD), + (A, CallKind::Core, ROOT), + ], + ..NOTHING + }, + }, + InputRow { + name: "k10_suppressed_foreign_selector_still_rejects", + scenario: &K10_SCENARIO, + deny: &[], + denied: K10_SCENARIO.allow, + }, + // The grab-window copy is denied: no bytes, and B gets nothing, but the + // keyboard grab stays active. + InputRow { + name: "k11_denied_grab_window_copy_is_delivered", + scenario: &Scenario { + setup: setup_k11, + steps: &[PRESS], + allow: A_ROOT_COPY, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, ROOT)], + denied: Outcome { + calls: &[(A, CallKind::Core, ROOT)], + ..NOTHING + }, + }, + // The activating press is denied to A: the grab still activates and + // freezes with the press stored. + InputRow { + name: "k12_denied_activating_press_still_activates_and_freezes", + scenario: &Scenario { + setup: setup_k12, + steps: &[PRESS], + allow: Outcome { + grab: Some(K12_GRABS), + ..A_ROOT_COPY + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, ROOT)], + denied: Outcome { + calls: &[(A, CallKind::Core, ROOT)], + ..NOTHING + }, + }, + // A holds the slave keyboard's exact XI2 grab on FOCUS (owner_events + // false): the synthetic XI2 release is suppressed in the grab's protocol. + InputRow { + name: "k13_synthetic_xi2_release_to_a_grab_owner_is_suppressed", + scenario: &Scenario { + setup: setup_k5c_grab, + steps: &[Step::Event(Drive::After { + origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), + pressed: false, + master: false, + synthetic: true, + })], + allow: NOTHING, + order: CallOrder::Total, + }, + deny: &[], + denied: NOTHING, + }, + InputRow { + name: "k13_synthetic_detectable_core_release_to_a_grab_owner_is_suppressed", + scenario: &Scenario { + setup: setup_k13_detectable, + steps: &[SYNTH_RELEASE], + allow: Outcome { + grab: Some(A_GRABS_ROOT), + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[], + denied: NOTHING, + }, + // The synthetic release is suppressed for A, so A qualifies at CHILD with + // no Receive call and nothing is written; denying A at CHILD changes + // nothing, because no copy is checked. + InputRow { + name: "k13_suppressed_owner_qualifies_on_the_natural_walk", + scenario: &Scenario { + setup: setup_k13_natural, + steps: &[SYNTH_RELEASE], + allow: Outcome { + grab: Some(A_GRABS_ROOT), + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, CHILD)], + denied: NOTHING, + }, + // The slave-form copy goes first (slave pass), then the master copies of A + // and B. Denying A's master root copy drops only A's copy. + InputRow { + name: "k13_denied_raw_root_copy_drops_only_that_copy", + scenario: &K13_RAW_SCENARIO, + deny: &[(A, CallKind::Raw, ROOT)], + denied: Outcome { + frames: &[ + (B, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + (SEND_CLIENT, Kind::Raw(DEVICEID_XTEST_KEYBOARD), ROOT), + ], + calls: K13_RAW_SCENARIO.allow.calls, + ..NOTHING + }, + }, + // Denying A's root copy: the natural copy falls back to the grab window (a + // fresh check with CHILD as subject), and the root fanout is denied too. + // This row's allow run is also the allowed natural raw leg: the grab + // window is never asked when the natural copy is allowed. + InputRow { + name: "k14_denied_raw_owner_root_copy_falls_back_to_the_grab_window", + scenario: &Scenario { + setup: setup_k14, + steps: &[XTEST_RAW_PRESS], + allow: K14_ALLOW, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Raw, ROOT)], + denied: Outcome { + frames: &[(A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT)], + calls: &[ + (A, CallKind::Raw, ROOT), + (A, CallKind::Raw, CHILD), + (A, CallKind::Raw, ROOT), + ], + ..NOTHING + }, + }, + // Without RawKeyPress in the grab mask nothing falls back, so the owner + // gets no copy when its root copy is denied. + InputRow { + name: "k14b_denied_raw_owner_without_raw_grab_bit_gets_nothing", + scenario: &Scenario { + setup: setup_k14_without_raw_bit, + steps: &[XTEST_RAW_PRESS], + allow: K14_ALLOW, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Raw, ROOT)], + denied: Outcome { + calls: K14_ALLOW.calls, + ..NOTHING + }, + }, + // X selects the XI1 `DeviceKeyPress` on C (the pointer window, under focus + // F), Y on F. X's copy is denied: the focus walk goes on and Y gets it at F. + InputRow { + name: "k16_xi1_focused_key_denial_advances_the_focus_walk", + scenario: &Scenario { + setup: setup_k16, + steps: &[XTEST_PRESS], + allow: Outcome { + frames: &[(A, Kind::Xi1Key(DEVICEID_XTEST_KEYBOARD), CHILD)], + calls: &[(A, XI1_KEY_PRESS_CALL, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, XI1_KEY_PRESS_CALL, CHILD)], + denied: Outcome { + frames: &[(B, Kind::Xi1Key(DEVICEID_XTEST_KEYBOARD), FOCUS)], + moved: &[moved( + B, + Kind::Xi1Key(DEVICEID_XTEST_KEYBOARD), + FOCUS, + CHILD, + (20, 20), + )], + calls: &[ + (A, XI1_KEY_PRESS_CALL, CHILD), + (B, XI1_KEY_PRESS_CALL, FOCUS), + ], + ..NOTHING + }, + }, + // A synthetic repeat release to a detectable-repeat client gets no copy but + // stops the walk: nothing is written, X is not asked, Y is not reached. + InputRow { + name: "k17_xi1_detectable_repeat_release_stops_without_a_check", + scenario: &Scenario { + setup: setup_k17, + steps: &[Step::Event(Drive::After { + origin: InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD), + pressed: false, + master: false, + synthetic: true, + })], + allow: NOTHING, + order: CallOrder::Total, + }, + deny: &[(A, XI1_KEY_RELEASE_CALL, CHILD)], + denied: NOTHING, + }, +]; -/// A synthetic repeat release to a detectable-repeat client gets no copy but -/// stops the walk: nothing is written, X is not asked, Y is not reached. -/// Mutation: X is asked (a call) or the walk goes past it (Y gets a frame). #[test] -fn k17_xi1_detectable_repeat_release_stops_without_a_check() { - check_row(&K17); +fn key_rows() { + check_rows(ROWS); } From d7bf89af47b633cabafcf04541d46922b2baad76 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 12:12:47 -0300 Subject: [PATCH 44/72] test(access): input runner keeps queued-event variants and per-step attribution Held now keeps the QueuedInputEvent variant and its distinguishing fields (HostKey vs HostKeyTransition with its master and synthetic flags, HostPointer vs HostPointerMaster with its scroll payload, Xi1Routed, RawKey). k12 states the stored press as HostKeyTransition again. In multi-step scenarios a deny shorthand denies the matching description of every step's event, an expected-call shorthand names the event of the step that made the call, and frame detail and sequence are checked against the step that wrote the frame. One-step scenarios behave as before. Restores the Mutation comments on k16 and k17. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Sonnet 5.5 --- .../tests/access_input_support.rs | 294 ++++++++++++------ .../process_request/tests/access_key_input.rs | 6 +- 2 files changed, 212 insertions(+), 88 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index bfd62d2f1..a8775d356 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -608,9 +608,10 @@ fn names_of(events: &[EventDescription]) -> Option> { } /// Denies the listed (client, batch, window) Receive checks: a call is denied -/// when some entry names its whole ordered list and subject. `ev` is the event -/// type the row drives, used by the shorthand entries. -pub(super) fn decide(denied: &[Call], ev: u16, call: &RecordedExtensionCheck) -> Decision { +/// when some entry names its whole ordered list and subject. `evs` are the event +/// types the scenario drives; a shorthand entry denies the description of every +/// one of them. +pub(super) fn decide(denied: &[Call], evs: &[u16], call: &RecordedExtensionCheck) -> Decision { if call.hook != ExtensionHook::Receive { return Decision::Allow; } @@ -622,8 +623,10 @@ pub(super) fn decide(denied: &[Call], ev: u16, call: &RecordedExtensionCheck) -> return Decision::Allow; }; let hit = denied.iter().any(|entry| { - let (client, expected, subject) = expected_call(entry, ev); - client == call.client.0 && subject == window.0 && expected == names + evs.iter().any(|ev| { + let (client, expected, subject) = expected_call(entry, *ev); + client == call.client.0 && subject == window.0 && expected == names + }) }); if hit { DENY } else { Decision::Allow } } @@ -683,6 +686,8 @@ pub(super) struct ClientBytes { pub(super) order: ClientByteOrder, pub(super) sequence: u16, pub(super) bytes: Vec, + /// Per step: the byte length after it and the client's sequence then. + pub(super) steps: Vec<(usize, u16)>, } /// One fact of the grab state after a run. A row states the facts its denied @@ -713,32 +718,68 @@ pub(super) enum Grab { Queued { device: u16, held: Held }, } -/// A withheld input event, reduced to what the freeze rows state. +/// A withheld input event: the `QueuedInputEvent` variant and the fields that +/// tell the variants apart. #[derive(Clone, Copy, Debug, PartialEq)] pub(super) enum Held { - Key { pressed: bool, keycode: u8 }, - Raw { pressed: bool, keycode: u8 }, - Pointer { kind: PointerEventKind, detail: u8 }, - Xi1 { evcode: u8, detail: u8 }, + HostKey { + pressed: bool, + keycode: u8, + }, + /// A key already through the guards: the accepted master edge and the + /// synthetic-repeat marker ride along. + HostKeyTransition { + pressed: bool, + keycode: u8, + master: bool, + synthetic: bool, + }, + HostPointer { + kind: PointerEventKind, + detail: u8, + }, + /// The deferred master part of a pointer event, with its scroll payload. + HostPointerMaster { + kind: PointerEventKind, + detail: u8, + scroll: Option<(u8, i32)>, + }, + Xi1Routed { + evcode: u8, + detail: u8, + }, + RawKey { + pressed: bool, + keycode: u8, + }, } fn held(event: &QueuedInputEvent) -> Held { match event { - QueuedInputEvent::HostPointer(e) | QueuedInputEvent::HostPointerMaster(e, _) => { - Held::Pointer { - kind: e.kind, - detail: e.detail, - } - } - QueuedInputEvent::HostKey(e) | QueuedInputEvent::HostKeyTransition(e, ..) => Held::Key { + QueuedInputEvent::HostPointer(e) => Held::HostPointer { + kind: e.kind, + detail: e.detail, + }, + QueuedInputEvent::HostPointerMaster(e, scroll) => Held::HostPointerMaster { + kind: e.kind, + detail: e.detail, + scroll: *scroll, + }, + QueuedInputEvent::HostKey(e) => Held::HostKey { pressed: e.pressed, keycode: e.keycode, }, - QueuedInputEvent::Xi1Routed(q) => Held::Xi1 { + QueuedInputEvent::HostKeyTransition(e, master, synthetic) => Held::HostKeyTransition { + pressed: e.pressed, + keycode: e.keycode, + master: *master, + synthetic: *synthetic, + }, + QueuedInputEvent::Xi1Routed(q) => Held::Xi1Routed { evcode: q.evcode, detail: q.detail, }, - QueuedInputEvent::RawKey(e) => Held::Raw { + QueuedInputEvent::RawKey(e) => Held::RawKey { pressed: e.pressed, keycode: e.keycode, }, @@ -759,6 +800,8 @@ pub(super) struct PointerGrab { pub(super) struct Run { pub(super) clients: Vec, pub(super) calls: Vec, + /// The event type of the step that made each call, parallel to `calls`. + pub(super) call_evs: Vec, pub(super) state: String, pub(super) grab: Vec, } @@ -772,7 +815,7 @@ pub(super) fn run(row: &Row, policy: Option<&'static [Call]>) -> Run { } let calls = policy.map(|denied| { let ev = row.drive.ev(); - f.install_policy(move |_, call| decide(denied, ev, call)) + f.install_policy(move |_, call| decide(denied, &[ev], call)) }); drive(&mut f, row.drive); assert!( @@ -783,12 +826,15 @@ pub(super) fn run(row: &Row, policy: Option<&'static [Call]>) -> Run { let clients = [SEND_CLIENT, A, B] .into_iter() .map(|client| { + let bytes = f.drain(ClientId(client)); let state = &f.state.clients[&client]; + let sequence = state.last_sequence.load(Ordering::Relaxed); ClientBytes { client, order: state.byte_order, - sequence: state.last_sequence.load(Ordering::Relaxed), - bytes: f.drain(ClientId(client)), + sequence, + steps: vec![(bytes.len(), sequence)], + bytes, } }) .collect(); @@ -826,6 +872,7 @@ pub(super) fn run(row: &Row, policy: Option<&'static [Call]>) -> Run { Run { clients, calls, + call_evs: Vec::new(), state, grab, } @@ -903,20 +950,26 @@ pub(super) fn grouped( out } -/// The key frames a run wrote, with the client byte order and sequence checked. -pub(super) fn delivered(name: &str, run: &Run, details: &[u32], wheel_press: bool) -> Vec { +/// The frames a run wrote, with the client byte order checked, the sequence +/// checked against the client's sequence after the step that wrote the frame +/// and the detail against that step's `(detail, wheel press)`. +pub(super) fn delivered(name: &str, run: &Run, steps: &[(u32, bool)]) -> Vec { let mut frames = Vec::new(); for client in &run.clients { for frame in split_frames(&client.bytes, client.order) { if let Some((kind, window)) = decode(frame, client.order) { + let offset = frame.as_ptr() as usize - client.bytes.as_ptr() as usize; + let step = client.steps.iter().position(|(end, _)| offset < *end); + let step = step.expect("a frame belongs to a step"); + let (detail, wheel_press) = steps[step]; let sequence = match client.order { - ClientByteOrder::LittleEndian => client.sequence.to_le_bytes(), - ClientByteOrder::BigEndian => client.sequence.to_be_bytes(), + ClientByteOrder::LittleEndian => client.steps[step].1.to_le_bytes(), + ClientByteOrder::BigEndian => client.steps[step].1.to_be_bytes(), }; assert_eq!( &frame[2..4], sequence.as_slice(), - "{name}: client {} frame sequence", + "{name}: client {} step {step} frame sequence", client.client ); let keycode = match kind { @@ -925,20 +978,18 @@ pub(super) fn delivered(name: &str, run: &Run, details: &[u32], wheel_press: boo } // The valuator continuation has no detail byte (byte 1 is // the device). - Kind::Xi1Valuator(_) => details[0], + Kind::Xi1Valuator(_) => detail, Kind::Xi2(_) | Kind::Raw(_) => dec32(&frame[16..20], client.order), }; // The smooth-scroll Motion of a wheel press carries no button. let is_scroll_motion = wheel_press && matches!(kind, Kind::Xi2(_)) && dec16(&frame[8..10], client.order) == 6; - assert!( - if is_scroll_motion { - keycode == 0 - } else { - details.contains(&keycode) - }, - "{name}: frame detail {keycode} not in {details:?}" + let expected = if is_scroll_motion { 0 } else { detail }; + assert_eq!( + keycode, expected, + "{name}: client {} step {step} frame detail", + client.client ); frames.push((client.client, kind, window)); } @@ -963,9 +1014,13 @@ pub(super) fn check_run(row: &Row, run: &Run, expect: &Expect, mode: &str) { ); assert_eq!( grouped( - delivered(name, run, &[row.drive.detail()], row.drive.is_wheel_press()) - .into_iter() - .map(|(c, k, w)| (c, (k, w))) + delivered( + name, + run, + &[(row.drive.detail(), row.drive.is_wheel_press())] + ) + .into_iter() + .map(|(c, k, w)| (c, (k, w))) ), grouped(expect.frames.iter().map(|&(c, k, w)| (c, (k, w)))), "{name} [{mode}]: frames per client" @@ -1254,20 +1309,29 @@ pub(super) struct InputRow { pub(super) denied: Outcome, } -/// The event type the shorthand calls of a scenario name: its first event. -fn first_event(scenario: &Scenario) -> Drive { +/// The event each step runs under: an event step's own, and for a request step +/// the event before it (a thaw replays that event), or the first one. +fn step_events(scenario: &Scenario) -> Vec { + let first = scenario.steps.iter().find_map(|step| match step { + Step::Event(drive) => Some(*drive), + Step::Request(_) => None, + }); + let mut current = first.expect("a scenario drives at least one event"); scenario .steps .iter() - .find_map(|step| match step { - Step::Event(drive) => Some(*drive), - Step::Request(_) => None, + .map(|step| { + if let Step::Event(drive) = step { + current = *drive; + } + current }) - .expect("a scenario drives at least one event") + .collect() } /// Runs a scenario from a fresh fixture. `policy` is `None` for no policy, or -/// the calls to deny under a recording policy. +/// the calls to deny under a recording policy. Frames and Receive calls are +/// attributed to the step that made them. fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run { let mut f = NotifyFixture::new(); (scenario.setup)(&mut f); @@ -1275,49 +1339,70 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run for client in [SEND_CLIENT, A, B] { f.drain(ClientId(client)); } - let ev = first_event(scenario).ev(); - let calls = policy.map(|denied| f.install_policy(move |_, call| decide(denied, ev, call))); - for step in scenario.steps { + let drives = step_events(scenario); + let evs: Vec = drives.iter().map(|drive| drive.ev()).collect(); + let recorder = policy.map(|denied| { + let evs = evs.clone(); + f.install_policy(move |_, call| decide(denied, &evs, call)) + }); + let mut clients: Vec = [SEND_CLIENT, A, B] + .into_iter() + .map(|client| ClientBytes { + client, + order: f.state.clients[&client].byte_order, + sequence: 0, + bytes: Vec::new(), + steps: Vec::new(), + }) + .collect(); + let mut call_evs = Vec::new(); + let mut seen_calls = 0; + for (index, step) in scenario.steps.iter().enumerate() { match step { Step::Event(event) => drive(&mut f, *event), Step::Request(request) => request(&mut f), } + for client in &mut clients { + client.bytes.extend(f.drain(ClientId(client.client))); + client.sequence = f.state.clients[&client.client] + .last_sequence + .load(Ordering::Relaxed); + client.steps.push((client.bytes.len(), client.sequence)); + } + if let Some(recorder) = &recorder { + let total = recorder.lock().unwrap().len(); + call_evs.extend((seen_calls..total).map(|_| evs[index])); + seen_calls = total; + } } assert!( client_io::failed_writers(&f.state.clients).is_empty(), "{name}: delivery queued a disconnect" ); - let clients = [SEND_CLIENT, A, B] - .into_iter() - .map(|client| { - let state = &f.state.clients[&client]; - ClientBytes { - client, - order: state.byte_order, - sequence: state.last_sequence.load(Ordering::Relaxed), - bytes: f.drain(ClientId(client)), - } - }) - .collect(); - let calls = calls - .map(|calls| { - calls + // The recorder holds every hook; keep the named Receive calls, with the + // event type of the step that made each. + let (calls, call_evs) = recorder + .map(|recorder| { + recorder .lock() .unwrap() .iter() - .filter(|call| call.hook == ExtensionHook::Receive) - .filter_map(|call| { + .zip(call_evs) + .filter(|(call, _)| call.hook == ExtensionHook::Receive) + .filter_map(|(call, ev)| { let EventSubject::Window(window) = call.receive? else { panic!("{name}: Receive subject {:?}", call.receive); }; - Some((call.client.0, names_of(call.events.as_deref()?)?, window.0)) + let seen = (call.client.0, names_of(call.events.as_deref()?)?, window.0); + Some((seen, ev)) }) - .collect() + .unzip() }) .unwrap_or_default(); Run { clients, calls, + call_evs, state: format!("{:?}", (f.state.core_focus.raw, f.state.keys_down)), grab: grab_facts(&f.state), } @@ -1397,26 +1482,45 @@ fn moved_frames(name: &str, allow: &Run, denied: &Run) -> Vec<(u32, Move)> { moved } -/// The details a scenario's frames may carry: the one of each event step. -fn details_of(scenario: &Scenario) -> (Vec, bool) { - let events = scenario.steps.iter().filter_map(|step| match step { - Step::Event(drive) => Some(*drive), - Step::Request(_) => None, - }); - ( - events.clone().map(Drive::detail).collect(), - events.into_iter().any(Drive::is_wheel_press), - ) +/// A recorded call with a shorthand's number zeroed when it names the event of +/// the step that made it, so it compares with a shorthand entry of a row. +fn canonical_seen(call: &Seen, ev: u16) -> Seen { + let (client, names, window) = call; + let own = match names.as_slice() { + [Named::Core(n)] if *n == ev => vec![Named::Core(0)], + [Named::Xi2(n)] if *n == ev => vec![Named::Xi2(0)], + [Named::Raw(n)] if *n == ev => vec![Named::Raw(0)], + _ => names.clone(), + }; + (*client, own, *window) +} + +/// A row's expected call in the same form: a shorthand is the zeroed name. +fn canonical_call(call: &Call) -> Seen { + let (client, kind, window) = *call; + let names = match kind { + CallKind::Core => vec![Named::Core(0)], + CallKind::Xi2 => vec![Named::Xi2(0)], + CallKind::Raw => vec![Named::Raw(0)], + CallKind::Batch(list) => list.to_vec(), + }; + (client, names, window) } -/// Compares a run's frames and Receive trace with a stated outcome. +/// Compares a run's frames and Receive trace with a stated outcome. A shorthand +/// call names the event of the step that made it (`Core(0)` below). fn check_outcome(name: &str, mode: &str, scenario: &Scenario, run: &Run, want: &Outcome) { - let ev = first_event(scenario).ev(); - let calls: Vec = want.calls.iter().map(|c| expected_call(c, ev)).collect(); + let got: Vec = run + .calls + .iter() + .zip(&run.call_evs) + .map(|(call, ev)| canonical_seen(call, *ev)) + .collect(); + let calls: Vec = want.calls.iter().map(canonical_call).collect(); let calls_match = match scenario.order { - CallOrder::Total => run.calls == calls, + CallOrder::Total => got == calls, CallOrder::PerClient => { - grouped(run.calls.iter().map(|(c, n, w)| (*c, (n.clone(), *w)))) + grouped(got.iter().map(|(c, n, w)| (*c, (n.clone(), *w)))) == grouped(calls.iter().map(|(c, n, w)| (*c, (n.clone(), *w)))) } CallOrder::Multiset => { @@ -1424,18 +1528,21 @@ fn check_outcome(name: &str, mode: &str, scenario: &Scenario, run: &Run, want: & calls.sort(); calls }; - sorted(run.calls.clone()) == sorted(calls.clone()) + sorted(got.clone()) == sorted(calls.clone()) } }; assert!( calls_match, - "{name} [{mode}]: Receive calls ({:?}) differ\n got: {:?}\n want: {calls:?}", - scenario.order, run.calls + "{name} [{mode}]: Receive calls ({:?}) differ\n got: {got:?}\n want: {calls:?}", + scenario.order ); - let (details, wheel) = details_of(scenario); + let steps: Vec<(u32, bool)> = step_events(scenario) + .into_iter() + .map(|drive| (drive.detail(), drive.is_wheel_press())) + .collect(); assert_eq!( grouped( - delivered(name, run, &details, wheel) + delivered(name, run, &steps) .into_iter() .map(|(c, k, w)| (c, (k, w))) ), @@ -1540,4 +1647,17 @@ mod batch_naming { let xi1: Call = (B, CallKind::Batch(&[Named::Xi1(6)]), FOCUS); assert_eq!(expected_call(&xi1, 4), (B, vec![Named::Xi1(6)], FOCUS)); } + + /// A shorthand names the event of the step that made the call: the same + /// recorded call is the shorthand under its own step's event and an + /// explicit name under another step's. + #[test] + fn a_shorthand_call_resolves_per_step() { + let recorded: Seen = (A, vec![Named::Core(6)], CHILD); + let shorthand: Call = (A, CallKind::Core, CHILD); + assert_eq!(canonical_seen(&recorded, 6), canonical_call(&shorthand)); + assert_ne!(canonical_seen(&recorded, 4), canonical_call(&shorthand)); + let explicit: Call = (A, CallKind::Batch(&[Named::Core(6)]), CHILD); + assert_eq!(canonical_seen(&recorded, 4), canonical_call(&explicit)); + } } diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs index 056ce8743..44e62b7af 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -445,9 +445,11 @@ const K12_GRABS: &[Grab] = &[ device: DEVICEID_MASTER_KEYBOARD, state: Xi1SyncState::FrozenWithEvent, other: None, - stored: Some(Held::Key { + stored: Some(Held::HostKeyTransition { pressed: true, keycode: KEYCODE, + master: true, + synthetic: false, }), }, ]; @@ -864,6 +866,7 @@ const ROWS: &[InputRow] = &[ }, // X selects the XI1 `DeviceKeyPress` on C (the pointer window, under focus // F), Y on F. X's copy is denied: the focus walk goes on and Y gets it at F. + // Mutation: a denied XI1 selector stops the walk. InputRow { name: "k16_xi1_focused_key_denial_advances_the_focus_walk", scenario: &Scenario { @@ -895,6 +898,7 @@ const ROWS: &[InputRow] = &[ }, // A synthetic repeat release to a detectable-repeat client gets no copy but // stops the walk: nothing is written, X is not asked, Y is not reached. + // Mutation: X is asked (a call) or the walk goes past it (Y gets a frame). InputRow { name: "k17_xi1_detectable_repeat_release_stops_without_a_check", scenario: &Scenario { From 86b42cf306e04e94c636a83d04bad6b5545380e0 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 12:32:43 -0300 Subject: [PATCH 45/72] test(access): pointer table Port p1-p28 (incl. p4b, p4c, p5b, p5c, p20b, i1a, i1b) of the pointer Receive tests to one ROWS table run by the shared input runner. p14, p15 and p28 are step lists; each intermediate assertion is its own checkpoint row named `@`. Activation, activate_denied, follow_with_motion, Replay, replay_p28 and the inline second run of p15 are gone, and with them the old Row/Expect/Moved/run/check_run/check_row/literal_moved runner, the CallOrder::Multiset mode nothing uses, and the two dead_code expects. Rows dropped as duplicates (each is the allow-all run of the row named): - P4_ALLOWED: p4_slave_and_master_forms_share_one_check - P4C_ALLOWED: p4c_slave_press_and_master_forms_share_one_check - P5_ALLOWED: p5_denied_xi2_reopens_that_clients_core - P23_TWO_FORMS (empty denial): p23_scroll_stop_is_not_rerouted_two_forms_denied - P26_OWNER_ALLOWED (empty denial): p26_xi1_grab_owner_denied_falls_to_the_grab_window Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Sonnet 5.5 --- .../tests/access_input_support.rs | 416 +- .../process_request/tests/access_key_input.rs | 10 - .../tests/access_pointer_input.rs | 4008 ++++++++--------- 3 files changed, 1856 insertions(+), 2578 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index a8775d356..5a890e412 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -1,11 +1,10 @@ //! Shared scenario harness for the key and pointer Receive tests (PR 4c -//! part 2): request helpers, the run/decode machinery, the old `Row` shape -//! (the pointer file, until it is ported) and the `InputRow` runner. A test -//! module holds its scenario setups, one `ROWS` table and one `#[test]` that -//! calls `check_rows`. +//! part 2): request helpers, the run/decode machinery and the `InputRow` +//! runner. A test module holds its scenario setups, one `ROWS` table and one +//! `#[test]` that calls `check_rows`. use super::{ - access_notify_support::{DENY, NotifyFixture, dec16, dec32, enc16, enc32, split_frames}, + access_notify_support::{DENY, NotifyFixture, dec16, dec32, split_frames}, extensions::{ExtensionHook, RecordedExtensionCheck}, xi2::xi_select_body, }; @@ -95,7 +94,8 @@ pub(super) enum CallKind { /// One raw key description; its number is the row's event type. Raw, /// An ordered list of descriptions, each with its own numbering. A batch - /// is denied or traced as one call. + /// is denied or traced as one call. A one-name batch that names the event + /// of the step that made the call is never matched: use the shorthand. Batch(&'static [Named]), } @@ -125,13 +125,6 @@ fn expected_call(call: &Call, ev: u16) -> Seen { (client, names, window) } -/// The number a named description carries, for the shorthand check. -fn number(named: Named) -> u16 { - match named { - Named::Core(n) | Named::Xi2(n) | Named::Raw(n) | Named::Xi1(n) => n, - } -} - #[derive(Clone, Copy)] pub(super) enum Drive { /// `key_event_fanout_to_state`: the transition-checked entry. @@ -219,49 +212,12 @@ impl Drive { } } -pub(super) struct Expect { - pub(super) frames: &'static [Frame], - pub(super) calls: &'static [Call], -} - -/// A frame the denial moves to another window: the literal bytes the row pins. -/// Core KeyPress/KeyRelease only; the event is the key's, so only its window, -/// child and coordinates vary. -#[derive(Clone, Copy)] -pub(super) struct Moved { - pub(super) client: u32, - pub(super) window: u32, - pub(super) child: u32, - pub(super) event: (i16, i16), -} - -pub(super) struct Row { - pub(super) name: &'static str, - pub(super) setup: fn(&mut NotifyFixture), - pub(super) drive: Drive, - /// (client, check, window) Receive calls to deny. - pub(super) deny: &'static [Call], - /// The denied run's grab facts when they differ from allow-all; `None` means - /// the same as allow-all. - pub(super) denied_grab: Option<&'static [Grab]>, - /// Frames only the denied run writes, pinned in full. - pub(super) moved: &'static [Moved], - pub(super) allow: Expect, - pub(super) denied: Expect, -} - // ---- request helpers ----------------------------------------------------- /// Sends one request from `client` with the next sequence number of that -/// client, checks it was handled with no writer failure, and returns the bytes -/// the requester was sent (a reply, or nothing). -pub(super) fn send_with_reply( - f: &mut NotifyFixture, - client: u32, - opcode: u8, - data: u8, - body: &[u8], -) -> Vec { +/// client and checks it was handled with no writer failure. Nothing is drained: +/// the bytes the request makes any client write stay queued. +pub(super) fn request(f: &mut NotifyFixture, client: u32, opcode: u8, data: u8, body: &[u8]) { let sequence = { let state = &f.state.clients[&client]; let next = state.last_sequence.load(Ordering::Relaxed).wrapping_add(1); @@ -284,6 +240,17 @@ pub(super) fn send_with_reply( client_io::failed_writers(&f.state.clients).is_empty(), "request queued a disconnect" ); +} + +/// `request`, then the bytes the requester was sent (a reply, or nothing). +pub(super) fn send_with_reply( + f: &mut NotifyFixture, + client: u32, + opcode: u8, + data: u8, + body: &[u8], +) -> Vec { + request(f, client, opcode, data, body); f.drain(ClientId(client)) } @@ -806,78 +773,6 @@ pub(super) struct Run { pub(super) grab: Vec, } -pub(super) fn run(row: &Row, policy: Option<&'static [Call]>) -> Run { - let mut f = NotifyFixture::new(); - (row.setup)(&mut f); - f.state.clients.get_mut(&A).expect("client A").byte_order = ClientByteOrder::BigEndian; - for client in [SEND_CLIENT, A, B] { - f.drain(ClientId(client)); - } - let calls = policy.map(|denied| { - let ev = row.drive.ev(); - f.install_policy(move |_, call| decide(denied, &[ev], call)) - }); - drive(&mut f, row.drive); - assert!( - client_io::failed_writers(&f.state.clients).is_empty(), - "{}: delivery queued a disconnect", - row.name - ); - let clients = [SEND_CLIENT, A, B] - .into_iter() - .map(|client| { - let bytes = f.drain(ClientId(client)); - let state = &f.state.clients[&client]; - let sequence = state.last_sequence.load(Ordering::Relaxed); - ClientBytes { - client, - order: state.byte_order, - sequence, - steps: vec![(bytes.len(), sequence)], - bytes, - } - }) - .collect(); - let calls = calls - .map(|calls| { - calls - .lock() - .unwrap() - .iter() - .filter(|call| call.hook == ExtensionHook::Receive) - .filter_map(|call| { - let subject = match call.receive? { - EventSubject::Window(window) => window.0, - other => panic!("{}: key Receive subject {other:?}", row.name), - }; - let names = names_of(call.events.as_deref()?)?; - if let [single] = names.as_slice() - && !matches!(single, Named::Xi1(_) | Named::Raw(15..=17)) - && !row.drive.is_wheel_press() - { - assert_eq!( - number(*single), - row.drive.ev(), - "{}: Receive names another event", - row.name - ); - } - Some((call.client.0, names, subject)) - }) - .collect() - }) - .unwrap_or_default(); - let state = format!("{:?}", (f.state.core_focus.raw, f.state.keys_down)); - let grab = grab_facts(&f.state); - Run { - clients, - calls, - call_evs: Vec::new(), - state, - grab, - } -} - /// The grab facts of a server state, in a fixed order: keyboard grab, master /// pointer grab, slave pointer grabs by device, XI1 grabs by device, the freeze /// of every device by device id, then the withheld events in queue order. @@ -998,247 +893,6 @@ pub(super) fn delivered(name: &str, run: &Run, steps: &[(u32, bool)]) -> Vec Vec { - let mut bytes = vec![ev as u8, detail as u8]; - bytes.extend(enc16(order, sequence)); - bytes.extend(enc32(order, TIME)); - bytes.extend(enc32(order, ROOT_WINDOW.0)); - bytes.extend(enc32(order, moved.window)); - bytes.extend(enc32(order, moved.child)); - bytes.extend(enc16(order, POINTER.0 as u16)); - bytes.extend(enc16(order, POINTER.1 as u16)); - bytes.extend(enc16(order, moved.event.0 as u16)); - bytes.extend(enc16(order, moved.event.1 as u16)); - bytes.extend(enc16(order, 0)); // state - bytes.extend([1, 0]); // same-screen, pad - assert_eq!(bytes.len(), 32); - bytes -} - -/// Runs one row under the three modes and checks it: literal frames and Receive -/// calls per run, byte identity of no-policy and allow-all, identical bytes for -/// a frame both allow-all and denied write, and literal bytes for each frame -/// only the denied run writes. -pub(super) fn check_row(row: &Row) { - let name = row.name; - let plain = run(row, None); - let allow = run(row, Some(&[])); - assert_eq!( - allow.clients.iter().map(|c| &c.bytes).collect::>(), - plain.clients.iter().map(|c| &c.bytes).collect::>(), - "{name}: allow-all changed the bytes" - ); - assert_eq!(allow.state, plain.state, "{name}: allow-all changed state"); - assert_eq!( - allow.grab, plain.grab, - "{name}: allow-all changed the grab and freeze state" - ); - check_run( - row, - &plain, - &Expect { - frames: row.allow.frames, - calls: &[], - }, - "no policy", - ); - check_run(row, &allow, &row.allow, "allow-all"); - - let denied = run(row, Some(row.deny)); - check_run(row, &denied, &row.denied, "denial"); - assert_eq!(denied.state, allow.state, "{name}: denial changed state"); - let expected_grab: Vec = match row.denied_grab { - Some(facts) => facts.to_vec(), - None => allow.grab.clone(), - }; - assert_eq!( - denied.grab, expected_grab, - "{name}: denied grab and freeze state" - ); - let mut moved_seen = 0; - for got in &denied.clients { - let allowed = allow - .clients - .iter() - .find(|c| c.client == got.client) - .expect("allow-all stream for the client"); - let allowed_frames: Vec<(Kind, u32, &[u8])> = split_frames(&allowed.bytes, allowed.order) - .into_iter() - .filter_map(|frame| { - decode(frame, allowed.order).map(|(kind, window)| (kind, window, frame)) - }) - .collect(); - // A frame is paired with the allow-all frame of the same kind and window - // at the same position among those (a stop writes two such frames). - let mut seen_before: Vec<(Kind, u32)> = Vec::new(); - for frame in split_frames(&got.bytes, got.order) { - let Some((kind, window)) = decode(frame, got.order) else { - continue; - }; - let nth = seen_before - .iter() - .filter(|(k, w)| *k == kind && *w == window) - .count(); - seen_before.push((kind, window)); - if let Some((_, _, same)) = allowed_frames - .iter() - .filter(|(k, w, _)| *k == kind && *w == window) - .nth(nth) - { - assert_eq!( - frame, *same, - "{name}: client {} {kind:?} @{window:#x} bytes under denial", - got.client - ); - continue; - } - // A core frame is pinned in full; an XI2 or raw frame is matched - // by client and window only (its literal is not encoded here). - // The valuator continuation rides on its motion frame, which is the - // one the row pins. - if let Kind::Xi1Valuator(device) = kind { - assert_eq!(u16::from(frame[1]), device, "{name}: valuator device"); - continue; - } - let moved = row - .moved - .iter() - .find(|m| m.client == got.client && m.window == window) - .unwrap_or_else(|| { - panic!( - "{name}: client {} {kind:?} @{window:#x} is moved by the denial and has no literal", - got.client - ) - }); - if let Kind::Xi2(_) = kind { - // The XI2 device event: child (byte 28), event_x and event_y - // as FP16.16 at bytes 40 and 44 (the event window is byte 24). - let child = dec32(&frame[28..32], got.order); - let event_x = dec32(&frame[40..44], got.order) as i32 >> 16; - let event_y = dec32(&frame[44..48], got.order) as i32 >> 16; - assert_eq!( - (child, event_x, event_y), - ( - moved.child, - i32::from(moved.event.0), - i32::from(moved.event.1) - ), - "{name}: client {} moved XI2 frame @{window:#x}", - got.client - ); - } - if let Kind::Xi1(device) = kind { - // A DeviceButtonPress has the core ButtonPress layout, except the - // event code and the device id in the last byte. - let mut expected = literal_moved( - row.drive.ev(), - row.drive.detail(), - got.order, - got.sequence, - moved, - ); - expected[0] = - crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET; - expected[31] = device as u8; - assert_eq!( - frame, - expected.as_slice(), - "{name}: client {} moved XI1 frame @{window:#x}", - got.client - ); - } - if let Kind::Xi1Key(device) | Kind::Xi1Motion(device) = kind { - // The core key or motion layout, with the XI1 event code and - // the device id (motion also carries MORE_EVENTS) at byte 31. - let (offset, last) = match kind { - Kind::Xi1Motion(_) => ( - crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET, - device as u8 | crate::xinput::XI1_MORE_EVENTS, - ), - _ if row.drive.ev() == 3 => { - (crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET, device as u8) - } - _ => (crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET, device as u8), - }; - let mut expected = literal_moved( - row.drive.ev(), - row.drive.detail(), - got.order, - got.sequence, - moved, - ); - expected[0] = crate::server::XI_FIRST_EVENT + offset; - expected[31] = last; - if let Drive::Pointer { to, .. } = row.drive { - // The root position of the event (bytes 20..24). - expected[20..22].copy_from_slice(&enc16(got.order, to.0 as u16)); - expected[22..24].copy_from_slice(&enc16(got.order, to.1 as u16)); - } - assert_eq!( - frame, - expected.as_slice(), - "{name}: client {} moved XI1 frame @{window:#x}", - got.client - ); - } - if kind == Kind::Core { - assert_eq!( - frame, - literal_moved( - row.drive.ev(), - row.drive.detail(), - got.order, - got.sequence, - moved - ) - .as_slice(), - "{name}: client {} moved frame @{window:#x}", - got.client - ); - } - moved_seen += 1; - } - } - assert_eq!(moved_seen, row.moved.len(), "{name}: moved frames written"); -} - // ---- the InputRow runner ------------------------------------------------- /// One step of a scenario: an input event the server fans out, or a request @@ -1246,19 +900,16 @@ pub(super) fn check_row(row: &Row) { #[derive(Clone, Copy)] pub(super) enum Step { Event(Drive), - #[expect(dead_code, reason = "first used by the pointer table's step lists")] Request(fn(&mut NotifyFixture)), } -/// How a scenario's Receive trace is compared: in total order, in order per +/// How a scenario's Receive trace is compared: in total order, or in order per /// client (`state.clients` is a HashMap, so the order across clients is not a -/// contract), or as a multiset. +/// contract). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum CallOrder { Total, PerClient, - #[expect(dead_code, reason = "first used by the pointer table")] - Multiset, } /// A frame the denial moves: the denied run writes it where the allow-all run @@ -1273,6 +924,22 @@ pub(super) struct Move { pub(super) event: (i16, i16), } +pub(super) const fn moved( + client: u32, + kind: Kind, + window: u32, + child: u32, + event: (i16, i16), +) -> Move { + Move { + client, + kind, + window, + child, + event, + } +} + /// What one run of a scenario produces. In a denied outcome `grab: None` means /// the scenario's stated allow grab, or, if it states none, the facts of the /// actual allow-all run. @@ -1523,13 +1190,6 @@ fn check_outcome(name: &str, mode: &str, scenario: &Scenario, run: &Run, want: & grouped(got.iter().map(|(c, n, w)| (*c, (n.clone(), *w)))) == grouped(calls.iter().map(|(c, n, w)| (*c, (n.clone(), *w)))) } - CallOrder::Multiset => { - let sorted = |mut calls: Vec| { - calls.sort(); - calls - }; - sorted(got.clone()) == sorted(calls.clone()) - } }; assert!( calls_match, diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs index 44e62b7af..dd5e1e5dd 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -290,16 +290,6 @@ const A_GRABS_ROOT: &[Grab] = &[Grab::Keyboard { window: ROOT, }]; -const fn moved(client: u32, kind: Kind, window: u32, child: u32, event: (i16, i16)) -> Move { - Move { - client, - kind, - window, - child, - event, - } -} - /// A press delivered by an allow-all policy to A at CHILD by a core selection. const A_AT_CHILD: Outcome = Outcome { frames: &[(A, Kind::Core, CHILD)], diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index e143f6ccb..eb5474f87 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -2,64 +2,90 @@ //! //! The tree is root > P (FOCUS) > C (CHILD), with the pointer over C. Rows use //! the master pointer origin `XTest(2)` and ButtonPress unless they state -//! otherwise. Each row runs the no-policy, allow-all and denied modes through -//! `check_row`, so the literal frames and Receive calls per client are pinned. -//! The mutation each test must kill is named in its comment. +//! otherwise. Each row names a scenario (setup, steps, allow-all outcome) and a +//! denial; `check_rows` runs it with no policy, allow-all and the denial and +//! compares frames, Receive trace, moved frames and grab and freeze facts with +//! the stated outcomes. A multi-step scenario (p14, p15, p28) has one row per +//! intermediate assertion, named `@`, whose steps are the prefix. +//! The mutation each row must kill is named in its comment. use super::{ - access_input_support::*, - access_notify_support::{DENY, NotifyFixture, split_frames}, - access_xi_notify::xi1_class, - extensions::ExtensionHook, + access_input_support::*, access_notify_support::NotifyFixture, access_xi_notify::xi1_class, }; use crate::{ - access::{Decision, EventSubject}, - core_loop::{DeviceInfo, InputOrigin, pointer_fanout::pointer_event_fanout_to_state}, - host_x11::{HostPointerEvent, HostXidMap, PointerEventKind}, - server::{QueuedInputEvent, ServerState, Xi1SyncState}, + core_loop::{DeviceInfo, InputOrigin}, + host_x11::PointerEventKind, + server::Xi1SyncState, xinput::{DEVICEID_MASTER_POINTER, DEVICEID_XTEST_POINTER, InputCapabilities, InputSourceId}, }; use yserver_protocol::x11::{ClientId, ResourceId}; -/// Core ButtonPressMask and MotionNotify mask bits. +/// Core ButtonPressMask, ButtonReleaseMask and MotionNotify mask bits. const CORE_BUTTON_PRESS: u32 = 1 << 2; -const CORE_MOTION: u32 = 1 << 6; const CORE_BUTTON_RELEASE: u32 = 1 << 3; -/// XI2 mask bits, one per event type: ButtonPress (4) and Motion (6). +const CORE_MOTION: u32 = 1 << 6; +/// XI2 mask bits, one per event type: ButtonPress (4), Motion (6), raw +/// ButtonPress (15). const XI_BUTTON_PRESS: u32 = 1 << 4; const XI_MOTION: u32 = 1 << 6; +const XI_RAW_BUTTON_PRESS: u32 = 1 << 15; /// XIAllDevices, the device id that selects every device. const XI_ALL_DEVICES: u16 = 0; -/// The source id of the physical pointer in the Physical-origin row. +/// The source id of the physical pointer, and the device id the registry gives it. const PHYSICAL_SOURCE: u64 = 0xA75_400; +const PHYSICAL_DEVICE: u16 = 6; const XTEST_MASTER: InputOrigin = InputOrigin::XTest(DEVICEID_MASTER_POINTER); const XTEST_SLAVE: InputOrigin = InputOrigin::XTest(DEVICEID_XTEST_POINTER); +const PHYSICAL: InputOrigin = InputOrigin::Physical(InputSourceId(PHYSICAL_SOURCE)); -const fn press(origin: InputOrigin) -> Drive { - Drive::Pointer { +const fn button(origin: InputOrigin, kind: PointerEventKind, to: (i16, i16)) -> Step { + Step::Event(Drive::Pointer { origin, - kind: PointerEventKind::ButtonPress, + kind, button: 1, - to: POINTER, + to, delta: (0, 0), - } + }) +} + +const fn press(origin: InputOrigin) -> Step { + button(origin, PointerEventKind::ButtonPress, POINTER) +} + +const fn release(origin: InputOrigin) -> Step { + button(origin, PointerEventKind::ButtonRelease, POINTER) } /// The root position of the motion rows: still over C. const MOTION_TO: (i16, i16) = (125, 125); /// A move from the pointer's place to `MOTION_TO`. -const fn motion(origin: InputOrigin) -> Drive { - Drive::Pointer { +const fn motion(origin: InputOrigin) -> Step { + Step::Event(Drive::Pointer { origin, kind: PointerEventKind::MotionNotify, button: 0, to: MOTION_TO, delta: (5, 5), - } + }) } +/// A physical wheel press (button 4) at C. +const WHEEL_PRESS: Step = Step::Event(Drive::Pointer { + origin: PHYSICAL, + kind: PointerEventKind::ButtonPress, + button: 4, + to: POINTER, + delta: (0, 0), +}); + +/// The two-Motion smooth-scroll stop of the physical pointer. +const SCROLL_STOP: Step = Step::Event(Drive::ScrollStop { + origin: PHYSICAL, + at: POINTER, +}); + /// The root origins of P (FOCUS) and C (CHILD) in the tree. const P_ORIGIN: (i16, i16) = (100, 100); const C_ORIGIN: (i16, i16) = (110, 110); @@ -71,8 +97,10 @@ const C_EVENT: (i16, i16) = (POINTER.0 - C_ORIGIN.0, POINTER.1 - C_ORIGIN.1); /// The event P gives a copy of the pointer at the motion target (`MOTION_TO`). const MOTION_EVENT_AT_P: (i16, i16) = (MOTION_TO.0 - P_ORIGIN.0, MOTION_TO.1 - P_ORIGIN.1); +// ---- setup helpers ------------------------------------------------------- + /// Registers a physical pointer source with the XI registry. -fn register_physical_pointer(state: &mut ServerState) { +fn register_physical_pointer(f: &mut NotifyFixture) { let info = DeviceInfo { source_id: InputSourceId(PHYSICAL_SOURCE), enabled: true, @@ -90,180 +118,173 @@ fn register_physical_pointer(state: &mut ServerState) { is_touchpad: false, config: crate::core_loop::message::LibinputConfigSnapshot::default(), }; - let _ = state.xi_register_source(&info); + let _ = f.state.xi_register_source(&info); } -/// Moves the sprite onto the pointer's place before the row's event, so the -/// slave pass starts from C as it does in a session (Xorg delivers slave motion -/// to the window the sprite left). Nothing is selected yet, so nothing is sent. -fn park_pointer(f: &mut NotifyFixture) { - park_pointer_at(f, POINTER); -} - -/// As `park_pointer`, at the root position `at`. +/// Moves the sprite to the root position `at` before the row's event, so the +/// slave pass starts from the window under it as it does in a session (Xorg +/// delivers slave motion to the window the sprite left). Nothing is selected +/// yet, so nothing is sent. fn park_pointer_at(f: &mut NotifyFixture, at: (i16, i16)) { - let dropped = pointer_event_fanout_to_state( - &mut f.state, - &mut f.backend, - &HostXidMap::new(), - HostPointerEvent { + drive( + f, + Drive::Pointer { origin: XTEST_MASTER, kind: PointerEventKind::MotionNotify, - host_xid: 0, - detail: 0, - time: TIME, - root_x: at.0, - root_y: at.1, - event_x: at.0, - event_y: at.1, - state: 0, - crossing_mode: 0, - child: 0, - raw_dx: 0, - raw_dy: 0, - device_axes: None, - tree_change: false, - }, - true, - false, + button: 0, + to: at, + delta: (0, 0), + }, ); - assert!( - dropped.is_empty(), - "parking the pointer queued a disconnect" +} + +fn park_pointer(f: &mut NotifyFixture) { + park_pointer_at(f, POINTER); +} + +const CORE_GRAB_POINTER: u8 = 26; +const CORE_GRAB_BUTTON: u8 = 28; +const XI_PASSIVE_GRAB_DEVICE: u8 = 54; +const XI_ALLOW_EVENTS: u8 = 53; +const XI_ALLOW_DEVICE_EVENTS_XI1: u8 = 19; +const XI_GRAB_DEVICE_XI1: u8 = 13; + +/// `GrabPointer` by `owner` on `window`, asynchronous, with the core event mask. +fn grab_pointer(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: bool, mask: u32) { + let mut body = Vec::with_capacity(20); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&(mask as u16).to_le_bytes()); + body.extend_from_slice(&[1, 1]); // async pointer, async keyboard + body.extend_from_slice(&[0; 12]); // no confinement, no cursor, CurrentTime + let bytes = send_with_reply(f, owner, CORE_GRAB_POINTER, u8::from(owner_events), &body); + let reply = &bytes[bytes.len() - 32..]; + assert_eq!((reply[0], reply[1]), (1, 0), "GrabPointer replies Success"); +} + +/// `GrabButton` of button 1 by `owner` on `window` for ButtonPress|Release, +/// with any modifier and the given pointer mode (0 = sync). +fn grab_button(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: bool, sync: bool) { + let mut body = Vec::with_capacity(20); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&0x000c_u16.to_le_bytes()); + body.extend_from_slice(&[u8::from(!sync), 1]); // pointer mode (0 sync), async keyboard + body.extend_from_slice(&[0; 8]); // no confinement, no cursor + body.extend_from_slice(&[1, 0]); // button 1, pad + body.extend_from_slice(&0x8000_u16.to_le_bytes()); // AnyModifier + send(f, owner, CORE_GRAB_BUTTON, u8::from(owner_events), &body); +} + +/// `XIGrabDevice` of the master pointer by `owner` on `window`. +fn xi_grab_master_pointer( + f: &mut NotifyFixture, + owner: u32, + window: u32, + owner_events: bool, + mask: u32, +) { + grab_keyboard_device( + f, + owner, + DEVICEID_MASTER_POINTER, + window, + owner_events, + mask, ); } -// ---- P1 ------------------------------------------------------------------ +/// `XIPassiveGrabDevice` of button 1 on the master pointer by A on `ROOT`, any +/// modifier, with the XI2 event mask, synchronous. +fn xi_passive_grab_master(f: &mut NotifyFixture, owner_events: bool, mask: u32) { + let mut body = Vec::with_capacity(36); + body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime + body.extend_from_slice(&ROOT.to_le_bytes()); + body.extend_from_slice(&0_u32.to_le_bytes()); // no cursor + body.extend_from_slice(&1_u32.to_le_bytes()); // button 1 + body.extend_from_slice(&DEVICEID_MASTER_POINTER.to_le_bytes()); + body.extend_from_slice(&1_u16.to_le_bytes()); // one modifier + body.extend_from_slice(&1_u16.to_le_bytes()); // one mask word + body.extend_from_slice(&[0, 0, 1, u8::from(owner_events)]); // Button, sync, async paired, owner_events + body.extend_from_slice(&0_u16.to_le_bytes()); // pad + body.extend_from_slice(&mask.to_le_bytes()); + body.extend_from_slice(&0x8000_0000_u32.to_le_bytes()); // XIAnyModifier + send_with_reply(f, A, XI_MAJOR, XI_PASSIVE_GRAB_DEVICE, &body); +} -fn setup_p1(f: &mut NotifyFixture) { - tree(f); - select_core(f, B, CHILD, CORE_BUTTON_PRESS); - select_core(f, A, FOCUS, CORE_BUTTON_PRESS); +/// The XI1 `GrabDevice` of the slave pointer by `owner` on `window`. +fn xi1_grab_device(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: bool) { + let mut body = Vec::with_capacity(16); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime + body.extend_from_slice(&0_u16.to_le_bytes()); // no event classes + body.extend_from_slice(&[1, 1, u8::from(owner_events)]); // async modes + body.push(DEVICEID_XTEST_POINTER as u8); + body.extend_from_slice(&[0, 0]); + let bytes = send_with_reply(f, owner, XI_MAJOR, XI_GRAB_DEVICE_XI1, &body); + let reply = &bytes[bytes.len() - 32..]; + assert_eq!((reply[0], reply[8]), (1, 0), "GrabDevice replies Success"); } -const P1: Row = Row { - name: "p1_denied_core_selector_does_not_stop_the_core_walk", - setup: setup_p1, - drive: press(XTEST_MASTER), - deny: &[(B, CallKind::Core, CHILD)], - denied_grab: Some(&[Grab::Pointer(PointerGrab { - owner: A, - window: FOCUS, - implicit: true, - passive: false, - via_xi2: false, - })]), - moved: &[Moved { - client: A, - window: FOCUS, - child: CHILD, - event: P_EVENT, - }], - allow: Expect { - frames: &[(B, Kind::Core, CHILD)], - calls: &[(B, CallKind::Core, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Core, FOCUS)], - calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - }, -}; +/// A `GrabDeviceButton` of the slave by `owner` on `window`, any button and +/// modifier, installed directly. +fn xi1_passive_grab(f: &mut NotifyFixture, owner: u32, window: u32, sync: bool) { + f.state + .xi1_passive_grabs + .push(crate::server::Xi1PassiveGrab { + owner: ClientId(owner), + deviceid: DEVICEID_XTEST_POINTER, + grab_window: ResourceId(window), + detail: 0, + modifiers: 0x8000, + owner_events: false, + this_mode: u8::from(!sync), + other_mode: 1, + is_key: false, + }); +} -/// Mutation: the core walk stops at any window with a core selector, without -/// asking Receive (selection-only stop). A then never sees the press. -#[test] -fn p1_denied_core_selector_does_not_stop_the_core_walk() { - check_row(&P1); +/// The requests of the p14 and p28 step lists: `XIAllowEvents(AsyncDevice)` of +/// the master pointer by A, and the XI1 `AllowDeviceEvents(ReplayThisDevice)` +/// of the slave by the requester. A thaw may write events to its requester, so +/// the first does not drain. +fn thaw_master(f: &mut NotifyFixture) { + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime + body.extend_from_slice(&DEVICEID_MASTER_POINTER.to_le_bytes()); + body.extend_from_slice(&[0, 0]); // XIAsyncDevice + request(f, A, XI_MAJOR, XI_ALLOW_EVENTS, &body); +} + +fn replay_slave(f: &mut NotifyFixture) { + let mut body = Vec::new(); + body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime + body.extend_from_slice(&[2, DEVICEID_XTEST_POINTER as u8, 0, 0]); // ReplayThisDevice + send(f, SEND_CLIENT, XI_MAJOR, XI_ALLOW_DEVICE_EVENTS_XI1, &body); } -// ---- P2 ------------------------------------------------------------------ +// ---- setups -------------------------------------------------------------- +// +// A is the grab owner and B the foreign selector in the grab rows; the grab +// window G is the root unless a row says otherwise: it is on no selection. -fn setup_p2(f: &mut NotifyFixture) { +/// A selects core on FOCUS, B on CHILD. +fn setup_p1(f: &mut NotifyFixture) { tree(f); - select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + select_core(f, B, CHILD, CORE_BUTTON_PRESS); select_core(f, A, FOCUS, CORE_BUTTON_PRESS); } -const P2: Row = Row { - name: "p2_denied_xi2_selector_does_not_absorb_core", - setup: setup_p2, - drive: press(XTEST_MASTER), - deny: &[(B, CallKind::Xi2, CHILD)], - denied_grab: Some(&[Grab::Pointer(PointerGrab { - owner: A, - window: FOCUS, - implicit: true, - passive: false, - via_xi2: false, - })]), - moved: &[Moved { - client: A, - window: FOCUS, - child: CHILD, - event: P_EVENT, - }], - allow: Expect { - frames: &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(B, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Core, FOCUS)], - calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Core, FOCUS)], - }, -}; - -/// Mutation: an XI2 selection absorbs the walk whether or not its copy is -/// allowed (selection-only absorption), or the denied XI2 copy is checked twice. -#[test] -fn p2_denied_xi2_selector_does_not_absorb_core() { - check_row(&P2); +fn setup_p2(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + select_core(f, A, FOCUS, CORE_BUTTON_PRESS); } -// ---- P3 ------------------------------------------------------------------ - fn setup_p3(f: &mut NotifyFixture) { tree(f); select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); select_xi2(f, A, FOCUS, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); } -const P3: Row = Row { - name: "p3_xi2_walk_skips_a_denied_window", - setup: setup_p3, - drive: press(XTEST_MASTER), - deny: &[(B, CallKind::Xi2, CHILD)], - denied_grab: Some(&[Grab::Pointer(PointerGrab { - owner: A, - window: FOCUS, - implicit: true, - passive: false, - via_xi2: true, - })]), - moved: &[Moved { - client: A, - window: FOCUS, - child: CHILD, - event: P_EVENT, - }], - allow: Expect { - frames: &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(B, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], - calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], - }, -}; - -/// Mutation: the XI2 route window is the first window with a selection rather -/// than the first with an allowed one, so the denied copy at C ends the walk. -#[test] -fn p3_xi2_walk_skips_a_denied_window() { - check_row(&P3); -} - -// ---- P4 ------------------------------------------------------------------ - fn setup_p4(f: &mut NotifyFixture) { tree(f); park_pointer(f); @@ -271,67 +292,6 @@ fn setup_p4(f: &mut NotifyFixture) { select_xi2(f, A, FOCUS, DEVICEID_MASTER_POINTER, XI_MOTION); } -/// Allow-all: B's slave and master forms at C come from one check. -const P4_ALLOWED: Row = Row { - name: "p4_slave_and_master_forms_share_one_check", - setup: setup_p4, - drive: motion(XTEST_SLAVE), - deny: &[], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[ - (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), - (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - ], - calls: &[(B, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[ - (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), - (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - ], - calls: &[(B, CallKind::Xi2, CHILD)], - }, -}; - -/// Denied: B's one check covers both forms, so B gets neither and A's master -/// form at P is the only copy. -const P4_DENIED: Row = Row { - name: "p4_slave_and_master_forms_share_one_check", - setup: setup_p4, - drive: motion(XTEST_SLAVE), - deny: &[(B, CallKind::Xi2, CHILD)], - denied_grab: None, - moved: &[Moved { - client: A, - window: FOCUS, - child: CHILD, - event: MOTION_EVENT_AT_P, - }], - allow: Expect { - frames: &[ - (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), - (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - ], - calls: &[(B, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], - calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], - }, -}; - -/// Mutation: the slave and master forms each ask Receive (two calls for B), -/// or the master form is checked at the slave pass's window. -#[test] -fn p4_slave_and_master_forms_share_one_check() { - check_row(&P4_ALLOWED); - check_row(&P4_DENIED); -} - -// ---- P4b ----------------------------------------------------------------- - /// The pointer sits on P outside C, so the slave pass starts from P while the /// live target is C. const OUTSIDE_C: (i16, i16) = (105, 105); @@ -342,161 +302,17 @@ fn setup_p4b(f: &mut NotifyFixture) { select_xi2(f, B, CHILD, DEVICEID_XTEST_POINTER, XI_MOTION); } -/// A slave motion moves the sprite from P into C. B selects the slave form on C -/// only, so the slave form (routed from P) has no recipient and B gets nothing, -/// in every mode. The route from the live target C writes no slave copy, so it -/// asks nothing. -const P4B: Row = Row { - name: "p4b_no_check_for_the_slave_route_from_the_live_target", - setup: setup_p4b, - drive: motion(XTEST_SLAVE), - deny: &[(B, CallKind::Xi2, CHILD)], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[], - calls: &[], - }, - denied: Expect { - frames: &[], - calls: &[], - }, -}; - -/// Mutation: the slave form's route from the live target (not the earlier -/// window) goes through the memo (`slave_form_checked` there), so B's selection -/// on C is asked although no copy of it is ever written. -#[test] -fn p4b_no_check_for_the_slave_route_from_the_live_target() { - check_row(&P4B); -} - -// ---- P4c ----------------------------------------------------------------- - fn setup_p4c(f: &mut NotifyFixture) { tree(f); select_xi2(f, B, CHILD, XI_ALL_DEVICES, XI_BUTTON_PRESS); } -/// Allow-all: B's slave press copy (routed by the slave press route) and its -/// master copy at C share the one check the master route made. -const P4C_ALLOWED: Row = Row { - name: "p4c_slave_press_and_master_forms_share_one_check", - setup: setup_p4c, - drive: press(XTEST_SLAVE), - deny: &[], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[ - (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), - (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - ], - calls: &[(B, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[ - (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), - (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - ], - calls: &[(B, CallKind::Xi2, CHILD)], - }, -}; - -/// Denied: neither form is written, and the one call is not repeated. -const P4C_DENIED: Row = Row { - name: "p4c_slave_press_and_master_forms_share_one_check", - setup: setup_p4c, - drive: press(XTEST_SLAVE), - deny: &[(B, CallKind::Xi2, CHILD)], - denied_grab: Some(&[]), - moved: &[], - allow: Expect { - frames: &[ - (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), - (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - ], - calls: &[(B, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[], - calls: &[(B, CallKind::Xi2, CHILD)], - }, -}; - -/// Mutation: the slave press copy (not a grab attempt) takes a fresh -/// `receive_allows` instead of the dispatch memo, so B is asked twice. -#[test] -fn p4c_slave_press_and_master_forms_share_one_check() { - check_row(&P4C_ALLOWED); - check_row(&P4C_DENIED); -} - -// ---- P5 ------------------------------------------------------------------ - fn setup_p5(f: &mut NotifyFixture) { tree(f); select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); select_core(f, A, CHILD, CORE_BUTTON_PRESS); } -/// Allow-all: A's master XI2 copy shadows its core copy at C. -const P5_ALLOWED: Row = Row { - name: "p5_denied_xi2_reopens_that_clients_core", - setup: setup_p5, - drive: press(XTEST_MASTER), - deny: &[], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - }, -}; - -/// Denied: A's XI2 copy is refused, so its core copy at C is delivered. -const P5_DENIED: Row = Row { - name: "p5_denied_xi2_reopens_that_clients_core", - setup: setup_p5, - drive: press(XTEST_MASTER), - deny: &[(A, CallKind::Xi2, CHILD)], - denied_grab: Some(&[Grab::Pointer(PointerGrab { - owner: A, - window: CHILD, - implicit: true, - passive: false, - via_xi2: false, - })]), - moved: &[Moved { - client: A, - window: CHILD, - child: 0, - event: C_EVENT, - }], - allow: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], - }, -}; - -/// Mutation: A's core copy is shadowed by its XI2 selection, not by the copy -/// that is allowed, so the denied XI2 still hides the core copy at C. -#[test] -fn p5_denied_xi2_reopens_that_clients_core() { - check_row(&P5_ALLOWED); - check_row(&P5_DENIED); -} - -// ---- P5b ----------------------------------------------------------------- - fn setup_p5b(f: &mut NotifyFixture) { tree(f); select_core(f, A, CHILD, CORE_BUTTON_PRESS); @@ -504,66 +320,6 @@ fn setup_p5b(f: &mut NotifyFixture) { select_core(f, B, FOCUS, CORE_BUTTON_PRESS); } -/// Denying A's core copy at C changes nothing: a shadowed core copy is not -/// checked, and the walk stops at C as it does with allow-all. -const P5B_CORE_DENIED: Row = Row { - name: "p5b_shadow_follows_the_master_copy_anywhere", - setup: setup_p5b, - drive: press(XTEST_MASTER), - deny: &[(A, CallKind::Core, CHILD)], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], - calls: &[(A, CallKind::Xi2, FOCUS)], - }, - denied: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], - calls: &[(A, CallKind::Xi2, FOCUS)], - }, -}; - -/// Denying A's master XI2 copy at P reopens A's core copy at C, and the walk -/// stops there, so B at P gets nothing. -const P5B_XI2_DENIED: Row = Row { - name: "p5b_shadow_follows_the_master_copy_anywhere", - setup: setup_p5b, - drive: press(XTEST_MASTER), - deny: &[(A, CallKind::Xi2, FOCUS)], - denied_grab: Some(&[Grab::Pointer(PointerGrab { - owner: A, - window: CHILD, - implicit: true, - passive: false, - via_xi2: false, - })]), - moved: &[Moved { - client: A, - window: CHILD, - child: 0, - event: C_EVENT, - }], - allow: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], - calls: &[(A, CallKind::Xi2, FOCUS)], - }, - denied: Expect { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Xi2, FOCUS), (A, CallKind::Core, CHILD)], - }, -}; - -/// Mutation: a shadow that only applies at the same window (the core copy at C -/// is checked and then deduplicated), or a shadowed core copy that is still -/// checked before the walk stops. -#[test] -fn p5b_shadow_follows_the_master_copy_anywhere() { - check_row(&P5B_CORE_DENIED); - check_row(&P5B_XI2_DENIED); -} - -// ---- P5c ----------------------------------------------------------------- - fn setup_p5c(f: &mut NotifyFixture) { tree(f); park_pointer(f); @@ -573,91 +329,12 @@ fn setup_p5c(f: &mut NotifyFixture) { select_xi2(f, A, FOCUS, DEVICEID_XTEST_POINTER, XI_MOTION); } -/// Denied: the master route is P (A's master copy), so A's core copy at C is -/// shadowed and A gets its slave and master forms at P, with no core copy. -const P5C_DENIED: Row = Row { - name: "p5c_shadow_uses_the_allowed_master_route", - setup: setup_p5c, - drive: motion(XTEST_SLAVE), - deny: &[(B, CallKind::Xi2, CHILD)], - denied_grab: None, - moved: &[Moved { - client: A, - window: FOCUS, - child: CHILD, - event: MOTION_EVENT_AT_P, - }], - allow: Expect { - frames: &[ - (A, Kind::Xi2(DEVICEID_XTEST_POINTER), FOCUS), - (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - ], - calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], - }, - denied: Expect { - frames: &[ - (A, Kind::Xi2(DEVICEID_XTEST_POINTER), FOCUS), - (A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS), - ], - calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], - }, -}; - -/// Mutation: the shadow uses the selection-only master route, which ends at C -/// (B's selection); A then keeps its core copy at C and gets no XI2 at P. -#[test] -fn p5c_shadow_uses_the_allowed_master_route() { - check_row(&P5C_DENIED); -} - -// ---- P6 ------------------------------------------------------------------ - fn setup_p6(f: &mut NotifyFixture) { tree(f); select_xi2(f, A, CHILD, DEVICEID_XTEST_POINTER, XI_BUTTON_PRESS); select_core(f, A, CHILD, CORE_BUTTON_PRESS); } -/// A slave press: A's core copy is deferred behind the slave pass. Denying it -/// drops that copy at admission, after the slave XI2 copy was written. -const P6_DENIED: Row = Row { - name: "p6_deferred_core_copy_is_checked_at_admission", - setup: setup_p6, - drive: press(XTEST_SLAVE), - deny: &[(A, CallKind::Core, CHILD)], - denied_grab: Some(&[Grab::SlavePointer { - device: DEVICEID_XTEST_POINTER, - grab: PointerGrab { - owner: A, - window: CHILD, - implicit: true, - passive: false, - via_xi2: true, - }, - }]), - moved: &[], - allow: Expect { - frames: &[ - (A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), - (A, Kind::Core, CHILD), - ], - calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Xi2, CHILD)], - }, -}; - -/// Mutation: the deferred core copy is checked again at the flush (two calls), -/// or never checked (the copy is written with no call). -#[test] -fn p6_deferred_core_copy_is_checked_at_admission() { - check_row(&P6_DENIED); -} - -// ---- P7 ------------------------------------------------------------------ - /// A physical pointer holds button 1; the XTest slave then presses button 1, /// so the master form is not written and B's master XI2 copy is never checked. /// The physical press runs first, before B selects, so no grab exists when the @@ -665,11 +342,11 @@ fn p6_deferred_core_copy_is_checked_at_admission() { /// that keeps the natural call from happening. fn setup_p7(f: &mut NotifyFixture) { tree(f); - register_physical_pointer(&mut f.state); + register_physical_pointer(f); drive( f, Drive::Pointer { - origin: InputOrigin::Physical(InputSourceId(PHYSICAL_SOURCE)), + origin: PHYSICAL, kind: PointerEventKind::ButtonPress, button: 1, to: POINTER, @@ -679,195 +356,26 @@ fn setup_p7(f: &mut NotifyFixture) { select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); } -const P7: Row = Row { - name: "p7_no_check_for_a_form_not_emitted", - setup: setup_p7, - drive: press(XTEST_SLAVE), - deny: &[(B, CallKind::Xi2, CHILD)], - denied_grab: Some(&[]), - moved: &[], - allow: Expect { - frames: &[], - calls: &[], - }, - denied: Expect { - frames: &[], - calls: &[], - }, -}; - -/// Guard: a master form that is not written asks nothing, so denying B's copy -/// changes nothing. Passes today. -#[test] -fn p7_no_check_for_a_form_not_emitted() { - check_row(&P7); +fn setup_p8(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, CHILD, CORE_BUTTON_PRESS); + select_core(f, A, FOCUS, CORE_BUTTON_PRESS); + grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); } -// ---- grabs and passive activation --------------------------------- -// -// O is client A, the foreign selector F is client B. Core grabs go through -// `GrabPointer`/`GrabButton`, XI2 grabs through `XIGrabDevice`/ -// `XIPassiveGrabDevice`. The grab window G is the root unless a row says -// otherwise: it is on no selection of the rows below. +/// A selects the master XI2 press on C, B the core press on C (a core +/// ButtonPress selection is exclusive per window, so the two cannot both be core). +fn setup_p9(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + // A also selects on P: a walk the denial did not reject would end there. + select_xi2(f, A, FOCUS, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + select_core(f, B, CHILD, CORE_BUTTON_PRESS); + grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); +} -const CORE_GRAB_POINTER: u8 = 26; -const CORE_GRAB_BUTTON: u8 = 28; -const XI_PASSIVE_GRAB_DEVICE: u8 = 54; -const XI_ALLOW_EVENTS: u8 = 53; - -/// `GrabPointer` by `owner` on `window`, asynchronous, with the core event mask. -fn grab_pointer(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: bool, mask: u32) { - let mut body = Vec::with_capacity(20); - body.extend_from_slice(&window.to_le_bytes()); - body.extend_from_slice(&(mask as u16).to_le_bytes()); - body.extend_from_slice(&[1, 1]); // async pointer, async keyboard - body.extend_from_slice(&[0; 12]); // no confinement, no cursor, CurrentTime - let bytes = send_with_reply(f, owner, CORE_GRAB_POINTER, u8::from(owner_events), &body); - let reply = &bytes[bytes.len() - 32..]; - assert_eq!((reply[0], reply[1]), (1, 0), "GrabPointer replies Success"); -} - -/// `GrabButton` of button 1 by `owner` on `window` for ButtonPress|Release, -/// with any modifier and the given pointer mode (0 = sync). -fn grab_button(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: bool, sync: bool) { - let mut body = Vec::with_capacity(20); - body.extend_from_slice(&window.to_le_bytes()); - body.extend_from_slice(&0x000c_u16.to_le_bytes()); - body.extend_from_slice(&[u8::from(!sync), 1]); // pointer mode (0 sync), async keyboard - body.extend_from_slice(&[0; 8]); // no confinement, no cursor - body.extend_from_slice(&[1, 0]); // button 1, pad - body.extend_from_slice(&0x8000_u16.to_le_bytes()); // AnyModifier - send(f, owner, CORE_GRAB_BUTTON, u8::from(owner_events), &body); -} - -/// `XIGrabDevice` of the master pointer by `owner` on `window`. -fn xi_grab_master_pointer( - f: &mut NotifyFixture, - owner: u32, - window: u32, - owner_events: bool, - mask: u32, -) { - grab_keyboard_device( - f, - owner, - DEVICEID_MASTER_POINTER, - window, - owner_events, - mask, - ); -} - -/// `XIPassiveGrabDevice` of button 1 on `device` by `owner` on `window`, any -/// modifier, with the XI2 event mask and the given mode (0 = sync). -fn xi_passive_grab_button( - f: &mut NotifyFixture, - owner: u32, - device: u16, - window: u32, - sync: bool, - owner_events: bool, - mask: u32, -) { - let mut body = Vec::with_capacity(36); - body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime - body.extend_from_slice(&window.to_le_bytes()); - body.extend_from_slice(&0_u32.to_le_bytes()); // no cursor - body.extend_from_slice(&1_u32.to_le_bytes()); // button 1 - body.extend_from_slice(&device.to_le_bytes()); - body.extend_from_slice(&1_u16.to_le_bytes()); // one modifier - body.extend_from_slice(&1_u16.to_le_bytes()); // one mask word - body.extend_from_slice(&[0, u8::from(!sync), 1, u8::from(owner_events)]); // Button, mode, async paired, owner_events - body.extend_from_slice(&0_u16.to_le_bytes()); // pad - body.extend_from_slice(&mask.to_le_bytes()); - body.extend_from_slice(&0x8000_0000_u32.to_le_bytes()); // XIAnyModifier - send_with_reply(f, owner, XI_MAJOR, XI_PASSIVE_GRAB_DEVICE, &body); -} - -/// The literal frame the grab-window fallback writes to A: event window the -/// root, child its child toward the pointer (P), coordinates the root's. -const AT_ROOT: Moved = Moved { - client: A, - window: ROOT, - child: FOCUS, - event: POINTER, -}; - -// ---- P8 ------------------------------------------------------------------ - -fn setup_p8(f: &mut NotifyFixture) { - tree(f); - select_core(f, A, CHILD, CORE_BUTTON_PRESS); - select_core(f, A, FOCUS, CORE_BUTTON_PRESS); - grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); -} - -const P8: Row = Row { - name: "p8_denied_owner_copy_continues_the_natural_walk", - setup: setup_p8, - drive: press(XTEST_MASTER), - deny: &[(A, CallKind::Core, CHILD)], - denied_grab: None, - moved: &[Moved { - client: A, - window: FOCUS, - child: CHILD, - event: P_EVENT, - }], - allow: Expect { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Core, FOCUS)], - calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - }, -}; - -/// Mutation: the owner qualifies by selection (the route returns C although the -/// copy there is denied, so nothing is written), or the natural core write asks -/// again (a second call for A at C when allowed). -#[test] -fn p8_denied_owner_copy_continues_the_natural_walk() { - check_row(&P8); -} - -// ---- P9 ------------------------------------------------------------------ - -/// O selects the master XI2 press on C, F selects the core press on C (a core -/// ButtonPress selection is exclusive per window, so the two cannot both be core). -fn setup_p9(f: &mut NotifyFixture) { - tree(f); - select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); - // A also selects on P: a walk the denial did not reject would end there. - select_xi2(f, A, FOCUS, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); - select_core(f, B, CHILD, CORE_BUTTON_PRESS); - grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); -} - -const P9: Row = Row { - name: "p9_denied_owner_with_allowed_foreign_falls_back", - setup: setup_p9, - drive: press(XTEST_MASTER), - deny: &[(A, CallKind::Xi2, CHILD)], - denied_grab: None, - moved: &[AT_ROOT], - allow: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Core, ROOT)], - calls: &[ - (A, CallKind::Xi2, CHILD), - (B, CallKind::Core, CHILD), - (A, CallKind::Core, ROOT), - ], - }, -}; - -/// The core grab window is C itself: O core on C (denied), F master XI2 on C -/// (allowed). The core fallback is a distinct attempt, so O is asked at C again. +/// The core grab window is C itself: A core on C (denied), B master XI2 on C +/// (allowed). The core fallback is a distinct attempt, so A is asked at C again. fn setup_p9_core_same_window(f: &mut NotifyFixture) { tree(f); select_core(f, A, CHILD, CORE_BUTTON_PRESS); @@ -875,39 +383,6 @@ fn setup_p9_core_same_window(f: &mut NotifyFixture) { grab_pointer(f, A, CHILD, true, CORE_BUTTON_PRESS); } -const P9_CORE_SAME_WINDOW: Row = Row { - name: "p9_denied_owner_with_allowed_foreign_falls_back", - setup: setup_p9_core_same_window, - drive: press(XTEST_MASTER), - deny: &[(A, CallKind::Core, CHILD)], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - }, - denied: Expect { - frames: &[], - calls: &[ - (A, CallKind::Core, CHILD), - (B, CallKind::Xi2, CHILD), - (A, CallKind::Core, CHILD), - ], - }, -}; - -/// Mutation: the denied owner keeps walking (or is dropped) although an allowed -/// foreign selector rejects the walk, so the grab window gets no copy; or the -/// core fallback takes the memo's result for (O, G, core) instead of a fresh -/// check (the same-window row then has one call for O, not two). -#[test] -fn p9_denied_owner_with_allowed_foreign_falls_back() { - check_row(&P9); - check_row(&P9_CORE_SAME_WINDOW); -} - -// ---- P10 ----------------------------------------------------------------- - fn setup_p10(f: &mut NotifyFixture) { tree(f); select_core(f, B, CHILD, CORE_BUTTON_PRESS); @@ -915,37 +390,6 @@ fn setup_p10(f: &mut NotifyFixture) { grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); } -const P10: Row = Row { - name: "p10_denied_foreign_selector_does_not_reject", - setup: setup_p10, - drive: press(XTEST_MASTER), - deny: &[(B, CallKind::Core, CHILD)], - denied_grab: None, - moved: &[Moved { - client: A, - window: FOCUS, - child: CHILD, - event: P_EVENT, - }], - allow: Expect { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, ROOT)], - }, - denied: Expect { - frames: &[(A, Kind::Core, FOCUS)], - calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - }, -}; - -/// Mutation: a foreign selector rejects the walk by selection (the denied -/// selector at C sends A to the grab window instead of on to P). -#[test] -fn p10_denied_foreign_selector_does_not_reject() { - check_row(&P10); -} - -// ---- P11 ----------------------------------------------------------------- - fn setup_p11(f: &mut NotifyFixture) { tree(f); select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); @@ -953,27 +397,6 @@ fn setup_p11(f: &mut NotifyFixture) { grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); } -const P11: Row = Row { - name: "p11_owner_qualifies_in_a_later_protocol", - setup: setup_p11, - drive: press(XTEST_MASTER), - deny: &[(A, CallKind::Core, CHILD)], - denied_grab: None, - moved: &[AT_ROOT], - allow: Expect { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Core, ROOT)], - calls: &[ - (A, CallKind::Core, CHILD), - (B, CallKind::Xi2, CHILD), - (A, CallKind::Core, ROOT), - ], - }, -}; - /// A selects the master XI2 press (denied) and the core press (allowed) on C: /// it qualifies through the later protocol. fn setup_p11_own_protocols(f: &mut NotifyFixture) { @@ -983,64 +406,12 @@ fn setup_p11_own_protocols(f: &mut NotifyFixture) { grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); } -const P11_OWN_PROTOCOLS: Row = Row { - name: "p11_owner_qualifies_in_a_later_protocol", - setup: setup_p11_own_protocols, - drive: press(XTEST_MASTER), - deny: &[(A, CallKind::Xi2, CHILD)], - denied_grab: None, - moved: &[Moved { - client: A, - window: CHILD, - child: 0, - event: C_EVENT, - }], - allow: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], - }, -}; - -/// Mutation: the foreign selectors are evaluated before the owner (an extra -/// call for B when A qualifies), F's master XI2 copy is asked under the -/// grab-owned master form (a call for B in the allowed run), or the owner -/// qualifies only through the first protocol it selected (the second row falls -/// back to the grab window). -#[test] -fn p11_owner_qualifies_in_a_later_protocol() { - check_row(&P11); - check_row(&P11_OWN_PROTOCOLS); -} - -// ---- P12 ----------------------------------------------------------------- - fn setup_p12(f: &mut NotifyFixture) { tree(f); select_core(f, B, CHILD, CORE_BUTTON_PRESS); grab_pointer(f, A, ROOT, false, CORE_BUTTON_PRESS); } -const P12: Row = Row { - name: "p12_grab_window_denial_counts_as_delivered", - setup: setup_p12, - drive: press(XTEST_MASTER), - deny: &[(A, CallKind::Core, ROOT)], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(A, CallKind::Core, ROOT)], - }, - denied: Expect { - frames: &[], - calls: &[(A, CallKind::Core, ROOT)], - }, -}; - /// The grab mask lacks ButtonPress: no frame in any mode, but the check still /// comes first, so the trace has the call at G. fn setup_p12_mask(f: &mut NotifyFixture) { @@ -1049,60 +420,14 @@ fn setup_p12_mask(f: &mut NotifyFixture) { grab_pointer(f, A, ROOT, false, CORE_MOTION); } -const P12_MASK: Row = Row { - name: "p12_grab_window_denial_counts_as_delivered", - setup: setup_p12_mask, - drive: press(XTEST_MASTER), - deny: &[(A, CallKind::Core, ROOT)], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[], - calls: &[(A, CallKind::Core, ROOT)], - }, - denied: Expect { - frames: &[], - calls: &[(A, CallKind::Core, ROOT)], - }, -}; - /// An XI2 master grab with owner_events false: the grab-window copy is the -/// only call; F's master XI2 selector on C is never asked. +/// only call; B's master XI2 selector on C is never asked. fn setup_p12_xi2(f: &mut NotifyFixture) { tree(f); select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); xi_grab_master_pointer(f, A, ROOT, false, XI_BUTTON_PRESS); } -const P12_XI2: Row = Row { - name: "p12_grab_window_denial_counts_as_delivered", - setup: setup_p12_xi2, - drive: press(XTEST_MASTER), - deny: &[(A, CallKind::Xi2, ROOT)], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], - calls: &[(A, CallKind::Xi2, ROOT)], - }, - denied: Expect { - frames: &[], - calls: &[(A, CallKind::Xi2, ROOT)], - }, -}; - -/// Mutation: the check moves behind the grab mask (second row has no call), the -/// denial is not a delivery (C's selectors get the press), or the XI2 grab asks -/// F's selector (a call for B). -#[test] -fn p12_grab_window_denial_counts_as_delivered() { - check_row(&P12); - check_row(&P12_MASK); - check_row(&P12_XI2); -} - -// ---- P13 ----------------------------------------------------------------- - fn setup_p13(f: &mut NotifyFixture) { tree(f); select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); @@ -1110,27 +435,6 @@ fn setup_p13(f: &mut NotifyFixture) { xi_grab_master_pointer(f, A, ROOT, true, XI_BUTTON_PRESS); } -const P13: Row = Row { - name: "p13_xi2_owner_events_fallback_is_fresh", - setup: setup_p13, - drive: press(XTEST_MASTER), - deny: &[(A, CallKind::Xi2, CHILD)], - denied_grab: None, - moved: &[AT_ROOT], - allow: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], - calls: &[ - (A, CallKind::Xi2, CHILD), - (B, CallKind::Xi2, CHILD), - (A, CallKind::Xi2, ROOT), - ], - }, -}; - /// The grab window is C itself: the fallback is a distinct attempt, so A is /// asked a second time at C (and denied again), not served from the memo. fn setup_p13_same_window(f: &mut NotifyFixture) { @@ -1140,266 +444,39 @@ fn setup_p13_same_window(f: &mut NotifyFixture) { xi_grab_master_pointer(f, A, CHILD, true, XI_BUTTON_PRESS); } -const P13_SAME_WINDOW: Row = Row { - name: "p13_xi2_owner_events_fallback_is_fresh", - setup: setup_p13_same_window, - drive: press(XTEST_MASTER), - deny: &[(A, CallKind::Xi2, CHILD)], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[], - calls: &[ - (A, CallKind::Xi2, CHILD), - (B, CallKind::Xi2, CHILD), - (A, CallKind::Xi2, CHILD), - ], - }, -}; - -/// Mutation: the XI2 owner qualifies by selection (nothing is written at C), -/// the natural XI2 write asks again (two calls for A at C when allowed), or the -/// fallback reuses the memo for G (one call for A at C in the same-window row). -#[test] -fn p13_xi2_owner_events_fallback_is_fresh() { - check_row(&P13); - check_row(&P13_SAME_WINDOW); -} - -// ---- P14 ----------------------------------------------------------------- - -/// What one denied activating press left behind: the Receive calls -/// (client, event window, XI2 or core), the bytes each client got, and the -/// fixture to inspect the grab, freeze and queue. -struct Activation { - f: NotifyFixture, - seen: std::sync::Arc>>, - calls: Vec<(u32, u32, bool)>, -} - -/// Runs the activating press of `origin` with every Receive call of `client` -/// at `window` denied, after `setup`. -fn activate_denied( - setup: fn(&mut NotifyFixture), - origin: InputOrigin, - client: u32, - window: u32, -) -> Activation { - let mut f = NotifyFixture::new(); - setup(&mut f); - for id in [SEND_CLIENT, A, B] { - f.drain(ClientId(id)); - } - let seen = f.install_policy(move |_, call| { - let denied = call.hook == ExtensionHook::Receive - && call.client.0 == client - && call.receive == Some(EventSubject::Window(ResourceId(window))); - if denied { DENY } else { Decision::Allow } - }); - drive(&mut f, press(origin)); - let mut run = Activation { - f, - seen, - calls: Vec::new(), - }; - run.calls = run.receive_calls(); - run -} - -impl Activation { - /// Every Receive call so far: (client, event window, XI2 or core). - fn receive_calls(&self) -> Vec<(u32, u32, bool)> { - self.seen - .lock() - .unwrap() - .iter() - .filter(|call| call.hook == ExtensionHook::Receive) - .map(|call| { - let Some(EventSubject::Window(subject)) = call.receive else { - panic!("pointer Receive subject {:?}", call.receive); - }; - let events = call.events.as_deref().expect("Receive batch"); - (call.client.0, subject.0, events[0].extension.is_some()) - }) - .collect() - } - - /// No client was sent a byte, in particular nobody got the denied press. - fn assert_no_bytes(&mut self) { - for id in [SEND_CLIENT, A, B] { - assert_eq!(self.f.drain(ClientId(id)), Vec::::new(), "client {id}"); - } - } - - /// The sync freeze of `device` holds the press: state and stored event. - fn assert_frozen_with_press(&self, device: u16) { - let freeze = self.f.state.xi1_frozen.get(&device).expect("freeze entry"); - assert_eq!(freeze.state, Xi1SyncState::FrozenWithEvent); - assert!( - matches!(&freeze.stored, Some(QueuedInputEvent::HostPointer(event)) - if event.kind == PointerEventKind::ButtonPress), - "the press is stored: {:?}", - freeze.stored - ); - } - - /// The devices and shape of the queued events, in order. - fn queued(&self) -> Vec<(u16, &'static str)> { - self.f - .state - .sync_pending - .iter() - .map(|pending| { - let shape = match &pending.event { - QueuedInputEvent::HostPointer(_) => "HostPointer", - QueuedInputEvent::HostPointerMaster(..) => "HostPointerMaster", - _ => "other", - }; - (pending.device, shape) - }) - .collect() - } -} - +/// A sync `GrabButton` on G. fn setup_p14_core(f: &mut NotifyFixture) { tree(f); grab_button(f, A, ROOT, false, true); } -/// A sync `GrabButton` on G: the activating press is denied to its owner, and -/// the grab still activates, freezes and stores the press. Mutation (all three -/// p14 tests): the denial skips the activation, the freeze or the stored press -/// (a `delivered` gate on the freeze), or a second owner call is made, or the -/// unchecked owner write under `xi2_grab_delivery` delivers the denied copy. -#[test] -fn p14_denied_activating_press_still_activates_and_freezes() { - let mut run = activate_denied(setup_p14_core, XTEST_MASTER, A, ROOT); - assert_eq!(run.calls, vec![(A, ROOT, false)], "one fresh check at G"); - run.assert_no_bytes(); - let grab = run.f.state.active_pointer_grab.expect("the grab activated"); - assert_eq!( - (grab.owner.0, grab.grab_window.0, grab.passive), - (A, ROOT, true) - ); - run.assert_frozen_with_press(DEVICEID_MASTER_POINTER); - follow_with_motion(&mut run, XTEST_MASTER); - assert_eq!(run.queued(), vec![(DEVICEID_MASTER_POINTER, "HostPointer")]); -} - +/// A sync `XIPassiveGrabDevice` on the master, to be activated from an attached +/// slave origin. fn setup_p14_xi2_master_from_slave(f: &mut NotifyFixture) { tree(f); - xi_passive_grab_button( - f, - A, - DEVICEID_MASTER_POINTER, - ROOT, - true, - false, - XI_BUTTON_PRESS, - ); + xi_passive_grab_master(f, false, XI_BUTTON_PRESS); } +/// The same grab, activated from a master origin (`xi2_grab_delivery`): A also +/// selects the master XI2 press on C, which is the window its copy is routed to. fn setup_p14_xi2_master_origin(f: &mut NotifyFixture) { tree(f); select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); - xi_passive_grab_button( - f, - A, - DEVICEID_MASTER_POINTER, - ROOT, - true, - false, - XI_BUTTON_PRESS, - ); -} - -/// The motion that follows the activating press, from `origin`. -fn follow_with_motion(run: &mut Activation, origin: InputOrigin) { - drive( - &mut run.f, - Drive::Pointer { - origin, - kind: PointerEventKind::MotionNotify, - button: 0, - to: MOTION_TO, - delta: (5, 5), - }, - ); - run.assert_no_bytes(); -} - -/// A sync `XIPassiveGrabDevice` on the master from an attached slave origin: -/// A's copy on G is denied, nobody else gets the press, and the grab still -/// freezes with the press stored. The next motion delivers its slave part and -/// defers the master part behind the freeze. Mutation: the XI2 master block asks -/// for the grab window without the emitted-form gate (a phantom call after the -/// motion, and a second one at the thaw). -#[test] -fn p14_denied_xi2_activating_press_still_freezes_from_a_slave_origin() { - let mut run = activate_denied(setup_p14_xi2_master_from_slave, XTEST_SLAVE, A, ROOT); - assert_eq!(run.calls, vec![(A, ROOT, true)], "one fresh XI2 check at G"); - run.assert_no_bytes(); - let grab = run.f.state.active_pointer_grab.expect("the grab activated"); - assert_eq!( - (grab.owner.0, grab.grab_window.0, grab.passive, grab.via_xi2), - (A, ROOT, true, true) - ); - run.assert_frozen_with_press(DEVICEID_MASTER_POINTER); - follow_with_motion(&mut run, XTEST_SLAVE); - assert_eq!( - run.queued(), - vec![(DEVICEID_MASTER_POINTER, "HostPointerMaster")] - ); - // The deferred master part is not written yet, so nobody is asked for it. - assert_eq!( - run.receive_calls(), - run.calls, - "no call for the deferred master part" - ); - // Thawing runs the master part: that is the one attempt, asked once. - let mut body = Vec::with_capacity(8); - body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime - body.extend_from_slice(&DEVICEID_MASTER_POINTER.to_le_bytes()); - body.extend_from_slice(&[0, 0]); // XIAsyncDevice - send(&mut run.f, A, XI_MAJOR, XI_ALLOW_EVENTS, &body); - let mut expected = run.calls.clone(); - expected.push((A, ROOT, true)); - assert_eq!( - run.receive_calls(), - expected, - "one call when the master part runs" - ); + xi_passive_grab_master(f, false, XI_BUTTON_PRESS); } -/// The same grab from a master origin (`xi2_grab_delivery`): A also selects the -/// master XI2 press on C, which is the window its copy is routed to. Denying -/// that copy writes nothing, asks once, and still freezes with the press stored. -#[test] -fn p14_denied_xi2_activating_press_from_a_master_origin_still_freezes() { - let mut run = activate_denied(setup_p14_xi2_master_origin, XTEST_MASTER, A, CHILD); - assert_eq!(run.calls, vec![(A, CHILD, true)], "one XI2 check, at C"); - run.assert_no_bytes(); - assert!( - run.f - .state - .active_pointer_grab - .is_some_and(|grab| grab.passive) - ); - run.assert_frozen_with_press(DEVICEID_MASTER_POINTER); - follow_with_motion(&mut run, XTEST_MASTER); - assert_eq!(run.queued(), vec![(DEVICEID_MASTER_POINTER, "HostPointer")]); +/// The same sync master grab with owner_events, and A selecting the master XI2 +/// motion on C. +fn setup_p14_owner_events_from_slave(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_MOTION); + xi_passive_grab_master(f, true, XI_BUTTON_PRESS | XI_MOTION); } -// ---- I2 ------------------------------------------------------------------ - /// An async `GrabButton` with owner_events on G: the activation dispatch writes -/// only the activating press, on G. O selects core on C and XI2 on P. The core +/// only the activating press, on G. A selects core on C and XI2 on P. The core /// grab block did not route this dispatch, so the XI2 route asks nothing about -/// O's core copy at C, and a denial there changes nothing. +/// A's core copy at C, and a denial there changes nothing. fn setup_activation_owner_events(f: &mut NotifyFixture) { tree(f); select_core(f, A, CHILD, CORE_BUTTON_PRESS); @@ -1407,68 +484,6 @@ fn setup_activation_owner_events(f: &mut NotifyFixture) { grab_button(f, A, ROOT, true, false); } -const ACTIVATION_OWNER_EVENTS: Row = Row { - name: "activation_route_asks_no_core_copy", - setup: setup_activation_owner_events, - drive: press(XTEST_MASTER), - deny: &[(A, CallKind::Core, CHILD)], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(A, CallKind::Core, ROOT)], - }, - denied: Expect { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(A, CallKind::Core, ROOT)], - }, -}; - -/// Mutation: the XI2 block's route asks the core leg in an activation dispatch -/// (`core_checked` true): the denied run then has an O@C core call and walks -/// on to an XI2 press at P. -#[test] -fn activation_route_asks_no_core_copy() { - check_row(&ACTIVATION_OWNER_EVENTS); -} - -fn setup_p14_owner_events_from_slave(f: &mut NotifyFixture) { - tree(f); - select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_MOTION); - xi_passive_grab_button( - f, - A, - DEVICEID_MASTER_POINTER, - ROOT, - true, - true, - XI_BUTTON_PRESS | XI_MOTION, - ); -} - -/// The same sync master grab with owner_events, and A selecting the master XI2 -/// motion on C: the follow-up slave motion defers its master part, so the -/// route that would ask A@C for that copy must not ask yet. -/// Mutation: the master block's route takes the memo although the master form -/// is not emitted in this dispatch (a phantom A@C call). -#[test] -fn p14_deferred_master_part_asks_nothing_in_the_route() { - let mut run = activate_denied(setup_p14_owner_events_from_slave, XTEST_SLAVE, A, ROOT); - let before = run.receive_calls(); - follow_with_motion(&mut run, XTEST_SLAVE); - assert_eq!( - run.queued(), - vec![(DEVICEID_MASTER_POINTER, "HostPointerMaster")] - ); - assert_eq!( - run.receive_calls(), - before, - "no call for the deferred master part" - ); -} - -// ---- P15-P20: implicit grabs and the slave press protocol ----------------- - /// The class value of an XI1 `DeviceButtonGrab` selection, which the router /// reads as "this input client selected the button grab" (the low byte is the /// class code, not an event code). @@ -1484,130 +499,26 @@ fn xi1_slave_press() -> u32 { ) } -/// The Receive batch of an XI1 `DeviceButtonPress` copy. -const XI1_PRESS_CALL: CallKind = CallKind::Batch(&[Named::Xi1( - crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET as u16, -)]); - -/// The grab fact of a core implicit grab. -const fn core_implicit(owner: u32, window: u32) -> Grab { - Grab::Pointer(PointerGrab { - owner, - window, - implicit: true, - passive: false, - via_xi2: false, - }) -} - -const fn xi1_implicit(owner: u32, window: u32) -> Grab { - Grab::Xi1 { - device: DEVICEID_XTEST_POINTER, - owner, - window, - } +/// The XI1 class of the slave's `DeviceMotionNotify`. +fn xi1_slave_motion() -> u32 { + xi1_class( + DEVICEID_XTEST_POINTER, + crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET, + ) } +/// A and B select press and release on different windows: A on C, B on P. fn setup_p15(f: &mut NotifyFixture) { tree(f); select_core(f, A, CHILD, CORE_BUTTON_PRESS | CORE_BUTTON_RELEASE); select_core(f, B, FOCUS, CORE_BUTTON_PRESS | CORE_BUTTON_RELEASE); } -const P15: Row = Row { - name: "p15_denied_candidate_is_not_the_implicit_owner", - setup: setup_p15, - drive: press(XTEST_MASTER), - deny: &[(A, CallKind::Core, CHILD)], - denied_grab: Some(&[core_implicit(B, FOCUS)]), - moved: &[Moved { - client: B, - window: FOCUS, - child: CHILD, - event: P_EVENT, - }], - allow: Expect { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - }, - denied: Expect { - frames: &[(B, Kind::Core, FOCUS)], - calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, FOCUS)], - }, -}; - -/// A denied on C: B on P gets the press and owns the implicit grab; the release, -/// with the pointer still over C, goes to B at P. Mutation (the core -/// candidate): the candidate is any walk recipient, denied or not, so A owns the -/// grab and the release goes to A at C. -#[test] -fn p15_denied_candidate_is_not_the_implicit_owner() { - check_row(&P15); - let mut f = NotifyFixture::new(); - setup_p15(&mut f); - for id in [SEND_CLIENT, A, B] { - f.drain(ClientId(id)); - } - f.install_policy(|_, call| { - let denied = call.hook == ExtensionHook::Receive - && call.client.0 == A - && call.receive == Some(EventSubject::Window(ResourceId(CHILD))); - if denied { DENY } else { Decision::Allow } - }); - drive(&mut f, press(XTEST_MASTER)); - for id in [A, B] { - f.drain(ClientId(id)); - } - drive( - &mut f, - Drive::Pointer { - origin: XTEST_MASTER, - kind: PointerEventKind::ButtonRelease, - button: 1, - to: POINTER, - delta: (0, 0), - }, - ); - let mut released = Vec::new(); - for id in [A, B] { - let order = f.state.clients[&id].byte_order; - for frame in split_frames(&f.drain(ClientId(id)), order) { - released.extend(decode(frame, order).map(|seen| (id, seen))); - } - } - assert_eq!(released, vec![(B, (Kind::Core, FOCUS))], "release owner"); -} - fn setup_p16(f: &mut NotifyFixture) { tree(f); select_core(f, A, CHILD, CORE_BUTTON_PRESS); } -const P16: Row = Row { - name: "p16_all_denied_no_implicit_grab", - setup: setup_p16, - drive: press(XTEST_MASTER), - deny: &[(A, CallKind::Core, CHILD)], - denied_grab: Some(&[]), - moved: &[], - allow: Expect { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - }, - denied: Expect { - frames: &[], - calls: &[(A, CallKind::Core, CHILD)], - }, -}; - -/// A alone on C, denied: nobody receives the press and no pointer grab is -/// active afterwards. Mutation (the core candidate): the denied recipient -/// still qualifies, so A owns an implicit grab it never received a press for. -#[test] -fn p16_all_denied_no_implicit_grab() { - check_row(&P16); -} - fn setup_p17(f: &mut NotifyFixture) { tree(f); // A owns C, so it is the implicit-grab owner among equal candidates there. @@ -1620,125 +531,19 @@ fn setup_p17(f: &mut NotifyFixture) { select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); } -const P17: Row = Row { - name: "p17_xi2_owner_preference_among_allowed", - setup: setup_p17, - drive: press(XTEST_MASTER), - deny: &[(A, CallKind::Xi2, CHILD)], - denied_grab: Some(&[Grab::Pointer(PointerGrab { - owner: B, - window: CHILD, - implicit: true, - passive: false, - via_xi2: true, - })]), - moved: &[], - allow: Expect { - frames: &[ - (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - ], - calls: &[(A, CallKind::Xi2, CHILD), (B, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD), (B, CallKind::Xi2, CHILD)], - }, -}; - -/// Both select the master pointer's XI2 press on C; A is the window's owner and -/// wins with allow-all, and with A denied B owns the grab. Mutation (the -/// XI2 candidate): a denied copy still enters the owner preference. -#[test] -fn p17_xi2_owner_preference_among_allowed() { - check_row(&P17); - // The allow-all grab fact is A (the owner), not B. - let allow = run(&P17, Some(&[])); - assert_eq!( - allow.grab, - vec![Grab::Pointer(PointerGrab { - owner: A, - window: CHILD, - implicit: true, - passive: false, - via_xi2: true, - })] - ); -} - fn setup_p18(f: &mut NotifyFixture) { tree(f); select_xi2(f, A, CHILD, DEVICEID_XTEST_POINTER, XI_BUTTON_PRESS); select_xi1(f, B, CHILD, &[xi1_slave_press()]); } -const P18: Row = Row { - name: "p18_denied_slave_xi2_falls_to_xi1", - setup: setup_p18, - drive: press(XTEST_SLAVE), - deny: &[(A, CallKind::Xi2, CHILD)], - denied_grab: Some(&[xi1_implicit(B, CHILD)]), - moved: &[Moved { - client: B, - window: CHILD, - child: 0, - event: C_EVENT, - }], - allow: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - }, - denied: Expect { - frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD), (B, XI1_PRESS_CALL, CHILD)], - }, -}; - -/// Slave origin; A selects the slave's XI2 press on C, B its XI1 press on C. A -/// denied: B gets the XI1 form at C and owns the XI1 implicit grab, with one -/// call. Mutation: the protocol is chosen by selection (the XI2 selector wins -/// though denied: B gets nothing); or the XI1 copy is checked a second time. -#[test] -fn p18_denied_slave_xi2_falls_to_xi1() { - check_row(&P18); -} - fn setup_p19(f: &mut NotifyFixture) { tree(f); select_xi1(f, A, CHILD, &[xi1_slave_press()]); select_xi1(f, B, FOCUS, &[xi1_slave_press()]); } -const P19: Row = Row { - name: "p19_denied_xi1_press_continues", - setup: setup_p19, - drive: press(XTEST_SLAVE), - deny: &[(A, XI1_PRESS_CALL, CHILD)], - denied_grab: Some(&[xi1_implicit(B, FOCUS)]), - moved: &[Moved { - client: B, - window: FOCUS, - child: CHILD, - event: P_EVENT, - }], - allow: Expect { - frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[(A, XI1_PRESS_CALL, CHILD)], - }, - denied: Expect { - frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], - calls: &[(A, XI1_PRESS_CALL, CHILD), (B, XI1_PRESS_CALL, FOCUS)], - }, -}; - -/// A's XI1 press selector on C is denied, B's on P is not: the walk continues -/// and B gets the press at P. Mutation: a denied XI1 selector stops the walk -/// (selection decides the window), so B gets nothing. -#[test] -fn p19_denied_xi1_press_continues() { - check_row(&P19); -} - +/// Two XI1 press selectors on C; B also selected the button grab class. fn setup_p20(f: &mut NotifyFixture) { tree(f); select_xi1(f, A, CHILD, &[xi1_slave_press()]); @@ -1750,90 +555,11 @@ fn setup_p20(f: &mut NotifyFixture) { ); } -const P20: Row = Row { - name: "p20_xi1_implicit_owner_from_allowed", - setup: setup_p20, - drive: press(XTEST_SLAVE), - deny: &[(B, XI1_PRESS_CALL, CHILD)], - denied_grab: Some(&[xi1_implicit(A, CHILD)]), - moved: &[], - allow: Expect { - frames: &[ - (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), - (B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), - ], - calls: &[(A, XI1_PRESS_CALL, CHILD), (B, XI1_PRESS_CALL, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[(A, XI1_PRESS_CALL, CHILD), (B, XI1_PRESS_CALL, CHILD)], - }, -}; - -/// Two XI1 press selectors on C, the one that also selected the button grab -/// class is denied: the other owns the XI1 implicit grab (allow-all: the grab -/// class holder). Mutation: the owner is chosen among the selectors, not among -/// the allowed recipients, so the denied B owns the grab. -#[test] -fn p20_xi1_implicit_owner_from_allowed() { - check_row(&P20); - let allow = run(&P20, Some(&[])); - assert_eq!(allow.grab, vec![xi1_implicit(B, CHILD)]); -} - +/// B holds an async XI1 passive grab on P. fn setup_p20b(f: &mut NotifyFixture) { tree(f); select_xi1(f, A, CHILD, &[xi1_slave_press()]); - f.state - .xi1_passive_grabs - .push(crate::server::Xi1PassiveGrab { - owner: ClientId(B), - deviceid: DEVICEID_XTEST_POINTER, - grab_window: ResourceId(FOCUS), - detail: 0, - modifiers: 0x8000, - owner_events: false, - this_mode: 1, - other_mode: 1, - is_key: false, - }); -} - -const P20B: Row = Row { - name: "p20b_xi1_passive_activation_asks_no_selector", - setup: setup_p20b, - drive: press(XTEST_SLAVE), - deny: &[(A, XI1_PRESS_CALL, CHILD)], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], - calls: &[(B, XI1_PRESS_CALL, FOCUS)], - }, - denied: Expect { - frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], - calls: &[(B, XI1_PRESS_CALL, FOCUS)], - }, -}; - -/// An XI1 passive grab takes the slave press, so the router never reaches the -/// selection walk: A's selector copy is not written and Receive is not asked -/// (the activating write is the grab owner's one fresh check). Mutation: the -/// route asks the XI1 selectors although a passive grab matches (`xi1_routed` -/// ignores it). With the owner denied the grab still activates and nobody gets -/// the press; mutation: the activating write is unchecked. -#[test] -fn p20b_xi1_passive_activation_asks_no_selector() { - check_row(&P20B); - check_row(&Row { - name: "p20b_xi1_passive_activation_owner_denied", - deny: &[(B, XI1_PRESS_CALL, FOCUS)], - denied: Expect { - frames: &[], - calls: &[(B, XI1_PRESS_CALL, FOCUS)], - }, - ..P20B - }); + xi1_passive_grab(f, B, FOCUS, false); } /// The press over a root that nothing can hit (unmapped, as `unhit_root` @@ -1851,16 +577,6 @@ fn unhit_root(f: &mut NotifyFixture) { .map_state = crate::resources::MapState::Unmapped; } -const fn press_at_bare_root(origin: InputOrigin) -> Drive { - Drive::Pointer { - origin, - kind: PointerEventKind::ButtonPress, - button: 1, - to: BARE_ROOT, - delta: (0, 0), - } -} - fn setup_i1a(f: &mut NotifyFixture) { tree(f); park_pointer_at(f, BARE_ROOT); @@ -1869,32 +585,6 @@ fn setup_i1a(f: &mut NotifyFixture) { select_xi1(f, B, ROOT, &[xi1_slave_press()]); } -const I1A: Row = Row { - name: "i1a_bare_root_slave_xi2_is_not_asked", - setup: setup_i1a, - drive: press_at_bare_root(XTEST_SLAVE), - deny: &[(A, CallKind::Xi2, ROOT)], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[], - calls: &[], - }, - denied: Expect { - frames: &[], - calls: &[], - }, -}; - -/// A selects the slave's XI2 press on the root, B its XI1 press, and the press -/// is over the bare root: no XI2 copy is written, so Receive is not asked for -/// A's, and a denial must not hand the press to B (nor give B an XI1 grab). -/// Mutation: the XI2 leg is asked without the top-level condition. -#[test] -fn i1a_bare_root_slave_xi2_is_not_asked() { - check_row(&I1A); -} - fn setup_i1b(f: &mut NotifyFixture) { tree(f); park_pointer_at(f, BARE_ROOT); @@ -1903,46 +593,6 @@ fn setup_i1b(f: &mut NotifyFixture) { select_xi1(f, B, ROOT, &[xi1_slave_press()]); } -const I1B: Row = Row { - name: "i1b_bare_root_xi1_selectors_are_checked", - setup: setup_i1b, - drive: press_at_bare_root(XTEST_SLAVE), - deny: &[(A, XI1_PRESS_CALL, ROOT)], - denied_grab: Some(&[xi1_implicit(B, ROOT)]), - moved: &[], - allow: Expect { - frames: &[ - (A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT), - (B, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT), - ], - calls: &[(A, XI1_PRESS_CALL, ROOT), (B, XI1_PRESS_CALL, ROOT)], - }, - denied: Expect { - frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT)], - calls: &[(A, XI1_PRESS_CALL, ROOT), (B, XI1_PRESS_CALL, ROOT)], - }, -}; - -/// Only XI1 selectors on the root, the press over the bare root: the router -/// writes the XI1 form, so each selector is asked once and the denied one gets -/// nothing. Mutation: the XI1 check is gated on the XI2 flag (here false). -#[test] -fn i1b_bare_root_xi1_selectors_are_checked() { - check_row(&I1B); -} - -// ---- raw copies and smooth scroll ----------------------------------- -// -// X is client A, Y is client B, S is the send client. - -/// XI2 raw and Motion selection bits. -const XI_RAW_BUTTON_PRESS: u32 = 1 << 15; -const RAW_BUTTON_PRESS_CALL: CallKind = CallKind::Batch(&[Named::Raw(15)]); - -/// The device id the registry gives the physical pointer of these rows. -const PHYSICAL_DEVICE: u16 = 6; -const PHYSICAL_SOURCE_ORIGIN: InputOrigin = InputOrigin::Physical(InputSourceId(PHYSICAL_SOURCE)); - fn setup_p21(f: &mut NotifyFixture) { tree(f); select_xi2(f, A, ROOT, DEVICEID_MASTER_POINTER, XI_RAW_BUTTON_PRESS); @@ -1956,260 +606,29 @@ fn setup_p21(f: &mut NotifyFixture) { ); } -const P21: Row = Row { - name: "p21_denied_raw_root_copy_drops_only_that_copy", - setup: setup_p21, - drive: press(XTEST_SLAVE), - deny: &[(A, RAW_BUTTON_PRESS_CALL, ROOT)], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[ - (SEND_CLIENT, Kind::Raw(DEVICEID_XTEST_POINTER), ROOT), - (A, Kind::Raw(DEVICEID_MASTER_POINTER), ROOT), - (B, Kind::Raw(DEVICEID_MASTER_POINTER), ROOT), - ], - calls: &[ - (SEND_CLIENT, RAW_BUTTON_PRESS_CALL, ROOT), - (A, RAW_BUTTON_PRESS_CALL, ROOT), - (B, RAW_BUTTON_PRESS_CALL, ROOT), - ], - }, - denied: Expect { - frames: &[ - (SEND_CLIENT, Kind::Raw(DEVICEID_XTEST_POINTER), ROOT), - (B, Kind::Raw(DEVICEID_MASTER_POINTER), ROOT), - ], - calls: &[ - (SEND_CLIENT, RAW_BUTTON_PRESS_CALL, ROOT), - (A, RAW_BUTTON_PRESS_CALL, ROOT), - (B, RAW_BUTTON_PRESS_CALL, ROOT), - ], - }, -}; - -/// A and B select the master raw press on the root, S the slave's; A is -/// denied: only A's copy goes, B and S keep theirs, in the same order. -/// Mutation: the raw copies are written unchecked (every denied-run assertion -/// fails), or a denial stops the raw fanout (B or S lose theirs). -#[test] -fn p21_denied_raw_root_copy_drops_only_that_copy() { - check_row(&P21); -} - -/// A physical wheel press (button 4) at C; the master XI2 Motion selectors -/// are X (A) on C and Y (B) on P. +/// The master XI2 Motion selectors are A on C and B on P. fn setup_scroll_walk(f: &mut NotifyFixture) { tree(f); - register_physical_pointer(&mut f.state); + register_physical_pointer(f); select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_MOTION); select_xi2(f, B, FOCUS, DEVICEID_MASTER_POINTER, XI_MOTION); } -const SCROLL_MOTION_CALL: CallKind = CallKind::Batch(&[Named::Xi2(6)]); - -const P22: Row = Row { - name: "p22_scroll_motion_follows_the_walk", - setup: setup_scroll_walk, - drive: Drive::Pointer { - origin: PHYSICAL_SOURCE_ORIGIN, - kind: PointerEventKind::ButtonPress, - button: 4, - to: POINTER, - delta: (0, 0), - }, - deny: &[(A, SCROLL_MOTION_CALL, CHILD)], - denied_grab: None, - moved: &[Moved { - client: B, - window: FOCUS, - child: CHILD, - event: P_EVENT, - }], - allow: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, SCROLL_MOTION_CALL, CHILD)], - }, - denied: Expect { - frames: &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], - calls: &[ - (A, SCROLL_MOTION_CALL, CHILD), - (B, SCROLL_MOTION_CALL, FOCUS), - ], - }, -}; - -/// The scroll Motion of a wheel press follows the ordinary walk: X's denied -/// copy on C does not stop it, and Y at P gets the Motion. -/// Mutation: the scroll Motion routes by selection only (the denied row then -/// writes nothing for Y and asks nothing of Y), or is written unchecked. -#[test] -fn p22_scroll_motion_follows_the_walk() { - check_row(&P22); -} - -const STOP_BATCH: CallKind = CallKind::Batch(&[Named::Xi2(6), Named::Xi2(6)]); - -const fn scroll_stop() -> Drive { - Drive::ScrollStop { - origin: PHYSICAL_SOURCE_ORIGIN, - at: POINTER, - } -} - -const P23_ALLOWED_AND_DENIED: Row = Row { - name: "p23_scroll_stop_is_not_rerouted", - setup: setup_scroll_walk, - drive: scroll_stop(), - deny: &[(A, STOP_BATCH, CHILD)], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[ - (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - ], - calls: &[(A, STOP_BATCH, CHILD)], - }, - denied: Expect { - frames: &[], - calls: &[(A, STOP_BATCH, CHILD)], - }, -}; - fn setup_scroll_stop_two_forms(f: &mut NotifyFixture) { tree(f); - register_physical_pointer(&mut f.state); + register_physical_pointer(f); select_xi2(f, A, CHILD, XI_ALL_DEVICES, XI_MOTION); } -const P23_TWO_FORMS: Row = Row { - name: "p23_scroll_stop_is_not_rerouted", - setup: setup_scroll_stop_two_forms, - drive: scroll_stop(), - deny: &[], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[ - (A, Kind::Xi2(PHYSICAL_DEVICE), CHILD), - (A, Kind::Xi2(PHYSICAL_DEVICE), CHILD), - (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - ], - calls: &[(A, STOP_BATCH, CHILD)], - }, - denied: Expect { - frames: &[ - (A, Kind::Xi2(PHYSICAL_DEVICE), CHILD), - (A, Kind::Xi2(PHYSICAL_DEVICE), CHILD), - (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - ], - calls: &[(A, STOP_BATCH, CHILD)], - }, -}; - -const P23_TWO_FORMS_DENIED: Row = Row { - deny: &[(A, STOP_BATCH, CHILD)], - denied: Expect { - frames: &[], - calls: &[(A, STOP_BATCH, CHILD)], - }, - ..P23_TWO_FORMS -}; - -/// The stop routes from its own probe hit, as today. X's denied batch on C -/// drops X's two Motions and the walk does not resume (Y at P gets nothing -/// and is not asked); allowed, X gets both. A client with both device forms on -/// one window is asked once for both forms' four events. -/// Mutations: the stop routes through the memo (Y gets it at P and is asked); -/// one check per event (two calls for X); one check per form (two calls in -/// the two-form row). -#[test] -fn p23_scroll_stop_is_not_rerouted() { - check_row(&P23_ALLOWED_AND_DENIED); - check_row(&P23_TWO_FORMS); - check_row(&P23_TWO_FORMS_DENIED); -} - /// A's XIGrabDevice on the master pointer at the root, owner_events false, /// selecting Motion only: a wheel press writes A the scroll Motion at the grab /// window and no button event. fn setup_p22_grab(f: &mut NotifyFixture) { tree(f); - register_physical_pointer(&mut f.state); + register_physical_pointer(f); xi_grab_master_pointer(f, A, ROOT, false, XI_MOTION); } -const P22_GRAB_PRESS_CALL: CallKind = CallKind::Batch(&[Named::Xi2(4)]); - -const P22_GRAB_MOTION_DENIED: Row = Row { - name: "p22_scroll_motion_grab_window_has_its_own_check", - setup: setup_p22_grab, - deny: &[(A, SCROLL_MOTION_CALL, ROOT)], - denied: Expect { - frames: &[], - calls: &[ - (A, P22_GRAB_PRESS_CALL, ROOT), - (A, SCROLL_MOTION_CALL, ROOT), - ], - }, - ..P22_GRAB_PRESS_DENIED -}; - -const P22_GRAB_PRESS_DENIED: Row = Row { - name: "p22_scroll_motion_grab_window_has_its_own_check", - setup: setup_p22_grab, - drive: P22.drive, - deny: &[(A, P22_GRAB_PRESS_CALL, ROOT)], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], - calls: &[ - (A, P22_GRAB_PRESS_CALL, ROOT), - (A, SCROLL_MOTION_CALL, ROOT), - ], - }, - denied: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], - calls: &[ - (A, P22_GRAB_PRESS_CALL, ROOT), - (A, SCROLL_MOTION_CALL, ROOT), - ], - }, -}; - -/// The scroll Motion of an XI2 grab with owner_events false is a grab-window -/// copy of its own: one fresh check, whatever the press's check at that -/// window said. Denying the press check leaves the Motion written; denying the -/// Motion check drops it. -/// Mutation: the Motion reuses the press's grab-window result (the first row -/// then drops the Motion), or is written unchecked (the second row writes it). -#[test] -fn p22_scroll_motion_grab_window_has_its_own_check() { - check_row(&P22_GRAB_PRESS_DENIED); - check_row(&P22_GRAB_MOTION_DENIED); -} - -// ---- P24-P28: the XI1 router ---------------------------------------------- - -/// The XI1 class of the slave's `DeviceMotionNotify`. -fn xi1_slave_motion() -> u32 { - xi1_class( - DEVICEID_XTEST_POINTER, - crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET, - ) -} - -/// The Receive batch of an XI1 `DeviceMotionNotify` copy: the motion event and -/// its `DeviceValuator` continuation are one batch (`dix/eventconvert.c:369`). -const XI1_MOTION_CALL: CallKind = CallKind::Batch(&[ - Named::Xi1(crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET as u16), - Named::Xi1(crate::xinput::XI_DEVICE_VALUATOR_OFFSET as u16), -]); - fn setup_p24(f: &mut NotifyFixture) { tree(f); park_pointer(f); @@ -2217,92 +636,12 @@ fn setup_p24(f: &mut NotifyFixture) { select_xi1(f, B, FOCUS, &[xi1_slave_motion()]); } -const P24: Row = Row { - name: "p24_denied_xi1_selector_advances_the_walk", - setup: setup_p24, - drive: motion(XTEST_SLAVE), - deny: &[(A, XI1_MOTION_CALL, CHILD)], - denied_grab: None, - moved: &[Moved { - client: B, - window: FOCUS, - child: CHILD, - event: MOTION_EVENT_AT_P, - }], - allow: Expect { - frames: &[ - (A, Kind::Xi1Motion(DEVICEID_XTEST_POINTER), CHILD), - (A, Kind::Xi1Valuator(DEVICEID_XTEST_POINTER), 0), - ], - calls: &[(A, XI1_MOTION_CALL, CHILD)], - }, - denied: Expect { - frames: &[ - (B, Kind::Xi1Motion(DEVICEID_XTEST_POINTER), FOCUS), - (B, Kind::Xi1Valuator(DEVICEID_XTEST_POINTER), 0), - ], - calls: &[(A, XI1_MOTION_CALL, CHILD), (B, XI1_MOTION_CALL, FOCUS)], - }, -}; - -/// Slave motion over C: A selects XI1 `DeviceMotionNotify` on C, B on P. A's -/// copy denied: the walk goes on and B gets it at P. Mutation: a denied XI1 -/// selector stops the walk (selection decides the window), so B gets nothing. -#[test] -fn p24_denied_xi1_selector_advances_the_walk() { - check_row(&P24); -} - fn setup_p25(f: &mut NotifyFixture) { tree(f); park_pointer(f); select_xi1(f, A, CHILD, &[xi1_slave_motion()]); } -const P25: Row = Row { - name: "p25_device_motion_and_valuator_are_one_batch", - setup: setup_p25, - drive: motion(XTEST_SLAVE), - deny: &[(A, XI1_MOTION_CALL, CHILD)], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[ - (A, Kind::Xi1Motion(DEVICEID_XTEST_POINTER), CHILD), - (A, Kind::Xi1Valuator(DEVICEID_XTEST_POINTER), 0), - ], - calls: &[(A, XI1_MOTION_CALL, CHILD)], - }, - denied: Expect { - frames: &[], - calls: &[(A, XI1_MOTION_CALL, CHILD)], - }, -}; - -/// The motion event and its valuator continuation are decided by one call with -/// the two-description batch: denied writes neither frame. Mutation: the route -/// or the write checks per event (two calls; the denied batch never matches -/// either single-description call, so both frames are written). -#[test] -fn p25_device_motion_and_valuator_are_one_batch() { - check_row(&P25); -} - -/// The XI1 `GrabDevice` of the slave pointer by `owner` on `window`. -fn xi1_grab_device(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: bool) { - const XI_GRAB_DEVICE_XI1: u8 = 13; - let mut body = Vec::with_capacity(16); - body.extend_from_slice(&window.to_le_bytes()); - body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime - body.extend_from_slice(&0_u16.to_le_bytes()); // no event classes - body.extend_from_slice(&[1, 1, u8::from(owner_events)]); // async modes - body.push(DEVICEID_XTEST_POINTER as u8); - body.extend_from_slice(&[0, 0]); - let bytes = send_with_reply(f, owner, XI_MAJOR, XI_GRAB_DEVICE_XI1, &body); - let reply = &bytes[bytes.len() - 32..]; - assert_eq!((reply[0], reply[8]), (1, 0), "GrabDevice replies Success"); -} - fn setup_p26_owner_events(f: &mut NotifyFixture) { tree(f); select_xi1(f, A, CHILD, &[xi1_slave_press()]); @@ -2310,40 +649,6 @@ fn setup_p26_owner_events(f: &mut NotifyFixture) { xi1_grab_device(f, A, ROOT, true); } -fn xi1_grab_fact(window: u32) -> Grab { - Grab::Xi1 { - device: DEVICEID_XTEST_POINTER, - owner: A, - window, - } -} - -const P26_OWNER_DENIED: Row = Row { - name: "p26_xi1_grab_owner_denied_falls_to_the_grab_window", - setup: setup_p26_owner_events, - drive: press(XTEST_SLAVE), - deny: &[(A, XI1_PRESS_CALL, CHILD)], - denied_grab: None, - moved: &[Moved { - client: A, - window: ROOT, - child: FOCUS, - event: POINTER, - }], - allow: Expect { - frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[(A, XI1_PRESS_CALL, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT)], - calls: &[ - (A, XI1_PRESS_CALL, CHILD), - (B, XI1_PRESS_CALL, CHILD), - (A, XI1_PRESS_CALL, ROOT), - ], - }, -}; - fn setup_p26_not_owner_events(f: &mut NotifyFixture) { tree(f); select_xi1(f, A, CHILD, &[xi1_slave_press()]); @@ -2351,35 +656,6 @@ fn setup_p26_not_owner_events(f: &mut NotifyFixture) { xi1_grab_device(f, A, ROOT, false); } -const P26_NO_OWNER_EVENTS: Row = Row { - name: "p26_xi1_grab_without_owner_events_asks_only_the_grab_window", - setup: setup_p26_not_owner_events, - drive: press(XTEST_SLAVE), - deny: &[(A, XI1_PRESS_CALL, ROOT)], - denied_grab: None, - moved: &[], - allow: Expect { - frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT)], - calls: &[(A, XI1_PRESS_CALL, ROOT)], - }, - denied: Expect { - frames: &[], - calls: &[(A, XI1_PRESS_CALL, ROOT)], - }, -}; - -const P26_OWNER_ALLOWED: Row = Row { - name: "p26_xi1_grab_owner_allowed_asks_no_foreign_selector", - setup: setup_p26_owner_events, - deny: &[], - moved: &[], - denied: Expect { - frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[(A, XI1_PRESS_CALL, CHILD)], - }, - ..P26_OWNER_DENIED -}; - fn setup_p26_foreign_rejects(f: &mut NotifyFixture) { tree(f); select_xi1(f, A, CHILD, &[xi1_slave_press()]); @@ -2388,93 +664,12 @@ fn setup_p26_foreign_rejects(f: &mut NotifyFixture) { xi1_grab_device(f, A, ROOT, true); } -/// O denied on C, F allowed on C: F's copy rejects the walk, so O does not -/// reach its own selector on P: it gets the event at G. -const P26_FOREIGN_REJECTS: Row = Row { - name: "p26_xi1_grab_foreign_copy_rejects_the_walk", - setup: setup_p26_foreign_rejects, - allow: Expect { - frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[(A, XI1_PRESS_CALL, CHILD)], - }, - ..P26_OWNER_DENIED -}; - -/// Slave origin, XI1 `GrabDevice` by A on G (the root). With `owner_events` -/// and A's own copy on C allowed A gets it at C and the foreign selector B is -/// not asked. With A denied, B (allowed) sends the event to G: A gets one fresh -/// check there. Without `owner_events` the natural walk is not checked at all: -/// only A's copy at G, and a denial there is a delivery (grab stays). -/// Mutations: the owner copy is not checked in the route (selection decides); -/// the foreign selector is asked before the owner; the grab-window copy is -/// written unchecked or the natural walk is asked without `owner_events`. -#[test] -fn p26_xi1_grab() { - check_row(&P26_OWNER_DENIED); - check_row(&P26_OWNER_ALLOWED); - check_row(&P26_NO_OWNER_EVENTS); - check_row(&P26_FOREIGN_REJECTS); - for row in [ - &P26_OWNER_DENIED, - &P26_NO_OWNER_EVENTS, - &P26_FOREIGN_REJECTS, - ] { - assert_eq!(run(row, Some(row.deny)).grab, vec![xi1_grab_fact(ROOT)]); - } -} - fn setup_p27(f: &mut NotifyFixture) { tree(f); select_xi1(f, A, CHILD, &[xi1_slave_press()]); grab_keyboard_device(f, A, DEVICEID_XTEST_POINTER, ROOT, true, XI_BUTTON_PRESS); } -const P27: Row = Row { - name: "p27_xi1_slave_grab_filter_agrees_with_the_xi2_route", - setup: setup_p27, - drive: press(XTEST_SLAVE), - deny: &[(A, XI1_PRESS_CALL, CHILD)], - denied_grab: None, - moved: &[Moved { - client: A, - window: ROOT, - child: FOCUS, - event: POINTER, - }], - allow: Expect { - frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[(A, XI1_PRESS_CALL, CHILD)], - }, - denied: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], - calls: &[(A, XI1_PRESS_CALL, CHILD), (A, CallKind::Xi2, ROOT)], - }, -}; - -/// An XIGrabDevice on the slave with `owner_events` and ButtonPress in its -/// mask; A selects the XI1 press on C. A's XI1 copy denied: the XI2 route -/// falls back to the grab window and the XI1 selection path delivers nothing -/// to A (one XI1 call, one XI2 grab-window call). Mutation: the filter is -/// selection-only (A also gets the XI1 copy at C: double delivery), or the -/// router asks again. -#[test] -fn p27_xi1_slave_grab_filter_agrees_with_the_xi2_route() { - check_row(&P27); -} - -/// Drains every client and appends the frames the walks write. -fn collect_frames(f: &mut NotifyFixture, frames: &mut Vec<(u32, Kind, u32)>) { - for id in [SEND_CLIENT, A, B] { - let order = f.state.clients[&id].byte_order; - let bytes = f.drain(ClientId(id)); - for frame in split_frames(&bytes, order) { - if let Some((kind, window)) = decode(frame, order) { - frames.push((id, kind, window)); - } - } - } -} - fn setup_p27_later_window(f: &mut NotifyFixture) { tree(f); select_xi1(f, B, CHILD, &[xi1_slave_press()]); @@ -2482,159 +677,1592 @@ fn setup_p27_later_window(f: &mut NotifyFixture) { grab_keyboard_device(f, A, DEVICEID_XTEST_POINTER, ROOT, true, XI_BUTTON_PRESS); } -/// B's foreign XI1 copy on C is denied, A's own is on P. Allow-all: B's copy -/// rejects the walk, A gets the XI2 grab-window copy. Denied: the route reaches -/// A's selector on P and the router writes it there, though a selection-only -/// walk would stop at B's selector on C and give A nothing. Mutation: the -/// router walks the selectors again without the memo. -const P27_LATER_WINDOW: Row = Row { - name: "p27_xi1_slave_grab_filter_writes_at_the_route_window", - setup: setup_p27_later_window, - drive: press(XTEST_SLAVE), - deny: &[(B, XI1_PRESS_CALL, CHILD)], - denied_grab: None, - moved: &[Moved { - client: A, - window: FOCUS, - child: CHILD, - event: P_EVENT, - }], - allow: Expect { - frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], - calls: &[(B, XI1_PRESS_CALL, CHILD), (A, CallKind::Xi2, ROOT)], - }, - denied: Expect { - frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], - calls: &[(B, XI1_PRESS_CALL, CHILD), (A, XI1_PRESS_CALL, FOCUS)], - }, -}; - -#[test] -fn p27_xi1_slave_grab_filter_writes_at_the_route_window() { - check_row(&P27_LATER_WINDOW); +/// A sync `GrabDeviceButton` by the requester on P, plus two XI1 press +/// selectors on C, of which B also selected the grab class. +fn setup_p28(f: &mut NotifyFixture) { + setup_p20(f); + xi1_passive_grab(f, SEND_CLIENT, FOCUS, true); } -/// What the thaw replay of p28 left: Receive calls and frames per client. -struct Replay { - calls: Vec<(u32, u32)>, - frames: Vec<(u32, Kind, u32)>, - grab: Vec, +// ---- calls and grab facts ------------------------------------------------ + +/// The Receive batch of an XI1 `DeviceButtonPress` copy. +const XI1_PRESS_CALL: CallKind = CallKind::Batch(&[Named::Xi1( + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET as u16, +)]); + +/// The Receive batch of an XI1 `DeviceMotionNotify` copy: the motion event and +/// its `DeviceValuator` continuation are one batch (`dix/eventconvert.c:369`). +const XI1_MOTION_CALL: CallKind = CallKind::Batch(&[ + Named::Xi1(crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET as u16), + Named::Xi1(crate::xinput::XI_DEVICE_VALUATOR_OFFSET as u16), +]); + +const RAW_BUTTON_PRESS_CALL: CallKind = CallKind::Batch(&[Named::Raw(15)]); +/// The scroll Motion of a wheel press: not the press's own event, so a batch. +const SCROLL_MOTION_CALL: CallKind = CallKind::Batch(&[Named::Xi2(6)]); +const STOP_BATCH: CallKind = CallKind::Batch(&[Named::Xi2(6), Named::Xi2(6)]); + +/// The grab fact of an implicit master pointer grab. +const fn implicit(owner: u32, window: u32, via_xi2: bool) -> Grab { + Grab::Pointer(PointerGrab { + owner, + window, + implicit: true, + passive: false, + via_xi2, + }) } -fn setup_p28(f: &mut NotifyFixture) { - tree(f); - select_xi1(f, A, CHILD, &[xi1_slave_press()]); - select_xi1( - f, - B, - CHILD, - &[xi1_slave_press(), xi1_grab_class(DEVICEID_XTEST_POINTER)], - ); - // A sync `GrabDeviceButton` by the requester on P, any button and modifier. - f.state - .xi1_passive_grabs - .push(crate::server::Xi1PassiveGrab { - owner: ClientId(SEND_CLIENT), - deviceid: DEVICEID_XTEST_POINTER, - grab_window: ResourceId(FOCUS), - detail: 0, - modifiers: 0x8000, - owner_events: false, - this_mode: 0, - other_mode: 1, - is_key: false, - }); +/// The grab fact of a passive master pointer grab by A. +const fn passive(window: u32, via_xi2: bool) -> Grab { + Grab::Pointer(PointerGrab { + owner: A, + window, + implicit: false, + passive: true, + via_xi2, + }) } -/// Runs p28: the press activates the sync grab and is stored, then the owner's -/// `AllowDeviceEvents(ReplayThisDevice)` re-routes it. `denied` denies B's XI1 -/// press copy at C. -fn replay_p28(denied: bool) -> Replay { - const XI_ALLOW_DEVICE_EVENTS_XI1: u8 = 19; - let mut f = NotifyFixture::new(); - setup_p28(&mut f); - for id in [SEND_CLIENT, A, B] { - f.drain(ClientId(id)); - } - let seen = f.install_policy(move |_, call| { - let hit = denied - && call.hook == ExtensionHook::Receive - && call.client.0 == B - && call.receive == Some(EventSubject::Window(ResourceId(CHILD))); - if hit { DENY } else { Decision::Allow } - }); - drive(&mut f, press(XTEST_SLAVE)); - let freeze = f - .state - .xi1_frozen - .get(&DEVICEID_XTEST_POINTER) - .expect("the sync grab froze the slave"); - assert_eq!(freeze.state, Xi1SyncState::FrozenWithEvent); - let activation_calls = seen.lock().unwrap().len(); - assert_eq!(activation_calls, 1, "the activating write: one fresh check"); - let mut frames = Vec::new(); - collect_frames(&mut f, &mut frames); - let mut body = Vec::new(); - body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime - body.extend_from_slice(&[2, DEVICEID_XTEST_POINTER as u8, 0, 0]); // ReplayThisDevice - send( - &mut f, - SEND_CLIENT, - XI_MAJOR, - XI_ALLOW_DEVICE_EVENTS_XI1, - &body, - ); - let calls = seen - .lock() - .unwrap() - .iter() - .filter(|call| call.hook == ExtensionHook::Receive) - .map(|call| { - let Some(EventSubject::Window(window)) = call.receive else { - panic!("Receive subject {:?}", call.receive); - }; - (call.client.0, window.0) - }) - .collect(); - collect_frames(&mut f, &mut frames); - Replay { - calls, - frames, - grab: grab_facts(&f.state), +const fn xi1_implicit(owner: u32, window: u32) -> Grab { + Grab::Xi1 { + device: DEVICEID_XTEST_POINTER, + owner, + window, } } -/// A sync `GrabDeviceButton` by the requester on P activates on the press and -/// stores it; its `AllowDeviceEvents(ReplayThisDevice)` re-routes the press -/// through the thaw with no decided delivery. Two XI1 press selectors on C; the -/// one that also selected the grab class (B) is denied: the other (A) owns the -/// XI1 implicit grab. Allow-all: B, the grab class holder. Mutation: the -/// implicit owner is chosen among the selectors (the denied B owns the grab), -/// or the replay walk is unchecked (B gets the copy). +/// The master pointer's freeze while a sync grab holds the activating press. +const FROZEN_BY_PRESS: Grab = Grab::Freeze { + device: DEVICEID_MASTER_POINTER, + state: Xi1SyncState::FrozenWithEvent, + other: None, + stored: Some(Held::HostPointer { + kind: PointerEventKind::ButtonPress, + detail: 1, + }), +}; + +/// A motion withheld behind the freeze, whole, or as its deferred master part. +const MOTION_QUEUED: Grab = Grab::Queued { + device: DEVICEID_MASTER_POINTER, + held: Held::HostPointer { + kind: PointerEventKind::MotionNotify, + detail: 0, + }, +}; +const MASTER_PART_QUEUED: Grab = Grab::Queued { + device: DEVICEID_MASTER_POINTER, + held: Held::HostPointerMaster { + kind: PointerEventKind::MotionNotify, + detail: 0, + scroll: None, + }, +}; + +/// A's slave XI2 implicit grab on C. +const SLAVE_GRAB: Grab = Grab::SlavePointer { + device: DEVICEID_XTEST_POINTER, + grab: PointerGrab { + owner: A, + window: CHILD, + implicit: true, + passive: false, + via_xi2: true, + }, +}; + +/// A selects core on C, XI2 (master) on P; B selects core on P. +const P5B_ALLOW: Outcome = Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], + calls: &[(A, CallKind::Xi2, FOCUS)], + ..NOTHING +}; +const P5B: Scenario = Scenario { + setup: setup_p5b, + steps: &[press(XTEST_MASTER)], + allow: P5B_ALLOW, + order: CallOrder::Total, +}; + +const P15_PRESS: Scenario = Scenario { + setup: setup_p15, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + grab: Some(&[implicit(A, CHILD, false)]), + ..NOTHING + }, + order: CallOrder::Total, +}; + +const P20B_ALLOW: Outcome = Outcome { + frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], + calls: &[(B, XI1_PRESS_CALL, FOCUS)], + grab: Some(&[xi1_implicit(B, FOCUS)]), + ..NOTHING +}; +const P20B: Scenario = Scenario { + setup: setup_p20b, + steps: &[press(XTEST_SLAVE)], + allow: P20B_ALLOW, + order: CallOrder::Total, +}; + +const P22_GRAB: Scenario = Scenario { + setup: setup_p22_grab, + steps: &[WHEEL_PRESS], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], + calls: &[(A, CallKind::Xi2, ROOT), (A, SCROLL_MOTION_CALL, ROOT)], + ..NOTHING + }, + order: CallOrder::Total, +}; + +const P26_OWNER_EVENTS: Scenario = Scenario { + setup: setup_p26_owner_events, + steps: &[press(XTEST_SLAVE)], + allow: Outcome { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + calls: &[(A, XI1_PRESS_CALL, CHILD)], + grab: Some(&[xi1_implicit(A, ROOT)]), + ..NOTHING + }, + order: CallOrder::Total, +}; +/// A denied on C and B allowed there: A gets the press at G, after one fresh +/// check, and keeps the explicit grab. +const P26_FALLS_TO_ROOT: Outcome = Outcome { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT)], + moved: &[moved( + A, + Kind::Xi1(DEVICEID_XTEST_POINTER), + ROOT, + FOCUS, + POINTER, + )], + calls: &[ + (A, XI1_PRESS_CALL, CHILD), + (B, XI1_PRESS_CALL, CHILD), + (A, XI1_PRESS_CALL, ROOT), + ], + grab: None, +}; + +/// The requester's sync grab on P holds the slave frozen with the routed press. +const P28_ACTIVATED: &[Grab] = &[ + xi1_implicit(SEND_CLIENT, FOCUS), + Grab::Freeze { + device: DEVICEID_XTEST_POINTER, + state: Xi1SyncState::FrozenWithEvent, + other: None, + stored: Some(Held::Xi1Routed { + evcode: crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET, + detail: 1, + }), + }, +]; + +const P28_PRESS: Scenario = Scenario { + setup: setup_p28, + steps: &[press(XTEST_SLAVE)], + allow: Outcome { + frames: &[(SEND_CLIENT, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], + calls: &[(SEND_CLIENT, XI1_PRESS_CALL, FOCUS)], + grab: Some(P28_ACTIVATED), + ..NOTHING + }, + order: CallOrder::PerClient, +}; + +// ---- rows ---------------------------------------------------------------- + +const ROWS: &[InputRow] = &[ + // A selects P, B selects C: B's denied copy does not stop the core walk. + // Mutation: the core walk stops at any window with a core selector, without + // asking Receive (selection-only stop). A then never sees the press. + InputRow { + name: "p1_denied_core_selector_does_not_stop_the_core_walk", + scenario: &Scenario { + setup: setup_p1, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(B, Kind::Core, CHILD)], + calls: &[(B, CallKind::Core, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(B, CallKind::Core, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Core, FOCUS)], + moved: &[moved(A, Kind::Core, FOCUS, CHILD, P_EVENT)], + calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + grab: Some(&[implicit(A, FOCUS, false)]), + }, + }, + // Mutation: an XI2 selection absorbs the walk whether or not its copy is + // allowed (selection-only absorption), or the denied XI2 copy is checked twice. + InputRow { + name: "p2_denied_xi2_selector_does_not_absorb_core", + scenario: &Scenario { + setup: setup_p2, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(B, CallKind::Xi2, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(B, CallKind::Xi2, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Core, FOCUS)], + moved: &[moved(A, Kind::Core, FOCUS, CHILD, P_EVENT)], + calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Core, FOCUS)], + grab: Some(&[implicit(A, FOCUS, false)]), + }, + }, + // Mutation: the XI2 route window is the first window with a selection rather + // than the first with an allowed one, so the denied copy at C ends the walk. + InputRow { + name: "p3_xi2_walk_skips_a_denied_window", + scenario: &Scenario { + setup: setup_p3, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(B, CallKind::Xi2, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(B, CallKind::Xi2, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], + moved: &[moved( + A, + Kind::Xi2(DEVICEID_MASTER_POINTER), + FOCUS, + CHILD, + P_EVENT, + )], + calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], + grab: Some(&[implicit(A, FOCUS, true)]), + }, + }, + // B's slave and master forms at C come from one check. Denied: B gets + // neither, and A's master form at P is the only copy. + // Mutation: the slave and master forms each ask Receive (two calls for B), + // or the master form is checked at the slave pass's window. + InputRow { + name: "p4_slave_and_master_forms_share_one_check", + scenario: &Scenario { + setup: setup_p4, + steps: &[motion(XTEST_SLAVE)], + allow: Outcome { + frames: &[ + (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), + (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + calls: &[(B, CallKind::Xi2, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(B, CallKind::Xi2, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], + moved: &[moved( + A, + Kind::Xi2(DEVICEID_MASTER_POINTER), + FOCUS, + CHILD, + MOTION_EVENT_AT_P, + )], + calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], + grab: None, + }, + }, + // A slave motion moves the sprite from P into C. B selects the slave form on C + // only, so the slave form (routed from P) has no recipient and B gets nothing, + // in every mode. The route from the live target C writes no slave copy, so it + // asks nothing. + // Mutation: the slave form's route from the live target (not the earlier + // window) goes through the memo (`slave_form_checked` there), so B's selection + // on C is asked although no copy of it is ever written. + InputRow { + name: "p4b_no_check_for_the_slave_route_from_the_live_target", + scenario: &Scenario { + setup: setup_p4b, + steps: &[motion(XTEST_SLAVE)], + allow: NOTHING, + order: CallOrder::Total, + }, + deny: &[(B, CallKind::Xi2, CHILD)], + denied: NOTHING, + }, + // B's slave press copy (routed by the slave press route) and its master copy + // at C share the one check the master route made. Denied: neither form is + // written, and the one call is not repeated. + // Mutation: the slave press copy (not a grab attempt) takes a fresh + // `receive_allows` instead of the dispatch memo, so B is asked twice. + InputRow { + name: "p4c_slave_press_and_master_forms_share_one_check", + scenario: &Scenario { + setup: setup_p4c, + steps: &[press(XTEST_SLAVE)], + allow: Outcome { + frames: &[ + (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), + (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + calls: &[(B, CallKind::Xi2, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(B, CallKind::Xi2, CHILD)], + denied: Outcome { + calls: &[(B, CallKind::Xi2, CHILD)], + grab: Some(&[]), + ..NOTHING + }, + }, + // A's master XI2 copy shadows its core copy at C. Denied: A's XI2 copy is + // refused, so its core copy at C is delivered. + // Mutation: A's core copy is shadowed by its XI2 selection, not by the copy + // that is allowed, so the denied XI2 still hides the core copy at C. + InputRow { + name: "p5_denied_xi2_reopens_that_clients_core", + scenario: &Scenario { + setup: setup_p5, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Core, CHILD)], + moved: &[moved(A, Kind::Core, CHILD, 0, C_EVENT)], + calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], + grab: Some(&[implicit(A, CHILD, false)]), + }, + }, + // Denying A's core copy at C changes nothing: a shadowed core copy is not + // checked, and the walk stops at C as it does with allow-all. + // Mutation: a shadowed core copy is still checked before the walk stops. + InputRow { + name: "p5b_shadow_follows_the_master_copy_anywhere_core_denied", + scenario: &P5B, + deny: &[(A, CallKind::Core, CHILD)], + denied: P5B.allow, + }, + // Denying A's master XI2 copy at P reopens A's core copy at C, and the walk + // stops there, so B at P gets nothing. + // Mutation: a shadow that only applies at the same window (the core copy at C + // is checked and then deduplicated). + InputRow { + name: "p5b_shadow_follows_the_master_copy_anywhere", + scenario: &P5B, + deny: &[(A, CallKind::Xi2, FOCUS)], + denied: Outcome { + frames: &[(A, Kind::Core, CHILD)], + moved: &[moved(A, Kind::Core, CHILD, 0, C_EVENT)], + calls: &[(A, CallKind::Xi2, FOCUS), (A, CallKind::Core, CHILD)], + grab: Some(&[implicit(A, CHILD, false)]), + }, + }, + // Denied: the master route is P (A's master copy), so A's core copy at C is + // shadowed and A gets its slave and master forms at P, with no core copy. + // Mutation: the shadow uses the selection-only master route, which ends at C + // (B's selection); A then keeps its core copy at C and gets no XI2 at P. + InputRow { + name: "p5c_shadow_uses_the_allowed_master_route", + scenario: &Scenario { + setup: setup_p5c, + steps: &[motion(XTEST_SLAVE)], + allow: Outcome { + frames: &[ + (A, Kind::Xi2(DEVICEID_XTEST_POINTER), FOCUS), + (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(B, CallKind::Xi2, CHILD)], + denied: Outcome { + frames: &[ + (A, Kind::Xi2(DEVICEID_XTEST_POINTER), FOCUS), + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS), + ], + moved: &[moved( + A, + Kind::Xi2(DEVICEID_MASTER_POINTER), + FOCUS, + CHILD, + MOTION_EVENT_AT_P, + )], + calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], + grab: None, + }, + }, + // A slave press: A's core copy is deferred behind the slave pass. Denying it + // drops that copy at admission, after the slave XI2 copy was written. + // Mutation: the deferred core copy is checked again at the flush (two calls), + // or never checked (the copy is written with no call). + InputRow { + name: "p6_deferred_core_copy_is_checked_at_admission", + scenario: &Scenario { + setup: setup_p6, + steps: &[press(XTEST_SLAVE)], + allow: Outcome { + frames: &[ + (A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), + (A, Kind::Core, CHILD), + ], + calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Xi2, CHILD)], + grab: Some(&[implicit(A, CHILD, false), SLAVE_GRAB]), + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD)], + calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Xi2, CHILD)], + grab: Some(&[SLAVE_GRAB]), + ..NOTHING + }, + }, + // Guard: a master form that is not written asks nothing, so denying B's copy + // changes nothing. Passes today. + InputRow { + name: "p7_no_check_for_a_form_not_emitted", + scenario: &Scenario { + setup: setup_p7, + steps: &[press(XTEST_SLAVE)], + allow: NOTHING, + order: CallOrder::Total, + }, + deny: &[(B, CallKind::Xi2, CHILD)], + denied: Outcome { + grab: Some(&[]), + ..NOTHING + }, + }, + // Mutation: the owner qualifies by selection (the route returns C although the + // copy there is denied, so nothing is written), or the natural core write asks + // again (a second call for A at C when allowed). + InputRow { + name: "p8_denied_owner_copy_continues_the_natural_walk", + scenario: &Scenario { + setup: setup_p8, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Core, FOCUS)], + moved: &[moved(A, Kind::Core, FOCUS, CHILD, P_EVENT)], + calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + grab: None, + }, + }, + // Mutation: the denied owner keeps walking (or is dropped) although an allowed + // foreign selector rejects the walk, so the grab window gets no copy. + InputRow { + name: "p9_denied_owner_with_allowed_foreign_falls_back", + scenario: &Scenario { + setup: setup_p9, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Core, ROOT)], + moved: &[moved(A, Kind::Core, ROOT, FOCUS, POINTER)], + calls: &[ + (A, CallKind::Xi2, CHILD), + (B, CallKind::Core, CHILD), + (A, CallKind::Core, ROOT), + ], + grab: None, + }, + }, + // Mutation: the core fallback takes the memo's result for (A, G, core) + // instead of a fresh check (this row then has one call for A, not two). + InputRow { + name: "p9_denied_owner_with_allowed_foreign_falls_back_core_same_window", + scenario: &Scenario { + setup: setup_p9_core_same_window, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, CHILD)], + denied: Outcome { + calls: &[ + (A, CallKind::Core, CHILD), + (B, CallKind::Xi2, CHILD), + (A, CallKind::Core, CHILD), + ], + ..NOTHING + }, + }, + // Mutation: a foreign selector rejects the walk by selection (the denied + // selector at C sends A to the grab window instead of on to P). + InputRow { + name: "p10_denied_foreign_selector_does_not_reject", + scenario: &Scenario { + setup: setup_p10, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, ROOT)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(B, CallKind::Core, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Core, FOCUS)], + moved: &[moved(A, Kind::Core, FOCUS, CHILD, P_EVENT)], + calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + grab: None, + }, + }, + // Mutation: the foreign selectors are evaluated before the owner (an extra + // call for B when A qualifies), B's master XI2 copy is asked under the + // grab-owned master form (a call for B in the allowed run), or the owner + // qualifies only through the first protocol it selected. + InputRow { + name: "p11_owner_qualifies_in_a_later_protocol", + scenario: &Scenario { + setup: setup_p11, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Core, ROOT)], + moved: &[moved(A, Kind::Core, ROOT, FOCUS, POINTER)], + calls: &[ + (A, CallKind::Core, CHILD), + (B, CallKind::Xi2, CHILD), + (A, CallKind::Core, ROOT), + ], + grab: None, + }, + }, + InputRow { + name: "p11_owner_qualifies_in_a_later_protocol_own_protocols", + scenario: &Scenario { + setup: setup_p11_own_protocols, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Core, CHILD)], + moved: &[moved(A, Kind::Core, CHILD, 0, C_EVENT)], + calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], + grab: None, + }, + }, + // A denial at the grab window is a delivery: C's selectors get nothing. + // Mutation: the denial is not a delivery (C's selectors get the press). + InputRow { + name: "p12_grab_window_denial_counts_as_delivered", + scenario: &Scenario { + setup: setup_p12, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(A, CallKind::Core, ROOT)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, ROOT)], + denied: Outcome { + calls: &[(A, CallKind::Core, ROOT)], + ..NOTHING + }, + }, + // Mutation: the check moves behind the grab mask (no call here). + InputRow { + name: "p12_grab_window_denial_counts_as_delivered_mask", + scenario: &Scenario { + setup: setup_p12_mask, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + calls: &[(A, CallKind::Core, ROOT)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, ROOT)], + denied: Outcome { + calls: &[(A, CallKind::Core, ROOT)], + ..NOTHING + }, + }, + // Mutation: the XI2 grab asks B's selector (a call for B). + InputRow { + name: "p12_grab_window_denial_counts_as_delivered_xi2", + scenario: &Scenario { + setup: setup_p12_xi2, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], + calls: &[(A, CallKind::Xi2, ROOT)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Xi2, ROOT)], + denied: Outcome { + calls: &[(A, CallKind::Xi2, ROOT)], + ..NOTHING + }, + }, + // Mutation: the XI2 owner qualifies by selection (nothing is written at C), + // or the natural XI2 write asks again (two calls for A at C when allowed). + InputRow { + name: "p13_xi2_owner_events_fallback_is_fresh", + scenario: &Scenario { + setup: setup_p13, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], + moved: &[moved( + A, + Kind::Xi2(DEVICEID_MASTER_POINTER), + ROOT, + FOCUS, + POINTER, + )], + calls: &[ + (A, CallKind::Xi2, CHILD), + (B, CallKind::Xi2, CHILD), + (A, CallKind::Xi2, ROOT), + ], + grab: None, + }, + }, + // Mutation: the fallback reuses the memo for G (one call for A at C here). + InputRow { + name: "p13_xi2_owner_events_fallback_is_fresh_same_window", + scenario: &Scenario { + setup: setup_p13_same_window, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: Outcome { + calls: &[ + (A, CallKind::Xi2, CHILD), + (B, CallKind::Xi2, CHILD), + (A, CallKind::Xi2, CHILD), + ], + ..NOTHING + }, + }, + // A sync `GrabButton` on G: the activating press is denied to its owner, and + // the grab still activates, freezes and stores the press; the next motion is + // queued behind the freeze. + // Mutation (all p14 rows): the denial skips the activation, the freeze or the + // stored press (a `delivered` gate on the freeze), or a second owner call is + // made, or the unchecked owner write under `xi2_grab_delivery` delivers the + // denied copy. + InputRow { + name: "p14_denied_activating_press_still_activates_and_freezes@press", + scenario: &Scenario { + setup: setup_p14_core, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(A, CallKind::Core, ROOT)], + grab: Some(&[passive(ROOT, false), FROZEN_BY_PRESS]), + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, ROOT)], + denied: Outcome { + calls: &[(A, CallKind::Core, ROOT)], + ..NOTHING + }, + }, + InputRow { + name: "p14_denied_activating_press_still_activates_and_freezes", + scenario: &Scenario { + setup: setup_p14_core, + steps: &[press(XTEST_MASTER), motion(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(A, CallKind::Core, ROOT)], + grab: Some(&[passive(ROOT, false), FROZEN_BY_PRESS, MOTION_QUEUED]), + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, ROOT)], + denied: Outcome { + calls: &[(A, CallKind::Core, ROOT)], + ..NOTHING + }, + }, + // A sync `XIPassiveGrabDevice` on the master from an attached slave origin: + // A's copy on G is denied, nobody else gets the press, and the grab still + // freezes with the press stored. The next motion delivers its slave part and + // defers the master part behind the freeze; thawing runs the master part, + // which is the one attempt, asked once. + // Mutation: the XI2 master block asks for the grab window without the + // emitted-form gate (a phantom call after the motion, and a second one at + // the thaw). + InputRow { + name: "p14_denied_xi2_activating_press_still_freezes_from_a_slave_origin@press", + scenario: &Scenario { + setup: setup_p14_xi2_master_from_slave, + steps: &[press(XTEST_SLAVE)], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], + calls: &[(A, CallKind::Xi2, ROOT)], + grab: Some(&[passive(ROOT, true), FROZEN_BY_PRESS]), + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Xi2, ROOT)], + denied: Outcome { + calls: &[(A, CallKind::Xi2, ROOT)], + ..NOTHING + }, + }, + InputRow { + name: "p14_denied_xi2_activating_press_still_freezes_from_a_slave_origin@motion", + scenario: &Scenario { + setup: setup_p14_xi2_master_from_slave, + steps: &[press(XTEST_SLAVE), motion(XTEST_SLAVE)], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], + calls: &[(A, CallKind::Xi2, ROOT)], + grab: Some(&[passive(ROOT, true), FROZEN_BY_PRESS, MASTER_PART_QUEUED]), + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Xi2, ROOT)], + denied: Outcome { + calls: &[(A, CallKind::Xi2, ROOT)], + ..NOTHING + }, + }, + InputRow { + name: "p14_denied_xi2_activating_press_still_freezes_from_a_slave_origin", + scenario: &Scenario { + setup: setup_p14_xi2_master_from_slave, + steps: &[ + press(XTEST_SLAVE), + motion(XTEST_SLAVE), + Step::Request(thaw_master), + ], + allow: Outcome { + frames: &[ + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT), + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT), + ], + calls: &[(A, CallKind::Xi2, ROOT), (A, CallKind::Xi2, ROOT)], + grab: Some(&[passive(ROOT, true)]), + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Xi2, ROOT)], + denied: Outcome { + calls: &[(A, CallKind::Xi2, ROOT), (A, CallKind::Xi2, ROOT)], + ..NOTHING + }, + }, + // The same grab from a master origin (`xi2_grab_delivery`): A also selects the + // master XI2 press on C, which is the window its copy is routed to. Denying + // that copy writes nothing, asks once, and still freezes with the press stored. + InputRow { + name: "p14_denied_xi2_activating_press_from_a_master_origin_still_freezes@press", + scenario: &Scenario { + setup: setup_p14_xi2_master_origin, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + grab: Some(&[passive(ROOT, true), FROZEN_BY_PRESS]), + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: Outcome { + calls: &[(A, CallKind::Xi2, CHILD)], + ..NOTHING + }, + }, + InputRow { + name: "p14_denied_xi2_activating_press_from_a_master_origin_still_freezes", + scenario: &Scenario { + setup: setup_p14_xi2_master_origin, + steps: &[press(XTEST_MASTER), motion(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + grab: Some(&[passive(ROOT, true), FROZEN_BY_PRESS, MOTION_QUEUED]), + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: Outcome { + calls: &[(A, CallKind::Xi2, CHILD)], + ..NOTHING + }, + }, + // The same sync master grab with owner_events, and A selecting the master XI2 + // motion on C: the follow-up slave motion defers its master part, so the + // route that would ask A@C for that copy must not ask yet. + // Mutation: the master block's route takes the memo although the master form + // is not emitted in this dispatch (a phantom A@C call). + InputRow { + name: "p14_deferred_master_part_asks_nothing_in_the_route@press", + scenario: &Scenario { + setup: setup_p14_owner_events_from_slave, + steps: &[press(XTEST_SLAVE)], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], + calls: &[(A, CallKind::Xi2, ROOT)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Xi2, ROOT)], + denied: Outcome { + calls: &[(A, CallKind::Xi2, ROOT)], + ..NOTHING + }, + }, + InputRow { + name: "p14_deferred_master_part_asks_nothing_in_the_route", + scenario: &Scenario { + setup: setup_p14_owner_events_from_slave, + steps: &[press(XTEST_SLAVE), motion(XTEST_SLAVE)], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], + calls: &[(A, CallKind::Xi2, ROOT)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Xi2, ROOT)], + denied: Outcome { + calls: &[(A, CallKind::Xi2, ROOT)], + ..NOTHING + }, + }, + // The activation dispatch writes only the press, on G, so the XI2 route asks + // nothing about A's core copy at C and a denial there changes nothing. + // Mutation: the XI2 block's route asks the core leg in an activation dispatch + // (`core_checked` true): the denied run then has an A@C core call and walks + // on to an XI2 press at P. + InputRow { + name: "activation_route_asks_no_core_copy", + scenario: &Scenario { + setup: setup_activation_owner_events, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(A, CallKind::Core, ROOT)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(A, CallKind::Core, ROOT)], + ..NOTHING + }, + }, + // A denied on C: B on P gets the press and owns the implicit grab. + // Mutation (the core candidate): the candidate is any walk recipient, denied + // or not, so A owns the grab and the release goes to A at C. + InputRow { + name: "p15_denied_candidate_is_not_the_implicit_owner@press", + scenario: &P15_PRESS, + deny: &[(A, CallKind::Core, CHILD)], + denied: Outcome { + frames: &[(B, Kind::Core, FOCUS)], + moved: &[moved(B, Kind::Core, FOCUS, CHILD, P_EVENT)], + calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, FOCUS)], + grab: Some(&[implicit(B, FOCUS, false)]), + }, + }, + // The release, with the pointer still over C, goes to B at P. + InputRow { + name: "p15_denied_candidate_is_not_the_implicit_owner", + scenario: &Scenario { + steps: &[press(XTEST_MASTER), release(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Core, CHILD), (A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, CHILD)], + grab: Some(&[]), + ..NOTHING + }, + ..P15_PRESS + }, + deny: &[(A, CallKind::Core, CHILD)], + denied: Outcome { + frames: &[(B, Kind::Core, FOCUS), (B, Kind::Core, FOCUS)], + moved: &[ + moved(B, Kind::Core, FOCUS, CHILD, P_EVENT), + moved(B, Kind::Core, FOCUS, CHILD, P_EVENT), + ], + calls: &[ + (A, CallKind::Core, CHILD), + (B, CallKind::Core, FOCUS), + (B, CallKind::Core, FOCUS), + ], + grab: None, + }, + }, + // A alone on C, denied: nobody receives the press and no pointer grab is + // active afterwards. + // Mutation (the core candidate): the denied recipient still qualifies, so A + // owns an implicit grab it never received a press for. + InputRow { + name: "p16_all_denied_no_implicit_grab", + scenario: &Scenario { + setup: setup_p16, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + grab: Some(&[implicit(A, CHILD, false)]), + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, CHILD)], + denied: Outcome { + calls: &[(A, CallKind::Core, CHILD)], + grab: Some(&[]), + ..NOTHING + }, + }, + // Both select the master pointer's XI2 press on C; A is the window's owner and + // wins with allow-all, and with A denied B owns the grab. + // Mutation (the XI2 candidate): a denied copy still enters the owner preference. + InputRow { + name: "p17_xi2_owner_preference_among_allowed", + scenario: &Scenario { + setup: setup_p17, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[ + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + calls: &[(A, CallKind::Xi2, CHILD), (B, CallKind::Xi2, CHILD)], + grab: Some(&[implicit(A, CHILD, true)]), + ..NOTHING + }, + order: CallOrder::PerClient, + }, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: Outcome { + frames: &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD), (B, CallKind::Xi2, CHILD)], + grab: Some(&[implicit(B, CHILD, true)]), + ..NOTHING + }, + }, + // Slave origin; A selects the slave's XI2 press on C, B its XI1 press on C. A + // denied: B gets the XI1 form at C and owns the XI1 implicit grab, with one + // call. + // Mutation: the protocol is chosen by selection (the XI2 selector wins + // though denied: B gets nothing); or the XI1 copy is checked a second time. + InputRow { + name: "p18_denied_slave_xi2_falls_to_xi1", + scenario: &Scenario { + setup: setup_p18, + steps: &[press(XTEST_SLAVE)], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + grab: Some(&[SLAVE_GRAB]), + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: Outcome { + frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + moved: &[moved( + B, + Kind::Xi1(DEVICEID_XTEST_POINTER), + CHILD, + 0, + C_EVENT, + )], + calls: &[(A, CallKind::Xi2, CHILD), (B, XI1_PRESS_CALL, CHILD)], + grab: Some(&[xi1_implicit(B, CHILD)]), + }, + }, + // A's XI1 press selector on C is denied, B's on P is not: the walk continues + // and B gets the press at P. + // Mutation: a denied XI1 selector stops the walk (selection decides the + // window), so B gets nothing. + InputRow { + name: "p19_denied_xi1_press_continues", + scenario: &Scenario { + setup: setup_p19, + steps: &[press(XTEST_SLAVE)], + allow: Outcome { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + calls: &[(A, XI1_PRESS_CALL, CHILD)], + grab: Some(&[xi1_implicit(A, CHILD)]), + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, XI1_PRESS_CALL, CHILD)], + denied: Outcome { + frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], + moved: &[moved( + B, + Kind::Xi1(DEVICEID_XTEST_POINTER), + FOCUS, + CHILD, + P_EVENT, + )], + calls: &[(A, XI1_PRESS_CALL, CHILD), (B, XI1_PRESS_CALL, FOCUS)], + grab: Some(&[xi1_implicit(B, FOCUS)]), + }, + }, + // Two XI1 press selectors on C, the one that also selected the button grab + // class is denied: the other owns the XI1 implicit grab (allow-all: the grab + // class holder). + // Mutation: the owner is chosen among the selectors, not among the allowed + // recipients, so the denied B owns the grab. + InputRow { + name: "p20_xi1_implicit_owner_from_allowed", + scenario: &Scenario { + setup: setup_p20, + steps: &[press(XTEST_SLAVE)], + allow: Outcome { + frames: &[ + (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + (B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + ], + calls: &[(A, XI1_PRESS_CALL, CHILD), (B, XI1_PRESS_CALL, CHILD)], + grab: Some(&[xi1_implicit(B, CHILD)]), + ..NOTHING + }, + order: CallOrder::PerClient, + }, + deny: &[(B, XI1_PRESS_CALL, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + calls: &[(A, XI1_PRESS_CALL, CHILD), (B, XI1_PRESS_CALL, CHILD)], + grab: Some(&[xi1_implicit(A, CHILD)]), + ..NOTHING + }, + }, + // An XI1 passive grab takes the slave press, so the router never reaches the + // selection walk: A's selector copy is not written and Receive is not asked + // (the activating write is the grab owner's one fresh check). + // Mutation: the route asks the XI1 selectors although a passive grab matches + // (`xi1_routed` ignores it). + InputRow { + name: "p20b_xi1_passive_activation_asks_no_selector", + scenario: &P20B, + deny: &[(A, XI1_PRESS_CALL, CHILD)], + denied: P20B.allow, + }, + // With the owner denied the grab still activates and nobody gets the press. + // Mutation: the activating write is unchecked. + InputRow { + name: "p20b_xi1_passive_activation_owner_denied", + scenario: &P20B, + deny: &[(B, XI1_PRESS_CALL, FOCUS)], + denied: Outcome { + calls: &[(B, XI1_PRESS_CALL, FOCUS)], + ..NOTHING + }, + }, + // A selects the slave's XI2 press on the root, B its XI1 press, and the press + // is over the bare root: no XI2 copy is written, so Receive is not asked for + // A's, and a denial must not hand the press to B (nor give B an XI1 grab). + // Mutation: the XI2 leg is asked without the top-level condition. + InputRow { + name: "i1a_bare_root_slave_xi2_is_not_asked", + scenario: &Scenario { + setup: setup_i1a, + steps: &[button( + XTEST_SLAVE, + PointerEventKind::ButtonPress, + BARE_ROOT, + )], + allow: NOTHING, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Xi2, ROOT)], + denied: NOTHING, + }, + // Only XI1 selectors on the root, the press over the bare root: the router + // writes the XI1 form, so each selector is asked once and the denied one gets + // nothing. + // Mutation: the XI1 check is gated on the XI2 flag (here false). + InputRow { + name: "i1b_bare_root_xi1_selectors_are_checked", + scenario: &Scenario { + setup: setup_i1b, + steps: &[button( + XTEST_SLAVE, + PointerEventKind::ButtonPress, + BARE_ROOT, + )], + allow: Outcome { + frames: &[ + (A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT), + (B, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT), + ], + calls: &[(A, XI1_PRESS_CALL, ROOT), (B, XI1_PRESS_CALL, ROOT)], + ..NOTHING + }, + order: CallOrder::PerClient, + }, + deny: &[(A, XI1_PRESS_CALL, ROOT)], + denied: Outcome { + frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT)], + calls: &[(A, XI1_PRESS_CALL, ROOT), (B, XI1_PRESS_CALL, ROOT)], + grab: Some(&[xi1_implicit(B, ROOT)]), + ..NOTHING + }, + }, + // A and B select the master raw press on the root, the requester the slave's; + // A is denied: only A's copy goes, B and the requester keep theirs. + // Mutation: the raw copies are written unchecked (every denied-run assertion + // fails), or a denial stops the raw fanout (B or the requester lose theirs). + InputRow { + name: "p21_denied_raw_root_copy_drops_only_that_copy", + scenario: &Scenario { + setup: setup_p21, + steps: &[press(XTEST_SLAVE)], + allow: Outcome { + frames: &[ + (SEND_CLIENT, Kind::Raw(DEVICEID_XTEST_POINTER), ROOT), + (A, Kind::Raw(DEVICEID_MASTER_POINTER), ROOT), + (B, Kind::Raw(DEVICEID_MASTER_POINTER), ROOT), + ], + calls: &[ + (SEND_CLIENT, RAW_BUTTON_PRESS_CALL, ROOT), + (A, RAW_BUTTON_PRESS_CALL, ROOT), + (B, RAW_BUTTON_PRESS_CALL, ROOT), + ], + ..NOTHING + }, + order: CallOrder::PerClient, + }, + deny: &[(A, RAW_BUTTON_PRESS_CALL, ROOT)], + denied: Outcome { + frames: &[ + (SEND_CLIENT, Kind::Raw(DEVICEID_XTEST_POINTER), ROOT), + (B, Kind::Raw(DEVICEID_MASTER_POINTER), ROOT), + ], + calls: &[ + (SEND_CLIENT, RAW_BUTTON_PRESS_CALL, ROOT), + (A, RAW_BUTTON_PRESS_CALL, ROOT), + (B, RAW_BUTTON_PRESS_CALL, ROOT), + ], + ..NOTHING + }, + }, + // The scroll Motion of a wheel press follows the ordinary walk: A's denied + // copy on C does not stop it, and B at P gets the Motion. + // Mutation: the scroll Motion routes by selection only (the denied row then + // writes nothing for B and asks nothing of B), or is written unchecked. + InputRow { + name: "p22_scroll_motion_follows_the_walk", + scenario: &Scenario { + setup: setup_scroll_walk, + steps: &[WHEEL_PRESS], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, SCROLL_MOTION_CALL, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, SCROLL_MOTION_CALL, CHILD)], + denied: Outcome { + frames: &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], + moved: &[moved( + B, + Kind::Xi2(DEVICEID_MASTER_POINTER), + FOCUS, + CHILD, + P_EVENT, + )], + calls: &[ + (A, SCROLL_MOTION_CALL, CHILD), + (B, SCROLL_MOTION_CALL, FOCUS), + ], + grab: None, + }, + }, + // The stop routes from its own probe hit. A's denied batch on C drops A's two + // Motions and the walk does not resume (B at P gets nothing and is not + // asked); allowed, A gets both. + // Mutations: the stop routes through the memo (B gets it at P and is asked); + // one check per event (two calls for A). + InputRow { + name: "p23_scroll_stop_is_not_rerouted", + scenario: &Scenario { + setup: setup_scroll_walk, + steps: &[SCROLL_STOP], + allow: Outcome { + frames: &[ + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + calls: &[(A, STOP_BATCH, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, STOP_BATCH, CHILD)], + denied: Outcome { + calls: &[(A, STOP_BATCH, CHILD)], + ..NOTHING + }, + }, + // A client with both device forms on one window is asked once for both forms' + // four events. + // Mutation: one check per form (two calls here). + InputRow { + name: "p23_scroll_stop_is_not_rerouted_two_forms_denied", + scenario: &Scenario { + setup: setup_scroll_stop_two_forms, + steps: &[SCROLL_STOP], + allow: Outcome { + frames: &[ + (A, Kind::Xi2(PHYSICAL_DEVICE), CHILD), + (A, Kind::Xi2(PHYSICAL_DEVICE), CHILD), + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + calls: &[(A, STOP_BATCH, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, STOP_BATCH, CHILD)], + denied: Outcome { + calls: &[(A, STOP_BATCH, CHILD)], + ..NOTHING + }, + }, + // The scroll Motion of an XI2 grab with owner_events false is a grab-window + // copy of its own: one fresh check, whatever the press's check at that + // window said. Denying the press check leaves the Motion written. + // Mutation: the Motion reuses the press's grab-window result (this row then + // drops the Motion). + InputRow { + name: "p22_scroll_motion_grab_window_has_its_own_check_press_denied", + scenario: &P22_GRAB, + deny: &[(A, CallKind::Xi2, ROOT)], + denied: P22_GRAB.allow, + }, + // Denying the Motion check drops it. + // Mutation: the Motion is written unchecked (this row writes it). + InputRow { + name: "p22_scroll_motion_grab_window_has_its_own_check_motion_denied", + scenario: &P22_GRAB, + deny: &[(A, SCROLL_MOTION_CALL, ROOT)], + denied: Outcome { + calls: P22_GRAB.allow.calls, + ..NOTHING + }, + }, + // Slave motion over C: A selects XI1 `DeviceMotionNotify` on C, B on P. A's + // copy denied: the walk goes on and B gets it at P. + // Mutation: a denied XI1 selector stops the walk (selection decides the + // window), so B gets nothing. + InputRow { + name: "p24_denied_xi1_selector_advances_the_walk", + scenario: &Scenario { + setup: setup_p24, + steps: &[motion(XTEST_SLAVE)], + allow: Outcome { + frames: &[ + (A, Kind::Xi1Motion(DEVICEID_XTEST_POINTER), CHILD), + (A, Kind::Xi1Valuator(DEVICEID_XTEST_POINTER), 0), + ], + calls: &[(A, XI1_MOTION_CALL, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, XI1_MOTION_CALL, CHILD)], + denied: Outcome { + frames: &[ + (B, Kind::Xi1Motion(DEVICEID_XTEST_POINTER), FOCUS), + (B, Kind::Xi1Valuator(DEVICEID_XTEST_POINTER), 0), + ], + moved: &[moved( + B, + Kind::Xi1Motion(DEVICEID_XTEST_POINTER), + FOCUS, + CHILD, + MOTION_EVENT_AT_P, + )], + calls: &[(A, XI1_MOTION_CALL, CHILD), (B, XI1_MOTION_CALL, FOCUS)], + grab: None, + }, + }, + // The motion event and its valuator continuation are decided by one call with + // the two-description batch: denied writes neither frame. + // Mutation: the route or the write checks per event (two calls; the denied + // batch never matches either single-description call, so both frames are + // written). + InputRow { + name: "p25_device_motion_and_valuator_are_one_batch", + scenario: &Scenario { + setup: setup_p25, + steps: &[motion(XTEST_SLAVE)], + allow: Outcome { + frames: &[ + (A, Kind::Xi1Motion(DEVICEID_XTEST_POINTER), CHILD), + (A, Kind::Xi1Valuator(DEVICEID_XTEST_POINTER), 0), + ], + calls: &[(A, XI1_MOTION_CALL, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, XI1_MOTION_CALL, CHILD)], + denied: Outcome { + calls: &[(A, XI1_MOTION_CALL, CHILD)], + ..NOTHING + }, + }, + // Slave origin, XI1 `GrabDevice` by A on G with `owner_events`: with A's own + // copy on C allowed A gets it at C and the foreign selector B is not asked + // (the allow-all run). With A denied, B (allowed) sends the event to G: A + // gets one fresh check there. + // Mutations: the owner copy is not checked in the route (selection decides); + // the foreign selector is asked before the owner; the grab-window copy is + // written unchecked. + InputRow { + name: "p26_xi1_grab_owner_denied_falls_to_the_grab_window", + scenario: &P26_OWNER_EVENTS, + deny: &[(A, XI1_PRESS_CALL, CHILD)], + denied: P26_FALLS_TO_ROOT, + }, + // Without `owner_events` the natural walk is not checked at all: only A's + // copy at G, and a denial there is a delivery (the grab stays). + // Mutation: the natural walk is asked without `owner_events`. + InputRow { + name: "p26_xi1_grab_without_owner_events_asks_only_the_grab_window", + scenario: &Scenario { + setup: setup_p26_not_owner_events, + steps: &[press(XTEST_SLAVE)], + allow: Outcome { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT)], + calls: &[(A, XI1_PRESS_CALL, ROOT)], + grab: Some(&[xi1_implicit(A, ROOT)]), + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, XI1_PRESS_CALL, ROOT)], + denied: Outcome { + calls: &[(A, XI1_PRESS_CALL, ROOT)], + ..NOTHING + }, + }, + // O denied on C, F allowed on C: F's copy rejects the walk, so O does not + // reach its own selector on P: it gets the event at G. + InputRow { + name: "p26_xi1_grab_foreign_copy_rejects_the_walk", + scenario: &Scenario { + setup: setup_p26_foreign_rejects, + ..P26_OWNER_EVENTS + }, + deny: &[(A, XI1_PRESS_CALL, CHILD)], + denied: P26_FALLS_TO_ROOT, + }, + // An XIGrabDevice on the slave with `owner_events` and ButtonPress in its + // mask; A selects the XI1 press on C. A's XI1 copy denied: the XI2 route + // falls back to the grab window and the XI1 selection path delivers nothing + // to A (one XI1 call, one XI2 grab-window call). + // Mutation: the filter is selection-only (A also gets the XI1 copy at C: + // double delivery), or the router asks again. + InputRow { + name: "p27_xi1_slave_grab_filter_agrees_with_the_xi2_route", + scenario: &Scenario { + setup: setup_p27, + steps: &[press(XTEST_SLAVE)], + allow: Outcome { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + calls: &[(A, XI1_PRESS_CALL, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, XI1_PRESS_CALL, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], + moved: &[moved( + A, + Kind::Xi2(DEVICEID_XTEST_POINTER), + ROOT, + FOCUS, + POINTER, + )], + calls: &[(A, XI1_PRESS_CALL, CHILD), (A, CallKind::Xi2, ROOT)], + grab: None, + }, + }, + // B's foreign XI1 copy on C is denied, A's own is on P. Allow-all: B's copy + // rejects the walk, A gets the XI2 grab-window copy. Denied: the route reaches + // A's selector on P and the router writes it there, though a selection-only + // walk would stop at B's selector on C and give A nothing. + // Mutation: the router walks the selectors again without the memo. + InputRow { + name: "p27_xi1_slave_grab_filter_writes_at_the_route_window", + scenario: &Scenario { + setup: setup_p27_later_window, + steps: &[press(XTEST_SLAVE)], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], + calls: &[(B, XI1_PRESS_CALL, CHILD), (A, CallKind::Xi2, ROOT)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(B, XI1_PRESS_CALL, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], + moved: &[moved( + A, + Kind::Xi1(DEVICEID_XTEST_POINTER), + FOCUS, + CHILD, + P_EVENT, + )], + calls: &[(B, XI1_PRESS_CALL, CHILD), (A, XI1_PRESS_CALL, FOCUS)], + grab: None, + }, + }, + // A sync `GrabDeviceButton` by the requester on P activates on the press and + // stores it (the activating write is one fresh check). + InputRow { + name: "p28_thawed_xi1_press_picks_the_owner_from_allowed@press", + scenario: &P28_PRESS, + deny: &[(B, XI1_PRESS_CALL, CHILD)], + denied: P28_PRESS.allow, + }, + // Its `AllowDeviceEvents(ReplayThisDevice)` re-routes the press through the + // thaw with no decided delivery. Two XI1 press selectors on C; the one that + // also selected the grab class (B) is denied: the other (A) owns the XI1 + // implicit grab. Allow-all: B, the grab class holder. + // Mutation: the implicit owner is chosen among the selectors (the denied B + // owns the grab), or the replay walk is unchecked (B gets the copy). + InputRow { + name: "p28_thawed_xi1_press_picks_the_owner_from_allowed", + scenario: &Scenario { + steps: &[press(XTEST_SLAVE), Step::Request(replay_slave)], + allow: Outcome { + frames: &[ + (SEND_CLIENT, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS), + (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + (B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + ], + calls: &[ + (SEND_CLIENT, XI1_PRESS_CALL, FOCUS), + (A, XI1_PRESS_CALL, CHILD), + (B, XI1_PRESS_CALL, CHILD), + ], + grab: Some(&[xi1_implicit(B, CHILD)]), + ..NOTHING + }, + ..P28_PRESS + }, + deny: &[(B, XI1_PRESS_CALL, CHILD)], + denied: Outcome { + frames: &[ + (SEND_CLIENT, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS), + (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + ], + calls: &[ + (SEND_CLIENT, XI1_PRESS_CALL, FOCUS), + (A, XI1_PRESS_CALL, CHILD), + (B, XI1_PRESS_CALL, CHILD), + ], + grab: Some(&[xi1_implicit(A, CHILD)]), + ..NOTHING + }, + }, +]; + #[test] -fn p28_thawed_xi1_press_picks_the_owner_from_allowed() { - let xi1 = |client| (client, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD); - let owner = |client| { - vec![Grab::Xi1 { - device: DEVICEID_XTEST_POINTER, - owner: client, - window: CHILD, - }] - }; - let allow = replay_p28(false); - // The activating write first, then one call per selector (their order is - // the selection order, not part of the contract). - assert_eq!(allow.calls[0], (SEND_CLIENT, FOCUS)); - let mut replay_calls = allow.calls[1..].to_vec(); - replay_calls.sort_unstable(); - assert_eq!(replay_calls, vec![(A, CHILD), (B, CHILD)]); - assert!(allow.frames.contains(&xi1(A)) && allow.frames.contains(&xi1(B))); - assert_eq!(allow.grab, owner(B)); - let denied = replay_p28(true); - assert_eq!( - denied.calls, allow.calls, - "one call per recipient per attempt" - ); - assert!(denied.frames.contains(&xi1(A)) && !denied.frames.contains(&xi1(B))); - assert_eq!(denied.grab, owner(A)); +fn pointer_rows() { + check_rows(ROWS); } From af7d9934f095073ed38df791b6f340929b59f7a3 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 12:50:04 -0300 Subject: [PATCH 46/72] test(access): pointer table states the deferred master part, shares outcomes and setups - The two p14_deferred_master_part_asks_nothing_in_the_route rows state their grab, freeze and queue facts, including the queued HostPointerMaster the baseline asserted. - Rows dropped as duplicates, completing the list of 86b42cf3: the row p26_xi1_grab_owner_allowed_asks_no_foreign_selector (const P26_OWNER_ALLOWED, empty denial) is the allow-all run of p26_xi1_grab_owner_denied_falls_to_the_grab_window, which states the allow grab. - Both request steps (thaw_master, replay_slave) use `request`, so the runner collects what a step writes to its requester; ClientBytes.sequence is a local. - Size: p14 prefix scenarios built with `..PREFIX`, named consts for repeated outcomes, composed and const-generic setups, xi_grab_device replaces xi_grab_master_pointer, canonical_call is expected_call(call, 0), shared next_sequence. Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Sonnet 5.5 --- .../tests/access_input_support.rs | 41 +- .../process_request/tests/access_key_input.rs | 2 +- .../tests/access_pointer_input.rs | 446 +++++++----------- 3 files changed, 192 insertions(+), 297 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index 5a890e412..81f808cc1 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -214,16 +214,19 @@ impl Drive { // ---- request helpers ----------------------------------------------------- +/// Advances and returns the sequence number of `client`'s next request. +fn next_sequence(f: &NotifyFixture, client: u32) -> u16 { + let state = &f.state.clients[&client]; + let next = state.last_sequence.load(Ordering::Relaxed).wrapping_add(1); + state.last_sequence.store(next, Ordering::Relaxed); + next +} + /// Sends one request from `client` with the next sequence number of that /// client and checks it was handled with no writer failure. Nothing is drained: /// the bytes the request makes any client write stay queued. pub(super) fn request(f: &mut NotifyFixture, client: u32, opcode: u8, data: u8, body: &[u8]) { - let sequence = { - let state = &f.state.clients[&client]; - let next = state.last_sequence.load(Ordering::Relaxed).wrapping_add(1); - state.last_sequence.store(next, Ordering::Relaxed); - next - }; + let sequence = next_sequence(f, client); let header = RequestHeader { opcode, data, @@ -350,12 +353,7 @@ pub(super) fn set_detectable_repeat(f: &mut NotifyFixture, client: u32) { /// One XKB request through `handle_xkb_request`, with its reply drained. pub(super) fn xkb_request(f: &mut NotifyFixture, client: u32, opcode: u8, minor: u8, body: &[u8]) { - let sequence = { - let state = &f.state.clients[&client]; - let next = state.last_sequence.load(Ordering::Relaxed).wrapping_add(1); - state.last_sequence.store(next, Ordering::Relaxed); - next - }; + let sequence = next_sequence(f, client); crate::core_loop::process_request::xkb::handle_xkb_request( &mut f.state, &mut f.backend, @@ -376,7 +374,7 @@ pub(super) fn xkb_request(f: &mut NotifyFixture, client: u32, opcode: u8, minor: /// The slave keyboard's exact XI2 grab owned by `owner` on `grab_window`, made /// with XIGrabDevice (asynchronous, not owner-events, KeyPress mask). pub(super) fn grab_slave_keyboard(f: &mut NotifyFixture, owner: u32, grab_window: u32) { - grab_keyboard_device( + xi_grab_device( f, owner, DEVICEID_XTEST_KEYBOARD, @@ -389,7 +387,7 @@ pub(super) fn grab_slave_keyboard(f: &mut NotifyFixture, owner: u32, grab_window /// XIGrabDevice of `device` by `owner` on `grab_window` with the given /// owner_events and one mask word. A master keyboard grab is the /// `active_keyboard_grab` the raw master leg reads; a slave grab is per device. -pub(super) fn grab_keyboard_device( +pub(super) fn xi_grab_device( f: &mut NotifyFixture, owner: u32, device: u16, @@ -651,7 +649,6 @@ pub(super) fn decode(frame: &[u8], order: ClientByteOrder) -> Option<(Kind, u32) pub(super) struct ClientBytes { pub(super) client: u32, pub(super) order: ClientByteOrder, - pub(super) sequence: u16, pub(super) bytes: Vec, /// Per step: the byte length after it and the client's sequence then. pub(super) steps: Vec<(usize, u16)>, @@ -1017,7 +1014,6 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run .map(|client| ClientBytes { client, order: f.state.clients[&client].byte_order, - sequence: 0, bytes: Vec::new(), steps: Vec::new(), }) @@ -1031,10 +1027,10 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run } for client in &mut clients { client.bytes.extend(f.drain(ClientId(client.client))); - client.sequence = f.state.clients[&client.client] + let sequence = f.state.clients[&client.client] .last_sequence .load(Ordering::Relaxed); - client.steps.push((client.bytes.len(), client.sequence)); + client.steps.push((client.bytes.len(), sequence)); } if let Some(recorder) = &recorder { let total = recorder.lock().unwrap().len(); @@ -1164,14 +1160,7 @@ fn canonical_seen(call: &Seen, ev: u16) -> Seen { /// A row's expected call in the same form: a shorthand is the zeroed name. fn canonical_call(call: &Call) -> Seen { - let (client, kind, window) = *call; - let names = match kind { - CallKind::Core => vec![Named::Core(0)], - CallKind::Xi2 => vec![Named::Xi2(0)], - CallKind::Raw => vec![Named::Raw(0)], - CallKind::Batch(list) => list.to_vec(), - }; - (client, names, window) + expected_call(call, 0) } /// Compares a run's frames and Receive trace with a stated outcome. A shorthand diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs index dd5e1e5dd..892f8de68 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -224,7 +224,7 @@ fn setup_k14_without_raw_bit(f: &mut NotifyFixture) { fn setup_k14_with_mask(f: &mut NotifyFixture, mask: u32) { tree(f); set_focus_pointer_root(f); - grab_keyboard_device(f, A, DEVICEID_MASTER_KEYBOARD, CHILD, true, mask); + xi_grab_device(f, A, DEVICEID_MASTER_KEYBOARD, CHILD, true, mask); select_xi2(f, A, ROOT, DEVICEID_MASTER_KEYBOARD, XI_RAW_KEY_PRESS); } diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index eb5474f87..55a66f24a 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -174,24 +174,6 @@ fn grab_button(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: boo send(f, owner, CORE_GRAB_BUTTON, u8::from(owner_events), &body); } -/// `XIGrabDevice` of the master pointer by `owner` on `window`. -fn xi_grab_master_pointer( - f: &mut NotifyFixture, - owner: u32, - window: u32, - owner_events: bool, - mask: u32, -) { - grab_keyboard_device( - f, - owner, - DEVICEID_MASTER_POINTER, - window, - owner_events, - mask, - ); -} - /// `XIPassiveGrabDevice` of button 1 on the master pointer by A on `ROOT`, any /// modifier, with the XI2 event mask, synchronous. fn xi_passive_grab_master(f: &mut NotifyFixture, owner_events: bool, mask: u32) { @@ -244,8 +226,9 @@ fn xi1_passive_grab(f: &mut NotifyFixture, owner: u32, window: u32, sync: bool) /// The requests of the p14 and p28 step lists: `XIAllowEvents(AsyncDevice)` of /// the master pointer by A, and the XI1 `AllowDeviceEvents(ReplayThisDevice)` -/// of the slave by the requester. A thaw may write events to its requester, so -/// the first does not drain. +/// of the slave by the requester. Both use `request`, not `send`: a thaw may +/// write events to its own requester, and the runner, which drains after every +/// step, must see them rather than have the request helper swallow or reject them. fn thaw_master(f: &mut NotifyFixture) { let mut body = Vec::with_capacity(8); body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime @@ -258,7 +241,7 @@ fn replay_slave(f: &mut NotifyFixture) { let mut body = Vec::new(); body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime body.extend_from_slice(&[2, DEVICEID_XTEST_POINTER as u8, 0, 0]); // ReplayThisDevice - send(f, SEND_CLIENT, XI_MAJOR, XI_ALLOW_DEVICE_EVENTS_XI1, &body); + request(f, SEND_CLIENT, XI_MAJOR, XI_ALLOW_DEVICE_EVENTS_XI1, &body); } // ---- setups -------------------------------------------------------------- @@ -400,24 +383,17 @@ fn setup_p11(f: &mut NotifyFixture) { /// A selects the master XI2 press (denied) and the core press (allowed) on C: /// it qualifies through the later protocol. fn setup_p11_own_protocols(f: &mut NotifyFixture) { - tree(f); - select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); - select_core(f, A, CHILD, CORE_BUTTON_PRESS); + setup_p5(f); grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); } -fn setup_p12(f: &mut NotifyFixture) { - tree(f); - select_core(f, B, CHILD, CORE_BUTTON_PRESS); - grab_pointer(f, A, ROOT, false, CORE_BUTTON_PRESS); -} - -/// The grab mask lacks ButtonPress: no frame in any mode, but the check still -/// comes first, so the trace has the call at G. -fn setup_p12_mask(f: &mut NotifyFixture) { +/// B selects the core press on C; A grabs the pointer on G with `mask` +/// (without owner_events). With a mask lacking ButtonPress there is no frame in +/// any mode, but the check still comes first, so the trace has the call at G. +fn setup_p12(f: &mut NotifyFixture) { tree(f); select_core(f, B, CHILD, CORE_BUTTON_PRESS); - grab_pointer(f, A, ROOT, false, CORE_MOTION); + grab_pointer(f, A, ROOT, false, MASK); } /// An XI2 master grab with owner_events false: the grab-window copy is the @@ -425,23 +401,17 @@ fn setup_p12_mask(f: &mut NotifyFixture) { fn setup_p12_xi2(f: &mut NotifyFixture) { tree(f); select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); - xi_grab_master_pointer(f, A, ROOT, false, XI_BUTTON_PRESS); + xi_grab_device(f, A, DEVICEID_MASTER_POINTER, ROOT, false, XI_BUTTON_PRESS); } -fn setup_p13(f: &mut NotifyFixture) { +/// A and B select the master XI2 press on C; A grabs the master pointer with +/// owner_events on `GRAB`. With `GRAB` = C the fallback is a distinct attempt, +/// so A is asked a second time at C (and denied again), not served from the memo. +fn setup_p13(f: &mut NotifyFixture) { tree(f); select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); - xi_grab_master_pointer(f, A, ROOT, true, XI_BUTTON_PRESS); -} - -/// The grab window is C itself: the fallback is a distinct attempt, so A is -/// asked a second time at C (and denied again), not served from the memo. -fn setup_p13_same_window(f: &mut NotifyFixture) { - tree(f); - select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); - select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); - xi_grab_master_pointer(f, A, CHILD, true, XI_BUTTON_PRESS); + xi_grab_device(f, A, DEVICEID_MASTER_POINTER, GRAB, true, XI_BUTTON_PRESS); } /// A sync `GrabButton` on G. @@ -460,9 +430,8 @@ fn setup_p14_xi2_master_from_slave(f: &mut NotifyFixture) { /// The same grab, activated from a master origin (`xi2_grab_delivery`): A also /// selects the master XI2 press on C, which is the window its copy is routed to. fn setup_p14_xi2_master_origin(f: &mut NotifyFixture) { - tree(f); + setup_p14_xi2_master_from_slave(f); select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); - xi_passive_grab_master(f, false, XI_BUTTON_PRESS); } /// The same sync master grab with owner_events, and A selecting the master XI2 @@ -577,18 +546,20 @@ fn unhit_root(f: &mut NotifyFixture) { .map_state = crate::resources::MapState::Unmapped; } -fn setup_i1a(f: &mut NotifyFixture) { +fn bare_root_tree(f: &mut NotifyFixture) { tree(f); park_pointer_at(f, BARE_ROOT); unhit_root(f); +} + +fn setup_i1a(f: &mut NotifyFixture) { + bare_root_tree(f); select_xi2(f, A, ROOT, DEVICEID_XTEST_POINTER, XI_BUTTON_PRESS); select_xi1(f, B, ROOT, &[xi1_slave_press()]); } fn setup_i1b(f: &mut NotifyFixture) { - tree(f); - park_pointer_at(f, BARE_ROOT); - unhit_root(f); + bare_root_tree(f); select_xi1(f, A, ROOT, &[xi1_slave_press()]); select_xi1(f, B, ROOT, &[xi1_slave_press()]); } @@ -626,14 +597,7 @@ fn setup_scroll_stop_two_forms(f: &mut NotifyFixture) { fn setup_p22_grab(f: &mut NotifyFixture) { tree(f); register_physical_pointer(f); - xi_grab_master_pointer(f, A, ROOT, false, XI_MOTION); -} - -fn setup_p24(f: &mut NotifyFixture) { - tree(f); - park_pointer(f); - select_xi1(f, A, CHILD, &[xi1_slave_motion()]); - select_xi1(f, B, FOCUS, &[xi1_slave_motion()]); + xi_grab_device(f, A, DEVICEID_MASTER_POINTER, ROOT, false, XI_MOTION); } fn setup_p25(f: &mut NotifyFixture) { @@ -642,39 +606,36 @@ fn setup_p25(f: &mut NotifyFixture) { select_xi1(f, A, CHILD, &[xi1_slave_motion()]); } -fn setup_p26_owner_events(f: &mut NotifyFixture) { - tree(f); - select_xi1(f, A, CHILD, &[xi1_slave_press()]); - select_xi1(f, B, CHILD, &[xi1_slave_press()]); - xi1_grab_device(f, A, ROOT, true); +fn setup_p24(f: &mut NotifyFixture) { + setup_p25(f); + select_xi1(f, B, FOCUS, &[xi1_slave_motion()]); } -fn setup_p26_not_owner_events(f: &mut NotifyFixture) { +/// A and B select the XI1 press on C; A holds an XI1 `GrabDevice` on G. +fn setup_p26(f: &mut NotifyFixture) { tree(f); select_xi1(f, A, CHILD, &[xi1_slave_press()]); select_xi1(f, B, CHILD, &[xi1_slave_press()]); - xi1_grab_device(f, A, ROOT, false); + xi1_grab_device(f, A, ROOT, OWNER_EVENTS); } +/// A also selects the press on P. fn setup_p26_foreign_rejects(f: &mut NotifyFixture) { - tree(f); - select_xi1(f, A, CHILD, &[xi1_slave_press()]); + setup_p26::(f); select_xi1(f, A, FOCUS, &[xi1_slave_press()]); - select_xi1(f, B, CHILD, &[xi1_slave_press()]); - xi1_grab_device(f, A, ROOT, true); } fn setup_p27(f: &mut NotifyFixture) { tree(f); select_xi1(f, A, CHILD, &[xi1_slave_press()]); - grab_keyboard_device(f, A, DEVICEID_XTEST_POINTER, ROOT, true, XI_BUTTON_PRESS); + xi_grab_device(f, A, DEVICEID_XTEST_POINTER, ROOT, true, XI_BUTTON_PRESS); } fn setup_p27_later_window(f: &mut NotifyFixture) { tree(f); select_xi1(f, B, CHILD, &[xi1_slave_press()]); select_xi1(f, A, FOCUS, &[xi1_slave_press()]); - grab_keyboard_device(f, A, DEVICEID_XTEST_POINTER, ROOT, true, XI_BUTTON_PRESS); + xi_grab_device(f, A, DEVICEID_XTEST_POINTER, ROOT, true, XI_BUTTON_PRESS); } /// A sync `GrabDeviceButton` by the requester on P, plus two XI1 press @@ -823,7 +784,7 @@ const P22_GRAB: Scenario = Scenario { }; const P26_OWNER_EVENTS: Scenario = Scenario { - setup: setup_p26_owner_events, + setup: setup_p26::, steps: &[press(XTEST_SLAVE)], allow: Outcome { frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], @@ -878,6 +839,101 @@ const P28_PRESS: Scenario = Scenario { order: CallOrder::PerClient, }; +/// The allow-all outcomes several scenarios share, and the denied outcome that +/// only asks (nothing written). +const A_XI2_AT_CHILD: Outcome = Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + ..NOTHING +}; +const A_CORE_AT_CHILD: Outcome = Outcome { + frames: &[(A, Kind::Core, CHILD)], + calls: &[(A, CallKind::Core, CHILD)], + ..NOTHING +}; +const B_XI2_AT_CHILD: Outcome = Outcome { + frames: &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(B, CallKind::Xi2, CHILD)], + ..NOTHING +}; +/// B gets the slave and the master form at C from one check. +const B_BOTH_FORMS_AT_CHILD: Outcome = Outcome { + frames: &[ + (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), + (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + calls: &[(B, CallKind::Xi2, CHILD)], + ..NOTHING +}; +/// A gets the slave motion and its valuator continuation at C from one check. +const A_XI1_MOTION_AT_CHILD: Outcome = Outcome { + frames: &[ + (A, Kind::Xi1Motion(DEVICEID_XTEST_POINTER), CHILD), + (A, Kind::Xi1Valuator(DEVICEID_XTEST_POINTER), 0), + ], + calls: &[(A, XI1_MOTION_CALL, CHILD)], + ..NOTHING +}; +const ASKED_A_CORE_ROOT: Outcome = Outcome { + calls: &[(A, CallKind::Core, ROOT)], + ..NOTHING +}; +const ASKED_A_XI2_ROOT: Outcome = Outcome { + calls: &[(A, CallKind::Xi2, ROOT)], + ..NOTHING +}; +const ASKED_A_XI2_CHILD: Outcome = Outcome { + calls: &[(A, CallKind::Xi2, CHILD)], + ..NOTHING +}; + +/// The p14 scenarios up to the activating press; the rows with more steps build +/// on them with `..PREFIX`. +const P14_CORE: Scenario = Scenario { + setup: setup_p14_core, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(A, CallKind::Core, ROOT)], + grab: Some(&[passive(ROOT, false), FROZEN_BY_PRESS]), + ..NOTHING + }, + order: CallOrder::Total, +}; +const P14_FROM_SLAVE: Scenario = Scenario { + setup: setup_p14_xi2_master_from_slave, + steps: &[press(XTEST_SLAVE)], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], + calls: &[(A, CallKind::Xi2, ROOT)], + grab: Some(&[passive(ROOT, true), FROZEN_BY_PRESS]), + ..NOTHING + }, + order: CallOrder::Total, +}; +const P14_FROM_MASTER: Scenario = Scenario { + setup: setup_p14_xi2_master_origin, + steps: &[press(XTEST_MASTER)], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + grab: Some(&[passive(ROOT, true), FROZEN_BY_PRESS]), + ..NOTHING + }, + order: CallOrder::Total, +}; +const P14_OWNER_EVENTS: Scenario = Scenario { + setup: setup_p14_owner_events_from_slave, + steps: &[press(XTEST_SLAVE)], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], + calls: &[(A, CallKind::Xi2, ROOT)], + grab: Some(&[passive(ROOT, true), FROZEN_BY_PRESS]), + ..NOTHING + }, + order: CallOrder::Total, +}; + // ---- rows ---------------------------------------------------------------- const ROWS: &[InputRow] = &[ @@ -911,11 +967,7 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p2, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(B, CallKind::Xi2, CHILD)], - ..NOTHING - }, + allow: B_XI2_AT_CHILD, order: CallOrder::Total, }, deny: &[(B, CallKind::Xi2, CHILD)], @@ -933,11 +985,7 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p3, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(B, CallKind::Xi2, CHILD)], - ..NOTHING - }, + allow: B_XI2_AT_CHILD, order: CallOrder::Total, }, deny: &[(B, CallKind::Xi2, CHILD)], @@ -963,14 +1011,7 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p4, steps: &[motion(XTEST_SLAVE)], - allow: Outcome { - frames: &[ - (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), - (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - ], - calls: &[(B, CallKind::Xi2, CHILD)], - ..NOTHING - }, + allow: B_BOTH_FORMS_AT_CHILD, order: CallOrder::Total, }, deny: &[(B, CallKind::Xi2, CHILD)], @@ -1015,14 +1056,7 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p4c, steps: &[press(XTEST_SLAVE)], - allow: Outcome { - frames: &[ - (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), - (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - ], - calls: &[(B, CallKind::Xi2, CHILD)], - ..NOTHING - }, + allow: B_BOTH_FORMS_AT_CHILD, order: CallOrder::Total, }, deny: &[(B, CallKind::Xi2, CHILD)], @@ -1041,11 +1075,7 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p5, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - ..NOTHING - }, + allow: A_XI2_AT_CHILD, order: CallOrder::Total, }, deny: &[(A, CallKind::Xi2, CHILD)], @@ -1084,6 +1114,8 @@ const ROWS: &[InputRow] = &[ // shadowed and A gets its slave and master forms at P, with no core copy. // Mutation: the shadow uses the selection-only master route, which ends at C // (B's selection); A then keeps its core copy at C and gets no XI2 at P. + // Open gap: this selection-only mutation (P-5c) is not caught by any row; the + // row does catch P-5 (both routes selection-only). InputRow { name: "p5c_shadow_uses_the_allowed_master_route", scenario: &Scenario { @@ -1168,11 +1200,7 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p8, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - ..NOTHING - }, + allow: A_CORE_AT_CHILD, order: CallOrder::Total, }, deny: &[(A, CallKind::Core, CHILD)], @@ -1190,11 +1218,7 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p9, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - ..NOTHING - }, + allow: A_XI2_AT_CHILD, order: CallOrder::Total, }, deny: &[(A, CallKind::Xi2, CHILD)], @@ -1216,11 +1240,7 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p9_core_same_window, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - ..NOTHING - }, + allow: A_CORE_AT_CHILD, order: CallOrder::Total, }, deny: &[(A, CallKind::Core, CHILD)], @@ -1264,11 +1284,7 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p11, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - ..NOTHING - }, + allow: A_CORE_AT_CHILD, order: CallOrder::Total, }, deny: &[(A, CallKind::Core, CHILD)], @@ -1288,11 +1304,7 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p11_own_protocols, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - ..NOTHING - }, + allow: A_XI2_AT_CHILD, order: CallOrder::Total, }, deny: &[(A, CallKind::Xi2, CHILD)], @@ -1308,7 +1320,7 @@ const ROWS: &[InputRow] = &[ InputRow { name: "p12_grab_window_denial_counts_as_delivered", scenario: &Scenario { - setup: setup_p12, + setup: setup_p12::, steps: &[press(XTEST_MASTER)], allow: Outcome { frames: &[(A, Kind::Core, ROOT)], @@ -1318,16 +1330,13 @@ const ROWS: &[InputRow] = &[ order: CallOrder::Total, }, deny: &[(A, CallKind::Core, ROOT)], - denied: Outcome { - calls: &[(A, CallKind::Core, ROOT)], - ..NOTHING - }, + denied: ASKED_A_CORE_ROOT, }, // Mutation: the check moves behind the grab mask (no call here). InputRow { name: "p12_grab_window_denial_counts_as_delivered_mask", scenario: &Scenario { - setup: setup_p12_mask, + setup: setup_p12::, steps: &[press(XTEST_MASTER)], allow: Outcome { calls: &[(A, CallKind::Core, ROOT)], @@ -1336,10 +1345,7 @@ const ROWS: &[InputRow] = &[ order: CallOrder::Total, }, deny: &[(A, CallKind::Core, ROOT)], - denied: Outcome { - calls: &[(A, CallKind::Core, ROOT)], - ..NOTHING - }, + denied: ASKED_A_CORE_ROOT, }, // Mutation: the XI2 grab asks B's selector (a call for B). InputRow { @@ -1355,23 +1361,16 @@ const ROWS: &[InputRow] = &[ order: CallOrder::Total, }, deny: &[(A, CallKind::Xi2, ROOT)], - denied: Outcome { - calls: &[(A, CallKind::Xi2, ROOT)], - ..NOTHING - }, + denied: ASKED_A_XI2_ROOT, }, // Mutation: the XI2 owner qualifies by selection (nothing is written at C), // or the natural XI2 write asks again (two calls for A at C when allowed). InputRow { name: "p13_xi2_owner_events_fallback_is_fresh", scenario: &Scenario { - setup: setup_p13, + setup: setup_p13::, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - ..NOTHING - }, + allow: A_XI2_AT_CHILD, order: CallOrder::Total, }, deny: &[(A, CallKind::Xi2, CHILD)], @@ -1396,13 +1395,9 @@ const ROWS: &[InputRow] = &[ InputRow { name: "p13_xi2_owner_events_fallback_is_fresh_same_window", scenario: &Scenario { - setup: setup_p13_same_window, + setup: setup_p13::, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - ..NOTHING - }, + allow: A_XI2_AT_CHILD, order: CallOrder::Total, }, deny: &[(A, CallKind::Xi2, CHILD)], @@ -1424,41 +1419,22 @@ const ROWS: &[InputRow] = &[ // denied copy. InputRow { name: "p14_denied_activating_press_still_activates_and_freezes@press", - scenario: &Scenario { - setup: setup_p14_core, - steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(A, CallKind::Core, ROOT)], - grab: Some(&[passive(ROOT, false), FROZEN_BY_PRESS]), - ..NOTHING - }, - order: CallOrder::Total, - }, + scenario: &P14_CORE, deny: &[(A, CallKind::Core, ROOT)], - denied: Outcome { - calls: &[(A, CallKind::Core, ROOT)], - ..NOTHING - }, + denied: ASKED_A_CORE_ROOT, }, InputRow { name: "p14_denied_activating_press_still_activates_and_freezes", scenario: &Scenario { - setup: setup_p14_core, steps: &[press(XTEST_MASTER), motion(XTEST_MASTER)], allow: Outcome { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(A, CallKind::Core, ROOT)], grab: Some(&[passive(ROOT, false), FROZEN_BY_PRESS, MOTION_QUEUED]), - ..NOTHING + ..P14_CORE.allow }, - order: CallOrder::Total, + ..P14_CORE }, deny: &[(A, CallKind::Core, ROOT)], - denied: Outcome { - calls: &[(A, CallKind::Core, ROOT)], - ..NOTHING - }, + denied: ASKED_A_CORE_ROOT, }, // A sync `XIPassiveGrabDevice` on the master from an attached slave origin: // A's copy on G is denied, nobody else gets the press, and the grab still @@ -1470,46 +1446,26 @@ const ROWS: &[InputRow] = &[ // the thaw). InputRow { name: "p14_denied_xi2_activating_press_still_freezes_from_a_slave_origin@press", - scenario: &Scenario { - setup: setup_p14_xi2_master_from_slave, - steps: &[press(XTEST_SLAVE)], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], - calls: &[(A, CallKind::Xi2, ROOT)], - grab: Some(&[passive(ROOT, true), FROZEN_BY_PRESS]), - ..NOTHING - }, - order: CallOrder::Total, - }, + scenario: &P14_FROM_SLAVE, deny: &[(A, CallKind::Xi2, ROOT)], - denied: Outcome { - calls: &[(A, CallKind::Xi2, ROOT)], - ..NOTHING - }, + denied: ASKED_A_XI2_ROOT, }, InputRow { name: "p14_denied_xi2_activating_press_still_freezes_from_a_slave_origin@motion", scenario: &Scenario { - setup: setup_p14_xi2_master_from_slave, steps: &[press(XTEST_SLAVE), motion(XTEST_SLAVE)], allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], - calls: &[(A, CallKind::Xi2, ROOT)], grab: Some(&[passive(ROOT, true), FROZEN_BY_PRESS, MASTER_PART_QUEUED]), - ..NOTHING + ..P14_FROM_SLAVE.allow }, - order: CallOrder::Total, + ..P14_FROM_SLAVE }, deny: &[(A, CallKind::Xi2, ROOT)], - denied: Outcome { - calls: &[(A, CallKind::Xi2, ROOT)], - ..NOTHING - }, + denied: ASKED_A_XI2_ROOT, }, InputRow { name: "p14_denied_xi2_activating_press_still_freezes_from_a_slave_origin", scenario: &Scenario { - setup: setup_p14_xi2_master_from_slave, steps: &[ press(XTEST_SLAVE), motion(XTEST_SLAVE), @@ -1524,7 +1480,7 @@ const ROWS: &[InputRow] = &[ grab: Some(&[passive(ROOT, true)]), ..NOTHING }, - order: CallOrder::Total, + ..P14_FROM_SLAVE }, deny: &[(A, CallKind::Xi2, ROOT)], denied: Outcome { @@ -1537,41 +1493,22 @@ const ROWS: &[InputRow] = &[ // that copy writes nothing, asks once, and still freezes with the press stored. InputRow { name: "p14_denied_xi2_activating_press_from_a_master_origin_still_freezes@press", - scenario: &Scenario { - setup: setup_p14_xi2_master_origin, - steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - grab: Some(&[passive(ROOT, true), FROZEN_BY_PRESS]), - ..NOTHING - }, - order: CallOrder::Total, - }, + scenario: &P14_FROM_MASTER, deny: &[(A, CallKind::Xi2, CHILD)], - denied: Outcome { - calls: &[(A, CallKind::Xi2, CHILD)], - ..NOTHING - }, + denied: ASKED_A_XI2_CHILD, }, InputRow { name: "p14_denied_xi2_activating_press_from_a_master_origin_still_freezes", scenario: &Scenario { - setup: setup_p14_xi2_master_origin, steps: &[press(XTEST_MASTER), motion(XTEST_MASTER)], allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], grab: Some(&[passive(ROOT, true), FROZEN_BY_PRESS, MOTION_QUEUED]), - ..NOTHING + ..P14_FROM_MASTER.allow }, - order: CallOrder::Total, + ..P14_FROM_MASTER }, deny: &[(A, CallKind::Xi2, CHILD)], - denied: Outcome { - calls: &[(A, CallKind::Xi2, CHILD)], - ..NOTHING - }, + denied: ASKED_A_XI2_CHILD, }, // The same sync master grab with owner_events, and A selecting the master XI2 // motion on C: the follow-up slave motion defers its master part, so the @@ -1580,39 +1517,22 @@ const ROWS: &[InputRow] = &[ // is not emitted in this dispatch (a phantom A@C call). InputRow { name: "p14_deferred_master_part_asks_nothing_in_the_route@press", - scenario: &Scenario { - setup: setup_p14_owner_events_from_slave, - steps: &[press(XTEST_SLAVE)], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], - calls: &[(A, CallKind::Xi2, ROOT)], - ..NOTHING - }, - order: CallOrder::Total, - }, + scenario: &P14_OWNER_EVENTS, deny: &[(A, CallKind::Xi2, ROOT)], - denied: Outcome { - calls: &[(A, CallKind::Xi2, ROOT)], - ..NOTHING - }, + denied: ASKED_A_XI2_ROOT, }, InputRow { name: "p14_deferred_master_part_asks_nothing_in_the_route", scenario: &Scenario { - setup: setup_p14_owner_events_from_slave, steps: &[press(XTEST_SLAVE), motion(XTEST_SLAVE)], allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], - calls: &[(A, CallKind::Xi2, ROOT)], - ..NOTHING + grab: Some(&[passive(ROOT, true), FROZEN_BY_PRESS, MASTER_PART_QUEUED]), + ..P14_OWNER_EVENTS.allow }, - order: CallOrder::Total, + ..P14_OWNER_EVENTS }, deny: &[(A, CallKind::Xi2, ROOT)], - denied: Outcome { - calls: &[(A, CallKind::Xi2, ROOT)], - ..NOTHING - }, + denied: ASKED_A_XI2_ROOT, }, // The activation dispatch writes only the press, on G, so the XI2 route asks // nothing about A's core copy at C and a denial there changes nothing. @@ -2049,14 +1969,7 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p24, steps: &[motion(XTEST_SLAVE)], - allow: Outcome { - frames: &[ - (A, Kind::Xi1Motion(DEVICEID_XTEST_POINTER), CHILD), - (A, Kind::Xi1Valuator(DEVICEID_XTEST_POINTER), 0), - ], - calls: &[(A, XI1_MOTION_CALL, CHILD)], - ..NOTHING - }, + allow: A_XI1_MOTION_AT_CHILD, order: CallOrder::Total, }, deny: &[(A, XI1_MOTION_CALL, CHILD)], @@ -2086,14 +1999,7 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p25, steps: &[motion(XTEST_SLAVE)], - allow: Outcome { - frames: &[ - (A, Kind::Xi1Motion(DEVICEID_XTEST_POINTER), CHILD), - (A, Kind::Xi1Valuator(DEVICEID_XTEST_POINTER), 0), - ], - calls: &[(A, XI1_MOTION_CALL, CHILD)], - ..NOTHING - }, + allow: A_XI1_MOTION_AT_CHILD, order: CallOrder::Total, }, deny: &[(A, XI1_MOTION_CALL, CHILD)], @@ -2121,7 +2027,7 @@ const ROWS: &[InputRow] = &[ InputRow { name: "p26_xi1_grab_without_owner_events_asks_only_the_grab_window", scenario: &Scenario { - setup: setup_p26_not_owner_events, + setup: setup_p26::, steps: &[press(XTEST_SLAVE)], allow: Outcome { frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT)], From 246634d1461f9c76bcee3c1b96ca61c594a99c2f Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 13:21:00 -0300 Subject: [PATCH 47/72] test(access): input runner attributes request steps and decodes XI1 releases - A request step names the event steps whose events it writes (Step::Request(fn, &[Step])); its frames are checked against those events' details and its calls take their shorthand from them, so a thaw or replay that writes a different event than the previous step can be stated. New row p14_denied_xi2_activating_press_from_a_master_origin_still_freezes@replay (press, motion, XIAllowEvents(ReplayDevice)) states the replayed press. - decode handles XI1 DeviceButtonRelease; an XI1 event frame or XI2 touch frame with no Kind now panics instead of being skipped (unit test). - grab_facts includes xi2_keyboard_grabs and xi2_detached_masters; the two key rows built on the slave keyboard grab state it. - Mutation comments name only what probes.md shows the row catches; the header claim is narrowed. - Vestigial surface removed: private items nothing else uses, an assertion that an allow outcome states no moved frames, the redundant cfg(test). Co-Authored-By: Claude Opus 5.5 Implemented-By: Claude Sonnet 5.5 --- .../tests/access_input_support.rs | 225 ++++++++++++------ .../process_request/tests/access_key_input.rs | 20 +- .../tests/access_pointer_input.rs | 88 +++++-- 3 files changed, 234 insertions(+), 99 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index 81f808cc1..35efbab5f 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -37,14 +37,14 @@ pub(super) const FOCUS: u32 = 0x0061_0001; pub(super) const CHILD: u32 = 0x0061_0002; pub(super) const POINTER: (i16, i16) = (120, 120); pub(super) const KEYCODE: u8 = 38; -pub(super) const TIME: u32 = 0x5678; +const TIME: u32 = 0x5678; pub(super) const XI_MAJOR: u8 = 137; pub(super) const XI_SELECT_EVENTS: u8 = 46; -pub(super) const CORE_CHANGE_WINDOW_ATTRIBUTES: u8 = 2; -pub(super) const CORE_CREATE_WINDOW: u8 = 1; -pub(super) const CORE_MAP_WINDOW: u8 = 8; -pub(super) const CORE_SET_INPUT_FOCUS: u8 = 42; -pub(super) const CW_EVENT_MASK: u32 = 0x800; +const CORE_CHANGE_WINDOW_ATTRIBUTES: u8 = 2; +const CORE_CREATE_WINDOW: u8 = 1; +const CORE_MAP_WINDOW: u8 = 8; +const CORE_SET_INPUT_FOCUS: u8 = 42; +const CW_EVENT_MASK: u32 = 0x800; pub(super) const KEY_PRESS: u32 = 1; pub(super) const KEY_RELEASE: u32 = 2; /// XI2 mask word for KeyPress (bit 2) and KeyRelease (bit 3). @@ -66,8 +66,10 @@ type Call = (u32, CallKind, u32); pub(super) enum Kind { Core, Xi2(u16), - /// An XI1 `DeviceButtonPress`: its device. The frame carries the button in - /// its detail byte and the event window at byte 12, as a core frame does. + /// An XI1 `DeviceButtonPress` or `DeviceButtonRelease`: its device. The + /// frame carries the button in its detail byte and the event window at byte + /// 12, as a core frame does; a press and a release differ only in the event + /// code, so only their order tells them apart. Xi1(u16), /// An XI1 `DeviceKeyPress` or `DeviceKeyRelease`: its device. Xi1Key(u16), @@ -110,7 +112,7 @@ pub(super) enum Named { } /// A Receive call as traced: (client, ordered descriptions, subject window). -pub(super) type Seen = (u32, Vec, u32); +type Seen = (u32, Vec, u32); /// The traced form of an expected call. The shorthand kinds name one /// description with the row's event type. @@ -200,7 +202,7 @@ impl Drive { /// A wheel press (buttons 4..=7): besides its own press events it writes a /// smooth-scroll Motion, so the calls and frames of a row may name Motion. - pub(super) fn is_wheel_press(self) -> bool { + fn is_wheel_press(self) -> bool { matches!( self, Drive::Pointer { @@ -599,12 +601,17 @@ pub(super) fn decide(denied: &[Call], evs: &[u16], call: &RecordedExtensionCheck /// Decodes a frame the walks write: a core key, button or motion event (event /// window at byte 12), an XI2 key, button or motion GenericEvent (device at /// byte 10, event window at byte 24) or a raw key GenericEvent (device at byte -/// 10, always the root). `None` for any other frame. +/// 10, always the root), or an XI1 device event. `None` for a frame that is no +/// input event (a reply, a crossing, a mapping notify...); an XI1 event frame or +/// an XI2 touch frame with no `Kind` panics, so it is never skipped. pub(super) fn decode(frame: &[u8], order: ClientByteOrder) -> Option<(Kind, u32)> { match frame[0] & 0x7f { 2..=6 => Some((Kind::Core, dec32(&frame[12..16], order))), code if code - == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET => + == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET + || code + == crate::server::XI_FIRST_EVENT + + crate::xinput::XI_DEVICE_BUTTON_RELEASE_OFFSET => { Some(( Kind::Xi1(u16::from(frame[31] & 0x7f)), @@ -640,18 +647,25 @@ pub(super) fn decode(frame: &[u8], order: ClientByteOrder) -> Option<(Kind, u32) dec32(&frame[24..28], order), )), 13..=17 => Some((Kind::Raw(dec16(&frame[10..12], order)), ROOT)), + touch @ 18..=24 => panic!("undecoded XI2 touch frame {touch}: add a Kind"), _ => None, }, + code if (crate::server::XI_FIRST_EVENT + ..=crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_PROPERTY_NOTIFY_OFFSET) + .contains(&code) => + { + panic!("undecoded XI1 frame {code}: add a Kind") + } _ => None, } } -pub(super) struct ClientBytes { - pub(super) client: u32, - pub(super) order: ClientByteOrder, - pub(super) bytes: Vec, +struct ClientBytes { + client: u32, + order: ClientByteOrder, + bytes: Vec, /// Per step: the byte length after it and the client's sequence then. - pub(super) steps: Vec<(usize, u16)>, + steps: Vec<(usize, u16)>, } /// One fact of the grab state after a run. A row states the facts its denied @@ -662,6 +676,14 @@ pub(super) enum Grab { Keyboard { owner: u32, window: u32 }, /// The active master pointer grab. Pointer(PointerGrab), + /// A slave keyboard's exact XI2 grab, keyed by the slave's device id. + SlaveKeyboard { + device: u16, + owner: u32, + window: u32, + }, + /// A slave detached from its master by an explicit XI2 grab. + Detached { device: u16, master: u16 }, /// A slave pointer's XI2 grab, keyed by the slave's device id. SlavePointer { device: u16, grab: PointerGrab }, /// An XI1 device grab (implicit or explicit), keyed by device id. @@ -761,19 +783,19 @@ pub(super) struct PointerGrab { pub(super) via_xi2: bool, } -pub(super) struct Run { - pub(super) clients: Vec, - pub(super) calls: Vec, - /// The event type of the step that made each call, parallel to `calls`. - pub(super) call_evs: Vec, - pub(super) state: String, - pub(super) grab: Vec, +struct Run { + clients: Vec, + calls: Vec, + /// The event types of the step that made each call, parallel to `calls`. + call_evs: Vec>, + state: String, + grab: Vec, } -/// The grab facts of a server state, in a fixed order: keyboard grab, master -/// pointer grab, slave pointer grabs by device, XI1 grabs by device, the freeze +/// The grab facts of a server state, in a fixed order: keyboard grab, slave +/// keyboard grabs and detached slaves by device, master pointer grab, slave pointer grabs by device, XI1 grabs by device, the freeze /// of every device by device id, then the withheld events in queue order. -pub(super) fn grab_facts(state: &ServerState) -> Vec { +fn grab_facts(state: &ServerState) -> Vec { let pointer = |grab: &crate::server::ActivePointerGrab| PointerGrab { owner: grab.owner.0, window: grab.grab_window.0, @@ -791,6 +813,23 @@ pub(super) fn grab_facts(state: &ServerState) -> Vec { if let Some(grab) = state.active_pointer_grab.as_ref() { facts.push(Grab::Pointer(pointer(grab))); } + let mut keyboards: Vec<_> = state.xi2_keyboard_grabs.iter().collect(); + keyboards.sort_by_key(|(device, _)| **device); + for (device, grab) in keyboards { + facts.push(Grab::SlaveKeyboard { + device: *device, + owner: grab.owner.0, + window: grab.grab_window.0, + }); + } + let mut detached: Vec<_> = state.xi2_detached_masters.iter().collect(); + detached.sort_by_key(|(device, _)| **device); + for (device, master) in detached { + facts.push(Grab::Detached { + device: *device, + master: *master, + }); + } let mut slaves: Vec<_> = state.xi2_pointer_grabs.iter().collect(); slaves.sort_by_key(|(device, _)| **device); for (device, grab) in slaves { @@ -844,8 +883,9 @@ pub(super) fn grouped( /// The frames a run wrote, with the client byte order checked, the sequence /// checked against the client's sequence after the step that wrote the frame -/// and the detail against that step's `(detail, wheel press)`. -pub(super) fn delivered(name: &str, run: &Run, steps: &[(u32, bool)]) -> Vec { +/// and the detail against the `(detail, wheel press)` of one of the events the +/// step runs under. +fn delivered(name: &str, run: &Run, steps: &[Vec<(u32, bool)>]) -> Vec { let mut frames = Vec::new(); for client in &run.clients { for frame in split_frames(&client.bytes, client.order) { @@ -853,7 +893,6 @@ pub(super) fn delivered(name: &str, run: &Run, steps: &[(u32, bool)]) -> Vec client.steps[step].1.to_le_bytes(), ClientByteOrder::BigEndian => client.steps[step].1.to_be_bytes(), @@ -864,24 +903,25 @@ pub(super) fn delivered(name: &str, run: &Run, steps: &[(u32, bool)]) -> Vec { - u32::from(frame[1]) + Some(u32::from(frame[1])) } - // The valuator continuation has no detail byte (byte 1 is - // the device). - Kind::Xi1Valuator(_) => detail, - Kind::Xi2(_) | Kind::Raw(_) => dec32(&frame[16..20], client.order), + Kind::Xi1Valuator(_) => None, + Kind::Xi2(_) | Kind::Raw(_) => Some(dec32(&frame[16..20], client.order)), }; // The smooth-scroll Motion of a wheel press carries no button. - let is_scroll_motion = wheel_press - && matches!(kind, Kind::Xi2(_)) - && dec16(&frame[8..10], client.order) == 6; - let expected = if is_scroll_motion { 0 } else { detail }; - assert_eq!( - keycode, expected, - "{name}: client {} step {step} frame detail", - client.client + let scroll_motion = + matches!(kind, Kind::Xi2(_)) && dec16(&frame[8..10], client.order) == 6; + assert!( + keycode.is_none_or(|keycode| steps[step].iter().any(|&(detail, wheel)| { + keycode == if wheel && scroll_motion { 0 } else { detail } + })), + "{name}: client {} step {step} frame detail {keycode:?} is none of {:?}", + client.client, + steps[step] ); frames.push((client.client, kind, window)); } @@ -897,7 +937,10 @@ pub(super) fn delivered(name: &str, run: &Run, steps: &[(u32, bool)]) -> Vec Vec { - let first = scenario.steps.iter().find_map(|step| match step { +/// The events each step runs under: an event step's own; a request step's +/// named ones, or the event before it, or the first one. +fn step_events(scenario: &Scenario) -> Vec> { + let event = |step: &Step| match step { Step::Event(drive) => Some(*drive), - Step::Request(_) => None, - }); - let mut current = first.expect("a scenario drives at least one event"); + Step::Request(..) => None, + }; + let mut current = scenario.steps.iter().find_map(event); scenario .steps .iter() - .map(|step| { - if let Step::Event(drive) = step { - current = *drive; + .map(|step| match step { + Step::Event(drive) => { + current = Some(*drive); + vec![*drive] } - current + Step::Request(_, []) => { + vec![current.expect("a scenario drives at least one event")] + } + Step::Request(_, replays) => replays.iter().filter_map(event).collect(), }) .collect() } @@ -1003,10 +1050,12 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run for client in [SEND_CLIENT, A, B] { f.drain(ClientId(client)); } - let drives = step_events(scenario); - let evs: Vec = drives.iter().map(|drive| drive.ev()).collect(); + let step_evs: Vec> = step_events(scenario) + .iter() + .map(|drives| drives.iter().map(|drive| drive.ev()).collect()) + .collect(); let recorder = policy.map(|denied| { - let evs = evs.clone(); + let evs: Vec = step_evs.concat(); f.install_policy(move |_, call| decide(denied, &evs, call)) }); let mut clients: Vec = [SEND_CLIENT, A, B] @@ -1023,7 +1072,7 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run for (index, step) in scenario.steps.iter().enumerate() { match step { Step::Event(event) => drive(&mut f, *event), - Step::Request(request) => request(&mut f), + Step::Request(request, _) => request(&mut f), } for client in &mut clients { client.bytes.extend(f.drain(ClientId(client.client))); @@ -1034,7 +1083,7 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run } if let Some(recorder) = &recorder { let total = recorder.lock().unwrap().len(); - call_evs.extend((seen_calls..total).map(|_| evs[index])); + call_evs.extend((seen_calls..total).map(|_| step_evs[index].clone())); seen_calls = total; } } @@ -1145,14 +1194,15 @@ fn moved_frames(name: &str, allow: &Run, denied: &Run) -> Vec<(u32, Move)> { moved } -/// A recorded call with a shorthand's number zeroed when it names the event of -/// the step that made it, so it compares with a shorthand entry of a row. -fn canonical_seen(call: &Seen, ev: u16) -> Seen { +/// A recorded call with a shorthand's number zeroed when it names one of the +/// events of the step that made it, so it compares with a shorthand entry of a +/// row. +fn canonical_seen(call: &Seen, evs: &[u16]) -> Seen { let (client, names, window) = call; let own = match names.as_slice() { - [Named::Core(n)] if *n == ev => vec![Named::Core(0)], - [Named::Xi2(n)] if *n == ev => vec![Named::Xi2(0)], - [Named::Raw(n)] if *n == ev => vec![Named::Raw(0)], + [Named::Core(n)] if evs.contains(n) => vec![Named::Core(0)], + [Named::Xi2(n)] if evs.contains(n) => vec![Named::Xi2(0)], + [Named::Raw(n)] if evs.contains(n) => vec![Named::Raw(0)], _ => names.clone(), }; (*client, own, *window) @@ -1170,7 +1220,7 @@ fn check_outcome(name: &str, mode: &str, scenario: &Scenario, run: &Run, want: & .calls .iter() .zip(&run.call_evs) - .map(|(call, ev)| canonical_seen(call, *ev)) + .map(|(call, evs)| canonical_seen(call, evs)) .collect(); let calls: Vec = want.calls.iter().map(canonical_call).collect(); let calls_match = match scenario.order { @@ -1185,9 +1235,14 @@ fn check_outcome(name: &str, mode: &str, scenario: &Scenario, run: &Run, want: & "{name} [{mode}]: Receive calls ({:?}) differ\n got: {got:?}\n want: {calls:?}", scenario.order ); - let steps: Vec<(u32, bool)> = step_events(scenario) - .into_iter() - .map(|drive| (drive.detail(), drive.is_wheel_press())) + let steps: Vec> = step_events(scenario) + .iter() + .map(|drives| { + drives + .iter() + .map(|drive| (drive.detail(), drive.is_wheel_press())) + .collect() + }) .collect(); assert_eq!( grouped( @@ -1224,6 +1279,10 @@ fn check_input_row(row: &InputRow) { allow.grab, plain.grab, "{name}: allow-all changed the grab and freeze state" ); + assert!( + scenario.allow.moved.is_empty(), + "{name}: an allow outcome has no moved frames" + ); check_outcome(name, "allow-all", scenario, &allow, &scenario.allow); if let Some(facts) = scenario.allow.grab { assert_eq!(allow.grab, facts, "{name}: allow-all grab and freeze state"); @@ -1272,7 +1331,6 @@ pub(super) fn check_rows(rows: &[InputRow]) { ); } -#[cfg(test)] mod batch_naming { use super::*; @@ -1304,9 +1362,28 @@ mod batch_naming { fn a_shorthand_call_resolves_per_step() { let recorded: Seen = (A, vec![Named::Core(6)], CHILD); let shorthand: Call = (A, CallKind::Core, CHILD); - assert_eq!(canonical_seen(&recorded, 6), canonical_call(&shorthand)); - assert_ne!(canonical_seen(&recorded, 4), canonical_call(&shorthand)); + assert_eq!(canonical_seen(&recorded, &[6]), canonical_call(&shorthand)); + assert_ne!(canonical_seen(&recorded, &[4]), canonical_call(&shorthand)); let explicit: Call = (A, CallKind::Batch(&[Named::Core(6)]), CHILD); - assert_eq!(canonical_seen(&recorded, 4), canonical_call(&explicit)); + assert_eq!(canonical_seen(&recorded, &[4]), canonical_call(&explicit)); + } + + /// An XI1 `DeviceButtonRelease` decodes like the press, and an XI1 event frame + /// the runner has no `Kind` for fails instead of being skipped. + #[test] + fn xi1_releases_decode_and_unknown_xi1_frames_fail() { + let frame = |offset: u8| { + let mut frame = [0_u8; 32]; + frame[0] = crate::server::XI_FIRST_EVENT + offset; + frame[1] = 1; + frame[12..16].copy_from_slice(&CHILD.to_le_bytes()); + frame[31] = 4; + frame + }; + let order = ClientByteOrder::LittleEndian; + let release = frame(crate::xinput::XI_DEVICE_BUTTON_RELEASE_OFFSET); + assert_eq!(decode(&release, order), Some((Kind::Xi1(4), CHILD))); + let focus = frame(crate::xinput::XI_DEVICE_FOCUS_IN_OFFSET); + assert!(std::panic::catch_unwind(|| decode(&focus, order)).is_err()); } } diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs index 892f8de68..531b219c5 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -284,6 +284,20 @@ const XTEST_RAW_PRESS: Step = Step::Event(Drive::Raw { pressed: true, }); +/// The grab facts of A's exact XI2 grab of the slave keyboard on FOCUS (it +/// detaches the slave from its master). +const A_GRABS_SLAVE: &[Grab] = &[ + Grab::SlaveKeyboard { + device: DEVICEID_XTEST_KEYBOARD, + owner: A, + window: FOCUS, + }, + Grab::Detached { + device: DEVICEID_XTEST_KEYBOARD, + master: DEVICEID_MASTER_KEYBOARD, + }, +]; + /// The grab facts of an active core keyboard grab by A on the root. const A_GRABS_ROOT: &[Grab] = &[Grab::Keyboard { owner: A, @@ -367,6 +381,7 @@ const K5C_GRAB_SCENARIO: Scenario = Scenario { setup: setup_k5c_grab, steps: &[SLAVE_PRESS], allow: Outcome { + grab: Some(A_GRABS_SLAVE), frames: &[(A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), FOCUS)], calls: &[(A, CallKind::Xi2, FOCUS)], ..NOTHING @@ -763,7 +778,10 @@ const ROWS: &[InputRow] = &[ master: false, synthetic: true, })], - allow: NOTHING, + allow: Outcome { + grab: Some(A_GRABS_SLAVE), + ..NOTHING + }, order: CallOrder::Total, }, deny: &[], diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index 55a66f24a..f076309d5 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -7,7 +7,8 @@ //! compares frames, Receive trace, moved frames and grab and freeze facts with //! the stated outcomes. A multi-step scenario (p14, p15, p28) has one row per //! intermediate assertion, named `@`, whose steps are the prefix. -//! The mutation each row must kill is named in its comment. +//! A row's comment names the mutation it kills where probes.md records a probe +//! for it; a row without one is caught through its siblings. use super::{ access_input_support::*, access_notify_support::NotifyFixture, access_xi_notify::xi1_class, @@ -224,16 +225,19 @@ fn xi1_passive_grab(f: &mut NotifyFixture, owner: u32, window: u32, sync: bool) }); } -/// The requests of the p14 and p28 step lists: `XIAllowEvents(AsyncDevice)` of -/// the master pointer by A, and the XI1 `AllowDeviceEvents(ReplayThisDevice)` +/// The requests of the p14 and p28 step lists: `XIAllowEvents` of the master +/// pointer by A with mode `MODE`, and the XI1 `AllowDeviceEvents(ReplayThisDevice)` /// of the slave by the requester. Both use `request`, not `send`: a thaw may /// write events to its own requester, and the runner, which drains after every /// step, must see them rather than have the request helper swallow or reject them. -fn thaw_master(f: &mut NotifyFixture) { +const XI_ASYNC_DEVICE: u8 = 0; +const XI_REPLAY_DEVICE: u8 = 2; + +fn allow_master(f: &mut NotifyFixture) { let mut body = Vec::with_capacity(8); body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime body.extend_from_slice(&DEVICEID_MASTER_POINTER.to_le_bytes()); - body.extend_from_slice(&[0, 0]); // XIAsyncDevice + body.extend_from_slice(&[MODE, 0]); request(f, A, XI_MAJOR, XI_ALLOW_EVENTS, &body); } @@ -659,6 +663,9 @@ const XI1_MOTION_CALL: CallKind = CallKind::Batch(&[ Named::Xi1(crate::xinput::XI_DEVICE_VALUATOR_OFFSET as u16), ]); +/// The XI2 Motion description, for a request step that replays a press and then +/// releases the motion queued behind it. +const MOTION_CALL: CallKind = CallKind::Batch(&[Named::Xi2(6)]); const RAW_BUTTON_PRESS_CALL: CallKind = CallKind::Batch(&[Named::Raw(15)]); /// The scroll Motion of a wheel press: not the press's own event, so a batch. const SCROLL_MOTION_CALL: CallKind = CallKind::Batch(&[Named::Xi2(6)]); @@ -1277,8 +1284,7 @@ const ROWS: &[InputRow] = &[ }, // Mutation: the foreign selectors are evaluated before the owner (an extra // call for B when A qualifies), B's master XI2 copy is asked under the - // grab-owned master form (a call for B in the allowed run), or the owner - // qualifies only through the first protocol it selected. + // grab-owned master form (a call for B in the allowed run). InputRow { name: "p11_owner_qualifies_in_a_later_protocol", scenario: &Scenario { @@ -1299,6 +1305,8 @@ const ROWS: &[InputRow] = &[ grab: None, }, }, + // Mutation: the owner qualifies only through the first protocol it selected + // (this row then falls back to the grab window). InputRow { name: "p11_owner_qualifies_in_a_later_protocol_own_protocols", scenario: &Scenario { @@ -1391,7 +1399,8 @@ const ROWS: &[InputRow] = &[ grab: None, }, }, - // Mutation: the fallback reuses the memo for G (one call for A at C here). + // The fallback reuses the memo for G (one call for A at C here): no probe + // replays this edit. InputRow { name: "p13_xi2_owner_events_fallback_is_fresh_same_window", scenario: &Scenario { @@ -1413,10 +1422,8 @@ const ROWS: &[InputRow] = &[ // A sync `GrabButton` on G: the activating press is denied to its owner, and // the grab still activates, freezes and stores the press; the next motion is // queued behind the freeze. - // Mutation (all p14 rows): the denial skips the activation, the freeze or the - // stored press (a `delivered` gate on the freeze), or a second owner call is - // made, or the unchecked owner write under `xi2_grab_delivery` delivers the - // denied copy. + // Mutation: the passive core activating write is unchecked (p14 core rows and + // the activation row). InputRow { name: "p14_denied_activating_press_still_activates_and_freezes@press", scenario: &P14_CORE, @@ -1441,9 +1448,9 @@ const ROWS: &[InputRow] = &[ // freezes with the press stored. The next motion delivers its slave part and // defers the master part behind the freeze; thawing runs the master part, // which is the one attempt, asked once. - // Mutation: the XI2 master block asks for the grab window without the - // emitted-form gate (a phantom call after the motion, and a second one at - // the thaw). + // Mutation: the grab-window result is ignored, or the XI2 master block asks + // for the grab window without the emitted-form gate (a phantom call after the + // motion, and a second one at the thaw); the slave rows catch both. InputRow { name: "p14_denied_xi2_activating_press_still_freezes_from_a_slave_origin@press", scenario: &P14_FROM_SLAVE, @@ -1469,7 +1476,7 @@ const ROWS: &[InputRow] = &[ steps: &[ press(XTEST_SLAVE), motion(XTEST_SLAVE), - Step::Request(thaw_master), + Step::Request(allow_master::, &[]), ], allow: Outcome { frames: &[ @@ -1491,12 +1498,46 @@ const ROWS: &[InputRow] = &[ // The same grab from a master origin (`xi2_grab_delivery`): A also selects the // master XI2 press on C, which is the window its copy is routed to. Denying // that copy writes nothing, asks once, and still freezes with the press stored. + // Mutation: the unchecked owner write under `xi2_grab_delivery` delivers the + // denied copy. InputRow { name: "p14_denied_xi2_activating_press_from_a_master_origin_still_freezes@press", scenario: &P14_FROM_MASTER, deny: &[(A, CallKind::Xi2, CHILD)], denied: ASKED_A_XI2_CHILD, }, + // XIAllowEvents(ReplayDevice) replays the stored press, not the motion queued + // behind it: the request step states the event it writes. + InputRow { + name: "p14_denied_xi2_activating_press_from_a_master_origin_still_freezes@replay", + scenario: &Scenario { + steps: &[ + press(XTEST_MASTER), + motion(XTEST_MASTER), + Step::Request(allow_master::, &[press(XTEST_MASTER)]), + ], + allow: Outcome { + frames: &[ + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + calls: &[ + (A, CallKind::Xi2, CHILD), + (A, CallKind::Xi2, CHILD), + (A, MOTION_CALL, CHILD), + ], + grab: Some(&[implicit(A, CHILD, true)]), + ..P14_FROM_MASTER.allow + }, + ..P14_FROM_MASTER + }, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: Outcome { + calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Xi2, CHILD)], + grab: Some(&[]), + ..NOTHING + }, + }, InputRow { name: "p14_denied_xi2_activating_press_from_a_master_origin_still_freezes", scenario: &Scenario { @@ -1513,14 +1554,14 @@ const ROWS: &[InputRow] = &[ // The same sync master grab with owner_events, and A selecting the master XI2 // motion on C: the follow-up slave motion defers its master part, so the // route that would ask A@C for that copy must not ask yet. - // Mutation: the master block's route takes the memo although the master form - // is not emitted in this dispatch (a phantom A@C call). InputRow { name: "p14_deferred_master_part_asks_nothing_in_the_route@press", scenario: &P14_OWNER_EVENTS, deny: &[(A, CallKind::Xi2, ROOT)], denied: ASKED_A_XI2_ROOT, }, + // Mutation: the master block's route takes the memo although the master form + // is not emitted in this dispatch (a phantom A@C call, after the motion). InputRow { name: "p14_deferred_master_part_asks_nothing_in_the_route", scenario: &Scenario { @@ -1625,8 +1666,8 @@ const ROWS: &[InputRow] = &[ }, }, // Both select the master pointer's XI2 press on C; A is the window's owner and - // wins with allow-all, and with A denied B owns the grab. - // Mutation (the XI2 candidate): a denied copy still enters the owner preference. + // wins with allow-all, and with A denied B owns the grab. (The mutation that a + // denied copy still enters the owner preference is not caught by any probe.) InputRow { name: "p17_xi2_owner_preference_among_allowed", scenario: &Scenario { @@ -2013,8 +2054,7 @@ const ROWS: &[InputRow] = &[ // (the allow-all run). With A denied, B (allowed) sends the event to G: A // gets one fresh check there. // Mutations: the owner copy is not checked in the route (selection decides); - // the foreign selector is asked before the owner; the grab-window copy is - // written unchecked. + // the grab-window copy is written unchecked (the three p26 rows). InputRow { name: "p26_xi1_grab_owner_denied_falls_to_the_grab_window", scenario: &P26_OWNER_EVENTS, @@ -2043,7 +2083,7 @@ const ROWS: &[InputRow] = &[ ..NOTHING }, }, - // O denied on C, F allowed on C: F's copy rejects the walk, so O does not + // A denied on C, B allowed on C: B's copy rejects the walk, so A does not // reach its own selector on P: it gets the event at G. InputRow { name: "p26_xi1_grab_foreign_copy_rejects_the_walk", @@ -2134,7 +2174,7 @@ const ROWS: &[InputRow] = &[ InputRow { name: "p28_thawed_xi1_press_picks_the_owner_from_allowed", scenario: &Scenario { - steps: &[press(XTEST_SLAVE), Step::Request(replay_slave)], + steps: &[press(XTEST_SLAVE), Step::Request(replay_slave, &[])], allow: Outcome { frames: &[ (SEND_CLIENT, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS), From b4052e18a350800ca464a98a5048e796b325fe6a Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 13:31:46 -0300 Subject: [PATCH 48/72] docs(plan): access control PR 4c part 2, plan 3 (replay, thaw, freeze) Co-Authored-By: Claude Opus 5.5 --- .../2026-12-02-access-control-pr4c-replay.md | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 docs/superpowers/plans/2026-12-02-access-control-pr4c-replay.md diff --git a/docs/superpowers/plans/2026-12-02-access-control-pr4c-replay.md b/docs/superpowers/plans/2026-12-02-access-control-pr4c-replay.md new file mode 100644 index 000000000..9ac2b33c7 --- /dev/null +++ b/docs/superpowers/plans/2026-12-02-access-control-pr4c-replay.md @@ -0,0 +1,78 @@ +# Access control PR 4c part 2, plan 3: replay, thaw and freeze under denial + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Pin the spec's replay, thaw and freeze rules with rows, fix the three phantom checks plans 1–2 left on those paths, close the coverage gaps carried from plans 2 and 2b, and make the branch ready for the PR. + +**Architecture:** Plans 1 and 2 already converted every write site that replay and thaw reach (`pointer_event_fanout_to_state_inner` with one `ReceiveMemo` per dispatch, `xi1_route_device_event` with a fresh memo per thaw re-entry, `deliver_key_to_window` for key replay). This plan does not convert them again. It changes production code only where a replay or thaw attempt asks Receive for a copy it never writes, or asks about a gone client. Everything else is rows on plan 2b's input runner (`access_input_support.rs`), which gets the two fixes its final review asked for. + +**Tech Stack:** Rust, yserver-core (`crates/yserver-core/src/core_loop/`), tests in `core_loop/process_request/tests/`. + +**Spec:** `docs/superpowers/specs/2026-10-30-access-control-layer-design.md` §"Input delivery under denial" (l.353–527), in particular "Replay and thaw", "Freeze", "Passive grab activation", "Grab window". Carry list: `/data/Projects/claude-scratch/access-control/pr4c-input/plan3-carry.md`. + +**Series context:** plan 1 (keyboard) `aa8338c3`, plan 2 (pointer + XI1 router) `44f7dfb3`, plan 2b (tests in the #389 shape) `246634d1`. All one PR. Carry items closed elsewhere: plan 1 M4 (freeze read only the master keyboard) is closed by 2b's per-device grab facts; plan 2 T5 M3 (p28 without a no-policy run) is closed by 2b's runner; 1a M1 (cross-client order) was triaged "leave" (the spec does not order calls across clients); 1a M5 (Device subject panic) went with 2b's runner rewrite. + +## Global Constraints + +- With no policy, and with an allow-all policy, every scenario's bytes on every client, the order per client, and the grab/freeze/queue state equal today's (spec l.357–359). The runner checks this on every row. +- Queue bookkeeping, thaw, the choice of event to replay, and a passive grab matching again are not checked (spec "Replay and thaw"): queuing an event or storing it asks Receive nothing. +- A replayed or thawed event is checked again at each write, under the rule that applies at that write; it never reuses a result from the attempt that queued or stored it. Each thaw re-entry (each `sync_pending` entry played, each stored event replayed) is a distinct attempt with its own memo. +- Receive is asked for a copy only when this attempt writes that copy if allowed (spec l.374–385). A form a replay does not emit routes selection-only (`None`), as in plan 2. +- Freeze: a sync grab freezes on today's triggers; a denied grab-window delivery counts as delivered for a trigger that depends on delivery (spec "Freeze", `dix/events.c:4390`, `4467-4473`). A denied activating write still activates, freezes and stores the event (spec "Passive grab activation"). +- A gone client is never asked (as `grab_window_allows` and `fanout_event_to_clients_inner` already do). +- Tests: rows on the plan 2b runner (`InputRow`, `Scenario`, `Step`, `Outcome`, `check_rows`), denied outcomes stated in full, never derived (grab fallback as in 2b), checkpoints as `@` scenarios, no literal frame encoders, no `rustfmt::skip`, no macro DSL. Each row's comment names the mutation it kills; that mutation is in `sdd-p2b/probes.md` (or a `sdd-p3/probes.md` that extends it) and was replayed with the 2b replay script: compiled, caught by that row. Cite Xorg 21.1.24 as `dix/events.c:`. +- Reuse first: no new production code except where a decision needs it; no new `YSERVER_*` env vars. +- Commits signed (`-S`), a blank line before the trailers `Co-Authored-By: Claude Opus 5.5 ` and `Implemented-By: Claude Sonnet 5.5`; no URLs. Gate per task: `cargo +nightly fmt --all`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo build --bin yserver` alone, `cargo test -p yserver-core --lib`; Tasks 2 and 4 also `cargo test --workspace --features xdmcp`. + +## Review Focus + +1. A thaw or replay that asks Receive for a form it does not write (master XI2 under a slave-only replay, XI2 legs in the XI1 thaw filter, a non-emitted form in `play_queued_master_pointer_event`). +2. A result from the original attempt reused by its replay (a memo hoisted out of the `xi1_compute_freezes` loop or shared between the activation and `AllowEvents` replay). +3. A freeze, store or activation that depends on whether the grab-window or activating write was allowed. +4. A thaw request whose requester gets an X error or reply bytes the row never states. +5. Two queued events of the same (client, window, description) played in one thaw, the second answered from the first's result. + +--- + +### Task 1: runner fixes and the carried coverage rows + +**Files:** Modify `crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs`, `access_pointer_input.rs`. Create (outside the repo) `/data/Projects/claude-scratch/access-control/pr4c-input/sdd-p3/probes.md` (new probes, same format as `sdd-p2b/probes.md`; reuse `sdd-p2b/replay.py`). + +**Interfaces (produces):** the runner as in 2b, plus: a call names its step shorthand only when its step lists exactly one event (2b R2-I1); every client's non-input bytes during the steps (errors, replies, non-input events) are compared against the row's stated `Outcome.other: &'static [(u32, u8)]` (client, first byte: 0 error, 1 reply, else event code), default empty through `..NOTHING`; the recorded hook trace holds only Receive calls unless the row states otherwise (2b Task 2 M2: a non-Receive hook fails the row). + +- [ ] **Step 1:** Add the new probes to `sdd-p3/probes.md` and replay them at HEAD (`246634d1`) to show each is uncaught or the runner cannot state it: R2-I1 (a two-event request step whose press and motion calls are swapped), M3 (a thaw step whose requester receives an X error), P-5c (text in `sdd-p2b/probes.md`), T5 M1 (move the XI1 grab-window check after the `device_mask` test, `pointer_fanout.rs` ~3369-3381). +- [ ] **Step 2:** Runner: the three interface changes above. Existing rows keep passing unchanged except where a row now has to state bytes it receives (list each in the report with what they are). +- [ ] **Step 3:** Rows in `access_pointer_input.rs`: `p5d_denied_master_copy_does_not_shadow_that_clients_core` (two master-XI2 selectors at the route window, one denied; the denied client also selects core on the walk; its core copy is written; kills P-5c) and `p26_xi1_implicit_grab_window_is_checked_before_the_device_mask` (XI1 implicit grab whose `device_mask` filters the event: the grab-window call is in the trace; kills T5 M1). +- [ ] **Step 4:** Replay all probes (2b's and the new ones): each caught by its stated row; P-5c no longer open. Gate. Commit `test(access): input runner states request bytes; shadow and XI1 grab-window rows`. + +### Task 2: no phantom check on replay and thaw + +**Files:** Modify `crates/yserver-core/src/core_loop/pointer_fanout.rs`, `pointer_fanout/owner_events.rs`, `core_loop/fanout.rs` (only if `ReceiveMemo` needs the lookup below); tests in `access_pointer_input.rs`. + +**Interfaces:** `owner_events_route` replaces `core_checked: bool` with per-leg modes for the core and XI2 legs, `LegCheck::{Ask, KnownOnly, SelectionOnly}` (XI1 leg as today). `KnownOnly` uses the result the memo already holds for that (client, subject, batch) and otherwise routes selection-only; it never asks. `ReceiveMemo::known(&self, client, subject, batch) -> Option` if the memo has no such lookup. With `receive: None` every leg is selection-only, as today. + +- [ ] **Step 1: rows first (RED).** Each row fails at HEAD on its trace or frames: + - `r1_slave_only_replay_asks_no_master_xi2_copy` (plan 2 final m3): a slave-only replay (`replay_has_master_form` false) while a core `owner_events` master grab is live, the owner selecting master XI2 on the walk; the owner's master XI2 copy denied. No master XI2 call; the owner gets what it gets with no policy (`Natural{Xi2}` still consumes core). + - `r2_xi1_thaw_filter_asks_no_xi2_copy` (plan 2 final m6 / T5 M2): a queued XI1 press thawed under an `owner_events` XI2 slave grab (`xi2_grab_delivery`), the owner selecting slave XI2 at a window on the route; the owner's XI2 copy denied. The thaw asks only XI1 copies; the filter result equals no policy. `p27_*` keep passing (the live dispatch still shares the slave route's result). + - `r3_scroll_stop_asks_no_gone_grab_owner` (plan 2 T4 M2): only if reachable through production entries (a grab that survives its owner's disconnect until teardown while a stop arrives). If not reachable, write in the report why, make no code change for it, and record it in the ledger. + If r1's shape is not reachable through production entries, stop and report NEEDS_CONTEXT with what you tried. +- [ ] **Step 2:** The core grab block's `owner_events_route` call (`pointer_fanout.rs` ~1461) asks the XI2 leg only when the master XI2 form is emitted in this dispatch (lift the `master_form_emitted` predicate above the block, do not duplicate it); otherwise `SelectionOnly`. `xi1_selection_filter_for_slave_grab` passes `KnownOnly` for the XI2 leg. The scroll stop's grab branch skips a gone owner (r3, if reachable). +- [ ] **Step 3:** GREEN; replay all probes plus a probe per fix that restores the old argument (each caught by its row). Gate incl. workspace xdmcp. Commit `fix(access): replay and thaw ask no copy they do not write`. + +### Task 3: replay, thaw and freeze rows + +**Files:** Create `crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs` (setups + one `ROWS` + `#[test] fn replay_rows() { check_rows(ROWS) }`), register it in the tests `mod.rs`; input-only helpers go in `access_input_support.rs`. + +Rows (each with the named kill; denials on the client/window named): +- [ ] **Step 1: core replay.** `r4_replay_pointer_rechecks_the_natural_target` (sync passive button grab, activating write to the owner denied; `AllowEvents(ReplayPointer)`; the natural selector B gets the press with a new call in the trace; `@press` checkpoint: B asked nothing, freeze + stored press). Denied variant with B denied: the replayed press continues the walk to the next allowed selector. Kill: the replay answered from the activation's result, and a check added to the store/replay choice. `r5_replay_keyboard_rechecks_the_focus` the same for a sync key grab and `AllowEvents(ReplayKeyboard)`. +- [ ] **Step 2: thaw.** `r6_thawed_queued_motion_is_checked_at_its_write` (sync pointer grab, two motions queued, `AllowEvents(AsyncPointer)`): `@queue` checkpoint asks nothing; on thaw each motion is asked for its own recipients, two calls for the same (client, window, description) — kills a memo hoisted out of the `xi1_compute_freezes` loop; the denied recipient loses both copies, nobody else changes. `r7_thawed_queued_key_is_checked_at_its_write` the same for `HostKeyTransition` and the master `RawKey` leg (`AllowEvents(AsyncKeyboard)`). `r8_xi1_replay_this_device_rechecks` (`AllowDeviceEvents(ReplayThisDevice)` of a stored `Xi1Routed` press: fresh check at the replay's write, owner chosen from the allowed). +- [ ] **Step 3: freeze.** `r9_denied_grab_window_write_trips_freeze_next` (core pointer grab, `AllowEvents(SyncPointer)` arms FreezeNextEvent, next press to the grab window denied: FrozenWithEvent with that press stored, as with no policy; kill: gating `xi1_freeze_this_event_if_needed` on `deliver`), the same for an XI1 device grab (`AllowDeviceEvents(SyncThisDevice)`) and a key grab (`AllowEvents(SyncKeyboard)`). +- [ ] **Step 4:** Every request step states its requester's bytes (`other`), none expected for these requests. Replay all probes. Gate. Commit `test(access): replay, thaw and freeze rows`. + +### Task 4: PR readiness + +**Files:** Modify `docs/status.md`. + +- [ ] **Step 1:** One `docs/status.md` entry for PR 4c (both halves: #389's notifications and this PR's input delivery), in the file's existing format and date convention, naming the deletions (`emit_xi2_device_changed_slave_pointer` and its tests, `xi2_stamp_deviceid_for_source`) and the yserver rules the spec lists (activating-write check, stop batch, repeat rule, XKB device subject). +- [ ] **Step 2:** Full gate: fmt, clippy `-D warnings`, `cargo build --bin yserver` alone, `cargo test -p yserver-core --lib`, `cargo test --workspace --features xdmcp`, each `tests/*.rs` integration test, the CI `cargo test --workspace --features xdmcp -- --ignored` lavapipe suite (with `lvp-env.sh`), `just man`; the key/pointer/replay rows 20 times under 16 busy loops. Record commands and result lines in the report. Hardware parity (AMD, NVIDIA) is not part of this task: the controller asks the user. +- [ ] **Step 3:** Commit `docs(status): access control PR 4c`. From b005cb1a9bb78822b76d7a046c88cf146d77f349 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 13:31:57 -0300 Subject: [PATCH 49/72] docs(plan): plan 3 names the lavapipe env script Co-Authored-By: Claude Opus 5.5 --- docs/superpowers/plans/2026-12-02-access-control-pr4c-replay.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/superpowers/plans/2026-12-02-access-control-pr4c-replay.md b/docs/superpowers/plans/2026-12-02-access-control-pr4c-replay.md index 9ac2b33c7..321cf854a 100644 --- a/docs/superpowers/plans/2026-12-02-access-control-pr4c-replay.md +++ b/docs/superpowers/plans/2026-12-02-access-control-pr4c-replay.md @@ -74,5 +74,5 @@ Rows (each with the named kill; denials on the client/window named): **Files:** Modify `docs/status.md`. - [ ] **Step 1:** One `docs/status.md` entry for PR 4c (both halves: #389's notifications and this PR's input delivery), in the file's existing format and date convention, naming the deletions (`emit_xi2_device_changed_slave_pointer` and its tests, `xi2_stamp_deviceid_for_source`) and the yserver rules the spec lists (activating-write check, stop batch, repeat rule, XKB device subject). -- [ ] **Step 2:** Full gate: fmt, clippy `-D warnings`, `cargo build --bin yserver` alone, `cargo test -p yserver-core --lib`, `cargo test --workspace --features xdmcp`, each `tests/*.rs` integration test, the CI `cargo test --workspace --features xdmcp -- --ignored` lavapipe suite (with `lvp-env.sh`), `just man`; the key/pointer/replay rows 20 times under 16 busy loops. Record commands and result lines in the report. Hardware parity (AMD, NVIDIA) is not part of this task: the controller asks the user. +- [ ] **Step 2:** Full gate: fmt, clippy `-D warnings`, `cargo build --bin yserver` alone, `cargo test -p yserver-core --lib`, `cargo test --workspace --features xdmcp`, each `tests/*.rs` integration test, the CI `cargo test --workspace --features xdmcp -- --ignored` lavapipe suite (with `/data/Projects/claude-scratch/issue-388/walk/lvp-env.sh`), `just man`; the key/pointer/replay rows 20 times under 16 busy loops. Record commands and result lines in the report. Hardware parity (AMD, NVIDIA) is not part of this task: the controller asks the user. - [ ] **Step 3:** Commit `docs(status): access control PR 4c`. From 2081a900f03736f4ad3739527ffbda0c1bf9b947 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 13:41:22 -0300 Subject: [PATCH 50/72] docs(plan): plan 3 review round 1 Co-Authored-By: Claude Opus 5.5 --- .../2026-12-02-access-control-pr4c-replay.md | 80 ++++++++++--------- 1 file changed, 44 insertions(+), 36 deletions(-) diff --git a/docs/superpowers/plans/2026-12-02-access-control-pr4c-replay.md b/docs/superpowers/plans/2026-12-02-access-control-pr4c-replay.md index 321cf854a..5e5599053 100644 --- a/docs/superpowers/plans/2026-12-02-access-control-pr4c-replay.md +++ b/docs/superpowers/plans/2026-12-02-access-control-pr4c-replay.md @@ -2,77 +2,85 @@ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. -**Goal:** Pin the spec's replay, thaw and freeze rules with rows, fix the three phantom checks plans 1–2 left on those paths, close the coverage gaps carried from plans 2 and 2b, and make the branch ready for the PR. +**Goal:** Pin the spec's replay, thaw and freeze rules with rows, fix the one phantom check plans 1–2 left on the thaw path, close the coverage gaps carried from plans 2 and 2b, and make the branch ready for the PR. -**Architecture:** Plans 1 and 2 already converted every write site that replay and thaw reach (`pointer_event_fanout_to_state_inner` with one `ReceiveMemo` per dispatch, `xi1_route_device_event` with a fresh memo per thaw re-entry, `deliver_key_to_window` for key replay). This plan does not convert them again. It changes production code only where a replay or thaw attempt asks Receive for a copy it never writes, or asks about a gone client. Everything else is rows on plan 2b's input runner (`access_input_support.rs`), which gets the two fixes its final review asked for. +**Architecture:** Plans 1 and 2 already converted every write site that replay and thaw reach: `pointer_event_fanout_to_state_inner` builds one `ReceiveMemo` per dispatch (each replay or queued whole event is its own dispatch), `xi1_compute_freezes` gives each `Xi1Routed` entry a fresh memo, and key replay goes through `replay_frozen_key_to_focus{,_after_transition}` / `deliver_routed_key*` with plan 1's per-write checks. This plan does not convert them again. It changes production code at one site, the XI1 thaw filter's XI2 leg, which asks Receive for copies a thaw never writes. Everything else is rows on plan 2b's input runner (`access_input_support.rs`). **Tech Stack:** Rust, yserver-core (`crates/yserver-core/src/core_loop/`), tests in `core_loop/process_request/tests/`. **Spec:** `docs/superpowers/specs/2026-10-30-access-control-layer-design.md` §"Input delivery under denial" (l.353–527), in particular "Replay and thaw", "Freeze", "Passive grab activation", "Grab window". Carry list: `/data/Projects/claude-scratch/access-control/pr4c-input/plan3-carry.md`. -**Series context:** plan 1 (keyboard) `aa8338c3`, plan 2 (pointer + XI1 router) `44f7dfb3`, plan 2b (tests in the #389 shape) `246634d1`. All one PR. Carry items closed elsewhere: plan 1 M4 (freeze read only the master keyboard) is closed by 2b's per-device grab facts; plan 2 T5 M3 (p28 without a no-policy run) is closed by 2b's runner; 1a M1 (cross-client order) was triaged "leave" (the spec does not order calls across clients); 1a M5 (Device subject panic) went with 2b's runner rewrite. +**Series context and carry dispositions:** plan 1 (keyboard) `aa8338c3`, plan 2 (pointer + XI1 router) `44f7dfb3`, plan 2b (tests in the #389 shape) `246634d1`, all one PR. Closed without work here: +- plan 1 M4 (freeze read only the master keyboard): closed by 2b's per-device grab facts; +- plan 2 T5 M3 (p28 without a no-policy run): closed by 2b's runner; +- 1a M1 (cross-client call order): triaged "leave", the spec does not order calls across clients; 1a M5 (Device subject panic): went with 2b's runner rewrite; +- plan 2 final m3 (core grab block's owner-events route asks master XI2 under a slave-only replay): **not reachable**. A replay sets `master_accepted = replay_has_master_form` (`pointer_fanout.rs:708-710`), and `grab_for_form(.., Master, replay)` returns `None` for a slave replay, so a slave-only replay never enters the core grab block. No code, no row; the controller records it in the ledger. ## Global Constraints - With no policy, and with an allow-all policy, every scenario's bytes on every client, the order per client, and the grab/freeze/queue state equal today's (spec l.357–359). The runner checks this on every row. -- Queue bookkeeping, thaw, the choice of event to replay, and a passive grab matching again are not checked (spec "Replay and thaw"): queuing an event or storing it asks Receive nothing. -- A replayed or thawed event is checked again at each write, under the rule that applies at that write; it never reuses a result from the attempt that queued or stored it. Each thaw re-entry (each `sync_pending` entry played, each stored event replayed) is a distinct attempt with its own memo. -- Receive is asked for a copy only when this attempt writes that copy if allowed (spec l.374–385). A form a replay does not emit routes selection-only (`None`), as in plan 2. -- Freeze: a sync grab freezes on today's triggers; a denied grab-window delivery counts as delivered for a trigger that depends on delivery (spec "Freeze", `dix/events.c:4390`, `4467-4473`). A denied activating write still activates, freezes and stores the event (spec "Passive grab activation"). +- Queue bookkeeping, thaw, the choice of event to replay, and a passive grab matching again are not checked (spec "Replay and thaw"): queuing or storing an event asks Receive nothing. +- A replayed or thawed event is checked again at each write, under the rule that applies at that write; it never reuses a result from the attempt that queued or stored it. +- Receive is asked for a copy only when this attempt writes that copy if allowed (spec l.374–385). A form an attempt does not write routes selection-only, as in plan 2. +- Freeze: a sync grab freezes on today's triggers; a denied grab-window delivery counts as delivered for a trigger that depends on delivery (spec "Freeze", `dix/events.c:4390`, `4467-4473`). A denied activating write still activates, freezes and stores the event, and replay works as today (spec "Passive grab activation"). - A gone client is never asked (as `grab_window_allows` and `fanout_event_to_clients_inner` already do). -- Tests: rows on the plan 2b runner (`InputRow`, `Scenario`, `Step`, `Outcome`, `check_rows`), denied outcomes stated in full, never derived (grab fallback as in 2b), checkpoints as `@` scenarios, no literal frame encoders, no `rustfmt::skip`, no macro DSL. Each row's comment names the mutation it kills; that mutation is in `sdd-p2b/probes.md` (or a `sdd-p3/probes.md` that extends it) and was replayed with the 2b replay script: compiled, caught by that row. Cite Xorg 21.1.24 as `dix/events.c:`. +- Tests: rows on the plan 2b runner (`InputRow`, `Scenario`, `Step`, `Outcome`, `check_rows`), denied outcomes stated in full, never derived (grab fallback as in 2b), checkpoints as `@` scenarios, no literal frame encoders, no `rustfmt::skip`, no macro DSL. Each row's comment names a compile-valid mutation on a code path the row executes and what it changes (trace, frames or facts). Cite Xorg 21.1.24 as `dix/events.c:`. +- Probes: one source, `/data/Projects/claude-scratch/access-control/pr4c-input/sdd-p3/probes.py`, which imports the 2b list (`sdd-p2b/probes.py`) and appends plan 3's; one replay script `sdd-p3/replay.py` (a copy of `sdd-p2b/replay.py`) whose test filter is `access_key_input access_pointer_input access_replay_input`, results in `sdd-p3/results-.json`, logs in `sdd-p3/logs/`, table regenerated into `sdd-p3/probes.md` with 2b's `genmd.py`. A probe that does not compile is invalid, not caught. Every probe (2b and plan 3) is replayed against all three row files at the end of each task. - Reuse first: no new production code except where a decision needs it; no new `YSERVER_*` env vars. - Commits signed (`-S`), a blank line before the trailers `Co-Authored-By: Claude Opus 5.5 ` and `Implemented-By: Claude Sonnet 5.5`; no URLs. Gate per task: `cargo +nightly fmt --all`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo build --bin yserver` alone, `cargo test -p yserver-core --lib`; Tasks 2 and 4 also `cargo test --workspace --features xdmcp`. ## Review Focus -1. A thaw or replay that asks Receive for a form it does not write (master XI2 under a slave-only replay, XI2 legs in the XI1 thaw filter, a non-emitted form in `play_queued_master_pointer_event`). -2. A result from the original attempt reused by its replay (a memo hoisted out of the `xi1_compute_freezes` loop or shared between the activation and `AllowEvents` replay). +1. A thaw or replay that asks Receive for a form it does not write (XI2 legs in the XI1 thaw filter; a non-emitted form in `play_queued_master_pointer_event`). +2. The live XI1 filter diverging from the slave route it must agree with (an owner whose slave XI2 copy is denied losing its XI1 copy). 3. A freeze, store or activation that depends on whether the grab-window or activating write was allowed. -4. A thaw request whose requester gets an X error or reply bytes the row never states. -5. Two queued events of the same (client, window, description) played in one thaw, the second answered from the first's result. +4. A thaw or replay request whose requester gets an X error or reply the row never states. +5. A non-Receive policy hook (or a second Dispatch) added inside passive activation or inside a thaw request's replay. --- ### Task 1: runner fixes and the carried coverage rows -**Files:** Modify `crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs`, `access_pointer_input.rs`. Create (outside the repo) `/data/Projects/claude-scratch/access-control/pr4c-input/sdd-p3/probes.md` (new probes, same format as `sdd-p2b/probes.md`; reuse `sdd-p2b/replay.py`). +**Files:** Modify `crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs`, `access_pointer_input.rs`. Create (outside the repo) `sdd-p3/probes.py`, `sdd-p3/replay.py` as in Global Constraints. -**Interfaces (produces):** the runner as in 2b, plus: a call names its step shorthand only when its step lists exactly one event (2b R2-I1); every client's non-input bytes during the steps (errors, replies, non-input events) are compared against the row's stated `Outcome.other: &'static [(u32, u8)]` (client, first byte: 0 error, 1 reply, else event code), default empty through `..NOTHING`; the recorded hook trace holds only Receive calls unless the row states otherwise (2b Task 2 M2: a non-Receive hook fails the row). +**Interfaces (produces):** the 2b runner plus: +- a recorded call takes its step's shorthand only when its step lists exactly one event (2b R2-I1); +- request bytes: a request step's requester receives exactly the errors and replies the row states for that step, `Outcome.replies: &'static [(usize, u32, u8)]` (step index, client, first byte: 0 error, 1 reply), default empty through `..NOTHING`; other non-input frames stay out of scope; +- policy hooks: an event step records no non-Receive hook; a request step records exactly its own admission hooks (one `Dispatch` for an extension request, none for a core request), derived from the step, not stated per row; any other non-Receive hook fails the row. -- [ ] **Step 1:** Add the new probes to `sdd-p3/probes.md` and replay them at HEAD (`246634d1`) to show each is uncaught or the runner cannot state it: R2-I1 (a two-event request step whose press and motion calls are swapped), M3 (a thaw step whose requester receives an X error), P-5c (text in `sdd-p2b/probes.md`), T5 M1 (move the XI1 grab-window check after the `device_mask` test, `pointer_fanout.rs` ~3369-3381). -- [ ] **Step 2:** Runner: the three interface changes above. Existing rows keep passing unchanged except where a row now has to state bytes it receives (list each in the report with what they are). +- [ ] **Step 1:** Write `sdd-p3/probes.py` and `sdd-p3/replay.py`; replay the 2b probes at HEAD to confirm the baseline (74 caught, P-5c uncaught). Add and replay the new probes, each uncaught or unstateable at HEAD: R2-I1 (a two-event request step whose press and motion calls are swapped), M3 (a thaw step whose requester receives an X error, e.g. a thaw request with a bad device), M2 (a non-Receive hook added at passive activation, e.g. a `check_extension_dispatch`-style call in the activation path), P-5c (`sdd-p2b/probes.py`), T5 M1 (the XI1 grab-window check moved after the `device_mask` test, `pointer_fanout.rs` ~3369-3381). +- [ ] **Step 2:** Runner: the three interface changes. Existing rows keep passing unchanged; list in the report any row whose requester now has bytes to state, and what they are. - [ ] **Step 3:** Rows in `access_pointer_input.rs`: `p5d_denied_master_copy_does_not_shadow_that_clients_core` (two master-XI2 selectors at the route window, one denied; the denied client also selects core on the walk; its core copy is written; kills P-5c) and `p26_xi1_implicit_grab_window_is_checked_before_the_device_mask` (XI1 implicit grab whose `device_mask` filters the event: the grab-window call is in the trace; kills T5 M1). -- [ ] **Step 4:** Replay all probes (2b's and the new ones): each caught by its stated row; P-5c no longer open. Gate. Commit `test(access): input runner states request bytes; shadow and XI1 grab-window rows`. +- [ ] **Step 4:** Replay every probe; each caught by its stated row, P-5c by p5d. Gate. Commit `test(access): input runner states request bytes and hooks; shadow and XI1 grab-window rows`. -### Task 2: no phantom check on replay and thaw +### Task 2: the XI1 thaw filter asks no XI2 copy -**Files:** Modify `crates/yserver-core/src/core_loop/pointer_fanout.rs`, `pointer_fanout/owner_events.rs`, `core_loop/fanout.rs` (only if `ReceiveMemo` needs the lookup below); tests in `access_pointer_input.rs`. +**Files:** Modify `crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs` (and `core_loop/fanout.rs` only if `ReceiveMemo` needs the lookup below); rows in `access_pointer_input.rs`. -**Interfaces:** `owner_events_route` replaces `core_checked: bool` with per-leg modes for the core and XI2 legs, `LegCheck::{Ask, KnownOnly, SelectionOnly}` (XI1 leg as today). `KnownOnly` uses the result the memo already holds for that (client, subject, batch) and otherwise routes selection-only; it never asks. `ReceiveMemo::known(&self, client, subject, batch) -> Option` if the memo has no such lookup. With `receive: None` every leg is selection-only, as today. +**Interfaces:** `owner_events_route` keeps `core_checked: bool` and gains `xi2_known_only: bool`: when true, the XI2 leg uses the result the memo already holds for that (client, subject, batch) and otherwise counts the selection, and never asks. `ReceiveMemo::known(&self, client, subject, batch) -> Option` if the memo has no such lookup. Every caller except `xi1_selection_filter_for_slave_grab` passes `false`. With `receive: None`, every leg is selection-only, as today. -- [ ] **Step 1: rows first (RED).** Each row fails at HEAD on its trace or frames: - - `r1_slave_only_replay_asks_no_master_xi2_copy` (plan 2 final m3): a slave-only replay (`replay_has_master_form` false) while a core `owner_events` master grab is live, the owner selecting master XI2 on the walk; the owner's master XI2 copy denied. No master XI2 call; the owner gets what it gets with no policy (`Natural{Xi2}` still consumes core). - - `r2_xi1_thaw_filter_asks_no_xi2_copy` (plan 2 final m6 / T5 M2): a queued XI1 press thawed under an `owner_events` XI2 slave grab (`xi2_grab_delivery`), the owner selecting slave XI2 at a window on the route; the owner's XI2 copy denied. The thaw asks only XI1 copies; the filter result equals no policy. `p27_*` keep passing (the live dispatch still shares the slave route's result). - - `r3_scroll_stop_asks_no_gone_grab_owner` (plan 2 T4 M2): only if reachable through production entries (a grab that survives its owner's disconnect until teardown while a stop arrives). If not reachable, write in the report why, make no code change for it, and record it in the ledger. - If r1's shape is not reachable through production entries, stop and report NEEDS_CONTEXT with what you tried. -- [ ] **Step 2:** The core grab block's `owner_events_route` call (`pointer_fanout.rs` ~1461) asks the XI2 leg only when the master XI2 form is emitted in this dispatch (lift the `master_form_emitted` predicate above the block, do not duplicate it); otherwise `SelectionOnly`. `xi1_selection_filter_for_slave_grab` passes `KnownOnly` for the XI2 leg. The scroll stop's grab branch skips a gone owner (r3, if reachable). -- [ ] **Step 3:** GREEN; replay all probes plus a probe per fix that restores the old argument (each caught by its row). Gate incl. workspace xdmcp. Commit `fix(access): replay and thaw ask no copy they do not write`. +- [ ] **Step 1: rows first (RED).** + - `p27_thawed_xi1_press_filter_asks_no_xi2_copy` (plan 2 final m6 / T5 M2): a slave XI2 passive sync grab with `owner_events`; the live XI1 press is queued at router step 1; `XIAllowEvents(AsyncDevice)` thaws it through `xi1_compute_freezes`. The owner selects slave XI2 and XI1 on the route; its XI2 copy denied. The thaw asks only XI1 copies and the owner gets the XI1 copy it gets with no policy. Kill: the filter's XI2 leg asks (today's code). Fails at HEAD on the trace. + - `p27_live_filter_agrees_with_a_denied_slave_xi2_route` (invariant: in a live dispatch the filter's decision equals the slave route's for the same memo): the same selections in a live dispatch (no freeze), the owner's slave XI2 copy denied; the owner gets its XI1 copy where the slave route put it. Kill: the filter's XI2 leg routed selection-only. Passes at HEAD (pin). + - Gone grab owner (plan 2 T4 M2, and the filter's read of `xi2_pointer_grabs` without the gone-owner gate): one reachability ruling for both. If a grab can outlive its owner's disconnect until teardown while input arrives through production entries, add the guard (skip a gone owner, as `grab_window_allows` does) with a row each; if not, write why in the report, change no code, and the controller records it. +- [ ] **Step 2:** Implement `xi2_known_only` and pass `true` from `xi1_selection_filter_for_slave_grab`. +- [ ] **Step 3:** GREEN; replay every probe plus one per new row (the kills above). Gate incl. workspace xdmcp. Commit `fix(access): the XI1 thaw filter asks no XI2 copy`. ### Task 3: replay, thaw and freeze rows -**Files:** Create `crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs` (setups + one `ROWS` + `#[test] fn replay_rows() { check_rows(ROWS) }`), register it in the tests `mod.rs`; input-only helpers go in `access_input_support.rs`. +**Files:** Create `crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs` (setups + one `ROWS` + `#[test] fn replay_rows() { check_rows(ROWS) }`), registered in `process_request/tests/mod.rs` next to `access_key_input`; input-only helpers go in `access_input_support.rs`. -Rows (each with the named kill; denials on the client/window named): -- [ ] **Step 1: core replay.** `r4_replay_pointer_rechecks_the_natural_target` (sync passive button grab, activating write to the owner denied; `AllowEvents(ReplayPointer)`; the natural selector B gets the press with a new call in the trace; `@press` checkpoint: B asked nothing, freeze + stored press). Denied variant with B denied: the replayed press continues the walk to the next allowed selector. Kill: the replay answered from the activation's result, and a check added to the store/replay choice. `r5_replay_keyboard_rechecks_the_focus` the same for a sync key grab and `AllowEvents(ReplayKeyboard)`. -- [ ] **Step 2: thaw.** `r6_thawed_queued_motion_is_checked_at_its_write` (sync pointer grab, two motions queued, `AllowEvents(AsyncPointer)`): `@queue` checkpoint asks nothing; on thaw each motion is asked for its own recipients, two calls for the same (client, window, description) — kills a memo hoisted out of the `xi1_compute_freezes` loop; the denied recipient loses both copies, nobody else changes. `r7_thawed_queued_key_is_checked_at_its_write` the same for `HostKeyTransition` and the master `RawKey` leg (`AllowEvents(AsyncKeyboard)`). `r8_xi1_replay_this_device_rechecks` (`AllowDeviceEvents(ReplayThisDevice)` of a stored `Xi1Routed` press: fresh check at the replay's write, owner chosen from the allowed). -- [ ] **Step 3: freeze.** `r9_denied_grab_window_write_trips_freeze_next` (core pointer grab, `AllowEvents(SyncPointer)` arms FreezeNextEvent, next press to the grab window denied: FrozenWithEvent with that press stored, as with no policy; kill: gating `xi1_freeze_this_event_if_needed` on `deliver`), the same for an XI1 device grab (`AllowDeviceEvents(SyncThisDevice)`) and a key grab (`AllowEvents(SyncKeyboard)`). -- [ ] **Step 4:** Every request step states its requester's bytes (`other`), none expected for these requests. Replay all probes. Gate. Commit `test(access): replay, thaw and freeze rows`. +Already pinned by 2b rows, not repeated: `HostPointerMaster` thaw (p14 slave origin), XI2 `ReplayDevice` of a stored `HostPointer` (p14 master `@replay`), `AllowDeviceEvents(ReplayThisDevice)` of a stored `Xi1Routed` press with the owner from the allowed (p28). Paths that share writers with the rows below and get no row of their own: `xi_cleanup_source` → `xi1_compute_freezes`, the XI2 paired-master modes → `xi1_compute_freezes` (`grabs.rs` ~440-470), XI2 `ReplayDevice` of a stored `HostKeyTransition` (the same function as r5), `HostKey` entries (`deliver_routed_key`, `replay_frozen_key_to_focus`). + +- [ ] **Step 1: core replay.** `r4_replay_pointer_rechecks_the_natural_target`: a sync passive button grab, the activating write to the owner denied; `AllowEvents(ReplayPointer)`; the natural selector B gets the press with its own call in the trace. `@press` checkpoint: B asked nothing, freeze and stored press as with no policy (kill: a check added at the store or the replay choice). Denied variant with B denied: the replayed press continues to the next allowed selector (kill: the replay walk made selection-only, e.g. `None` for the replay dispatch's memo). `r5_replay_keyboard_rechecks_the_focus`: the same for a sync key grab and `AllowEvents(ReplayKeyboard)`. +- [ ] **Step 2: thaw.** `r6_thawed_queued_motion_is_checked_at_its_write`: a sync pointer grab with `owner_events`, a motion queued; `@queue` asks nothing; `AllowEvents(AsyncPointer)` thaws it and it is asked for its own recipient; the denied recipient loses it, nobody else changes. Kill: the thawed write made unchecked when `state.playing_sync_events` (name the exact site in the row comment). `r7_thawed_queued_key_is_checked_at_its_write`: the same for a queued `HostKeyTransition` and the master `RawKey` leg (`AllowEvents(AsyncKeyboard)`). The per-entry memo for whole-event entries is structural (each is its own dispatch); a memo hoisted out of the `xi1_compute_freezes` loop is killable only with two equal-key `Xi1Routed` entries in one pass: add that row only if the shape is constructible, otherwise the report says it is not and the controller records it. `r8_denied_xi1_activating_write_still_replays`: an XI1 passive sync grab whose activating write to the owner is denied, then `AllowDeviceEvents(ReplayThisDevice)`: the press replays to the natural selector as with no policy, checked at that write. +- [ ] **Step 3: freeze.** `r9_denied_xi1_grab_window_write_trips_freeze_next`: an XI1 device grab, `AllowDeviceEvents(SyncThisDevice)` arms FreezeNextEvent, the next press's grab-window write denied: FrozenWithEvent with that press stored, as with no policy. Kill: `xi1_freeze_this_event_if_needed` in router step 2 (`pointer_fanout.rs` ~3392) gated on `deliver`. Pins only (no denial-dependent mutation exists on their path; say so in the comment): the same for a core pointer grab (`AllowEvents(SyncPointer)`) and a key grab (`AllowEvents(SyncKeyboard)`), which trip through the router's bridged branch (~3535). +- [ ] **Step 4:** Every request step states its requester's replies and errors (none expected). Replay every probe. Gate. Commit `test(access): replay, thaw and freeze rows`. ### Task 4: PR readiness **Files:** Modify `docs/status.md`. -- [ ] **Step 1:** One `docs/status.md` entry for PR 4c (both halves: #389's notifications and this PR's input delivery), in the file's existing format and date convention, naming the deletions (`emit_xi2_device_changed_slave_pointer` and its tests, `xi2_stamp_deviceid_for_source`) and the yserver rules the spec lists (activating-write check, stop batch, repeat rule, XKB device subject). -- [ ] **Step 2:** Full gate: fmt, clippy `-D warnings`, `cargo build --bin yserver` alone, `cargo test -p yserver-core --lib`, `cargo test --workspace --features xdmcp`, each `tests/*.rs` integration test, the CI `cargo test --workspace --features xdmcp -- --ignored` lavapipe suite (with `/data/Projects/claude-scratch/issue-388/walk/lvp-env.sh`), `just man`; the key/pointer/replay rows 20 times under 16 busy loops. Record commands and result lines in the report. Hardware parity (AMD, NVIDIA) is not part of this task: the controller asks the user. -- [ ] **Step 3:** Commit `docs(status): access control PR 4c`. +- [ ] **Step 1:** A new `docs/status.md` entry for PR 4c part 2 in the file's format and date convention, after the part 1 entry (l.42, #389, which says "Pointer, keyboard and replay delivery follow in the next PR"; do not edit it). It describes input delivery under denial, the deletions this branch made (`emit_xi2_device_changed_slave_pointer` and its tests, `xi2_stamp_deviceid_for_source`), and the yserver rules the spec lists (activating-write check, stop batch, repeat rule). +- [ ] **Step 2:** Full gate: fmt, clippy `-D warnings`, `cargo build --bin yserver` alone, `cargo test -p yserver-core --lib`, `cargo test --workspace --features xdmcp`, each `tests/*.rs` integration test, the CI `cargo test --workspace --features xdmcp -- --ignored` lavapipe suite (with `/data/Projects/claude-scratch/issue-388/walk/lvp-env.sh`), `just man`; the key, pointer and replay rows 20 times under 16 busy loops. Record commands and result lines in the report. Hardware parity (AMD, NVIDIA) is not part of this task: the controller asks the user. +- [ ] **Step 3:** Commit `docs(status): access control PR 4c part 2`. From 0a88563b613bfdd8a1a8636917b95a930f7fe3e4 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 13:42:43 -0300 Subject: [PATCH 51/72] docs(plan): plan 3 review round 2 minors Co-Authored-By: Claude Opus 5.5 --- .../plans/2026-12-02-access-control-pr4c-replay.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/superpowers/plans/2026-12-02-access-control-pr4c-replay.md b/docs/superpowers/plans/2026-12-02-access-control-pr4c-replay.md index 5e5599053..47111b2ac 100644 --- a/docs/superpowers/plans/2026-12-02-access-control-pr4c-replay.md +++ b/docs/superpowers/plans/2026-12-02-access-control-pr4c-replay.md @@ -46,9 +46,9 @@ **Interfaces (produces):** the 2b runner plus: - a recorded call takes its step's shorthand only when its step lists exactly one event (2b R2-I1); - request bytes: a request step's requester receives exactly the errors and replies the row states for that step, `Outcome.replies: &'static [(usize, u32, u8)]` (step index, client, first byte: 0 error, 1 reply), default empty through `..NOTHING`; other non-input frames stay out of scope; -- policy hooks: an event step records no non-Receive hook; a request step records exactly its own admission hooks (one `Dispatch` for an extension request, none for a core request), derived from the step, not stated per row; any other non-Receive hook fails the row. +- policy hooks: an event step records no non-Receive hook; a request step records exactly its own admission hooks (one `Dispatch` for an extension request, none for a core request), derived from the step (the `request()` helper records the opcode it sent, so the runner allows exactly one `Dispatch` for that opcode), not stated per row; any other non-Receive hook fails the row. -- [ ] **Step 1:** Write `sdd-p3/probes.py` and `sdd-p3/replay.py`; replay the 2b probes at HEAD to confirm the baseline (74 caught, P-5c uncaught). Add and replay the new probes, each uncaught or unstateable at HEAD: R2-I1 (a two-event request step whose press and motion calls are swapped), M3 (a thaw step whose requester receives an X error, e.g. a thaw request with a bad device), M2 (a non-Receive hook added at passive activation, e.g. a `check_extension_dispatch`-style call in the activation path), P-5c (`sdd-p2b/probes.py`), T5 M1 (the XI1 grab-window check moved after the `device_mask` test, `pointer_fanout.rs` ~3369-3381). +- [ ] **Step 1:** Write `sdd-p3/probes.py` and `sdd-p3/replay.py`; replay the 2b probes at HEAD to confirm the baseline (74 caught, P-5c uncaught). Add and replay the new probes, each uncaught or unstateable at HEAD: R2-I1 (a two-event request step whose press and motion calls are swapped), M3 (a production edit that makes a thaw request also send its requester an X error, e.g. the `XIAllowEvents` handler queuing a `BadValue` after it thaws), M2 (a non-Receive hook added at passive activation, e.g. a `check_extension_dispatch`-style call in the activation path), P-5c (`sdd-p2b/probes.py`), T5 M1 (the XI1 grab-window check moved after the `device_mask` test, `pointer_fanout.rs` ~3369-3381). - [ ] **Step 2:** Runner: the three interface changes. Existing rows keep passing unchanged; list in the report any row whose requester now has bytes to state, and what they are. - [ ] **Step 3:** Rows in `access_pointer_input.rs`: `p5d_denied_master_copy_does_not_shadow_that_clients_core` (two master-XI2 selectors at the route window, one denied; the denied client also selects core on the walk; its core copy is written; kills P-5c) and `p26_xi1_implicit_grab_window_is_checked_before_the_device_mask` (XI1 implicit grab whose `device_mask` filters the event: the grab-window call is in the trace; kills T5 M1). - [ ] **Step 4:** Replay every probe; each caught by its stated row, P-5c by p5d. Gate. Commit `test(access): input runner states request bytes and hooks; shadow and XI1 grab-window rows`. @@ -73,7 +73,7 @@ Already pinned by 2b rows, not repeated: `HostPointerMaster` thaw (p14 slave origin), XI2 `ReplayDevice` of a stored `HostPointer` (p14 master `@replay`), `AllowDeviceEvents(ReplayThisDevice)` of a stored `Xi1Routed` press with the owner from the allowed (p28). Paths that share writers with the rows below and get no row of their own: `xi_cleanup_source` → `xi1_compute_freezes`, the XI2 paired-master modes → `xi1_compute_freezes` (`grabs.rs` ~440-470), XI2 `ReplayDevice` of a stored `HostKeyTransition` (the same function as r5), `HostKey` entries (`deliver_routed_key`, `replay_frozen_key_to_focus`). - [ ] **Step 1: core replay.** `r4_replay_pointer_rechecks_the_natural_target`: a sync passive button grab, the activating write to the owner denied; `AllowEvents(ReplayPointer)`; the natural selector B gets the press with its own call in the trace. `@press` checkpoint: B asked nothing, freeze and stored press as with no policy (kill: a check added at the store or the replay choice). Denied variant with B denied: the replayed press continues to the next allowed selector (kill: the replay walk made selection-only, e.g. `None` for the replay dispatch's memo). `r5_replay_keyboard_rechecks_the_focus`: the same for a sync key grab and `AllowEvents(ReplayKeyboard)`. -- [ ] **Step 2: thaw.** `r6_thawed_queued_motion_is_checked_at_its_write`: a sync pointer grab with `owner_events`, a motion queued; `@queue` asks nothing; `AllowEvents(AsyncPointer)` thaws it and it is asked for its own recipient; the denied recipient loses it, nobody else changes. Kill: the thawed write made unchecked when `state.playing_sync_events` (name the exact site in the row comment). `r7_thawed_queued_key_is_checked_at_its_write`: the same for a queued `HostKeyTransition` and the master `RawKey` leg (`AllowEvents(AsyncKeyboard)`). The per-entry memo for whole-event entries is structural (each is its own dispatch); a memo hoisted out of the `xi1_compute_freezes` loop is killable only with two equal-key `Xi1Routed` entries in one pass: add that row only if the shape is constructible, otherwise the report says it is not and the controller records it. `r8_denied_xi1_activating_write_still_replays`: an XI1 passive sync grab whose activating write to the owner is denied, then `AllowDeviceEvents(ReplayThisDevice)`: the press replays to the natural selector as with no policy, checked at that write. +- [ ] **Step 2: thaw.** `r6_thawed_queued_motion_is_checked_at_its_write`: a sync pointer grab with `owner_events`, a motion queued; `@queue` asks nothing; `AllowEvents(AsyncPointer)` thaws it and it is asked for its own recipient; the owner's natural copy denied, the motion falls back to the grab window with that attempt's own check, as at a live write (a second variant also denies the grab-window copy: the owner gets nothing and stays grabbed). Kill: the thawed write made unchecked when `state.playing_sync_events` (name the exact site in the row comment). `r7_thawed_queued_key_is_checked_at_its_write`: the same for a queued `HostKeyTransition` and the master `RawKey` leg (`AllowEvents(AsyncKeyboard)`). The per-entry memo for whole-event entries is structural (each is its own dispatch); a memo hoisted out of the `xi1_compute_freezes` loop is killable only with two equal-key `Xi1Routed` entries in one pass: add that row only if the shape is constructible, otherwise the report says it is not and the controller records it. `r8_denied_xi1_activating_write_still_replays`: an XI1 passive sync grab whose activating write to the owner is denied, then `AllowDeviceEvents(ReplayThisDevice)`: the press replays to the natural selector as with no policy, checked at that write. Kill: the XI1 activation's store or freeze gated on the activating copy's check. - [ ] **Step 3: freeze.** `r9_denied_xi1_grab_window_write_trips_freeze_next`: an XI1 device grab, `AllowDeviceEvents(SyncThisDevice)` arms FreezeNextEvent, the next press's grab-window write denied: FrozenWithEvent with that press stored, as with no policy. Kill: `xi1_freeze_this_event_if_needed` in router step 2 (`pointer_fanout.rs` ~3392) gated on `deliver`. Pins only (no denial-dependent mutation exists on their path; say so in the comment): the same for a core pointer grab (`AllowEvents(SyncPointer)`) and a key grab (`AllowEvents(SyncKeyboard)`), which trip through the router's bridged branch (~3535). - [ ] **Step 4:** Every request step states its requester's replies and errors (none expected). Replay every probe. Gate. Commit `test(access): replay, thaw and freeze rows`. From 2497c21f7a499044cc593b73a131026856197b27 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 14:53:41 -0300 Subject: [PATCH 52/72] test(access): input runner states request bytes and hooks; shadow and XI1 grab-window rows Request steps state their requester's replies and errors per step, and the runner allows exactly the admission hooks of the request a step sent (one Dispatch for an extension opcode, none for a core one); any other non-Receive hook fails the row. A call takes its step's shorthand only when the step lists exactly one event. New rows: p5d (a denied master XI2 copy does not shadow that client's core copy; closes the P-5c gap carried from plan 2) and p26 (the XI1 implicit grab window is checked before the device mask). Co-Authored-By: Claude Opus 5.5 Implemented-By: codex (gpt-6-luna xhigh) --- .../tests/access_input_support.rs | 155 +++++++++++++++++- .../tests/access_pointer_input.rs | 149 +++++++++++++++++ 2 files changed, 295 insertions(+), 9 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index 35efbab5f..c56543ee2 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -25,7 +25,7 @@ use crate::{ server::{QueuedInputEvent, ServerState, Xi1SyncState}, xinput::DEVICEID_XTEST_KEYBOARD, }; -use std::{collections::BTreeMap, sync::atomic::Ordering}; +use std::{cell::RefCell, collections::BTreeMap, sync::atomic::Ordering}; use yserver_protocol::x11::{ClientByteOrder, ClientId, RequestHeader, SequenceNumber}; pub(super) const SEND_CLIENT: u32 = 1; @@ -56,6 +56,15 @@ pub(super) const XI_RAW_KEY_PRESS: u32 = 1 << 13; /// The grab window of the grab rows: the root is on no walk to FOCUS. pub(super) const ROOT: u32 = ROOT_WINDOW.0; +thread_local! { + /// Requests sent by the test helper since the runner's previous step. + static SENT_REQUESTS: RefCell> = const { RefCell::new(Vec::new()) }; +} + +fn take_sent_requests() -> Vec<(u32, u8)> { + SENT_REQUESTS.with(|requests| std::mem::take(&mut *requests.borrow_mut())) +} + /// One frame the server writes: (client, what it is, event window). type Frame = (u32, Kind, u32); /// One Receive call the server makes: (client, description, subject window). @@ -112,7 +121,7 @@ pub(super) enum Named { } /// A Receive call as traced: (client, ordered descriptions, subject window). -type Seen = (u32, Vec, u32); +pub(super) type Seen = (u32, Vec, u32); /// The traced form of an expected call. The shorthand kinds name one /// description with the row's event type. @@ -228,6 +237,7 @@ fn next_sequence(f: &NotifyFixture, client: u32) -> u16 { /// client and checks it was handled with no writer failure. Nothing is drained: /// the bytes the request makes any client write stay queued. pub(super) fn request(f: &mut NotifyFixture, client: u32, opcode: u8, data: u8, body: &[u8]) { + SENT_REQUESTS.with(|requests| requests.borrow_mut().push((client, opcode))); let sequence = next_sequence(f, client); let header = RequestHeader { opcode, @@ -666,6 +676,8 @@ struct ClientBytes { bytes: Vec, /// Per step: the byte length after it and the client's sequence then. steps: Vec<(usize, u16)>, + /// The bytes added for each step, for request replies and errors. + step_bytes: Vec>, } /// One fact of the grab state after a run. A row states the facts its denied @@ -788,6 +800,12 @@ struct Run { calls: Vec, /// The event types of the step that made each call, parallel to `calls`. call_evs: Vec>, + /// Every hook, with the scenario step that caused it. + hooks: Vec<(usize, RecordedExtensionCheck)>, + /// Requests the runner's `request()` helper sent, by step. + requests: Vec<(usize, u32, u8)>, + /// Requester replies and X errors, by step and first byte. + replies: Vec<(usize, u32, u8)>, state: String, grab: Vec, } @@ -988,6 +1006,8 @@ pub(super) struct Outcome { pub(super) frames: &'static [Frame], pub(super) moved: &'static [Move], pub(super) calls: &'static [Call], + /// Requester replies and X errors: (step, client, first byte). + pub(super) replies: &'static [(usize, u32, u8)], pub(super) grab: Option<&'static [Grab]>, } @@ -996,6 +1016,7 @@ pub(super) const NOTHING: Outcome = Outcome { frames: &[], moved: &[], calls: &[], + replies: &[], grab: None, }; @@ -1050,6 +1071,7 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run for client in [SEND_CLIENT, A, B] { f.drain(ClientId(client)); } + take_sent_requests(); let step_evs: Vec> = step_events(scenario) .iter() .map(|drives| drives.iter().map(|drive| drive.ev()).collect()) @@ -1065,17 +1087,33 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run order: f.state.clients[&client].byte_order, bytes: Vec::new(), steps: Vec::new(), + step_bytes: Vec::new(), }) .collect(); let mut call_evs = Vec::new(); let mut seen_calls = 0; + let mut call_steps = Vec::new(); + let mut requests = Vec::new(); for (index, step) in scenario.steps.iter().enumerate() { + take_sent_requests(); match step { Step::Event(event) => drive(&mut f, *event), Step::Request(request, _) => request(&mut f), } + let sent = take_sent_requests(); + assert_eq!( + sent.len(), + usize::from(matches!(step, Step::Request(..))), + "{name}: step {index} sent the expected number of requests" + ); + requests.extend( + sent.into_iter() + .map(|(client, opcode)| (index, client, opcode)), + ); for client in &mut clients { - client.bytes.extend(f.drain(ClientId(client.client))); + let step_bytes = f.drain(ClientId(client.client)); + client.bytes.extend_from_slice(&step_bytes); + client.step_bytes.push(step_bytes); let sequence = f.state.clients[&client.client] .last_sequence .load(Ordering::Relaxed); @@ -1084,6 +1122,7 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run if let Some(recorder) = &recorder { let total = recorder.lock().unwrap().len(); call_evs.extend((seen_calls..total).map(|_| step_evs[index].clone())); + call_steps.extend((seen_calls..total).map(|_| index)); seen_calls = total; } } @@ -1091,8 +1130,21 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run client_io::failed_writers(&f.state.clients).is_empty(), "{name}: delivery queued a disconnect" ); - // The recorder holds every hook; keep the named Receive calls, with the - // event type of the step that made each. + let hooks = recorder + .as_ref() + .map(|recorder| { + recorder + .lock() + .unwrap() + .iter() + .cloned() + .zip(call_steps) + .map(|(call, step)| (step, call)) + .collect() + }) + .unwrap_or_default(); + // Keep the named Receive calls, with the event type of the step that made + // each. Other hooks are checked separately against the request step. let (calls, call_evs) = recorder .map(|recorder| { recorder @@ -1111,10 +1163,36 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run .unzip() }) .unwrap_or_default(); + let replies = clients + .iter() + .flat_map(|client| { + client + .step_bytes + .iter() + .enumerate() + .filter_map(|(step, bytes)| { + let requester = requests.iter().find_map(|(request_step, requester, _)| { + (*request_step == step).then_some(*requester) + }); + (requester == Some(client.client) + && matches!(scenario.steps[step], Step::Request(..))) + .then_some((step, bytes.as_slice())) + }) + .flat_map(move |(step, bytes)| { + split_frames(bytes, client.order) + .into_iter() + .filter(|frame| matches!(frame[0], 0 | 1)) + .map(move |frame| (step, client.client, frame[0])) + }) + }) + .collect(); Run { clients, calls, call_evs, + hooks, + requests, + replies, state: format!("{:?}", (f.state.core_focus.raw, f.state.keys_down)), grab: grab_facts(&f.state), } @@ -1197,12 +1275,12 @@ fn moved_frames(name: &str, allow: &Run, denied: &Run) -> Vec<(u32, Move)> { /// A recorded call with a shorthand's number zeroed when it names one of the /// events of the step that made it, so it compares with a shorthand entry of a /// row. -fn canonical_seen(call: &Seen, evs: &[u16]) -> Seen { +pub(super) fn canonical_seen(call: &Seen, evs: &[u16]) -> Seen { let (client, names, window) = call; let own = match names.as_slice() { - [Named::Core(n)] if evs.contains(n) => vec![Named::Core(0)], - [Named::Xi2(n)] if evs.contains(n) => vec![Named::Xi2(0)], - [Named::Raw(n)] if evs.contains(n) => vec![Named::Raw(0)], + [Named::Core(n)] if evs.len() == 1 && evs[0] == *n => vec![Named::Core(0)], + [Named::Xi2(n)] if evs.len() == 1 && evs[0] == *n => vec![Named::Xi2(0)], + [Named::Raw(n)] if evs.len() == 1 && evs[0] == *n => vec![Named::Raw(0)], _ => names.clone(), }; (*client, own, *window) @@ -1213,9 +1291,56 @@ fn canonical_call(call: &Call) -> Seen { expected_call(call, 0) } +fn check_hooks(name: &str, mode: &str, scenario: &Scenario, run: &Run) { + for (step_index, step) in scenario.steps.iter().enumerate() { + let actual: Vec<_> = run + .hooks + .iter() + .filter(|(index, call)| *index == step_index && call.hook != ExtensionHook::Receive) + .map(|(_, call)| call) + .collect(); + let request = run + .requests + .iter() + .find(|(index, _, _)| *index == step_index); + let expected_dispatch = match step { + Step::Event(_) => None, + Step::Request(..) => { + let (_, client, opcode) = request.unwrap_or_else(|| { + panic!("{name} [{mode}]: request step {step_index} did not record its request") + }); + (*opcode >= 128).then_some((*client, *opcode)) + } + }; + assert_eq!( + actual.len(), + usize::from(expected_dispatch.is_some()), + "{name} [{mode}]: step {step_index} non-Receive hooks" + ); + if let Some((client, opcode)) = expected_dispatch { + let hook = actual[0]; + assert_eq!( + hook.hook, + ExtensionHook::Dispatch, + "{name} [{mode}]: step {step_index} hook" + ); + assert_eq!( + hook.client.0, client, + "{name} [{mode}]: step {step_index} requester" + ); + assert_eq!( + hook.request.map(|request| request.major), + Some(opcode), + "{name} [{mode}]: step {step_index} dispatch opcode" + ); + } + } +} + /// Compares a run's frames and Receive trace with a stated outcome. A shorthand /// call names the event of the step that made it (`Core(0)` below). fn check_outcome(name: &str, mode: &str, scenario: &Scenario, run: &Run, want: &Outcome) { + check_hooks(name, mode, scenario, run); let got: Vec = run .calls .iter() @@ -1235,6 +1360,18 @@ fn check_outcome(name: &str, mode: &str, scenario: &Scenario, run: &Run, want: & "{name} [{mode}]: Receive calls ({:?}) differ\n got: {got:?}\n want: {calls:?}", scenario.order ); + let grouped_replies = |replies: &[(usize, u32, u8)]| { + let mut grouped = BTreeMap::<(usize, u32), Vec>::new(); + for &(step, client, first_byte) in replies { + grouped.entry((step, client)).or_default().push(first_byte); + } + grouped + }; + assert_eq!( + grouped_replies(&run.replies), + grouped_replies(want.replies), + "{name} [{mode}]: requester replies and errors" + ); let steps: Vec> = step_events(scenario) .iter() .map(|drives| { diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index f076309d5..98ca938d3 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -316,6 +316,15 @@ fn setup_p5c(f: &mut NotifyFixture) { select_xi2(f, A, FOCUS, DEVICEID_XTEST_POINTER, XI_MOTION); } +/// A and B select the master copy on P; A also selects core on C. Denying +/// A's master copy must leave A eligible for the core copy on the walk. +fn setup_p5d(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, FOCUS, DEVICEID_MASTER_POINTER, XI_MOTION); + select_xi2(f, B, FOCUS, DEVICEID_MASTER_POINTER, XI_MOTION); + select_core(f, A, CHILD, CORE_MOTION); +} + fn setup_p6(f: &mut NotifyFixture) { tree(f); select_xi2(f, A, CHILD, DEVICEID_XTEST_POINTER, XI_BUTTON_PRESS); @@ -629,6 +638,13 @@ fn setup_p26_foreign_rejects(f: &mut NotifyFixture) { select_xi1(f, A, FOCUS, &[xi1_slave_press()]); } +/// A selects only XI1 DeviceButtonPress on C. Its press creates an implicit +/// XI1 grab whose device mask excludes the following motion. +fn setup_p26_implicit_device_mask(f: &mut NotifyFixture) { + tree(f); + select_xi1(f, A, CHILD, &[xi1_slave_press()]); +} + fn setup_p27(f: &mut NotifyFixture) { tree(f); select_xi1(f, A, CHILD, &[xi1_slave_press()]); @@ -818,6 +834,8 @@ const P26_FALLS_TO_ROOT: Outcome = Outcome { (A, XI1_PRESS_CALL, ROOT), ], grab: None, + + ..NOTHING }; /// The requester's sync grab on P holds the slave frozen with the routed press. @@ -965,6 +983,8 @@ const ROWS: &[InputRow] = &[ moved: &[moved(A, Kind::Core, FOCUS, CHILD, P_EVENT)], calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], grab: Some(&[implicit(A, FOCUS, false)]), + + ..NOTHING }, }, // Mutation: an XI2 selection absorbs the walk whether or not its copy is @@ -983,6 +1003,8 @@ const ROWS: &[InputRow] = &[ moved: &[moved(A, Kind::Core, FOCUS, CHILD, P_EVENT)], calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Core, FOCUS)], grab: Some(&[implicit(A, FOCUS, false)]), + + ..NOTHING }, }, // Mutation: the XI2 route window is the first window with a selection rather @@ -1007,6 +1029,8 @@ const ROWS: &[InputRow] = &[ )], calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], grab: Some(&[implicit(A, FOCUS, true)]), + + ..NOTHING }, }, // B's slave and master forms at C come from one check. Denied: B gets @@ -1033,6 +1057,8 @@ const ROWS: &[InputRow] = &[ )], calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], grab: None, + + ..NOTHING }, }, // A slave motion moves the sprite from P into C. B selects the slave form on C @@ -1091,6 +1117,8 @@ const ROWS: &[InputRow] = &[ moved: &[moved(A, Kind::Core, CHILD, 0, C_EVENT)], calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], grab: Some(&[implicit(A, CHILD, false)]), + + ..NOTHING }, }, // Denying A's core copy at C changes nothing: a shadowed core copy is not @@ -1115,6 +1143,8 @@ const ROWS: &[InputRow] = &[ moved: &[moved(A, Kind::Core, CHILD, 0, C_EVENT)], calls: &[(A, CallKind::Xi2, FOCUS), (A, CallKind::Core, CHILD)], grab: Some(&[implicit(A, CHILD, false)]), + + ..NOTHING }, }, // Denied: the master route is P (A's master copy), so A's core copy at C is @@ -1153,6 +1183,8 @@ const ROWS: &[InputRow] = &[ )], calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], grab: None, + + ..NOTHING }, }, // A slave press: A's core copy is deferred behind the slave pass. Denying it @@ -1183,6 +1215,41 @@ const ROWS: &[InputRow] = &[ ..NOTHING }, }, + // A and B select master XI2 on P; denied A also selects core on C. + // Mutation: build the shadow list from selection-only recipients at P, so + // A's denied master copy still shadows its core copy on the walk. Xorg + // 21.1.24 checks Receive before delivery to each client (`dix/events.c:2291`). + InputRow { + name: "p5d_denied_master_copy_does_not_shadow_that_clients_core", + scenario: &Scenario { + setup: setup_p5d, + steps: &[motion(XTEST_MASTER)], + allow: Outcome { + frames: &[ + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS), + (B, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS), + ], + calls: &[(A, CallKind::Xi2, FOCUS), (B, CallKind::Xi2, FOCUS)], + ..NOTHING + }, + order: CallOrder::PerClient, + }, + deny: &[(A, CallKind::Xi2, FOCUS)], + denied: Outcome { + frames: &[ + (A, Kind::Core, CHILD), + (B, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS), + ], + moved: &[moved(A, Kind::Core, CHILD, 0, (15, 15))], + calls: &[ + (A, CallKind::Xi2, FOCUS), + (B, CallKind::Xi2, FOCUS), + (A, CallKind::Core, CHILD), + ], + grab: None, + ..NOTHING + }, + }, // Guard: a master form that is not written asks nothing, so denying B's copy // changes nothing. Passes today. InputRow { @@ -1216,6 +1283,8 @@ const ROWS: &[InputRow] = &[ moved: &[moved(A, Kind::Core, FOCUS, CHILD, P_EVENT)], calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], grab: None, + + ..NOTHING }, }, // Mutation: the denied owner keeps walking (or is dropped) although an allowed @@ -1238,6 +1307,8 @@ const ROWS: &[InputRow] = &[ (A, CallKind::Core, ROOT), ], grab: None, + + ..NOTHING }, }, // Mutation: the core fallback takes the memo's result for (A, G, core) @@ -1280,6 +1351,8 @@ const ROWS: &[InputRow] = &[ moved: &[moved(A, Kind::Core, FOCUS, CHILD, P_EVENT)], calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], grab: None, + + ..NOTHING }, }, // Mutation: the foreign selectors are evaluated before the owner (an extra @@ -1303,6 +1376,8 @@ const ROWS: &[InputRow] = &[ (A, CallKind::Core, ROOT), ], grab: None, + + ..NOTHING }, }, // Mutation: the owner qualifies only through the first protocol it selected @@ -1321,6 +1396,8 @@ const ROWS: &[InputRow] = &[ moved: &[moved(A, Kind::Core, CHILD, 0, C_EVENT)], calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], grab: None, + + ..NOTHING }, }, // A denial at the grab window is a delivery: C's selectors get nothing. @@ -1397,6 +1474,8 @@ const ROWS: &[InputRow] = &[ (A, CallKind::Xi2, ROOT), ], grab: None, + + ..NOTHING }, }, // The fallback reuses the memo for G (one call for A at C here): no probe @@ -1611,6 +1690,8 @@ const ROWS: &[InputRow] = &[ moved: &[moved(B, Kind::Core, FOCUS, CHILD, P_EVENT)], calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, FOCUS)], grab: Some(&[implicit(B, FOCUS, false)]), + + ..NOTHING }, }, // The release, with the pointer still over C, goes to B at P. @@ -1639,6 +1720,8 @@ const ROWS: &[InputRow] = &[ (B, CallKind::Core, FOCUS), ], grab: None, + + ..NOTHING }, }, // A alone on C, denied: nobody receives the press and no pointer grab is @@ -1722,6 +1805,8 @@ const ROWS: &[InputRow] = &[ )], calls: &[(A, CallKind::Xi2, CHILD), (B, XI1_PRESS_CALL, CHILD)], grab: Some(&[xi1_implicit(B, CHILD)]), + + ..NOTHING }, }, // A's XI1 press selector on C is denied, B's on P is not: the walk continues @@ -1753,6 +1838,8 @@ const ROWS: &[InputRow] = &[ )], calls: &[(A, XI1_PRESS_CALL, CHILD), (B, XI1_PRESS_CALL, FOCUS)], grab: Some(&[xi1_implicit(B, FOCUS)]), + + ..NOTHING }, }, // Two XI1 press selectors on C, the one that also selected the button grab @@ -1925,6 +2012,8 @@ const ROWS: &[InputRow] = &[ (B, SCROLL_MOTION_CALL, FOCUS), ], grab: None, + + ..NOTHING }, }, // The stop routes from its own probe hit. A's denied batch on C drops A's two @@ -2028,6 +2117,8 @@ const ROWS: &[InputRow] = &[ )], calls: &[(A, XI1_MOTION_CALL, CHILD), (B, XI1_MOTION_CALL, FOCUS)], grab: None, + + ..NOTHING }, }, // The motion event and its valuator continuation are decided by one call with @@ -2094,6 +2185,32 @@ const ROWS: &[InputRow] = &[ deny: &[(A, XI1_PRESS_CALL, CHILD)], denied: P26_FALLS_TO_ROOT, }, + // The press creates an implicit XI1 grab on C with a press-only device + // mask. The later motion is not written, but its grab-window Receive check + // still occurs before the mask, as in Xorg 21.1.24 `dix/events.c:4390`. + // Mutation: move that check below the device-mask test; the denied motion + // attempt then disappears from the trace. + InputRow { + name: "p26_xi1_implicit_grab_window_is_checked_before_the_device_mask", + scenario: &Scenario { + setup: setup_p26_implicit_device_mask, + steps: &[press(XTEST_SLAVE), motion(XTEST_SLAVE)], + allow: Outcome { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + calls: &[(A, XI1_PRESS_CALL, CHILD), (A, XI1_MOTION_CALL, CHILD)], + grab: Some(&[xi1_implicit(A, CHILD)]), + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, XI1_MOTION_CALL, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + calls: &[(A, XI1_PRESS_CALL, CHILD), (A, XI1_MOTION_CALL, CHILD)], + grab: Some(&[xi1_implicit(A, CHILD)]), + ..NOTHING + }, + }, // An XIGrabDevice on the slave with `owner_events` and ButtonPress in its // mask; A selects the XI1 press on C. A's XI1 copy denied: the XI2 route // falls back to the grab window and the XI1 selection path delivers nothing @@ -2124,6 +2241,8 @@ const ROWS: &[InputRow] = &[ )], calls: &[(A, XI1_PRESS_CALL, CHILD), (A, CallKind::Xi2, ROOT)], grab: None, + + ..NOTHING }, }, // B's foreign XI1 copy on C is denied, A's own is on P. Allow-all: B's copy @@ -2155,6 +2274,8 @@ const ROWS: &[InputRow] = &[ )], calls: &[(B, XI1_PRESS_CALL, CHILD), (A, XI1_PRESS_CALL, FOCUS)], grab: None, + + ..NOTHING }, }, // A sync `GrabDeviceButton` by the requester on P activates on the press and @@ -2212,3 +2333,31 @@ const ROWS: &[InputRow] = &[ fn pointer_rows() { check_rows(ROWS); } + +#[test] +fn multi_event_request_keeps_swapped_press_and_motion_calls_distinct() { + fn no_request(_: &mut NotifyFixture) {} + + const REQUEST_DRIVES: &[Step] = &[press(XTEST_SLAVE), motion(XTEST_SLAVE)]; + let request_step = Step::Request(no_request, REQUEST_DRIVES); + let Step::Request(_, drives) = request_step else { + unreachable!(); + }; + let evs: Vec<_> = drives + .iter() + .map(|step| match step { + Step::Event(drive) => drive.ev(), + Step::Request(..) => unreachable!(), + }) + .collect(); + assert_eq!(evs, [4, 6], "the request step names press then motion"); + + let press: Seen = (A, vec![Named::Xi2(4)], CHILD); + let motion: Seen = (A, vec![Named::Xi2(6)], CHILD); + let ordered = [canonical_seen(&press, &evs), canonical_seen(&motion, &evs)]; + let stated = [press.clone(), motion.clone()]; + assert_eq!(ordered, stated, "the event names remain explicit"); + + let swapped = [canonical_seen(&motion, &evs), canonical_seen(&press, &evs)]; + assert_ne!(swapped, stated, "a press/motion swap changes the trace"); +} From 8041510b758a0654b28cbd235531cefce2ef20a8 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 15:42:06 -0300 Subject: [PATCH 53/72] test(access): input runner checks replies from every client, full dispatch opcodes and server hooks Review round 1 of plan 3 Task 1: replies and errors are collected from every client at every step; the shared frame splitter reads a reply's wire length; a Dispatch hook is matched on the (major, minor) pair the request carried; the recording policy records Server hooks; the R2-I1 shortening rule is exercised through the p14 master replay row. Co-Authored-By: Claude Opus 5.5 Implemented-By: codex (gpt-6-luna max) --- .../tests/access_input_support.rs | 105 ++++++++++++++---- .../tests/access_notify_support.rs | 29 ++++- .../tests/access_pointer_input.rs | 50 ++++----- .../process_request/tests/extensions.rs | 16 +++ 4 files changed, 145 insertions(+), 55 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index c56543ee2..deb0745cf 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -9,7 +9,7 @@ use super::{ xi2::xi_select_body, }; use crate::{ - access::{Decision, EventDescription, EventSubject}, + access::{Decision, EventDescription, EventSubject, RequestOpcodes}, core_loop::{ InputOrigin, client_io, key_fanout::{ @@ -58,10 +58,10 @@ pub(super) const ROOT: u32 = ROOT_WINDOW.0; thread_local! { /// Requests sent by the test helper since the runner's previous step. - static SENT_REQUESTS: RefCell> = const { RefCell::new(Vec::new()) }; + static SENT_REQUESTS: RefCell> = const { RefCell::new(Vec::new()) }; } -fn take_sent_requests() -> Vec<(u32, u8)> { +fn take_sent_requests() -> Vec<(u32, u8, u8)> { SENT_REQUESTS.with(|requests| std::mem::take(&mut *requests.borrow_mut())) } @@ -237,13 +237,13 @@ fn next_sequence(f: &NotifyFixture, client: u32) -> u16 { /// client and checks it was handled with no writer failure. Nothing is drained: /// the bytes the request makes any client write stay queued. pub(super) fn request(f: &mut NotifyFixture, client: u32, opcode: u8, data: u8, body: &[u8]) { - SENT_REQUESTS.with(|requests| requests.borrow_mut().push((client, opcode))); let sequence = next_sequence(f, client); let header = RequestHeader { opcode, data, length_units: u32::try_from((4 + body.len()) / 4).expect("request length"), }; + SENT_REQUESTS.with(|requests| requests.borrow_mut().push((client, opcode, data))); let outcome = f .request(ClientId(client), SequenceNumber(sequence), header, body) .expect("request through process_request"); @@ -802,9 +802,10 @@ struct Run { call_evs: Vec>, /// Every hook, with the scenario step that caused it. hooks: Vec<(usize, RecordedExtensionCheck)>, - /// Requests the runner's `request()` helper sent, by step. - requests: Vec<(usize, u32, u8)>, - /// Requester replies and X errors, by step and first byte. + /// Requests the runner's `request()` helper sent, by step: client, major + /// opcode and data byte (the extension minor opcode). + requests: Vec<(usize, u32, u8, u8)>, + /// Reply and X error frames from every fixture client at every step. replies: Vec<(usize, u32, u8)>, state: String, grab: Vec, @@ -1108,7 +1109,7 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run ); requests.extend( sent.into_iter() - .map(|(client, opcode)| (index, client, opcode)), + .map(|(client, major, data)| (index, client, major, data)), ); for client in &mut clients { let step_bytes = f.drain(ClientId(client.client)); @@ -1170,14 +1171,6 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run .step_bytes .iter() .enumerate() - .filter_map(|(step, bytes)| { - let requester = requests.iter().find_map(|(request_step, requester, _)| { - (*request_step == step).then_some(*requester) - }); - (requester == Some(client.client) - && matches!(scenario.steps[step], Step::Request(..))) - .then_some((step, bytes.as_slice())) - }) .flat_map(move |(step, bytes)| { split_frames(bytes, client.order) .into_iter() @@ -1302,14 +1295,20 @@ fn check_hooks(name: &str, mode: &str, scenario: &Scenario, run: &Run) { let request = run .requests .iter() - .find(|(index, _, _)| *index == step_index); + .find(|(index, _, _, _)| *index == step_index); let expected_dispatch = match step { Step::Event(_) => None, Step::Request(..) => { - let (_, client, opcode) = request.unwrap_or_else(|| { + let (_, client, major, data) = request.unwrap_or_else(|| { panic!("{name} [{mode}]: request step {step_index} did not record its request") }); - (*opcode >= 128).then_some((*client, *opcode)) + (*major >= 128).then_some(( + *client, + RequestOpcodes { + major: *major, + minor: if *major < 128 { 0 } else { *data }, + }, + )) } }; assert_eq!( @@ -1329,9 +1328,9 @@ fn check_hooks(name: &str, mode: &str, scenario: &Scenario, run: &Run) { "{name} [{mode}]: step {step_index} requester" ); assert_eq!( - hook.request.map(|request| request.major), + hook.request, Some(opcode), - "{name} [{mode}]: step {step_index} dispatch opcode" + "{name} [{mode}]: step {step_index} dispatch opcode pair" ); } } @@ -1360,6 +1359,26 @@ fn check_outcome(name: &str, mode: &str, scenario: &Scenario, run: &Run, want: & "{name} [{mode}]: Receive calls ({:?}) differ\n got: {got:?}\n want: {calls:?}", scenario.order ); + for &(step, client, first_byte) in want.replies { + assert!( + matches!(first_byte, 0 | 1), + "{name} [{mode}]: stated reply frame type is 0 or 1" + ); + assert!( + matches!(scenario.steps.get(step), Some(Step::Request(..))), + "{name} [{mode}]: stated reply is on request step {step}" + ); + let requester = run + .requests + .iter() + .find(|(request_step, _, _, _)| *request_step == step) + .map(|(_, requester, _, _)| *requester); + assert_eq!( + requester, + Some(client), + "{name} [{mode}]: stated reply belongs to that step's requester" + ); + } let grouped_replies = |replies: &[(usize, u32, u8)]| { let mut grouped = BTreeMap::<(usize, u32), Vec>::new(); for &(step, client, first_byte) in replies { @@ -1370,7 +1389,7 @@ fn check_outcome(name: &str, mode: &str, scenario: &Scenario, run: &Run, want: & assert_eq!( grouped_replies(&run.replies), grouped_replies(want.replies), - "{name} [{mode}]: requester replies and errors" + "{name} [{mode}]: reply and error frames by step and client" ); let steps: Vec> = step_events(scenario) .iter() @@ -1392,6 +1411,48 @@ fn check_outcome(name: &str, mode: &str, scenario: &Scenario, run: &Run, want: & ); } +/// Exercises the real runner and verifies its stated outcome rejects a swap +/// between two named events produced by one multi-event request step. +pub(super) fn assert_swapped_request_calls_fail( + name: &str, + scenario: &Scenario, + client: u32, + window: u32, + request_events: &[u16], + first_event: u16, + second_event: u16, +) { + let run = play(name, scenario, Some(&[])); + let call_index = |event| { + run.calls + .iter() + .zip(&run.call_evs) + .position(|(call, evs)| { + call.0 == client + && call.1.as_slice() == [Named::Xi2(event)] + && call.2 == window + && evs.as_slice() == request_events + }) + .unwrap_or_else(|| panic!("{name}: request recorded the XI2 event {event}")) + }; + let first = call_index(first_event); + let second = call_index(second_event); + assert!( + first < second, + "{name}: request checks events in stated order" + ); + + let mut swapped = run; + swapped.calls.swap(first, second); + let rejected = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + check_outcome(name, "allow-all", scenario, &swapped, &scenario.allow); + })); + assert!( + rejected.is_err(), + "{name}: runner rejects swapped request calls" + ); +} + /// Runs one row under no policy, an allow-all policy and the row's denial. /// Allow-all must equal no policy in bytes, state and grab facts; each run is /// compared with its stated outcome; the denied run's moved frames, grab and diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_notify_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_notify_support.rs index 0dce86e84..7e104bcd5 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_notify_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_notify_support.rs @@ -309,13 +309,14 @@ impl Row { } } -/// Splits one client's stream into frames: 32 bytes each, except GenericEvent -/// (type 35), whose length in the client's byte order gives `32 + 4 * length`. +/// Splits one client's stream into frames: 32 bytes each, except replies +/// (type 1) and GenericEvents (type 35), whose length in the client's byte +/// order gives `32 + 4 * length`. pub(super) fn split_frames(bytes: &[u8], order: ClientByteOrder) -> Vec<&[u8]> { let mut frames = Vec::new(); let mut rest = bytes; while !rest.is_empty() { - let size = if (rest[0] & 0x7f) == 35 { + let size = if rest[0] == 1 || (rest[0] & 0x7f) == 35 { let length: [u8; 4] = rest[4..8].try_into().unwrap(); let length = match order { ClientByteOrder::LittleEndian => u32::from_le_bytes(length), @@ -559,4 +560,26 @@ mod split_frame_tests { assert_eq!(lengths, [32, 40], "{order:?}"); } } + + #[test] + fn split_frames_honours_variable_reply_length() { + for order in [ClientByteOrder::LittleEndian, ClientByteOrder::BigEndian] { + let mut reply = vec![0_u8; 36]; + reply[0] = 1; + let length = match order { + ClientByteOrder::LittleEndian => 1_u32.to_le_bytes(), + ClientByteOrder::BigEndian => 1_u32.to_be_bytes(), + }; + reply[4..8].copy_from_slice(&length); + let event = vec![0_u8; 32]; + let stream = [reply, event].concat(); + let frames = split_frames(&stream, order); + assert_eq!( + frames.iter().map(|frame| frame.len()).collect::>(), + [36, 32], + "{order:?}" + ); + assert_eq!(frames[0][0], 1, "{order:?}: reply stays one frame"); + } + } } diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index 98ca938d3..8422a5896 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -679,8 +679,10 @@ const XI1_MOTION_CALL: CallKind = CallKind::Batch(&[ Named::Xi1(crate::xinput::XI_DEVICE_VALUATOR_OFFSET as u16), ]); -/// The XI2 Motion description, for a request step that replays a press and then -/// releases the motion queued behind it. +/// The XI2 press description, stated explicitly beside the Motion in a replay +/// request so the two calls remain distinguishable. +const XI2_PRESS_CALL: CallKind = CallKind::Batch(&[Named::Xi2(4)]); +/// The XI2 Motion description, for the motion queued behind a replayed press. const MOTION_CALL: CallKind = CallKind::Batch(&[Named::Xi2(6)]); const RAW_BUTTON_PRESS_CALL: CallKind = CallKind::Batch(&[Named::Raw(15)]); /// The scroll Motion of a wheel press: not the press's own event, so a batch. @@ -1585,15 +1587,20 @@ const ROWS: &[InputRow] = &[ deny: &[(A, CallKind::Xi2, CHILD)], denied: ASKED_A_XI2_CHILD, }, - // XIAllowEvents(ReplayDevice) replays the stored press, not the motion queued - // behind it: the request step states the event it writes. + // XIAllowEvents(ReplayDevice) replays the stored press and then releases the + // motion queued behind it. Both checks happen in this one request step. + // Mutation: shortening every event named by this two-event step erases the + // press/motion distinction; swapping the checks then escapes the row. InputRow { name: "p14_denied_xi2_activating_press_from_a_master_origin_still_freezes@replay", scenario: &Scenario { steps: &[ press(XTEST_MASTER), motion(XTEST_MASTER), - Step::Request(allow_master::, &[press(XTEST_MASTER)]), + Step::Request( + allow_master::, + &[press(XTEST_MASTER), motion(XTEST_MASTER)], + ), ], allow: Outcome { frames: &[ @@ -1602,7 +1609,7 @@ const ROWS: &[InputRow] = &[ ], calls: &[ (A, CallKind::Xi2, CHILD), - (A, CallKind::Xi2, CHILD), + (A, XI2_PRESS_CALL, CHILD), (A, MOTION_CALL, CHILD), ], grab: Some(&[implicit(A, CHILD, true)]), @@ -1612,7 +1619,7 @@ const ROWS: &[InputRow] = &[ }, deny: &[(A, CallKind::Xi2, CHILD)], denied: Outcome { - calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Xi2, CHILD)], + calls: &[(A, CallKind::Xi2, CHILD), (A, XI2_PRESS_CALL, CHILD)], grab: Some(&[]), ..NOTHING }, @@ -2335,29 +2342,12 @@ fn pointer_rows() { } #[test] -fn multi_event_request_keeps_swapped_press_and_motion_calls_distinct() { - fn no_request(_: &mut NotifyFixture) {} - - const REQUEST_DRIVES: &[Step] = &[press(XTEST_SLAVE), motion(XTEST_SLAVE)]; - let request_step = Step::Request(no_request, REQUEST_DRIVES); - let Step::Request(_, drives) = request_step else { - unreachable!(); - }; - let evs: Vec<_> = drives +fn multi_event_request_runner_rejects_swapped_press_and_motion_calls() { + let row = ROWS .iter() - .map(|step| match step { - Step::Event(drive) => drive.ev(), - Step::Request(..) => unreachable!(), + .find(|row| { + row.name == "p14_denied_xi2_activating_press_from_a_master_origin_still_freezes@replay" }) - .collect(); - assert_eq!(evs, [4, 6], "the request step names press then motion"); - - let press: Seen = (A, vec![Named::Xi2(4)], CHILD); - let motion: Seen = (A, vec![Named::Xi2(6)], CHILD); - let ordered = [canonical_seen(&press, &evs), canonical_seen(&motion, &evs)]; - let stated = [press.clone(), motion.clone()]; - assert_eq!(ordered, stated, "the event names remain explicit"); - - let swapped = [canonical_seen(&motion, &evs), canonical_seen(&press, &evs)]; - assert_ne!(swapped, stated, "a press/motion swap changes the trace"); + .expect("the p14 master replay row"); + assert_swapped_request_calls_fail(row.name, row.scenario, A, CHILD, &[4, 6], 4, 6); } diff --git a/crates/yserver-core/src/core_loop/process_request/tests/extensions.rs b/crates/yserver-core/src/core_loop/process_request/tests/extensions.rs index 68ee5ff1d..6291554a8 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/extensions.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/extensions.rs @@ -7,6 +7,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(super) enum ExtensionHook { + Server, Access, Dispatch, Resource, @@ -234,6 +235,21 @@ impl RecordingExtensionPolicy { } impl AccessPolicy for RecordingExtensionPolicy { + fn server(&self, ctx: &AccessContext<'_>, client: ClientId, mode: AccessMode) -> Decision { + self.check( + ExtensionHook::Server, + ctx, + client, + "", + None, + None, + Some(mode), + None, + None, + None, + ) + } + fn extension_access( &self, ctx: &AccessContext<'_>, From cbed31a90abcb2bb1b99cc58eeaf575df98e4cf7 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 16:07:34 -0300 Subject: [PATCH 54/72] test(access): input runner matches each frame's detail to its own event Review round 2 of plan 3 Task 1: in a request step that lists several events, a frame's detail is checked against the event of the frame's decoded type, so a replayed ButtonPress written with detail 0 no longer borrows the motion's detail. The swap test checks the unswapped outcome first and requires the swapped run to fail at the Receive trace. Co-Authored-By: Claude Opus 5.5 Implemented-By: codex (gpt-6-luna max) --- .../tests/access_input_support.rs | 168 ++++++++++++++++-- .../tests/access_pointer_input.rs | 3 +- 2 files changed, 152 insertions(+), 19 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index deb0745cf..d61c4ebad 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -88,9 +88,9 @@ pub(super) enum Kind { /// The `DeviceValuator` continuation of a motion batch: its device. It has /// no event window; it decodes with window 0. Xi1Valuator(u16), - /// A raw key copy: its device, always on the root. A raw frame has no - /// event window, so the grab-leg copy and the root-fanout copy decode the - /// same; only the Receive trace tells them apart. + /// A raw XI2 input copy: its device, always on the root. A raw frame has + /// no event window, so the grab-leg copy and the root-fanout copy decode + /// the same; only the Receive trace tells them apart. Raw(u16), } @@ -194,6 +194,22 @@ impl Drive { } } + /// The input type used to match a frame's detail. Raw key events have + /// their own XI2 numbers, but correspond to the same key transition as the + /// core and XI2 device forms. + fn detail_event_type(self) -> u16 { + match self { + Drive::Raw { pressed, .. } => { + if pressed { + 2 + } else { + 3 + } + } + _ => self.ev(), + } + } + /// The detail byte every frame of this drive carries: the keycode for key /// events, the button for button events, zero for motion. pub(super) fn detail(self) -> u32 { @@ -610,8 +626,8 @@ pub(super) fn decide(denied: &[Call], evs: &[u16], call: &RecordedExtensionCheck /// Decodes a frame the walks write: a core key, button or motion event (event /// window at byte 12), an XI2 key, button or motion GenericEvent (device at -/// byte 10, event window at byte 24) or a raw key GenericEvent (device at byte -/// 10, always the root), or an XI1 device event. `None` for a frame that is no +/// byte 10, event window at byte 24) or a raw XI2 input GenericEvent (device at +/// byte 10, always the root), or an XI1 device event. `None` for a frame that is no /// input event (a reply, a crossing, a mapping notify...); an XI1 event frame or /// an XI2 touch frame with no `Kind` panics, so it is never skipped. pub(super) fn decode(frame: &[u8], order: ClientByteOrder) -> Option<(Kind, u32)> { @@ -670,6 +686,52 @@ pub(super) fn decode(frame: &[u8], order: ClientByteOrder) -> Option<(Kind, u32) } } +/// The event number a frame carries, normalized to the corresponding core/XI2 +/// input type. XI1's event code carries the same distinction in its code. +fn decoded_event_type(frame: &[u8], kind: Kind, order: ClientByteOrder) -> Option { + match kind { + Kind::Core => Some(u16::from(frame[0] & 0x7f)), + Kind::Xi1(_) => match frame[0] & 0x7f { + code if code + == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET => + { + Some(4) + } + code if code + == crate::server::XI_FIRST_EVENT + + crate::xinput::XI_DEVICE_BUTTON_RELEASE_OFFSET => + { + Some(5) + } + _ => unreachable!("decoded XI1 button frame has an unexpected event code"), + }, + Kind::Xi1Key(_) => match frame[0] & 0x7f { + code if code + == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET => + { + Some(2) + } + code if code + == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET => + { + Some(3) + } + _ => unreachable!("decoded XI1 key frame has an unexpected event code"), + }, + Kind::Xi1Motion(_) => Some(6), + Kind::Xi1Valuator(_) => None, + Kind::Xi2(_) => Some(dec16(&frame[8..10], order)), + Kind::Raw(_) => match dec16(&frame[8..10], order) { + 13 => Some(2), + 14 => Some(3), + 15 => Some(4), + 16 => Some(5), + 17 => Some(6), + _ => unreachable!("decoded XI2 raw frame has an unexpected event type"), + }, + } +} + struct ClientBytes { client: u32, order: ClientByteOrder, @@ -904,7 +966,7 @@ pub(super) fn grouped( /// checked against the client's sequence after the step that wrote the frame /// and the detail against the `(detail, wheel press)` of one of the events the /// step runs under. -fn delivered(name: &str, run: &Run, steps: &[Vec<(u32, bool)>]) -> Vec { +fn delivered(name: &str, run: &Run, steps: &[Vec<(u16, u32)>]) -> Vec { let mut frames = Vec::new(); for client in &run.clients { for frame in split_frames(&client.bytes, client.order) { @@ -924,21 +986,20 @@ fn delivered(name: &str, run: &Run, steps: &[Vec<(u32, bool)>]) -> Vec { ); // The valuator continuation has no detail byte (byte 1 is the // device). - let keycode = match kind { + let detail = match kind { Kind::Core | Kind::Xi1(_) | Kind::Xi1Key(_) | Kind::Xi1Motion(_) => { Some(u32::from(frame[1])) } Kind::Xi1Valuator(_) => None, Kind::Xi2(_) | Kind::Raw(_) => Some(dec32(&frame[16..20], client.order)), }; - // The smooth-scroll Motion of a wheel press carries no button. - let scroll_motion = - matches!(kind, Kind::Xi2(_)) && dec16(&frame[8..10], client.order) == 6; + let event_type = decoded_event_type(frame, kind, client.order); assert!( - keycode.is_none_or(|keycode| steps[step].iter().any(|&(detail, wheel)| { - keycode == if wheel && scroll_motion { 0 } else { detail } - })), - "{name}: client {} step {step} frame detail {keycode:?} is none of {:?}", + detail.is_none_or(|detail| { + event_type + .is_some_and(|event_type| steps[step].contains(&(event_type, detail))) + }), + "{name}: client {} step {step} frame event {event_type:?} detail {detail:?} is none of {:?}", client.client, steps[step] ); @@ -1391,12 +1452,20 @@ fn check_outcome(name: &str, mode: &str, scenario: &Scenario, run: &Run, want: & grouped_replies(want.replies), "{name} [{mode}]: reply and error frames by step and client" ); - let steps: Vec> = step_events(scenario) + let steps: Vec> = step_events(scenario) .iter() .map(|drives| { drives .iter() - .map(|drive| (drive.detail(), drive.is_wheel_press())) + .flat_map(|drive| { + let mut events = vec![(drive.detail_event_type(), drive.detail())]; + if drive.is_wheel_press() { + // A wheel button press also emits an XI2 Motion with + // detail zero for its smooth-scroll valuator update. + events.push((6, 0)); + } + events + }) .collect() }) .collect(); @@ -1423,6 +1492,7 @@ pub(super) fn assert_swapped_request_calls_fail( second_event: u16, ) { let run = play(name, scenario, Some(&[])); + check_outcome(name, "allow-all", scenario, &run, &scenario.allow); let call_index = |event| { run.calls .iter() @@ -1447,9 +1517,15 @@ pub(super) fn assert_swapped_request_calls_fail( let rejected = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { check_outcome(name, "allow-all", scenario, &swapped, &scenario.allow); })); + let panic = rejected.expect_err("{name}: runner rejects swapped request calls"); + let message = panic + .downcast_ref::() + .map(String::as_str) + .or_else(|| panic.downcast_ref::<&str>().copied()) + .unwrap_or_default(); assert!( - rejected.is_err(), - "{name}: runner rejects swapped request calls" + message.contains("Receive calls"), + "{name}: swapped calls fail at the Receive trace comparison, got {message:?}" ); } @@ -1532,6 +1608,62 @@ pub(super) fn check_rows(rows: &[InputRow]) { mod batch_naming { use super::*; + fn run_with_xi2_frame(evtype: u16, detail: u32) -> Run { + let order = ClientByteOrder::BigEndian; + let mut frame = [0_u8; 32]; + frame[0] = 35; + frame[1] = XI2_MAJOR_OPCODE; + frame[8..10].copy_from_slice(&evtype.to_be_bytes()); + frame[10..12].copy_from_slice(&crate::xinput::DEVICEID_MASTER_POINTER.to_be_bytes()); + frame[16..20].copy_from_slice(&detail.to_be_bytes()); + frame[24..28].copy_from_slice(&CHILD.to_be_bytes()); + Run { + clients: vec![ClientBytes { + client: A, + order, + bytes: frame.to_vec(), + steps: vec![(frame.len(), 0)], + step_bytes: vec![frame.to_vec()], + }], + calls: Vec::new(), + call_evs: Vec::new(), + hooks: Vec::new(), + requests: Vec::new(), + replies: Vec::new(), + state: String::new(), + grab: Vec::new(), + } + } + + /// Mutation: a replayed XI2 ButtonPress is encoded with detail zero. It + /// must not borrow zero from the Motion in the same request step. + #[test] + fn multi_event_frame_detail_is_checked_against_its_own_event_type() { + let bad_press = run_with_xi2_frame(4, 0); + let panic = std::panic::catch_unwind(|| { + delivered("multi-event detail", &bad_press, &[vec![(4, 1), (6, 0)]]) + }) + .expect_err("ButtonPress detail 0 must not borrow Motion detail 0"); + let message = panic + .downcast_ref::() + .map(String::as_str) + .or_else(|| panic.downcast_ref::<&str>().copied()) + .unwrap_or_default(); + assert!( + message.contains("frame event Some(4) detail Some(0)"), + "ButtonPress detail mismatch must be the rejected condition, got {message:?}" + ); + } + + #[test] + fn multi_event_motion_keeps_its_zero_detail() { + let motion = run_with_xi2_frame(6, 0); + assert_eq!( + delivered("multi-event detail", &motion, &[vec![(4, 1), (6, 0)]]), + vec![(A, Kind::Xi2(crate::xinput::DEVICEID_MASTER_POINTER), CHILD)] + ); + } + /// Mutation: a batch is traced by its first description, or the shorthand /// names a description with another event type than the row drives. The /// list order and each description's own numbering are what decide and the diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index 8422a5896..79c5a4e69 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -1590,7 +1590,8 @@ const ROWS: &[InputRow] = &[ // XIAllowEvents(ReplayDevice) replays the stored press and then releases the // motion queued behind it. Both checks happen in this one request step. // Mutation: shortening every event named by this two-event step erases the - // press/motion distinction; swapping the checks then escapes the row. + // press/motion distinction; encoding the replayed press with detail zero + // must fail even though the motion in this step correctly has detail zero. InputRow { name: "p14_denied_xi2_activating_press_from_a_master_origin_still_freezes@replay", scenario: &Scenario { From 91d5f3700e909c3091351da83ad9c9a2bea4f2ad Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 16:48:48 -0300 Subject: [PATCH 55/72] fix(access): the XI1 thaw filter asks no XI2 copy xi1_selection_filter_for_slave_grab routes the owner-events walk to choose which XI1 selector a slave XI2 grab lets through. On a thaw re-entry its memo is fresh, so its XI2 leg asked Receive for XI2 copies the thaw never writes. The XI2 leg now reuses a result the memo already holds (the live dispatch's slave route made it) and otherwise counts the selection, without asking. No policy and allow-all bytes are unchanged. A grab cannot outlive its owner's disconnect while input arrives (disconnect releases active grabs before the next HostInput), so the scroll stop and the filter need no gone-owner guard. Co-Authored-By: Claude Opus 5.5 Implemented-By: codex (gpt-6-luna xhigh) --- crates/yserver-core/src/core_loop/fanout.rs | 22 ++- .../src/core_loop/pointer_fanout.rs | 3 + .../core_loop/pointer_fanout/owner_events.rs | 37 ++++-- .../tests/access_pointer_input.rs | 125 +++++++++++++++++- 4 files changed, 168 insertions(+), 19 deletions(-) diff --git a/crates/yserver-core/src/core_loop/fanout.rs b/crates/yserver-core/src/core_loop/fanout.rs index 6053c0bc3..9c6fe9849 100644 --- a/crates/yserver-core/src/core_loop/fanout.rs +++ b/crates/yserver-core/src/core_loop/fanout.rs @@ -355,6 +355,20 @@ impl ReceiveMemo { } } + /// Return a result already recorded for this (client, subject, batch), + /// without asking the policy when the dispatch has no such entry. + pub(crate) fn known( + &self, + client: ClientId, + subject: EventSubject, + events: &EventBatch<'_>, + ) -> Option { + self.entries + .iter() + .find(|(c, s, e, _)| *c == client && *s == subject && e.as_slice() == events.events()) + .map(|(.., allowed)| *allowed) + } + /// First call per (client, subject, batch) asks `receive_allows`; later /// calls return the stored result without asking. pub(crate) fn allows( @@ -367,12 +381,8 @@ impl ReceiveMemo { if !state.policies_installed() { return true; } - if let Some((.., allowed)) = self - .entries - .iter() - .find(|(c, s, e, _)| *c == client && *s == subject && e.as_slice() == events.events()) - { - return *allowed; + if let Some(allowed) = self.known(client, subject, events) { + return allowed; } let allowed = receive_allows(state, client, subject, events); self.entries diff --git a/crates/yserver-core/src/core_loop/pointer_fanout.rs b/crates/yserver-core/src/core_loop/pointer_fanout.rs index a8d64625f..d70779eb5 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout.rs @@ -1471,6 +1471,7 @@ fn pointer_event_fanout_to_state_inner( None, Some(&mut receive), true, + false, ) }); if let Some(route) = natural_route { @@ -2058,6 +2059,7 @@ fn pointer_event_fanout_to_state_inner( xi1_class, slave_form_emitted.then_some(&mut receive), false, + false, ) } else { OwnerEventsRoute::Fallback @@ -2331,6 +2333,7 @@ fn pointer_event_fanout_to_state_inner( None, master_form_emitted.then_some(&mut receive), core_grab_routed, + false, ) } else { OwnerEventsRoute::Fallback diff --git a/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs b/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs index 7a4b55935..2edd6d367 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs @@ -142,6 +142,7 @@ pub(super) fn xi2_motion_targets_for_source( None, receive.as_deref_mut(), false, + false, ) } else { OwnerEventsRoute::Fallback @@ -286,6 +287,7 @@ pub(super) fn xi1_selection_filter_for_slave_grab( Some(class), Some(receive), false, + true, ) } else { OwnerEventsRoute::Fallback @@ -441,6 +443,8 @@ struct RouteLeg { /// nor rejects. `core_checked` says whether the core leg's copies are asked /// at all. The core copy's event code is the XI2 event type (4, 5, 6 are /// shared); a caller with no `xi2_evtype` has no core leg to check. +/// `xi2_known_only` uses an existing memo result for the XI2 leg and treats a +/// missing result as selection-only, without asking Receive. pub(super) fn owner_events_route( state: &ServerState, form: Xi2PointerForm, @@ -454,6 +458,7 @@ pub(super) fn owner_events_route( xi1_mask: Option, mut receive: Option<&mut ReceiveMemo>, core_checked: bool, + xi2_known_only: bool, ) -> OwnerEventsRoute { let mut current = start; let mut x = start_x; @@ -500,20 +505,29 @@ pub(super) fn owner_events_route( .collect(), }); } - let mut allowed = - |client: ClientId, batch: &[crate::access::EventDescription]| match receive - .as_deref_mut() - { - Some(memo) if !batch.is_empty() => memo.allows( - state, + let mut allowed = |client: ClientId, + batch: &[crate::access::EventDescription], + known_only: bool| match receive.as_deref_mut() + { + Some(memo) if !batch.is_empty() && known_only => memo + .known( client, crate::access::EventSubject::Window(current), &crate::access::EventBatch::new(batch), - ), - _ => true, - }; + ) + .unwrap_or(true), + Some(memo) if !batch.is_empty() => memo.allows( + state, + client, + crate::access::EventSubject::Window(current), + &crate::access::EventBatch::new(batch), + ), + _ => true, + }; for leg in &legs { - if leg.selectors.contains(&grab_client) && allowed(grab_client, &leg.batch) { + let known_only = xi2_known_only && matches!(leg.protocol, OwnerProtocol::Xi2); + if leg.selectors.contains(&grab_client) && allowed(grab_client, &leg.batch, known_only) + { return OwnerEventsRoute::Natural { window: current, x, @@ -525,8 +539,9 @@ pub(super) fn owner_events_route( } let mut rejected = false; for leg in &legs { + let known_only = xi2_known_only && matches!(leg.protocol, OwnerProtocol::Xi2); for client in leg.selectors.iter().filter(|c| **c != grab_client) { - rejected |= allowed(*client, &leg.batch); + rejected |= allowed(*client, &leg.batch, known_only); } } if rejected { diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index 79c5a4e69..60f05972d 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -178,19 +178,30 @@ fn grab_button(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: boo /// `XIPassiveGrabDevice` of button 1 on the master pointer by A on `ROOT`, any /// modifier, with the XI2 event mask, synchronous. fn xi_passive_grab_master(f: &mut NotifyFixture, owner_events: bool, mask: u32) { + xi_passive_grab_device(f, A, DEVICEID_MASTER_POINTER, owner_events, mask); +} + +/// `XIPassiveGrabDevice` on `device` by `owner`, any modifier, synchronous. +fn xi_passive_grab_device( + f: &mut NotifyFixture, + owner: u32, + device: u16, + owner_events: bool, + mask: u32, +) { let mut body = Vec::with_capacity(36); body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime body.extend_from_slice(&ROOT.to_le_bytes()); body.extend_from_slice(&0_u32.to_le_bytes()); // no cursor body.extend_from_slice(&1_u32.to_le_bytes()); // button 1 - body.extend_from_slice(&DEVICEID_MASTER_POINTER.to_le_bytes()); + body.extend_from_slice(&device.to_le_bytes()); body.extend_from_slice(&1_u16.to_le_bytes()); // one modifier body.extend_from_slice(&1_u16.to_le_bytes()); // one mask word body.extend_from_slice(&[0, 0, 1, u8::from(owner_events)]); // Button, sync, async paired, owner_events body.extend_from_slice(&0_u16.to_le_bytes()); // pad body.extend_from_slice(&mask.to_le_bytes()); body.extend_from_slice(&0x8000_0000_u32.to_le_bytes()); // XIAnyModifier - send_with_reply(f, A, XI_MAJOR, XI_PASSIVE_GRAB_DEVICE, &body); + send_with_reply(f, owner, XI_MAJOR, XI_PASSIVE_GRAB_DEVICE, &body); } /// The XI1 `GrabDevice` of the slave pointer by `owner` on `window`. @@ -241,6 +252,14 @@ fn allow_master(f: &mut NotifyFixture) { request(f, A, XI_MAJOR, XI_ALLOW_EVENTS, &body); } +fn allow_slave(f: &mut NotifyFixture) { + let mut body = Vec::with_capacity(8); + body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime + body.extend_from_slice(&DEVICEID_XTEST_POINTER.to_le_bytes()); + body.extend_from_slice(&[MODE, 0]); + request(f, A, XI_MAJOR, XI_ALLOW_EVENTS, &body); +} + fn replay_slave(f: &mut NotifyFixture) { let mut body = Vec::new(); body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime @@ -658,6 +677,24 @@ fn setup_p27_later_window(f: &mut NotifyFixture) { xi_grab_device(f, A, DEVICEID_XTEST_POINTER, ROOT, true, XI_BUTTON_PRESS); } +/// A selects the slave XI2 and XI1 press on C; a sync slave XI2 passive grab +/// with owner_events queues the XI1 press until AsyncDevice. +fn setup_p27_thawed_xi1_filter(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, CHILD, DEVICEID_XTEST_POINTER, XI_BUTTON_PRESS); + select_xi1(f, A, CHILD, &[xi1_slave_press()]); + xi_passive_grab_device(f, A, DEVICEID_XTEST_POINTER, true, XI_BUTTON_PRESS); +} + +/// The same selections as the thaw case, under an already active asynchronous +/// slave XI2 grab, so the XI1 filter shares the live dispatch's ReceiveMemo. +fn setup_p27_live_filter(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, CHILD, DEVICEID_XTEST_POINTER, XI_BUTTON_PRESS); + select_xi1(f, A, CHILD, &[xi1_slave_press()]); + xi_grab_device(f, A, DEVICEID_XTEST_POINTER, ROOT, true, XI_BUTTON_PRESS); +} + /// A sync `GrabDeviceButton` by the requester on P, plus two XI1 press /// selectors on C, of which B also selected the grab class. fn setup_p28(f: &mut NotifyFixture) { @@ -759,6 +796,17 @@ const SLAVE_GRAB: Grab = Grab::SlavePointer { }, }; +const SLAVE_PASSIVE_GRAB: Grab = Grab::SlavePointer { + device: DEVICEID_XTEST_POINTER, + grab: PointerGrab { + owner: A, + window: ROOT, + implicit: false, + passive: true, + via_xi2: true, + }, +}; + /// A selects core on C, XI2 (master) on P; B selects core on P. const P5B_ALLOW: Outcome = Outcome { frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], @@ -961,6 +1009,27 @@ const P14_OWNER_EVENTS: Scenario = Scenario { order: CallOrder::Total, }; +const P27_THAWED_XI1_FILTER: Scenario = Scenario { + setup: setup_p27_thawed_xi1_filter, + steps: &[ + press(XTEST_SLAVE), + Step::Request(allow_slave::, &[]), + ], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], + calls: &[(A, CallKind::Xi2, ROOT)], + grab: Some(&[ + Grab::Detached { + device: DEVICEID_XTEST_POINTER, + master: DEVICEID_MASTER_POINTER, + }, + SLAVE_PASSIVE_GRAB, + ]), + ..NOTHING + }, + order: CallOrder::Total, +}; + // ---- rows ---------------------------------------------------------------- const ROWS: &[InputRow] = &[ @@ -2286,6 +2355,58 @@ const ROWS: &[InputRow] = &[ ..NOTHING }, }, + // The activating press queues its XI1 route behind the sync slave grab; + // AsyncDevice re-enters the XI1 filter with a fresh memo. The filter must + // not ask Receive for the slave XI2 copy that this thaw does not write. + // Mutation: pass xi2_known_only=false from the thaw filter, adding its + // phantom XI2 call to the thaw trace. + InputRow { + name: "p27_thawed_xi1_press_filter_asks_no_xi2_copy", + scenario: &P27_THAWED_XI1_FILTER, + deny: &[(A, XI2_PRESS_CALL, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], + calls: &[(A, CallKind::Xi2, ROOT)], + grab: Some(&[ + Grab::Detached { + device: DEVICEID_XTEST_POINTER, + master: DEVICEID_MASTER_POINTER, + }, + SLAVE_PASSIVE_GRAB, + ]), + ..NOTHING + }, + }, + // The live filter follows the slave XI2 route's decision in their shared + // memo: when that XI2 copy is denied, A's selected XI1 copy is written. + // Mutation: make a known-only XI2 selector count as allowed in the filter, + // so it suppresses the XI1 copy after the slave route denied XI2. + InputRow { + name: "p27_live_filter_agrees_with_a_denied_slave_xi2_route", + scenario: &Scenario { + setup: setup_p27_live_filter, + steps: &[press(XTEST_SLAVE)], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD)], + calls: &[(A, CallKind::Xi2, CHILD)], + ..NOTHING + }, + order: CallOrder::Total, + }, + deny: &[(A, XI2_PRESS_CALL, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + moved: &[moved( + A, + Kind::Xi1(DEVICEID_XTEST_POINTER), + CHILD, + 0, + C_EVENT, + )], + calls: &[(A, CallKind::Xi2, CHILD), (A, XI1_PRESS_CALL, CHILD)], + ..NOTHING + }, + }, // A sync `GrabDeviceButton` by the requester on P activates on the press and // stores it (the activating write is one fresh check). InputRow { From bb724b185ae40f6a64aaee8760b30e002ecaa1a3 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 17:14:00 -0300 Subject: [PATCH 56/72] test(access): the XI1 thaw row pins the queued entry and its playback Review round 1 of plan 3 Task 2: a @press checkpoint states the frozen slave, the stored press and the queued Xi1Routed entry, and a companion row with no XI2 selection on the route observes the thawed XI1 press, so a thaw that drops the dequeued entry fails. Co-Authored-By: Claude Opus 5.5 Implemented-By: codex (gpt-6-luna max) --- .../tests/access_pointer_input.rs | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index 60f05972d..42ea33365 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -686,6 +686,14 @@ fn setup_p27_thawed_xi1_filter(f: &mut NotifyFixture) { xi_passive_grab_device(f, A, DEVICEID_XTEST_POINTER, true, XI_BUTTON_PRESS); } +/// The thaw fixture without A's XI2 selection on C: the queued XI1 press is +/// observable at thaw, while the same slave passive grab still freezes it. +fn setup_p27_thawed_xi1_delivery(f: &mut NotifyFixture) { + tree(f); + select_xi1(f, A, CHILD, &[xi1_slave_press()]); + xi_passive_grab_device(f, A, DEVICEID_XTEST_POINTER, true, XI_BUTTON_PRESS); +} + /// The same selections as the thaw case, under an already active asynchronous /// slave XI2 grab, so the XI1 filter shares the live dispatch's ReceiveMemo. fn setup_p27_live_filter(f: &mut NotifyFixture) { @@ -1030,6 +1038,65 @@ const P27_THAWED_XI1_FILTER: Scenario = Scenario { order: CallOrder::Total, }; +const P27_THAWED_XI1_FILTER_PRESS: Scenario = Scenario { + setup: setup_p27_thawed_xi1_filter, + steps: &[press(XTEST_SLAVE)], + allow: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], + calls: &[(A, CallKind::Xi2, ROOT)], + grab: Some(&[ + Grab::Detached { + device: DEVICEID_XTEST_POINTER, + master: DEVICEID_MASTER_POINTER, + }, + SLAVE_PASSIVE_GRAB, + Grab::Freeze { + device: DEVICEID_XTEST_POINTER, + state: Xi1SyncState::FrozenWithEvent, + other: None, + stored: Some(Held::HostPointer { + kind: PointerEventKind::ButtonPress, + detail: 1, + }), + }, + Grab::Queued { + device: DEVICEID_XTEST_POINTER, + held: Held::Xi1Routed { + evcode: crate::server::XI_FIRST_EVENT + + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET, + detail: 1, + }, + }, + ]), + ..NOTHING + }, + order: CallOrder::Total, +}; + +const P27_THAWED_XI1_DELIVERY: Scenario = Scenario { + setup: setup_p27_thawed_xi1_delivery, + steps: &[ + press(XTEST_SLAVE), + Step::Request(allow_slave::, &[]), + ], + allow: Outcome { + frames: &[ + (A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT), + (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + ], + calls: &[(A, CallKind::Xi2, ROOT), (A, XI1_PRESS_CALL, CHILD)], + grab: Some(&[ + Grab::Detached { + device: DEVICEID_XTEST_POINTER, + master: DEVICEID_MASTER_POINTER, + }, + SLAVE_PASSIVE_GRAB, + ]), + ..NOTHING + }, + order: CallOrder::Total, +}; + // ---- rows ---------------------------------------------------------------- const ROWS: &[InputRow] = &[ @@ -2360,6 +2427,12 @@ const ROWS: &[InputRow] = &[ // not ask Receive for the slave XI2 copy that this thaw does not write. // Mutation: pass xi2_known_only=false from the thaw filter, adding its // phantom XI2 call to the thaw trace. + InputRow { + name: "p27_thawed_xi1_press_filter_asks_no_xi2_copy@press", + scenario: &P27_THAWED_XI1_FILTER_PRESS, + deny: &[(A, XI2_PRESS_CALL, CHILD)], + denied: P27_THAWED_XI1_FILTER_PRESS.allow, + }, InputRow { name: "p27_thawed_xi1_press_filter_asks_no_xi2_copy", scenario: &P27_THAWED_XI1_FILTER, @@ -2377,6 +2450,27 @@ const ROWS: &[InputRow] = &[ ..NOTHING }, }, + // This sibling leaves XI2 unselected on C while retaining the sync slave + // passive grab and XI1 selection. The queued Xi1Routed press then produces + // an observable XI1 copy at thaw. Mutation: drop the dequeued Xi1Routed + // entry in xi1_compute_freezes without routing it. + InputRow { + name: "p27_thawed_xi1_routed_entry_delivers_xi1_copy", + scenario: &P27_THAWED_XI1_DELIVERY, + deny: &[(A, XI1_PRESS_CALL, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], + calls: &[(A, CallKind::Xi2, ROOT), (A, XI1_PRESS_CALL, CHILD)], + grab: Some(&[ + Grab::Detached { + device: DEVICEID_XTEST_POINTER, + master: DEVICEID_MASTER_POINTER, + }, + SLAVE_PASSIVE_GRAB, + ]), + ..NOTHING + }, + }, // The live filter follows the slave XI2 route's decision in their shared // memo: when that XI2 copy is denied, A's selected XI1 copy is written. // Mutation: make a known-only XI2 selector count as allowed in the filter, From 0bae7426af22ee9cd12bb156b81676c48f9e66a8 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 21:19:38 -0300 Subject: [PATCH 57/72] test(access): replay, thaw and freeze rows New access_replay_input table: ReplayPointer and ReplayKeyboard recheck the natural target, thawed queued motion and keys are checked at their own writes (with the owner_events fallback to the grab window), a denied XI1 activating write still stores and replays, and a denied XI1 grab-window write still trips FreezeNextEvent. Two equal-key Xi1Routed entries in one thaw pass are not reachable through the host entry, so the hoisted-memo case has no row. The core pointer and keyboard FreezeNextEvent pins are left out: they show that SyncPointer/SyncKeyboard never refreeze on the next event, which predates this series and is tracked separately. Co-Authored-By: Claude Opus 5.5 Implemented-By: codex (gpt-6-luna xhigh) --- .../tests/access_input_support.rs | 91 +++ .../tests/access_replay_input.rs | 650 ++++++++++++++++++ .../core_loop/process_request/tests/mod.rs | 1 + 3 files changed, 742 insertions(+) create mode 100644 crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index d61c4ebad..807ab97b8 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -41,6 +41,8 @@ const TIME: u32 = 0x5678; pub(super) const XI_MAJOR: u8 = 137; pub(super) const XI_SELECT_EVENTS: u8 = 46; const CORE_CHANGE_WINDOW_ATTRIBUTES: u8 = 2; +const CORE_GRAB_BUTTON: u8 = 28; +const CORE_ALLOW_EVENTS: u8 = 35; const CORE_CREATE_WINDOW: u8 = 1; const CORE_MAP_WINDOW: u8 = 8; const CORE_SET_INPUT_FOCUS: u8 = 42; @@ -460,6 +462,95 @@ pub(super) fn grab_keyboard(f: &mut NotifyFixture, owner: u32, window: u32, owne assert_eq!((reply[0], reply[1]), (1, 0), "GrabKeyboard replies Success"); } +/// A core `GrabKeyboard` with independently chosen pointer and keyboard modes. +pub(super) fn grab_keyboard_modes( + f: &mut NotifyFixture, + owner: u32, + window: u32, + owner_events: bool, + pointer_mode: u8, + keyboard_mode: u8, +) { + const CORE_GRAB_KEYBOARD: u8 = 31; + let mut body = Vec::with_capacity(12); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&[0; 4]); // CurrentTime + body.extend_from_slice(&[pointer_mode, keyboard_mode, 0, 0]); + let bytes = send_with_reply(f, owner, CORE_GRAB_KEYBOARD, u8::from(owner_events), &body); + let reply = &bytes[bytes.len() - 32..]; + assert_eq!((reply[0], reply[1]), (1, 0), "GrabKeyboard replies Success"); +} + +/// A core `GrabButton` of button 1 by `owner` on `window`, with the core +/// press/release mask and the requested pointer mode. +pub(super) fn grab_core_button( + f: &mut NotifyFixture, + owner: u32, + window: u32, + owner_events: bool, + pointer_mode: u8, +) { + let mut body = Vec::with_capacity(20); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&0x004c_u16.to_le_bytes()); // ButtonPress|ButtonRelease|PointerMotion + body.extend_from_slice(&[pointer_mode, 1]); // pointer mode, async keyboard + body.extend_from_slice(&[0; 8]); // no confinement, no cursor + body.extend_from_slice(&[1, 0]); // button 1, pad + body.extend_from_slice(&0x8000_u16.to_le_bytes()); // AnyModifier + send(f, owner, CORE_GRAB_BUTTON, u8::from(owner_events), &body); +} + +/// A synchronous XI1 `GrabDevice` on `device` by `owner` on `window`. +pub(super) fn grab_xi1_device( + f: &mut NotifyFixture, + owner: u32, + window: u32, + device: u16, + synchronous: bool, +) { + const XI1_GRAB_DEVICE: u8 = 13; + let mut body = Vec::with_capacity(16); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime + body.extend_from_slice(&0_u16.to_le_bytes()); // no event classes + body.extend_from_slice(&[u8::from(!synchronous), 1, 0, device as u8]); + body.extend_from_slice(&[0, 0]); // pad + let bytes = send_with_reply(f, owner, XI_MAJOR, XI1_GRAB_DEVICE, &body); + let reply = &bytes[bytes.len() - 32..]; + assert_eq!( + (reply[0], reply[8]), + (1, 0), + "XI1 GrabDevice replies Success" + ); +} + +/// A synchronous XI1 `GrabDeviceButton` for button 1 by `owner` on `window`. +pub(super) fn grab_xi1_device_button(f: &mut NotifyFixture, owner: u32, window: u32) { + const XI1_GRAB_DEVICE_BUTTON: u8 = 17; + let mut body = Vec::with_capacity(16); + body.extend_from_slice(&window.to_le_bytes()); + body.extend_from_slice(&[crate::xinput::DEVICEID_XTEST_POINTER as u8, 255]); // device, X keyboard modifiers + body.extend_from_slice(&0_u16.to_le_bytes()); // no event classes + body.extend_from_slice(&0x8000_u16.to_le_bytes()); // AnyModifier + body.extend_from_slice(&[0, 1, 1, 0]); // sync, async other device, button 1, owner_events false + body.extend_from_slice(&[0, 0]); // pad + send(f, owner, XI_MAJOR, XI1_GRAB_DEVICE_BUTTON, &body); +} + +/// Core `AllowEvents` with `mode` from its header data byte and CurrentTime. +pub(super) fn allow_core_events(f: &mut NotifyFixture) { + request(f, A, CORE_ALLOW_EVENTS, MODE, &[0; 4]); +} + +/// XI1 `AllowDeviceEvents` for the XTEST pointer, sent by A. +pub(super) fn allow_xi1_pointer_events(f: &mut NotifyFixture) { + const XI1_ALLOW_DEVICE_EVENTS: u8 = 19; + let mut body = vec![0; 4]; // CurrentTime + body.extend_from_slice(&[MODE, crate::xinput::DEVICEID_XTEST_POINTER as u8]); + body.extend_from_slice(&[0; 2]); + request(f, A, XI_MAJOR, XI1_ALLOW_DEVICE_EVENTS, &body); +} + /// The core GrabKey request by `owner` on `window` for `KEYCODE` with no /// modifiers, asynchronous pointer mode and the given keyboard mode. pub(super) fn grab_key( diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs new file mode 100644 index 000000000..5f779d752 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs @@ -0,0 +1,650 @@ +//! Replay, thaw and sync-freeze behavior under Receive policy (PR 4c part 2). +//! +//! Every row installs grabs and selections through requests, then drives +//! pointer or keyboard input through the host-event entry in the shared runner. +//! Checkpoint rows state the calls and grab/queue facts before a thaw or replay. + +use super::{access_input_support::*, access_notify_support::NotifyFixture}; +use crate::{ + core_loop::InputOrigin, + host_x11::PointerEventKind, + server::Xi1SyncState, + xinput::{ + DEVICEID_MASTER_KEYBOARD, DEVICEID_MASTER_POINTER, DEVICEID_XTEST_KEYBOARD, + DEVICEID_XTEST_POINTER, XI_DEVICE_BUTTON_PRESS_OFFSET, + }, +}; +use yserver_protocol::x11::ClientId; + +const XTEST_MASTER_POINTER: InputOrigin = InputOrigin::XTest(DEVICEID_MASTER_POINTER); +const XTEST_SLAVE_POINTER: InputOrigin = InputOrigin::XTest(DEVICEID_XTEST_POINTER); +const XTEST_MASTER_KEYBOARD: InputOrigin = InputOrigin::XTest(DEVICEID_MASTER_KEYBOARD); +const XTEST_SLAVE_KEYBOARD: InputOrigin = InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD); +const CORE_BUTTON_PRESS: u32 = 1 << 2; +const CORE_MOTION: u32 = 1 << 6; +const XI_RAW_KEY_PRESS: u32 = 1 << 13; +const MOTION_TO: (i16, i16) = (125, 125); +const FOCUS_EVENT: (i16, i16) = (20, 20); + +const CORE_BUTTON_PRESS_CALL: CallKind = CallKind::Core; +const CORE_MOTION_CALL: CallKind = CallKind::Core; +const CORE_KEY_PRESS_CALL: CallKind = CallKind::Core; +const XI1_BUTTON_PRESS_CALL: CallKind = + CallKind::Batch(&[Named::Xi1(XI_DEVICE_BUTTON_PRESS_OFFSET as u16)]); +const RAW_KEY_PRESS_CALL: CallKind = CallKind::Raw; + +const fn pointer_event(origin: InputOrigin, kind: PointerEventKind, to: (i16, i16)) -> Step { + Step::Event(Drive::Pointer { + origin, + kind, + button: if matches!(kind, PointerEventKind::MotionNotify) { + 0 + } else { + 1 + }, + to, + delta: ( + to.0 as i32 - POINTER.0 as i32, + to.1 as i32 - POINTER.1 as i32, + ), + }) +} + +const fn button_press(origin: InputOrigin) -> Step { + pointer_event(origin, PointerEventKind::ButtonPress, POINTER) +} + +const fn motion(origin: InputOrigin) -> Step { + pointer_event(origin, PointerEventKind::MotionNotify, MOTION_TO) +} + +const fn key_press(origin: InputOrigin) -> Step { + Step::Event(Drive::Entry { + origin, + pressed: true, + }) +} + +const fn raw_key_press(origin: InputOrigin) -> Step { + Step::Event(Drive::Raw { + origin, + pressed: true, + }) +} + +fn xi1_pointer_class(offset: u8) -> u32 { + (u32::from(DEVICEID_XTEST_POINTER) << 8) | u32::from(crate::server::XI_FIRST_EVENT + offset) +} + +fn setup_r4_replay_pointer(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, FOCUS, CORE_BUTTON_PRESS); + select_core(f, B, CHILD, CORE_BUTTON_PRESS); + grab_core_button(f, A, ROOT, false, 0); // synchronous passive GrabButton +} + +fn setup_r5_replay_keyboard(f: &mut NotifyFixture) { + tree(f); + select_core(f, B, FOCUS, KEY_PRESS); + grab_key(f, A, ROOT, false, true); +} + +fn setup_r6_queued_motion(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, CHILD, CORE_MOTION); + grab_core_button(f, A, ROOT, true, 0); // synchronous passive GrabButton +} + +fn setup_r7_queued_key(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, CHILD, KEY_PRESS); + select_xi2(f, B, ROOT, DEVICEID_MASTER_KEYBOARD, XI_RAW_KEY_PRESS); + grab_keyboard_modes(f, A, ROOT, true, 1, 0); // async pointer, sync keyboard +} + +fn setup_r8_xi1_replay(f: &mut NotifyFixture) { + tree(f); + select_xi1( + f, + B, + CHILD, + &[xi1_pointer_class(XI_DEVICE_BUTTON_PRESS_OFFSET)], + ); + select_xi1( + f, + A, + FOCUS, + &[xi1_pointer_class(XI_DEVICE_BUTTON_PRESS_OFFSET)], + ); + grab_xi1_device_button(f, A, ROOT); +} + +fn setup_r9_xi1_freeze_next(f: &mut NotifyFixture) { + tree(f); + grab_xi1_device(f, A, ROOT, DEVICEID_XTEST_POINTER, true); + allow_xi1_pointer_events::<1>(f); // SyncThisDevice arms FreezeNextEvent. + assert!( + f.drain(ClientId(A)).is_empty(), + "AllowDeviceEvents has no reply" + ); +} + +const PASSIVE_CORE_POINTER: Grab = Grab::Pointer(PointerGrab { + owner: A, + window: ROOT, + implicit: false, + passive: true, + via_xi2: false, +}); + +const CORE_POINTER_PRESS_FROZEN: Grab = Grab::Freeze { + device: DEVICEID_MASTER_POINTER, + state: Xi1SyncState::FrozenWithEvent, + other: None, + stored: Some(Held::HostPointer { + kind: PointerEventKind::ButtonPress, + detail: 1, + }), +}; + +const MASTER_POINTER_MOTION_QUEUED: Grab = Grab::Queued { + device: DEVICEID_MASTER_POINTER, + held: Held::HostPointer { + kind: PointerEventKind::MotionNotify, + detail: 0, + }, +}; + +const XI1_POINTER_PRESS_STORED: Grab = Grab::Freeze { + device: DEVICEID_XTEST_POINTER, + state: Xi1SyncState::FrozenWithEvent, + other: None, + stored: Some(Held::Xi1Routed { + evcode: crate::server::XI_FIRST_EVENT + XI_DEVICE_BUTTON_PRESS_OFFSET, + detail: 1, + }), +}; + +const XI1_KEYBOARD_QUEUE: Grab = Grab::Freeze { + device: DEVICEID_MASTER_KEYBOARD, + state: Xi1SyncState::FrozenNoEvent, + other: None, + stored: None, +}; + +const R4_PRESS: Scenario = Scenario { + setup: setup_r4_replay_pointer, + steps: &[button_press(XTEST_MASTER_POINTER)], + allow: Outcome { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], + grab: Some(&[PASSIVE_CORE_POINTER, CORE_POINTER_PRESS_FROZEN]), + ..NOTHING + }, + order: CallOrder::Total, +}; + +const R4_REPLAY: Scenario = Scenario { + setup: setup_r4_replay_pointer, + steps: &[ + button_press(XTEST_MASTER_POINTER), + Step::Request( + allow_core_events::<2>, + &[button_press(XTEST_MASTER_POINTER)], + ), + ], + allow: Outcome { + frames: &[(A, Kind::Core, ROOT), (B, Kind::Core, CHILD)], + calls: &[ + (A, CORE_BUTTON_PRESS_CALL, ROOT), + (B, CORE_BUTTON_PRESS_CALL, CHILD), + ], + grab: Some(&[Grab::Pointer(PointerGrab { + owner: B, + window: CHILD, + implicit: true, + passive: false, + via_xi2: false, + })]), + ..NOTHING + }, + order: CallOrder::Total, +}; + +const R5_REPLAY: Scenario = Scenario { + setup: setup_r5_replay_keyboard, + steps: &[ + key_press(XTEST_MASTER_KEYBOARD), + Step::Request(allow_core_events::<5>, &[key_press(XTEST_MASTER_KEYBOARD)]), + ], + allow: Outcome { + frames: &[(A, Kind::Core, ROOT), (B, Kind::Core, FOCUS)], + calls: &[ + (A, CORE_KEY_PRESS_CALL, ROOT), + (B, CORE_KEY_PRESS_CALL, FOCUS), + ], + grab: Some(&[]), + ..NOTHING + }, + order: CallOrder::Total, +}; + +const R6_QUEUE: Scenario = Scenario { + setup: setup_r6_queued_motion, + steps: &[ + button_press(XTEST_MASTER_POINTER), + motion(XTEST_MASTER_POINTER), + ], + allow: Outcome { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], + grab: Some(&[ + PASSIVE_CORE_POINTER, + CORE_POINTER_PRESS_FROZEN, + MASTER_POINTER_MOTION_QUEUED, + ]), + ..NOTHING + }, + order: CallOrder::Total, +}; + +const R6_THAW: Scenario = Scenario { + setup: setup_r6_queued_motion, + steps: &[ + button_press(XTEST_MASTER_POINTER), + motion(XTEST_MASTER_POINTER), + Step::Request(allow_core_events::<0>, &[]), + ], + allow: Outcome { + frames: &[(A, Kind::Core, ROOT), (A, Kind::Core, CHILD)], + calls: &[ + (A, CORE_BUTTON_PRESS_CALL, ROOT), + (A, CORE_MOTION_CALL, CHILD), + ], + grab: Some(&[PASSIVE_CORE_POINTER]), + ..NOTHING + }, + order: CallOrder::Total, +}; + +const R7_QUEUE: Scenario = Scenario { + setup: setup_r7_queued_key, + steps: &[ + raw_key_press(XTEST_SLAVE_KEYBOARD), + key_press(XTEST_SLAVE_KEYBOARD), + ], + allow: Outcome { + grab: Some(&[ + Grab::Keyboard { + owner: A, + window: ROOT, + }, + XI1_KEYBOARD_QUEUE, + Grab::Queued { + device: DEVICEID_MASTER_KEYBOARD, + held: Held::RawKey { + pressed: true, + keycode: KEYCODE, + }, + }, + Grab::Queued { + device: DEVICEID_MASTER_KEYBOARD, + held: Held::HostKeyTransition { + pressed: true, + keycode: KEYCODE, + master: true, + synthetic: false, + }, + }, + ]), + ..NOTHING + }, + order: CallOrder::Total, +}; + +const R7_THAW: Scenario = Scenario { + setup: setup_r7_queued_key, + steps: &[ + raw_key_press(XTEST_SLAVE_KEYBOARD), + key_press(XTEST_SLAVE_KEYBOARD), + Step::Request( + allow_core_events::<3>, + &[ + raw_key_press(XTEST_SLAVE_KEYBOARD), + key_press(XTEST_SLAVE_KEYBOARD), + ], + ), + ], + allow: Outcome { + frames: &[ + (B, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + (A, Kind::Core, CHILD), + ], + calls: &[ + (B, CallKind::Batch(&[Named::Raw(13)]), ROOT), + (A, CallKind::Batch(&[Named::Core(2)]), CHILD), + ], + grab: Some(&[Grab::Keyboard { + owner: A, + window: ROOT, + }]), + ..NOTHING + }, + order: CallOrder::Total, +}; + +const R8_REPLAY: Scenario = Scenario { + setup: setup_r8_xi1_replay, + steps: &[ + button_press(XTEST_SLAVE_POINTER), + Step::Request( + allow_xi1_pointer_events::<2>, + &[button_press(XTEST_SLAVE_POINTER)], + ), + ], + allow: Outcome { + frames: &[ + (A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT), + (B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + ], + calls: &[ + (A, XI1_BUTTON_PRESS_CALL, ROOT), + (B, XI1_BUTTON_PRESS_CALL, CHILD), + ], + grab: Some(&[Grab::Xi1 { + device: DEVICEID_XTEST_POINTER, + owner: B, + window: CHILD, + }]), + ..NOTHING + }, + order: CallOrder::Total, +}; + +const R9_XI1_FREEZE: Scenario = Scenario { + setup: setup_r9_xi1_freeze_next, + steps: &[button_press(XTEST_SLAVE_POINTER)], + allow: Outcome { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT)], + calls: &[(A, XI1_BUTTON_PRESS_CALL, ROOT)], + grab: Some(&[ + Grab::Xi1 { + device: DEVICEID_XTEST_POINTER, + owner: A, + window: ROOT, + }, + XI1_POINTER_PRESS_STORED, + ]), + ..NOTHING + }, + order: CallOrder::Total, +}; + +const ROWS: &[InputRow] = &[ + // Mutation: gate passive storage on a successful activating owner copy. + // Denying A@ROOT must still leave ReplayPointer able to deliver the press; + // Xorg 21.1.24 `dix/events.c:3833-3919` stores the activating event. + InputRow { + name: "r4_replay_pointer_rechecks_the_natural_target@press", + scenario: &R4_PRESS, + deny: &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], + denied: Outcome { + calls: &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], + grab: Some(&[PASSIVE_CORE_POINTER, CORE_POINTER_PRESS_FROZEN]), + ..NOTHING + }, + }, + // Mutation: make the replay's core selection route selection-only. B's + // denial must let A at FOCUS receive the press; Xorg 21.1.24 replay + // rematches below the released grab (`dix/events.c:1318-1371`). + InputRow { + name: "r4_replay_pointer_rechecks_the_natural_target", + scenario: &R4_REPLAY, + deny: &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], + denied: Outcome { + frames: &[(B, Kind::Core, CHILD)], + calls: &[ + (A, CORE_BUTTON_PRESS_CALL, ROOT), + (B, CORE_BUTTON_PRESS_CALL, CHILD), + ], + grab: Some(&[Grab::Pointer(PointerGrab { + owner: B, + window: CHILD, + implicit: true, + passive: false, + via_xi2: false, + })]), + ..NOTHING + }, + }, + InputRow { + name: "r4_replay_pointer_rechecks_the_natural_target_denied_at_B", + scenario: &R4_REPLAY, + deny: &[ + (A, CORE_BUTTON_PRESS_CALL, ROOT), + (B, CORE_BUTTON_PRESS_CALL, CHILD), + ], + denied: Outcome { + frames: &[(A, Kind::Core, FOCUS)], + moved: &[moved(A, Kind::Core, FOCUS, CHILD, FOCUS_EVENT)], + calls: &[ + (A, CORE_BUTTON_PRESS_CALL, ROOT), + (B, CORE_BUTTON_PRESS_CALL, CHILD), + (A, CORE_BUTTON_PRESS_CALL, FOCUS), + ], + grab: Some(&[Grab::Pointer(PointerGrab { + owner: A, + window: FOCUS, + implicit: true, + passive: false, + via_xi2: false, + })]), + ..NOTHING + }, + }, + // Mutation: skip Receive when replaying the held key. A denied focus copy + // must be dropped; Xorg 21.1.24 replays to focus at `dix/events.c:1360`. + InputRow { + name: "r5_replay_keyboard_rechecks_the_focus", + scenario: &R5_REPLAY, + deny: &[ + (A, CORE_KEY_PRESS_CALL, ROOT), + (B, CORE_KEY_PRESS_CALL, FOCUS), + ], + denied: Outcome { + calls: &[ + (A, CORE_KEY_PRESS_CALL, ROOT), + (B, CORE_KEY_PRESS_CALL, FOCUS), + ], + grab: Some(&[]), + ..NOTHING + }, + }, + // Pin only: queueing the motion makes no Receive call and preserves it; + // Xorg `ComputeFreezes` queues without a Receive hook (`dix/events.c:1320`). + InputRow { + name: "r6_thawed_queued_motion_is_checked_at_its_write@queue", + scenario: &R6_QUEUE, + deny: &[], + denied: Outcome { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], + grab: Some(&[ + PASSIVE_CORE_POINTER, + CORE_POINTER_PRESS_FROZEN, + MASTER_POINTER_MOTION_QUEUED, + ]), + ..NOTHING + }, + }, + // Mutation: omit Receive while `state.playing_sync_events` in the thawed + // pointer write. The denied natural owner copy must fall back to a fresh + // grab-window check, per Xorg 21.1.24 `dix/events.c:4388-4398`. + InputRow { + name: "r6_thawed_queued_motion_is_checked_at_its_write", + scenario: &R6_THAW, + deny: &[(A, CallKind::Batch(&[Named::Core(6)]), CHILD)], + denied: Outcome { + frames: &[(A, Kind::Core, ROOT), (A, Kind::Core, ROOT)], + moved: &[moved(A, Kind::Core, ROOT, FOCUS, MOTION_TO)], + calls: &[ + (A, CORE_BUTTON_PRESS_CALL, ROOT), + (A, CORE_MOTION_CALL, CHILD), + (A, CORE_MOTION_CALL, ROOT), + ], + grab: Some(&[PASSIVE_CORE_POINTER]), + ..NOTHING + }, + }, + InputRow { + name: "r6_thawed_queued_motion_denied_at_both_writes_stays_grabbed", + scenario: &R6_THAW, + deny: &[ + (A, CallKind::Batch(&[Named::Core(6)]), CHILD), + (A, CallKind::Batch(&[Named::Core(6)]), ROOT), + ], + denied: Outcome { + frames: &[(A, Kind::Core, ROOT)], + calls: &[ + (A, CORE_BUTTON_PRESS_CALL, ROOT), + (A, CORE_MOTION_CALL, CHILD), + (A, CORE_MOTION_CALL, ROOT), + ], + grab: Some(&[PASSIVE_CORE_POINTER]), + ..NOTHING + }, + }, + // Pin only: queueing the raw and cooked key makes no Receive call; Xorg + // queues during `ComputeFreezes` without a Receive hook (`dix/events.c:1320`). + InputRow { + name: "r7_thawed_queued_key_is_checked_at_its_write@queue", + scenario: &R7_QUEUE, + deny: &[], + denied: Outcome { + grab: Some(&[ + Grab::Keyboard { + owner: A, + window: ROOT, + }, + XI1_KEYBOARD_QUEUE, + Grab::Queued { + device: DEVICEID_MASTER_KEYBOARD, + held: Held::RawKey { + pressed: true, + keycode: KEYCODE, + }, + }, + Grab::Queued { + device: DEVICEID_MASTER_KEYBOARD, + held: Held::HostKeyTransition { + pressed: true, + keycode: KEYCODE, + master: true, + synthetic: false, + }, + }, + ]), + ..NOTHING + }, + }, + // Mutation: skip Receive during `playing_sync_events`. Both the queued + // RawKey root copy and HostKeyTransition natural copy are fresh writes; + // Xorg 21.1.24 routes each on thaw at `dix/events.c:1320-1371`. + InputRow { + name: "r7_thawed_queued_key_is_checked_at_its_write", + scenario: &R7_THAW, + deny: &[ + (B, RAW_KEY_PRESS_CALL, ROOT), + (A, CORE_KEY_PRESS_CALL, CHILD), + ], + denied: Outcome { + frames: &[(A, Kind::Core, ROOT)], + moved: &[moved(A, Kind::Core, ROOT, FOCUS, (120, 120))], + calls: &[ + (B, CallKind::Batch(&[Named::Raw(13)]), ROOT), + (A, CallKind::Batch(&[Named::Core(2)]), CHILD), + (A, CallKind::Batch(&[Named::Core(2)]), ROOT), + ], + grab: Some(&[Grab::Keyboard { + owner: A, + window: ROOT, + }]), + ..NOTHING + }, + }, + // Mutation: make XI1 activation store the event only when the owner copy + // is allowed. A denied activation still stores it for ReplayThisDevice; + // Xorg 21.1.24 `dix/events.c:3833-3919` keeps activation independent. + InputRow { + name: "r8_denied_xi1_activating_write_still_replays", + scenario: &R8_REPLAY, + deny: &[(A, XI1_BUTTON_PRESS_CALL, ROOT)], + denied: Outcome { + frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + calls: &[ + (A, XI1_BUTTON_PRESS_CALL, ROOT), + (B, XI1_BUTTON_PRESS_CALL, CHILD), + ], + grab: Some(&[Grab::Xi1 { + device: DEVICEID_XTEST_POINTER, + owner: B, + window: CHILD, + }]), + ..NOTHING + }, + }, + InputRow { + name: "r8_denied_xi1_activating_write_rechecks_the_replayed_selector", + scenario: &R8_REPLAY, + deny: &[ + (A, XI1_BUTTON_PRESS_CALL, ROOT), + (B, XI1_BUTTON_PRESS_CALL, CHILD), + ], + denied: Outcome { + frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], + moved: &[moved( + A, + Kind::Xi1(DEVICEID_XTEST_POINTER), + FOCUS, + CHILD, + FOCUS_EVENT, + )], + calls: &[ + (A, XI1_BUTTON_PRESS_CALL, ROOT), + (B, XI1_BUTTON_PRESS_CALL, CHILD), + (A, XI1_BUTTON_PRESS_CALL, FOCUS), + ], + grab: Some(&[Grab::Xi1 { + device: DEVICEID_XTEST_POINTER, + owner: A, + window: FOCUS, + }]), + ..NOTHING + }, + }, + // Mutation: gate `xi1_freeze_this_event_if_needed` on `deliver`. A denied + // grab-window write must still trip FreezeNextEvent and store the press; + // Xorg 21.1.24 `dix/events.c:4390,4467-4473` counts it as delivered. + InputRow { + name: "r9_denied_xi1_grab_window_write_trips_freeze_next", + scenario: &R9_XI1_FREEZE, + deny: &[(A, XI1_BUTTON_PRESS_CALL, ROOT)], + denied: Outcome { + calls: &[(A, XI1_BUTTON_PRESS_CALL, ROOT)], + grab: Some(&[ + Grab::Xi1 { + device: DEVICEID_XTEST_POINTER, + owner: A, + window: ROOT, + }, + XI1_POINTER_PRESS_STORED, + ]), + ..NOTHING + }, + }, +]; + +#[test] +fn replay_rows() { + check_rows(ROWS) +} diff --git a/crates/yserver-core/src/core_loop/process_request/tests/mod.rs b/crates/yserver-core/src/core_loop/process_request/tests/mod.rs index 0f6b43970..1807ac351 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/mod.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/mod.rs @@ -22,6 +22,7 @@ mod access_properties; mod access_randr; mod access_record; mod access_render; +mod access_replay_input; mod access_resources; mod access_saver; mod access_send; From 0f15036aec5925f1fe021eacaf7ee200a4beab09 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 22:19:18 -0300 Subject: [PATCH 58/72] test(access): replay rows cover equal-key thaw entries and key replay Review round 1 of plan 3 Task 3: two equal-key Xi1Routed entries are reachable through two synchronously grabbed pointers released by one AsyncBoth, so a row now pins one Receive call per thawed entry. r5 gains the keyboard counterparts of r4: the @press checkpoint, a denied activation with an allowed replay, and a denied selector that does not veto another selector at the focus. Storage probes now gate on the original write's result, and r6 names its mutation site. Co-Authored-By: Claude Opus 5.5 Implemented-By: codex (gpt-6-luna max) --- .../tests/access_replay_input.rs | 429 +++++++++++++++++- 1 file changed, 416 insertions(+), 13 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs index 5f779d752..326e64d54 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs @@ -6,12 +6,12 @@ use super::{access_input_support::*, access_notify_support::NotifyFixture}; use crate::{ - core_loop::InputOrigin, + core_loop::{DeviceInfo, InputOrigin}, host_x11::PointerEventKind, server::Xi1SyncState, xinput::{ DEVICEID_MASTER_KEYBOARD, DEVICEID_MASTER_POINTER, DEVICEID_XTEST_KEYBOARD, - DEVICEID_XTEST_POINTER, XI_DEVICE_BUTTON_PRESS_OFFSET, + DEVICEID_XTEST_POINTER, InputCapabilities, InputSourceId, XI_DEVICE_BUTTON_PRESS_OFFSET, }, }; use yserver_protocol::x11::ClientId; @@ -20,8 +20,12 @@ const XTEST_MASTER_POINTER: InputOrigin = InputOrigin::XTest(DEVICEID_MASTER_POI const XTEST_SLAVE_POINTER: InputOrigin = InputOrigin::XTest(DEVICEID_XTEST_POINTER); const XTEST_MASTER_KEYBOARD: InputOrigin = InputOrigin::XTest(DEVICEID_MASTER_KEYBOARD); const XTEST_SLAVE_KEYBOARD: InputOrigin = InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD); +const PHYSICAL_SOURCE: u64 = 0xA75_400; +const PHYSICAL_DEVICE: u16 = 6; +const PHYSICAL_POINTER: InputOrigin = InputOrigin::Physical(InputSourceId(PHYSICAL_SOURCE)); const CORE_BUTTON_PRESS: u32 = 1 << 2; const CORE_MOTION: u32 = 1 << 6; +const XI_BUTTON_PRESS: u32 = 1 << 4; const XI_RAW_KEY_PRESS: u32 = 1 << 13; const MOTION_TO: (i16, i16) = (125, 125); const FOCUS_EVENT: (i16, i16) = (20, 20); @@ -72,8 +76,51 @@ const fn raw_key_press(origin: InputOrigin) -> Step { }) } +fn xi1_pointer_class_for(device: u16, offset: u8) -> u32 { + (u32::from(device) << 8) | u32::from(crate::server::XI_FIRST_EVENT + offset) +} + fn xi1_pointer_class(offset: u8) -> u32 { - (u32::from(DEVICEID_XTEST_POINTER) << 8) | u32::from(crate::server::XI_FIRST_EVENT + offset) + xi1_pointer_class_for(DEVICEID_XTEST_POINTER, offset) +} + +fn register_physical_pointer(f: &mut NotifyFixture) { + let info = DeviceInfo { + source_id: InputSourceId(PHYSICAL_SOURCE), + enabled: true, + resume_key: None, + capabilities: InputCapabilities { + keyboard: false, + pointer: true, + touch: false, + }, + name: format!("pointer source {PHYSICAL_SOURCE}"), + device_node: format!("/dev/input/event{PHYSICAL_SOURCE}"), + sysname: format!("event{PHYSICAL_SOURCE}"), + vendor_id: 1, + product_id: PHYSICAL_SOURCE as u32, + is_touchpad: false, + config: crate::core_loop::message::LibinputConfigSnapshot::default(), + }; + let ids = f.state.xi_register_source(&info); + assert_eq!(ids.first(), Some(&PHYSICAL_DEVICE), "physical pointer id"); +} + +fn xi2_passive_button_grab(f: &mut NotifyFixture, device: u16) { + const XI_PASSIVE_GRAB_DEVICE: u8 = 54; + let mut body = Vec::with_capacity(36); + body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime + body.extend_from_slice(&ROOT.to_le_bytes()); + body.extend_from_slice(&0_u32.to_le_bytes()); // no cursor + body.extend_from_slice(&1_u32.to_le_bytes()); // button 1 + body.extend_from_slice(&device.to_le_bytes()); + body.extend_from_slice(&1_u16.to_le_bytes()); // one modifier + body.extend_from_slice(&1_u16.to_le_bytes()); // one mask word + body.extend_from_slice(&[0, 0, 1, 1]); // Button, sync device, async paired, owner_events + body.extend_from_slice(&0_u16.to_le_bytes()); // pad + body.extend_from_slice(&XI_BUTTON_PRESS.to_le_bytes()); + body.extend_from_slice(&0x8000_0000_u32.to_le_bytes()); // XIAnyModifier + let _ = send_with_reply(f, A, XI_MAJOR, XI_PASSIVE_GRAB_DEVICE, &body); } fn setup_r4_replay_pointer(f: &mut NotifyFixture) { @@ -89,6 +136,30 @@ fn setup_r5_replay_keyboard(f: &mut NotifyFixture) { grab_key(f, A, ROOT, false, true); } +fn setup_r5_replay_keyboard_continuation(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, FOCUS, KEY_PRESS); + select_core(f, B, FOCUS, KEY_PRESS); + grab_key(f, A, ROOT, false, true); +} + +fn setup_r1_equal_key_xi1_queue(f: &mut NotifyFixture) { + tree(f); + register_physical_pointer(f); + select_xi1( + f, + A, + CHILD, + &[ + xi1_pointer_class_for(DEVICEID_XTEST_POINTER, XI_DEVICE_BUTTON_PRESS_OFFSET), + xi1_pointer_class_for(PHYSICAL_DEVICE, XI_DEVICE_BUTTON_PRESS_OFFSET), + ], + ); + grab_keyboard_modes(f, A, ROOT, false, 1, 0); // async pointer, sync keyboard + xi2_passive_button_grab(f, DEVICEID_XTEST_POINTER); + xi2_passive_button_grab(f, PHYSICAL_DEVICE); +} + fn setup_r6_queued_motion(f: &mut NotifyFixture) { tree(f); select_core(f, A, CHILD, CORE_MOTION); @@ -165,6 +236,76 @@ const XI1_POINTER_PRESS_STORED: Grab = Grab::Freeze { }), }; +const MASTER_KEY_PRESS_FROZEN: Grab = Grab::Freeze { + device: DEVICEID_MASTER_KEYBOARD, + state: Xi1SyncState::FrozenWithEvent, + other: None, + stored: Some(Held::HostKeyTransition { + pressed: true, + keycode: KEYCODE, + master: true, + synthetic: false, + }), +}; + +const PHYSICAL_POINTER_PRESS_STORED: Grab = Grab::Freeze { + device: PHYSICAL_DEVICE, + state: Xi1SyncState::FrozenWithEvent, + other: None, + stored: Some(Held::HostPointer { + kind: PointerEventKind::ButtonPress, + detail: 1, + }), +}; + +const R1_XTEST_PRESS_STORED: Grab = Grab::Freeze { + device: DEVICEID_XTEST_POINTER, + state: Xi1SyncState::FrozenWithEvent, + other: None, + stored: Some(Held::HostPointer { + kind: PointerEventKind::ButtonPress, + detail: 1, + }), +}; + +const R1_XTEST_PASSIVE_GRAB: Grab = Grab::SlavePointer { + device: DEVICEID_XTEST_POINTER, + grab: PointerGrab { + owner: A, + window: ROOT, + implicit: false, + passive: true, + via_xi2: true, + }, +}; + +const R1_PHYSICAL_PASSIVE_GRAB: Grab = Grab::SlavePointer { + device: PHYSICAL_DEVICE, + grab: PointerGrab { + owner: A, + window: ROOT, + implicit: false, + passive: true, + via_xi2: true, + }, +}; + +const R1_XTEST_XI1_QUEUED: Grab = Grab::Queued { + device: DEVICEID_XTEST_POINTER, + held: Held::Xi1Routed { + evcode: crate::server::XI_FIRST_EVENT + XI_DEVICE_BUTTON_PRESS_OFFSET, + detail: 1, + }, +}; + +const R1_PHYSICAL_XI1_QUEUED: Grab = Grab::Queued { + device: PHYSICAL_DEVICE, + held: Held::Xi1Routed { + evcode: crate::server::XI_FIRST_EVENT + XI_DEVICE_BUTTON_PRESS_OFFSET, + detail: 1, + }, +}; + const XI1_KEYBOARD_QUEUE: Grab = Grab::Freeze { device: DEVICEID_MASTER_KEYBOARD, state: Xi1SyncState::FrozenNoEvent, @@ -229,6 +370,131 @@ const R5_REPLAY: Scenario = Scenario { order: CallOrder::Total, }; +const R5_PRESS: Scenario = Scenario { + setup: setup_r5_replay_keyboard, + steps: &[key_press(XTEST_MASTER_KEYBOARD)], + allow: Outcome { + frames: &[(A, Kind::Core, ROOT)], + calls: &[(A, CORE_KEY_PRESS_CALL, ROOT)], + grab: Some(&[ + Grab::Keyboard { + owner: A, + window: ROOT, + }, + MASTER_KEY_PRESS_FROZEN, + ]), + ..NOTHING + }, + order: CallOrder::Total, +}; + +const R5_CONTINUATION: Scenario = Scenario { + setup: setup_r5_replay_keyboard_continuation, + steps: &[ + key_press(XTEST_MASTER_KEYBOARD), + Step::Request(allow_core_events::<5>, &[key_press(XTEST_MASTER_KEYBOARD)]), + ], + allow: Outcome { + frames: &[ + (A, Kind::Core, ROOT), + (A, Kind::Core, FOCUS), + (B, Kind::Core, FOCUS), + ], + calls: &[ + (A, CORE_KEY_PRESS_CALL, ROOT), + (A, CORE_KEY_PRESS_CALL, FOCUS), + (B, CORE_KEY_PRESS_CALL, FOCUS), + ], + grab: Some(&[]), + ..NOTHING + }, + order: CallOrder::PerClient, +}; + +const R1_XI1_QUEUE: Scenario = Scenario { + setup: setup_r1_equal_key_xi1_queue, + steps: &[ + button_press(XTEST_SLAVE_POINTER), + button_press(PHYSICAL_POINTER), + ], + allow: Outcome { + frames: &[ + (A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT), + (A, Kind::Xi2(PHYSICAL_DEVICE), ROOT), + ], + calls: &[(A, CallKind::Xi2, ROOT), (A, CallKind::Xi2, ROOT)], + grab: Some(&[ + Grab::Keyboard { + owner: A, + window: ROOT, + }, + Grab::Detached { + device: DEVICEID_XTEST_POINTER, + master: DEVICEID_MASTER_POINTER, + }, + Grab::Detached { + device: PHYSICAL_DEVICE, + master: DEVICEID_MASTER_POINTER, + }, + R1_XTEST_PASSIVE_GRAB, + R1_PHYSICAL_PASSIVE_GRAB, + Grab::Freeze { + device: DEVICEID_MASTER_KEYBOARD, + state: Xi1SyncState::FrozenNoEvent, + other: None, + stored: None, + }, + R1_XTEST_PRESS_STORED, + PHYSICAL_POINTER_PRESS_STORED, + R1_XTEST_XI1_QUEUED, + R1_PHYSICAL_XI1_QUEUED, + ]), + ..NOTHING + }, + order: CallOrder::Total, +}; + +const R1_XI1_THAW: Scenario = Scenario { + setup: setup_r1_equal_key_xi1_queue, + steps: &[ + button_press(XTEST_SLAVE_POINTER), + button_press(PHYSICAL_POINTER), + Step::Request(allow_core_events::<6>, &[]), + ], + allow: Outcome { + frames: &[ + (A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT), + (A, Kind::Xi2(PHYSICAL_DEVICE), ROOT), + (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + (A, Kind::Xi1(PHYSICAL_DEVICE), CHILD), + ], + calls: &[ + (A, CallKind::Xi2, ROOT), + (A, CallKind::Xi2, ROOT), + (A, XI1_BUTTON_PRESS_CALL, CHILD), + (A, XI1_BUTTON_PRESS_CALL, CHILD), + ], + grab: Some(&[ + Grab::Keyboard { + owner: A, + window: ROOT, + }, + Grab::Detached { + device: DEVICEID_XTEST_POINTER, + master: DEVICEID_MASTER_POINTER, + }, + Grab::Detached { + device: PHYSICAL_DEVICE, + master: DEVICEID_MASTER_POINTER, + }, + R1_XTEST_PASSIVE_GRAB, + R1_PHYSICAL_PASSIVE_GRAB, + ]), + ..NOTHING + }, + order: CallOrder::Total, +}; + const R6_QUEUE: Scenario = Scenario { setup: setup_r6_queued_motion, steps: &[ @@ -381,9 +647,88 @@ const R9_XI1_FREEZE: Scenario = Scenario { }; const ROWS: &[InputRow] = &[ - // Mutation: gate passive storage on a successful activating owner copy. - // Denying A@ROOT must still leave ReplayPointer able to deliver the press; - // Xorg 21.1.24 `dix/events.c:3833-3919` stores the activating event. + // Mutation: hoist ReceiveMemo out of `xi1_compute_freezes`' per-entry + // router call. The different devices have the same client/window/batch + // key, so thaw must still ask Receive once for each queued write. + InputRow { + name: "r1_equal_key_xi1_routed_entries_share_freeze_pass@queue", + scenario: &R1_XI1_QUEUE, + deny: &[], + denied: Outcome { + frames: &[ + (A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT), + (A, Kind::Xi2(PHYSICAL_DEVICE), ROOT), + ], + calls: &[(A, CallKind::Xi2, ROOT), (A, CallKind::Xi2, ROOT)], + grab: Some(&[ + Grab::Keyboard { + owner: A, + window: ROOT, + }, + Grab::Detached { + device: DEVICEID_XTEST_POINTER, + master: DEVICEID_MASTER_POINTER, + }, + Grab::Detached { + device: PHYSICAL_DEVICE, + master: DEVICEID_MASTER_POINTER, + }, + R1_XTEST_PASSIVE_GRAB, + R1_PHYSICAL_PASSIVE_GRAB, + Grab::Freeze { + device: DEVICEID_MASTER_KEYBOARD, + state: Xi1SyncState::FrozenNoEvent, + other: None, + stored: None, + }, + R1_XTEST_PRESS_STORED, + PHYSICAL_POINTER_PRESS_STORED, + R1_XTEST_XI1_QUEUED, + R1_PHYSICAL_XI1_QUEUED, + ]), + ..NOTHING + }, + }, + InputRow { + name: "r1_equal_key_xi1_routed_entries_share_freeze_pass", + scenario: &R1_XI1_THAW, + deny: &[], + denied: Outcome { + frames: &[ + (A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT), + (A, Kind::Xi2(PHYSICAL_DEVICE), ROOT), + (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + (A, Kind::Xi1(PHYSICAL_DEVICE), CHILD), + ], + calls: &[ + (A, CallKind::Xi2, ROOT), + (A, CallKind::Xi2, ROOT), + (A, XI1_BUTTON_PRESS_CALL, CHILD), + (A, XI1_BUTTON_PRESS_CALL, CHILD), + ], + grab: Some(&[ + Grab::Keyboard { + owner: A, + window: ROOT, + }, + Grab::Detached { + device: DEVICEID_XTEST_POINTER, + master: DEVICEID_MASTER_POINTER, + }, + Grab::Detached { + device: PHYSICAL_DEVICE, + master: DEVICEID_MASTER_POINTER, + }, + R1_XTEST_PASSIVE_GRAB, + R1_PHYSICAL_PASSIVE_GRAB, + ]), + ..NOTHING + }, + }, + // Mutation: gate passive storage on the original activating write's + // Receive result. Denying A@ROOT must still leave ReplayPointer able to + // deliver the press; Xorg 21.1.24 `dix/events.c:3833-3919` stores it. + // Kill probe: `t3r1-r4-passive-store-gated-on-original-write-check`. InputRow { name: "r4_replay_pointer_rechecks_the_natural_target@press", scenario: &R4_PRESS, @@ -442,8 +787,64 @@ const ROWS: &[InputRow] = &[ ..NOTHING }, }, - // Mutation: skip Receive when replaying the held key. A denied focus copy - // must be dropped; Xorg 21.1.24 replays to focus at `dix/events.c:1360`. + // Mutation: gate activation storage on the original denied write. The + // checkpoint still requires A's active grab and stored transition, with + // no B call. Kill probe: `t3r1-r5-key-store-gated-on-activation-check`. + InputRow { + name: "r5_replay_keyboard_rechecks_the_focus@press", + scenario: &R5_PRESS, + deny: &[(A, CORE_KEY_PRESS_CALL, ROOT)], + denied: Outcome { + calls: &[(A, CORE_KEY_PRESS_CALL, ROOT)], + grab: Some(&[ + Grab::Keyboard { + owner: A, + window: ROOT, + }, + MASTER_KEY_PRESS_FROZEN, + ]), + ..NOTHING + }, + }, + // Mutation: gate the stored activating transition on its original + // Receive result. ReplayKeyboard must still hand a denied A copy to B. + // Kill probe: `t3r1-r5-key-store-gated-on-activation-check`. + InputRow { + name: "r5_replay_keyboard_rechecks_the_focus_denied_activation", + scenario: &R5_REPLAY, + deny: &[(A, CORE_KEY_PRESS_CALL, ROOT)], + denied: Outcome { + frames: &[(B, Kind::Core, FOCUS)], + calls: &[ + (A, CORE_KEY_PRESS_CALL, ROOT), + (B, CORE_KEY_PRESS_CALL, FOCUS), + ], + grab: Some(&[]), + ..NOTHING + }, + }, + // Mutation: a denied selector at the focused window vetoes another + // client's allowed copy. Kill probe: `t3r1-r5-key-denial-does-not-veto`. + InputRow { + name: "r5_replay_keyboard_rechecks_the_focus_denied_selector_continues", + scenario: &R5_CONTINUATION, + deny: &[ + (A, CORE_KEY_PRESS_CALL, ROOT), + (B, CORE_KEY_PRESS_CALL, FOCUS), + ], + denied: Outcome { + frames: &[(A, Kind::Core, FOCUS)], + calls: &[ + (A, CORE_KEY_PRESS_CALL, ROOT), + (A, CORE_KEY_PRESS_CALL, FOCUS), + (B, CORE_KEY_PRESS_CALL, FOCUS), + ], + grab: Some(&[]), + ..NOTHING + }, + }, + // Mutation: skip Receive for the replayed key's focus write. A denied + // focus copy must be dropped; Xorg 21.1.24 replays to focus at `dix/events.c:1360`. InputRow { name: "r5_replay_keyboard_rechecks_the_focus", scenario: &R5_REPLAY, @@ -477,9 +878,10 @@ const ROWS: &[InputRow] = &[ ..NOTHING }, }, - // Mutation: omit Receive while `state.playing_sync_events` in the thawed - // pointer write. The denied natural owner copy must fall back to a fresh - // grab-window check, per Xorg 21.1.24 `dix/events.c:4388-4398`. + // Mutation: bypass `fanout::receive_allows` while + // `state.playing_sync_events` in the thawed pointer write. The denied + // natural owner copy must fall back to a fresh grab-window check, per + // Xorg 21.1.24 `dix/events.c:4388-4398`. InputRow { name: "r6_thawed_queued_motion_is_checked_at_its_write", scenario: &R6_THAW, @@ -572,9 +974,10 @@ const ROWS: &[InputRow] = &[ ..NOTHING }, }, - // Mutation: make XI1 activation store the event only when the owner copy - // is allowed. A denied activation still stores it for ReplayThisDevice; + // Mutation: gate XI1 activation storage on the original write's Receive + // result. A denied activation still stores it for ReplayThisDevice; // Xorg 21.1.24 `dix/events.c:3833-3919` keeps activation independent. + // Kill probe: `t3r1-r8-xi1-store-gated-on-original-write-check`. InputRow { name: "r8_denied_xi1_activating_write_still_replays", scenario: &R8_REPLAY, From 161fa5a321fca65f681dd889fc85ae2b8fc42703 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 22:19:48 -0300 Subject: [PATCH 59/72] docs(status): access control PR 4c part 2 Co-Authored-By: Claude Opus 5.5 --- docs/status.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/status.md b/docs/status.md index 1f7c21822..626c1f34d 100644 --- a/docs/status.md +++ b/docs/status.md @@ -39,6 +39,8 @@ lives in [`code-quality-audit-2026-07-26.md`](code-quality-audit-2026-07-26.md). a server reset restores the startup value. This is a client scaling hint, not a change to physical dimensions or rendering. +- **2026-12-02 Access control layer, PR 4c part 2: Receive checks on pointer, keyboard and replay delivery (`feat/access-control-pr4c-input`):** every input copy is checked at its write, with the window it is written to as subject, and Receive decides each delivery attempt, whose writer reuses the result: a denied copy is a non-delivery, the walk goes on to the next selector or the grab window as it would with no selector, a denied candidate cannot take an implicit grab, and passive grab activation and its sync freeze are unchanged. Keyboard: the focused key walk, XI2 form shadowing, grabbed key delivery, and raw key copies with the master raw-key grab leg (owner's root selection first, then the grab window). Pointer: the natural walks, grabbed and owner-events delivery, the slave press protocol, raw pointer and smooth-scroll copies, and XI1 device events through the XI1 router. Replay and thaw: AllowEvents/XIAllowEvents/AllowDeviceEvents replay and thawed queued events are checked again at each write; queue bookkeeping, the replay choice and passive grab matching are not checked, and the XI1 thaw filter asks for no XI2 copy the thaw never writes. yserver rules from the spec: the activating write of a passive grab is checked for the grab owner, and a denial drops only those bytes (the grab activates, a sync grab freezes and stores the event, replay works); the two-event scroll stop is one batch; in key repeat the legacy release and the repeated press are checked separately and keep their order and detectable-repeat eligibility. Removed: the test-only `emit_xi2_device_changed_slave_pointer` and its tests, and `xi2_stamp_deviceid_for_source`. The input tests are table rows (`access_key_input`, `access_pointer_input`, `access_replay_input`) run through production entries, with no-policy and allow-all bytes, grab and freeze state compared for every row. Known and left for a separate change: core `AllowEvents(SyncPointer/SyncKeyboard)` does not refreeze on the next event. With no policy installed, bytes and state are unchanged. + - **2026-12-01 Access control layer, PR 4c part 1: Receive checks on input notifications (#389, merged as 3e09d8a9):** three areas. XI device notifications: XI1 and XI2 device notifications check each recipient before encoding, and a notification that is once per client uses the device as its subject. Crossings, focus, barriers and root/COW ConfigureNotify: the crossing, focus and barrier sites and the root and composite-overlay ConfigureNotify copies check their selectors, and a denied copy is a non-delivery that leaves the walk, the grab and the pointer state as allow-all left them. Native XKB: XKB notifications check their recipients with the XKB event as the description and device 1 as the subject. With no policy installed, bytes and state are unchanged. Pointer, keyboard and replay delivery follow in the next PR. - **2026-11-24 PR #379 review round 2 (`feat/passive-grab-activation`):** rebased on master; the maintainer's second-round items. (1) A slave Motion's `child` is taken toward its pre-move target in the event-window shortcut too. (2) XI1 classes 0-6 and 8 replace the device's selection as Xorg's `CreateMaskFromList` does; classes 0-6 keep private aggregate bits 19-25. (3) DeviceOwnerGrabButton (8) shares DeviceButtonGrab's bit: exclusive per window and device, owner priority. (4) DeviceButtonGrab on a buttonless device is accepted again. (5) Core AllowEvents, XIAllowEvents and paired modes share one `AllowSome` routine (Xorg 21.1.24 `dix/events.c:1825-1926`): admission is `(thisGrabbed && frozen) || thisSynced`, the time bound comes only from the requester's own grabs, Sync from a synced-only client is a no-op, paired modes act on masters only and need `othersFrozen`, Replay on a `FrozenNoEvent` slave is a no-op. A hardware run (marco click-to-focus) found a stuck master button after `ReplayPointer` when only the master was frozen (from the per-device freeze): the replay set the already-released slave bit again, so the queued master release was refused; the replay now takes the master-only transition (Xvfb-measured regression). XTest's axis-slot guard is restored and the branch's Xorg citations are pinned to 21.1.24. Sequences measured on Xvfb 21.1.24 are request-driven regressions. Gate: workspace `xdmcp` 5223/0, lavapipe `--ignored` 778/0, `just man`, rule F 5/5. Follow-ups: XI2 recipient order and implicit owner among equal selections (Xorg: selection order, once per matching InputClients entry; yserver: hash order), slave-keyboard/XI1 grabs carry no grab time (no lower bound), XI1 AllowDeviceEvents AsyncAll over several slave grabs, XI2 slave motion coordinates, projection cost of `refresh_xi_client_selection_projection`. - **2026-11-23 PR #379 review fixes (`feat/passive-grab-activation`):** the maintainer's five before-merge items. (1) AllowEvents(ReplayPointer/ReplayKeyboard) replays only for the client whose grab froze the device in `FrozenWithEvent`, checked before any state change (Xorg `AllowSome`); a synced-only client no longer panics the server, and a sync passive key grab now enters `FrozenWithEvent` as the pointer path does. (2) A slave Motion's `child` comes from the pre-move target it was routed from. (3) XTest DeviceValuator chunks are validated in `ProcXTestFakeInput`'s order (type, contiguity, 1..6, axis sum, detail); eight error rows match Xvfb. (4) A press the master already holds activates no master-pass grab (`UpdateDeviceState`). (5) The XI1 implicit grab owner follows Xorg's window InputClients list, now modelled explicitly per window (newest first, duplicate nodes, sticky XI1 aggregate, dont-propagate masks, server-owned node), created and freed at Xorg's request paths; DeviceButtonGrab is accepted and exclusive per window and device. 33 sequences measured on Xvfb 21.1.24 (raw client) are request-driven regressions. Oracles P1-P5, PR1-PR2, C1-C20, X1-X3 unchanged or matching Xvfb. Gate: workspace `xdmcp` 5194/0, lavapipe `--ignored` 774/0, `pointer_fanout` 5 runs under load. Follow-ups (user scope ruling): other XI1 classes creating positions, ClassFromMask aliases in GetSelectedExtensionEvents, device fields above 255, RetainPermanent/RetainTemporary close-down, duplicate nodes on XI2 and DeviceStateNotify paths, resource-hash freeing order; plus the maintainer's listed follow-ups (`host_x11` `as i16` wrap, `master_sprite_root` on macOS/Windows, UngrabButton vs AnyButton, XIPassiveGrabDevice conflicts) and post-move XI2 slave coordinates. From 151fa962091f801baaa9435912702736a9e86b43 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Wed, 2 Dec 2026 23:20:58 -0300 Subject: [PATCH 60/72] test(access): final review round for the replay rows Final review of plan 3: r7 also denies the cooked fallback at the root (no cooked frame, the keyboard grab survives), the runner shortens a call only for a step with exactly one event, and a probe adds a check where AllowEvents chooses the stored press. Co-Authored-By: Claude Opus 5.5 Implemented-By: codex (gpt-6-luna max) --- .../tests/access_input_support.rs | 67 ++++++++++++++++++- .../tests/access_replay_input.rs | 26 +++++++ 2 files changed, 90 insertions(+), 3 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index 807ab97b8..ba06f2a20 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -1422,10 +1422,11 @@ fn moved_frames(name: &str, allow: &Run, denied: &Run) -> Vec<(u32, Move)> { /// row. pub(super) fn canonical_seen(call: &Seen, evs: &[u16]) -> Seen { let (client, names, window) = call; + let is_current_event = |event| evs.len() == 1 && evs[0] == event; let own = match names.as_slice() { - [Named::Core(n)] if evs.len() == 1 && evs[0] == *n => vec![Named::Core(0)], - [Named::Xi2(n)] if evs.len() == 1 && evs[0] == *n => vec![Named::Xi2(0)], - [Named::Raw(n)] if evs.len() == 1 && evs[0] == *n => vec![Named::Raw(0)], + [Named::Core(n)] if is_current_event(*n) => vec![Named::Core(0)], + [Named::Xi2(n)] if is_current_event(*n) => vec![Named::Xi2(0)], + [Named::Raw(n)] if is_current_event(*n) => vec![Named::Raw(0)], _ => names.clone(), }; (*client, own, *window) @@ -1699,6 +1700,10 @@ pub(super) fn check_rows(rows: &[InputRow]) { mod batch_naming { use super::*; + fn no_setup(_: &mut NotifyFixture) {} + + fn no_request(_: &mut NotifyFixture) {} + fn run_with_xi2_frame(evtype: u16, detail: u32) -> Run { let order = ClientByteOrder::BigEndian; let mut frame = [0_u8; 32]; @@ -1789,6 +1794,62 @@ mod batch_naming { assert_eq!(canonical_seen(&recorded, &[4]), canonical_call(&explicit)); } + /// A two-press request step cannot make two explicit XI2 checks match two + /// shorthand expectations just because both presses have the same type. + #[test] + fn two_press_request_rejects_shorthand_expectations() { + const PRESS: Step = Step::Event(Drive::Pointer { + origin: InputOrigin::XTest(crate::xinput::DEVICEID_MASTER_POINTER), + kind: PointerEventKind::ButtonPress, + button: 1, + to: POINTER, + delta: (0, 0), + }); + const REQUEST_EVENTS: &[Step] = &[PRESS, PRESS]; + const REQUEST_STEP: &[Step] = &[Step::Request(no_request, REQUEST_EVENTS)]; + const SHORTHAND: &[Call] = &[(A, CallKind::Xi2, CHILD), (A, CallKind::Xi2, CHILD)]; + + let scenario = Scenario { + setup: no_setup, + steps: REQUEST_STEP, + allow: Outcome { + calls: SHORTHAND, + ..NOTHING + }, + order: CallOrder::Total, + }; + let one_press_call = (A, vec![Named::Xi2(4)], CHILD); + let run = Run { + clients: Vec::new(), + calls: vec![one_press_call.clone(), one_press_call], + call_evs: vec![vec![4, 4], vec![4, 4]], + hooks: Vec::new(), + requests: vec![(0, A, 35, 0)], + replies: Vec::new(), + state: String::new(), + grab: Vec::new(), + }; + let rejected = std::panic::catch_unwind(|| { + check_outcome( + "two-press request shorthand", + "allow-all", + &scenario, + &run, + &scenario.allow, + ); + }); + let panic = rejected.expect_err("a two-press step must reject shorthand expectations"); + let message = panic + .downcast_ref::() + .map(String::as_str) + .or_else(|| panic.downcast_ref::<&str>().copied()) + .unwrap_or_default(); + assert!( + message.contains("Receive calls"), + "shorthand rejection must come from the call trace comparison, got {message:?}" + ); + } + /// An XI1 `DeviceButtonRelease` decodes like the press, and an XI1 event frame /// the runner has no `Kind` for fails instead of being skipped. #[test] diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs index 326e64d54..922b9776f 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs @@ -742,6 +742,8 @@ const ROWS: &[InputRow] = &[ // Mutation: make the replay's core selection route selection-only. B's // denial must let A at FOCUS receive the press; Xorg 21.1.24 replay // rematches below the released grab (`dix/events.c:1318-1371`). + // Kill probe: `t4-r4-extra-receive-on-replay-choice` rejects a check made + // when AllowEvents chooses the stored press. InputRow { name: "r4_replay_pointer_rechecks_the_natural_target", scenario: &R4_REPLAY, @@ -974,6 +976,30 @@ const ROWS: &[InputRow] = &[ ..NOTHING }, }, + // Mutation: playback calls Receive for the ROOT fallback but discards its + // denial. Kill probe: `t4-r7-playback-discards-root-receive-denial`. + InputRow { + name: "r7_thawed_queued_key_denied_at_child_and_root_stays_grabbed", + scenario: &R7_THAW, + deny: &[ + (B, RAW_KEY_PRESS_CALL, ROOT), + (A, CORE_KEY_PRESS_CALL, CHILD), + (A, CORE_KEY_PRESS_CALL, ROOT), + ], + denied: Outcome { + frames: &[], + calls: &[ + (B, CallKind::Batch(&[Named::Raw(13)]), ROOT), + (A, CallKind::Batch(&[Named::Core(2)]), CHILD), + (A, CallKind::Batch(&[Named::Core(2)]), ROOT), + ], + grab: Some(&[Grab::Keyboard { + owner: A, + window: ROOT, + }]), + ..NOTHING + }, + }, // Mutation: gate XI1 activation storage on the original write's Receive // result. A denied activation still stores it for ReplayThisDevice; // Xorg 21.1.24 `dix/events.c:3833-3919` keeps activation independent. From 279e9280ac744ccc171ccf40384c9695d3fa0032 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Thu, 3 Dec 2026 00:24:15 -0300 Subject: [PATCH 61/72] refactor(input): move the XI1 router into pointer_fanout/xi1.rs pointer_fanout.rs grew past check-layout's 5000-line limit with the Receive checks of this series. The XI1 device-event router (selection walks, passive and device grabs, freeze state) moves unchanged into its own submodule; items private to pointer_fanout become pub(super) and are re-exported, so every caller keeps its path. Co-Authored-By: Claude Opus 5.5 --- .../src/core_loop/pointer_fanout.rs | 950 +---------------- .../src/core_loop/pointer_fanout/xi1.rs | 967 ++++++++++++++++++ 2 files changed, 969 insertions(+), 948 deletions(-) create mode 100644 crates/yserver-core/src/core_loop/pointer_fanout/xi1.rs diff --git a/crates/yserver-core/src/core_loop/pointer_fanout.rs b/crates/yserver-core/src/core_loop/pointer_fanout.rs index d70779eb5..4cbea822a 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout.rs @@ -19,6 +19,7 @@ mod tests; mod buttons; mod owner_events; +mod xi1; use buttons::{master_button_transition, pointer_button_transition}; pub(in crate::core_loop) use owner_events::xtest_wire_valuators; use owner_events::{ @@ -26,6 +27,7 @@ use owner_events::{ xi1_batch, xi1_device_mask_on_window, xi1_event_mask_bit, xi1_selection_filter_for_slave_grab, xi1_window_selectors, xi1_window_selectors_with_grab_class, xi2_motion_targets_for_source, }; +pub use xi1::*; use yserver_protocol::x11::{self, ClientId, ResourceId, SequenceNumber}; @@ -3251,954 +3253,6 @@ pub fn emit_scroll_stop_to_state( } } -/// Resolved natural delivery for one attached slave ButtonPress. Xorg's -/// DeliverDeviceEvents checks XI2 and then XI1 at each window, stopping at -/// the first protocol/window with recipients; the press delivery and XI1 -/// implicit-grab activation both consume this result. -#[derive(Debug)] -pub(crate) enum SlavePressDelivery { - Xi2 { - window: ResourceId, - recipients: Vec, - }, - Xi1 { - window: ResourceId, - recipients: Vec, - }, - None, -} - -/// Route one XI 1.x device input event through grab, freeze, and selection -/// semantics. Pointer and key fanouts and the AllowDeviceEvents thaw path -/// share this entry point. Synchronous grabs re-freeze after each key/button -/// event, passive grabs auto-release on their matching release, and a delivered -/// DeviceButtonPress selection creates an implicit grab (Xorg -/// `ActivateImplicitGrab`, `../xserver/dix/events.c:2152-2196`; MPX -/// `a511c445d` postdates XTS XSelectExtensionEvent assertion 5). -pub(crate) fn xi1_route_device_event( - state: &mut ServerState, - q: crate::server::Xi1QueuedEvent, - allow_freeze: bool, - slave_press_delivery: Option<&SlavePressDelivery>, - receive: &mut ReceiveMemo, -) -> Vec { - use crate::xinput::{ - XI_DEVICE_BUTTON_PRESS_OFFSET, XI_DEVICE_BUTTON_RELEASE_OFFSET, XI_DEVICE_KEY_PRESS_OFFSET, - XI_DEVICE_KEY_RELEASE_OFFSET, - }; - let first = crate::server::XI_FIRST_EVENT; - state.xi1_last_input_time = state.xi1_last_input_time.max(q.time); - let is_press = q.evcode == first + XI_DEVICE_KEY_PRESS_OFFSET - || q.evcode == first + XI_DEVICE_BUTTON_PRESS_OFFSET; - let is_release = q.evcode == first + XI_DEVICE_KEY_RELEASE_OFFSET - || q.evcode == first + XI_DEVICE_BUTTON_RELEASE_OFFSET; - let is_button_press = q.evcode == first + XI_DEVICE_BUTTON_PRESS_OFFSET; - let is_button_release = q.evcode == first + XI_DEVICE_BUTTON_RELEASE_OFFSET; - - // 1. Frozen → queue (Xorg FreezeThaw switching processInputProc - // to the enqueue proc: NOTHING is delivered while frozen, not - // even to the grab owner). - if state - .xi1_frozen - .get(&q.deviceid) - .is_some_and(crate::server::Xi1Freeze::frozen) - { - state - .sync_pending - .push_back(crate::server::PendingSyncEvent { - device: q.deviceid, - event: crate::server::QueuedInputEvent::Xi1Routed(q), - }); - log::debug!( - "xi1_route: device {} frozen — queued evcode={} detail={}", - q.deviceid, - q.evcode, - q.detail, - ); - return Vec::new(); - } - - // Maintain the per-device axis values (Xorg `axisVal`): real - // motion writes the sprite position into axes 0/1; faked device - // motion writes its explicit payload. After the frozen check, like - // the bitmask updates below. - if q.evcode == first + crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET { - let entry = state.xi1_device_input_state.entry(q.deviceid).or_default(); - if let Some(axes) = q.axes { - for i in 0..usize::from(axes.count.min(6)) { - if let Some(slot) = entry.valuators.get_mut(usize::from(axes.first) + i) { - *slot = axes.values[i]; - } - } - } else { - entry.valuators[0] = i32::from(q.root_x); - entry.valuators[1] = i32::from(q.root_y); - } - } - - // Maintain the per-device key/button-down bitmasks consumed by - // DeviceStateNotify (Xorg `dev->key->down` / `dev->button->down`). - // After the frozen check: queued events come back through here on - // thaw, so updating at queue time would double-count them. - if is_press || is_release { - let is_key = q.evcode == first + XI_DEVICE_KEY_PRESS_OFFSET - || q.evcode == first + XI_DEVICE_KEY_RELEASE_OFFSET; - let entry = state.xi1_device_input_state.entry(q.deviceid).or_default(); - let bits = if is_key { - &mut entry.keys_down - } else { - &mut entry.buttons_down - }; - let (byte, bit) = (usize::from(q.detail) / 8, q.detail % 8); - if is_press { - bits[byte] |= 1 << bit; - } else { - bits[byte] &= !(1 << bit); - } - } - - // 2. Active grab. - if let Some(grab) = state.xi1_active_grabs.get(&q.deviceid).copied() { - // owner_events: natural delivery at the first window whose copy the - // owner receives, unless a foreign allowed copy comes first. The - // grab-window copy is its own attempt with one fresh check, made before - // the implicit device-mask gate (`dix/events.c:4388-4398`); a denial - // counts as delivered. - let natural_window = if grab.owner_events { - xi1_owner_events_window(state, &q, grab.owner, receive) - } else { - None - }; - let event_window = natural_window.unwrap_or(grab.grab_window); - let copy_allowed = natural_window.is_some() - || xi1_grab_window_copy_allowed(state, &q, grab.owner, grab.grab_window); - let targets = vec![grab.owner]; - log::debug!( - "xi1_route: evcode={} GRAB owner={} window=0x{:x} detail={}", - q.evcode, - grab.owner.0, - event_window.0, - q.detail, - ); - let deliver = copy_allowed - && (!grab.implicit || grab.device_mask & xi1_event_mask_bit(q.evcode) != 0); - let dropped = if deliver { - xi1_fan_device_event(state, &targets, event_window, &q) - } else { - Vec::new() - }; - // Sync-state transition on a delivered key/button event (Xorg - // FreezeThisEventIfNeededForSyncGrab) — the FreezeNextEvent / - // FreezeBothNextEvent armed states trip to FrozenWithEvent - // here. A plain sync grab does NOT re-freeze on every press: - // CheckGrabForSyncs froze it once at activation. - if allow_freeze && (is_press || is_release) { - xi1_freeze_this_event_if_needed(state, q.deviceid, grab.owner, &q); - } - let implicit_grab_ended = grab.implicit - && is_button_release - && state - .xi1_device_input_state - .get(&q.deviceid) - .is_none_or(|device| device.buttons_down.iter().all(|byte| *byte == 0)); - if (is_release && grab.passive_detail == Some(q.detail)) || implicit_grab_ended { - xi1_deactivate_device_grab(state, q.deviceid); - } - return dropped; - } - - // 3. Passive grab activation on press. A ReplayThisDevice - // reprocessing pass skips grabs at or above the released grab's - // window — "as though they were not present" (the replay floor). - if is_press { - let matched = xi1_matching_passive_grab(state, &q); - if let Some(g) = matched { - state.xi1_active_grabs.insert( - q.deviceid, - crate::server::Xi1ActiveGrab { - owner: g.owner, - deviceid: q.deviceid, - grab_window: g.grab_window, - owner_events: g.owner_events, - this_mode: g.this_mode, - other_mode: g.other_mode, - implicit: false, - device_mask: 0, - passive_detail: Some(q.detail), - }, - ); - state.xi1_last_grab_time = q.time; - // CheckGrabForSyncs at activation, then deliver the - // activating press; a sync grab stores it for Replay - // (FROZEN_NO_EVENT → FROZEN_WITH_EVENT, Xorg - // DeliverGrabbedEvent / ActivateGrabNoDelivery tail). - if allow_freeze { - xi1_check_grab_for_syncs( - state, - q.deviceid, - g.owner, - g.this_mode == 0, - g.other_mode == 0, - ); - } - // The activating write is a grab-window copy: one fresh check; a - // denial still activates and freezes with the stored press. - let dropped = if xi1_grab_window_copy_allowed(state, &q, g.owner, g.grab_window) { - xi1_fan_device_event(state, &[g.owner], g.grab_window, &q) - } else { - Vec::new() - }; - if allow_freeze { - let sync = state.xi1_frozen.entry(q.deviceid).or_default(); - if sync.state == crate::server::Xi1SyncState::FrozenNoEvent { - sync.state = crate::server::Xi1SyncState::FrozenWithEvent; - sync.stored = Some(crate::server::QueuedInputEvent::Xi1Routed(q)); - } - } - return dropped; - } - } - - // 4. Selection delivery, gated by the device-focus route - // (DeliverFocusedEvent for keyboard devices; plain walk for - // pointer devices). - let (selection_filter, _direct_grab_route) = - xi1_selection_filter_for_slave_grab(state, &q, receive); - let mut dropped = Vec::new(); - let hit = if is_button_press - && let Some(delivery) = slave_press_delivery - && matches!(selection_filter, Xi1SelectionFilter::Unrestricted) - { - match delivery { - SlavePressDelivery::Xi1 { window, recipients } => Some((recipients.clone(), *window)), - SlavePressDelivery::Xi2 { .. } | SlavePressDelivery::None => None, - } - } else { - match selection_filter { - Xi1SelectionFilter::Suppress => None, - Xi1SelectionFilter::Unrestricted => compute_xi1_route_targets(state, &q, Some(receive)), - // The XI2 route already decided this owner copy with the dispatch - // memo: write it at that window, no second walk. - Xi1SelectionFilter::Client(client, window) => Some((vec![client], window)), - } - }; - let xi1_implicit_press = is_button_press - && !state.xi1_active_grabs.contains_key(&q.deviceid) - && !state.xi2_pointer_grabs.contains_key(&q.deviceid) - && match slave_press_delivery { - Some(SlavePressDelivery::Xi1 { recipients, .. }) => !recipients.is_empty(), - Some(SlavePressDelivery::Xi2 { .. } | SlavePressDelivery::None) => false, - None => matches!(selection_filter, Xi1SelectionFilter::Unrestricted) && hit.is_some(), - }; - log::debug!( - "xi1_route: evcode={} target=0x{:x} route={:?} hit={:?}", - q.evcode, - q.natural_target.0, - q.focus_route, - hit.as_ref() - .map(|(t, w)| (t.iter().map(|c| c.0).collect::>(), w.0)), - ); - let xi1_dropped = hit.as_ref().map_or_else(Vec::new, |(targets, w)| { - xi1_fan_device_event(state, targets, *w, &q) - }); - merge_dropped(&mut dropped, xi1_dropped); - if xi1_implicit_press && let Some((targets, grab_window)) = hit.as_ref() { - // ../xserver/dix/events.c:2277-2310 walks every delivering node, - // including duplicate clients. The first node with ButtonGrab wins; - // otherwise the last delivering node owns the implicit grab. - let owner = xi1_window_selectors_with_grab_class(state, *grab_window, q.evcode, q.deviceid) - .iter() - .find_map(|(client, has_grab_class)| { - (*has_grab_class && targets.contains(client)).then_some(*client) - }) - .or_else(|| targets.last().copied()); - if let Some(owner) = owner { - let device_mask = xi1_device_mask_on_window(state, *grab_window, q.deviceid); - state.xi1_active_grabs.insert( - q.deviceid, - crate::server::Xi1ActiveGrab { - owner, - deviceid: q.deviceid, - grab_window: *grab_window, - owner_events: false, - this_mode: 1, - other_mode: 1, - implicit: true, - device_mask, - passive_detail: None, - }, - ); - state.xi1_last_grab_time = q.time; - } - } - // A BRIDGED core grab (no XI1 grab, but the core pointer/keyboard - // grab controls this device) must still trip an armed - // FreezeNextEvent / FreezeBothNextEvent on key/button events — - // Xorg delivers through that one grab slot and trips there. - if allow_freeze - && (is_press || is_release) - && let Some(owner) = xi1_device_grab_owner(state, q.deviceid) - { - xi1_freeze_this_event_if_needed(state, q.deviceid, owner, &q); - } - dropped -} - -/// The windows the XI1 selection walk visits, in order: unbounded walk, -/// walk bounded at the focus window, focus-window-only, or none. -fn xi1_route_windows(state: &ServerState, q: &crate::server::Xi1QueuedEvent) -> Vec { - let stop_at = match q.focus_route { - crate::server::Xi1FocusRoute::Walk => None, - crate::server::Xi1FocusRoute::WalkUpTo(stop) => Some(stop), - crate::server::Xi1FocusRoute::WindowOnly(w) => return vec![w], - crate::server::Xi1FocusRoute::Drop => return Vec::new(), - }; - let mut windows = Vec::new(); - let mut window = q.natural_target; - loop { - windows.push(window); - if window == ROOT_WINDOW || stop_at == Some(window) { - break; - } - match state.resources.window(window).map(|w| w.parent) { - Some(parent) if parent != window => window = parent, - _ => break, - } - } - windows -} - -/// True when `client` selected this event but gets no copy of it: a synthetic -/// repeat release to a detectable-repeat client. Receive is not asked for it. -fn xi1_gets_no_copy( - state: &ServerState, - q: &crate::server::Xi1QueuedEvent, - client: ClientId, -) -> bool { - q.synthetic_repeat - && q.evcode == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET - && state - .xkb_clients - .get(&client.0) - .is_some_and(|flags| flags.wants_detectable_auto_repeat()) -} - -/// The selectors at `window` that stop the walk there: those whose copy is -/// allowed, plus the no-copy ones (they stop it with no call). With no memo -/// every selector counts (today's selection-only walk). -fn xi1_allowed_selectors( - state: &ServerState, - window: ResourceId, - q: &crate::server::Xi1QueuedEvent, - receive: Option<&mut ReceiveMemo>, -) -> Vec { - let mut selectors = xi1_window_selectors(state, window, q.evcode, q.deviceid); - if let Some(memo) = receive { - let batch = xi1_batch(q.evcode); - let events = EventBatch::new(&batch); - selectors.retain(|client| { - xi1_gets_no_copy(state, q, *client) - || memo.allows(state, *client, EventSubject::Window(window), &events) - }); - } - selectors -} - -/// Apply the event's [`Xi1FocusRoute`] to find selection-delivery -/// targets — the XI1 analogue of Xorg `DeliverFocusedEvent` -/// (dix/events.c:4202). A window with no allowed selector does not stop the -/// walk (a denied copy is a non-delivery); with `WindowOnly` it ends it. -fn compute_xi1_route_targets( - state: &ServerState, - q: &crate::server::Xi1QueuedEvent, - mut receive: Option<&mut ReceiveMemo>, -) -> Option<(Vec, ResourceId)> { - xi1_route_windows(state, q).into_iter().find_map(|window| { - let targets = xi1_allowed_selectors(state, window, q, receive.as_deref_mut()); - (!targets.is_empty()).then_some((targets, window)) - }) -} - -/// owner_events grab: the window whose copy the grab owner receives naturally. -/// At each window the owner qualifies first (its copy allowed, or no copy); -/// only if it does not are the foreign selectors evaluated (no short-circuit), -/// and an allowed one sends the event to the grab window. `None` = grab window. -fn xi1_owner_events_window( - state: &ServerState, - q: &crate::server::Xi1QueuedEvent, - owner: ClientId, - receive: &mut ReceiveMemo, -) -> Option { - let batch = xi1_batch(q.evcode); - let events = EventBatch::new(&batch); - for window in xi1_route_windows(state, q) { - let selectors = xi1_window_selectors(state, window, q.evcode, q.deviceid); - if selectors.is_empty() { - continue; - } - let mut copy_allowed = |client: ClientId| { - xi1_gets_no_copy(state, q, client) - || receive.allows(state, client, EventSubject::Window(window), &events) - }; - if selectors.contains(&owner) && copy_allowed(owner) { - return Some(window); - } - let mut rejected = false; - for client in selectors.iter().filter(|c| **c != owner) { - rejected |= copy_allowed(*client); - } - if rejected { - return None; - } - } - None -} - -/// The grab-window copy of an XI1 event is its own attempt: one fresh check in -/// the XI1 form. An owner that gets no copy is not asked. -fn xi1_grab_window_copy_allowed( - state: &ServerState, - q: &crate::server::Xi1QueuedEvent, - owner: ClientId, - grab_window: ResourceId, -) -> bool { - !xi1_gets_no_copy(state, q, owner) - && grab_window_allows_batch(state, owner, grab_window, &xi1_batch(q.evcode)) -} - -/// The XI1 passive grab an XI1 press activates, if any (the replay floor -/// hides the grabs at or above the released one). -fn xi1_matching_passive_grab( - state: &ServerState, - q: &crate::server::Xi1QueuedEvent, -) -> Option { - state - .xi1_passive_grabs - .iter() - .find(|g| { - g.deviceid == q.deviceid - && (g.detail == 0 || g.detail == q.detail) - && (g.modifiers == 0x8000 || g.modifiers == q.state_mask & 0x00ff) - && xi1_window_in_chain(state, q.natural_target, g.grab_window) - && !q - .replay_floor - .is_some_and(|floor| xi1_window_in_chain(state, floor, g.grab_window)) - }) - .copied() -} - -/// True when the router queues the device's XI1 events instead of delivering. -fn xi1_device_frozen(state: &ServerState, deviceid: u16) -> bool { - state - .xi1_frozen - .get(&deviceid) - .is_some_and(crate::server::Xi1Freeze::frozen) -} - -/// Chooses the protocol of a slave press: at each window from the target up, -/// the slave XI2 selectors whose copy is allowed, else the XI1 -/// `DeviceButtonPress` selectors whose copy is allowed, else the parent. With a -/// memo, an XI2 selection counts only if its copy is allowed (the same result -/// the write reuses); `xi1_checked` says the router writes the XI1 form, so its -/// selectors are asked too. The XI1 recipients returned are decided: the router -/// writes them as they stand and picks the XI1 implicit owner among them. -fn resolve_slave_press_delivery( - state: &ServerState, - target: ResourceId, - deviceid: u16, - xi1_evcode: u8, - receive: &mut ReceiveMemo, - xi2_checked: bool, - xi1_checked: bool, -) -> SlavePressDelivery { - let xi1_description = xi1_batch(xi1_evcode); - let xi1_events = EventBatch::new(&xi1_description); - let mut window = target; - for _ in 0..256 { - let xi2_recipients = xi2_form_targets_for_source( - state, - window, - Xi2PointerForm::Slave, - xi2_evtype(PointerEventKind::ButtonPress), - Some(deviceid), - xi2_checked.then_some(&mut *receive), - ); - if !xi2_recipients.is_empty() { - return SlavePressDelivery::Xi2 { - window, - recipients: xi2_recipients, - }; - } - - let mut xi1_recipients = xi1_window_selectors(state, window, xi1_evcode, deviceid); - if xi1_checked { - xi1_recipients.retain(|client| { - receive.allows(state, *client, EventSubject::Window(window), &xi1_events) - }); - } - if !xi1_recipients.is_empty() { - return SlavePressDelivery::Xi1 { - window, - recipients: xi1_recipients, - }; - } - - if window == ROOT_WINDOW { - break; - } - let Some(parent) = state.resources.parent_of(window) else { - break; - }; - window = parent; - } - SlavePressDelivery::None -} - -/// True when `grab_window` is `target` or one of its ancestors. -fn xi1_window_in_chain(state: &ServerState, target: ResourceId, grab_window: ResourceId) -> bool { - let mut window = target; - loop { - if window == grab_window { - return true; - } - if window == ROOT_WINDOW { - return false; - } - match state.resources.window(window).map(|w| w.parent) { - Some(parent) if parent != window => window = parent, - _ => return false, - } - } -} - -fn xi1_fan_device_event( - state: &mut ServerState, - targets: &[ClientId], - event_window: ResourceId, - q: &crate::server::Xi1QueuedEvent, -) -> Vec { - // DeviceMotionNotify MUST be a MORE_EVENTS chain with a trailing - // deviceValuator: libXi's XInputWireToEvent returns DONT_ENQUEUE - // unconditionally for the leading motion event and only enqueues - // when the valuator continuation lands (XExtInt.c) — a bare motion - // event silently vanishes inside every libXi client. Key/button - // events enqueue standalone. The valuator payload mirrors the - // device's X/Y axes (the sprite position), matching Xorg's - // getValuatorEvents for a 2-axis motion. - let is_motion = - q.evcode == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET; - // Xorg FixUpEventFromWindow: coordinates relative to the event - // window's inside origin; child per FindChildForEvent from the - // sprite window (the pointer hit for pointer events, the deepest - // window under the pointer for key events). - let is_key = q.evcode - == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET - || q.evcode == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET; - let targets: Vec = if q.synthetic_repeat - && q.evcode == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET - { - targets - .iter() - .copied() - .filter(|client| !xi1_gets_no_copy(state, q, *client)) - .collect() - } else { - targets.to_vec() - }; - if targets.is_empty() { - return Vec::new(); - } - let sprite = if is_key { - crate::core_loop::key_fanout::deepest_window_at_pointer(state) - } else { - q.natural_target - }; - let child = xi2_child_toward(state, event_window, sprite); - let (ox, oy) = state.resources.window_absolute_position(event_window); - let event_x = clamp_grab_coord(q.root_x, ox); - let event_y = clamp_grab_coord(q.root_y, oy); - let mut dropped = Vec::new(); - // The general fanout deduplicates client IDs. XI1 selection delivery - // instead sends once per InputClients node (../xserver/dix/events.c:2279-2316). - for client in targets { - let failed = fanout_event_to_clients(state, &[client], |buf, seq, order| { - crate::xinput::encode_xi1_device_input_event( - buf, - order, - q.evcode, - q.detail, - seq, - q.time, - ROOT_WINDOW.0, - event_window.0, - child.0, - q.root_x, - q.root_y, - event_x, - event_y, - q.state_mask, - if is_motion { - q.deviceid | u16::from(crate::xinput::XI1_MORE_EVENTS) - } else { - q.deviceid - }, - ); - if is_motion { - // Faked motion carries its explicit axis payload; real - // motion reports the X/Y axes (= sprite position). - let (num, first_v, values) = match q.axes { - Some(a) => (a.count.min(6), a.first, a.values), - None => (2, 0, [i32::from(q.root_x), i32::from(q.root_y), 0, 0, 0, 0]), - }; - #[allow(clippy::cast_possible_truncation)] - crate::xinput::encode_xi1_device_valuator( - buf, - order, - crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_VALUATOR_OFFSET, - q.deviceid as u8, - seq, - q.state_mask, - num, - first_v, - values, - ); - } - }); - merge_dropped(&mut dropped, failed); - } - dropped -} - -/// Resolve the Xorg paired master from the requested device's current -/// attachment. Floating slaves have no paired device. -pub(crate) fn xi1_other_input_device(state: &ServerState, deviceid: u16) -> Option { - state.xi_devices.paired_master(deviceid).or_else(|| { - state - .xi2_detached_masters - .get(&deviceid) - .and_then(|master| state.xi_devices.paired_master(*master)) - }) -} - -/// Force-thaw a device: reset its sync state outright and flush. Used -/// by teardown paths (client disconnect with no grabs left) where no -/// grab semantics apply — NOT by AllowDeviceEvents, which manipulates -/// the sync state per Xorg `AllowSome` and then calls -/// [`xi1_compute_freezes`]. -pub(crate) fn xi1_thaw_device( - state: &mut ServerState, - backend: &mut dyn crate::backend::Backend, - xid_map: &HostXidMap, - deviceid: u16, -) { - if let Some(freeze) = state.xi1_frozen.get_mut(&deviceid) { - freeze.state = crate::server::Xi1SyncState::Thawed; - freeze.other = None; - } - xi1_compute_freezes(state, backend, xid_map); -} - -/// Port of Xorg `ComputeFreezes` (dix/events.c:1320) over the -/// two-device model: re-derive each device's frozen flag from its sync -/// state and flush the queued events of every no-longer-frozen device. -/// Re-freezing mid-flush (a queued press activating a sync passive -/// grab) leaves the remainder queued, exactly like Xorg's restart loop. -pub(crate) fn xi1_compute_freezes( - state: &mut ServerState, - backend: &mut dyn crate::backend::Backend, - xid_map: &HostXidMap, -) { - if state.playing_sync_events { - return; - } - // SAFETY: local guard cannot outlive this mutable ServerState borrow. - let _replay_guard = - unsafe { crate::server::SyncReplayGuard::arm(&mut state.playing_sync_events) }; - // Xorg PlayReleasedEvents: after each delivery restart the search from - // the head, because that delivery can change another device's freeze. - loop { - let index = state.sync_pending.iter().position(|pending| { - !state - .xi1_frozen - .get(&pending.device) - .is_some_and(crate::server::Xi1Freeze::frozen) - }); - let Some(index) = index else { break }; - let pending = state - .sync_pending - .remove(index) - .expect("pending index is valid"); - match pending.event { - crate::server::QueuedInputEvent::HostPointer(event) => { - let _ = pointer_event_fanout_to_state(state, backend, xid_map, event, false, false); - } - crate::server::QueuedInputEvent::HostPointerMaster(event, scroll_motion) => { - let _ = play_queued_master_pointer_event( - state, - backend, - xid_map, - event, - pending.device, - scroll_motion, - ); - } - crate::server::QueuedInputEvent::HostKey(event) => { - let _ = crate::core_loop::key_fanout::deliver_routed_key(state, event); - } - crate::server::QueuedInputEvent::HostKeyTransition( - event, - master_transition_accepted, - synthetic_repeat, - ) => { - let _ = crate::core_loop::key_fanout::deliver_routed_key_after_transition( - state, - event, - master_transition_accepted, - synthetic_repeat, - ); - } - crate::server::QueuedInputEvent::Xi1Routed(event) => { - let _ = xi1_route_device_event(state, event, true, None, &mut ReceiveMemo::new()); - } - crate::server::QueuedInputEvent::RawKey(event) => { - let _ = crate::core_loop::key_fanout::deliver_raw_key_master(state, event); - } - } - } -} - -/// End active grabs on a physical source, restore its saved attachments, -/// and replay input released by a dynamic XI2 grab's paired-device hold. -/// The caller keeps the source registered until held-state releases have -/// passed through the normal fanout path, then disables and unregisters it. -pub fn xi_cleanup_source( - state: &mut ServerState, - backend: &mut dyn crate::backend::Backend, - source: crate::xinput::InputSourceId, -) { - let device_ids: Vec = [ - state - .xi_devices - .facet(source, crate::xinput::XiFacetKind::Keyboard), - state - .xi_devices - .facet(source, crate::xinput::XiFacetKind::PointerTouch), - ] - .into_iter() - .flatten() - .collect(); - - for device_id in device_ids { - xi1_deactivate_device_grab(state, device_id); - - let pointer_grab = state.xi2_pointer_grabs.get(&device_id).copied(); - let pointer_owner = pointer_grab - .filter(|grab| !grab.implicit) - .map(|grab| grab.owner); - if pointer_grab.is_some_and(|grab| grab.implicit) { - state.remove_implicit_xi2_pointer_grab(device_id); - } else if pointer_grab.is_some() { - state.xi2_pointer_grabs.remove(&device_id); - } - let keyboard_owner = state - .xi2_keyboard_grabs - .remove(&device_id) - .map(|grab| grab.owner); - for owner in [pointer_owner, keyboard_owner].into_iter().flatten() { - if let Some(freeze) = state.xi1_frozen.get_mut(&device_id) { - freeze.state = crate::server::Xi1SyncState::Thawed; - freeze.stored = None; - } - xi1_core_grab_bridge_release(state, device_id, owner); - } - if pointer_owner.is_some() - || keyboard_owner.is_some() - || state.xi2_detached_masters.contains_key(&device_id) - { - state.reattach_xi2_slave(device_id); - } - } - - let xid_map = backend.xid_map().clone(); - xi1_compute_freezes(state, backend, &xid_map); -} - -/// Port of Xorg `CheckGrabForSyncs` (dix/events.c:1424-1450): set the -/// sync state at grab activation. A sync `this_mode` freezes the -/// grabbed device ONCE (FrozenNoEvent); a sync `other_mode` holds the -/// paired device on behalf of this grab (`sync.other`). Async modes -/// release the same-client holds. -pub(crate) fn xi1_check_grab_for_syncs( - state: &mut ServerState, - deviceid: u16, - owner: ClientId, - this_sync: bool, - other_sync: bool, -) { - { - let sync = state.xi1_frozen.entry(deviceid).or_default(); - if this_sync { - sync.state = crate::server::Xi1SyncState::FrozenNoEvent; - } else { - sync.state = crate::server::Xi1SyncState::Thawed; - if sync.other == Some(owner) { - sync.other = None; - } - } - } - // Xorg CheckGrabForSyncs only synchronizes the paired device for a - // master grab (dix/events.c:1439). Slave grabs force paired_device_mode - // to Async and never freeze their paired master. - if matches!( - state.xi_devices.role(deviceid), - Some( - crate::xinput::XiDeviceRole::MasterPointer - | crate::xinput::XiDeviceRole::MasterKeyboard - ) - ) && let Some(other_dev) = xi1_other_input_device(state, deviceid) - { - let other = state.xi1_frozen.entry(other_dev).or_default(); - if other_sync { - other.other = Some(owner); - } else if other.other == Some(owner) { - other.other = None; - } - } -} - -/// Port of Xorg `FreezeThisEventIfNeededForSyncGrab` -/// (dix/events.c:4420-4447): after a key/button event is delivered -/// through the active grab, an armed FreezeNextEvent / -/// FreezeBothNextEvent state trips to FrozenWithEvent (storing the -/// event for Replay); FreezeBothNextEvent also re-holds the paired -/// device. -pub(crate) fn xi1_freeze_this_event_if_needed( - state: &mut ServerState, - deviceid: u16, - owner: ClientId, - q: &crate::server::Xi1QueuedEvent, -) { - use crate::server::Xi1SyncState; - let st = state - .xi1_frozen - .get(&deviceid) - .map_or(Xi1SyncState::Thawed, |f| f.state); - match st { - Xi1SyncState::FreezeBothNextEvent => { - let other_dev = xi1_other_input_device(state, deviceid); - let Some(other_dev) = other_dev else { - let sync = state.xi1_frozen.entry(deviceid).or_default(); - sync.state = Xi1SyncState::FrozenWithEvent; - sync.stored = Some(crate::server::QueuedInputEvent::Xi1Routed(*q)); - return; - }; - let other_owner = xi1_device_grab_owner(state, other_dev); - let other = state.xi1_frozen.entry(other_dev).or_default(); - if other.state == Xi1SyncState::FreezeBothNextEvent && other_owner == Some(owner) { - other.state = Xi1SyncState::FrozenNoEvent; - } else { - other.other = Some(owner); - } - let sync = state.xi1_frozen.entry(deviceid).or_default(); - sync.state = Xi1SyncState::FrozenWithEvent; - sync.stored = Some(crate::server::QueuedInputEvent::Xi1Routed(*q)); - } - Xi1SyncState::FreezeNextEvent => { - let sync = state.xi1_frozen.entry(deviceid).or_default(); - sync.state = Xi1SyncState::FrozenWithEvent; - sync.stored = Some(crate::server::QueuedInputEvent::Xi1Routed(*q)); - } - _ => {} - } -} - -/// Deactivate the active XI1 grab on `deviceid` (UngrabDevice, passive -/// release auto-end, disconnect teardown): reset its sync state and -/// release a paired-device hold owned by this grab (Xorg -/// DeactivateKeyboard/PointerGrab clears only `sync.other` references to -/// the departing grab, `../xserver/dix/events.c:1698-1700,1799-1801`). -pub(crate) fn xi1_deactivate_device_grab(state: &mut ServerState, deviceid: u16) { - let Some(grab) = state.xi1_active_grabs.remove(&deviceid) else { - return; - }; - if let Some(sync) = state.xi1_frozen.get_mut(&deviceid) { - sync.state = crate::server::Xi1SyncState::Thawed; - sync.stored = None; - } - // DeviceButtonPress implicit grabs are created on slave devices with - // asynchronous paired-device mode. They never own a paired hold, so - // an `other` hold from another same-client master grab must survive. - let other_dev = (!grab.implicit) - .then(|| xi1_other_input_device(state, deviceid)) - .flatten(); - if let Some(other) = other_dev.and_then(|id| state.xi1_frozen.get_mut(&id)) - && other.other == Some(grab.owner) - { - other.other = None; - } -} - -/// Release the core-grab bridge hold on `deviceid` at GRAB -/// DEACTIVATION (core UngrabPointer / UngrabKeyboard, passive key-grab -/// auto-release): thaw the device's sync state when no XI1 grab -/// controls it and release the paired device if held on `owner`'s -/// behalf — Xorg DeactivateKeyboard/PointerGrab clears every -/// `sync.other` pointing at the dying grab. -pub(crate) fn xi1_core_grab_bridge_release( - state: &mut ServerState, - deviceid: u16, - owner: ClientId, -) { - if !state.xi1_active_grabs.contains_key(&deviceid) - && let Some(sync) = state.xi1_frozen.get_mut(&deviceid) - { - sync.state = crate::server::Xi1SyncState::Thawed; - sync.stored = None; - } - let other_dev = xi1_other_input_device(state, deviceid); - if let Some(other) = other_dev.and_then(|id| state.xi1_frozen.get_mut(&id)) - && other.other == Some(owner) - { - other.other = None; - } -} - -/// The client owning the grab that controls `deviceid`'s sync state: -/// the XI1 device grab, or the bridged core grab (core pointer grab ↔ -/// slave pointer, core keyboard grab ↔ slave keyboard) — in Xorg these -/// are one `deviceGrab.grab` slot. -pub(crate) fn xi1_device_grab_owner(state: &ServerState, deviceid: u16) -> Option { - if let Some(g) = state.xi1_active_grabs.get(&deviceid) { - return Some(g.owner); - } - if let Some(g) = state.xi2_pointer_grabs.get(&deviceid) { - return Some(g.owner); - } - if let Some(g) = state.xi2_keyboard_grabs.get(&deviceid) { - return Some(g.owner); - } - match state.xi_devices.role(deviceid)? { - crate::xinput::XiDeviceRole::MasterPointer => { - state.active_pointer_grab.as_ref().map(|grab| grab.owner) - } - crate::xinput::XiDeviceRole::SlavePointer => { - let master = state.xi_devices.attachment(deviceid)?; - (master == crate::xinput::DEVICEID_MASTER_POINTER) - .then(|| state.active_pointer_grab.as_ref().map(|grab| grab.owner)) - .flatten() - } - crate::xinput::XiDeviceRole::MasterKeyboard => { - state.active_keyboard_grab.as_ref().map(|grab| grab.owner) - } - crate::xinput::XiDeviceRole::SlaveKeyboard => { - let master = state.xi_devices.attachment(deviceid)?; - (master == crate::xinput::DEVICEID_MASTER_KEYBOARD) - .then(|| state.active_keyboard_grab.as_ref().map(|grab| grab.owner)) - .flatten() - } - } -} - fn translate_host_event( state: &ServerState, xid_map: &HostXidMap, diff --git a/crates/yserver-core/src/core_loop/pointer_fanout/xi1.rs b/crates/yserver-core/src/core_loop/pointer_fanout/xi1.rs new file mode 100644 index 000000000..a883252fc --- /dev/null +++ b/crates/yserver-core/src/core_loop/pointer_fanout/xi1.rs @@ -0,0 +1,967 @@ +//! The XI1 device-event router: selection walks, passive and device grabs, +//! and the per-device freeze state that sync grabs and AllowDeviceEvents drive. + +use super::{ + ClientId, EventBatch, EventSubject, HostXidMap, PointerEventKind, ROOT_WINDOW, ReceiveMemo, + ResourceId, ServerState, Xi1SelectionFilter, Xi2PointerForm, clamp_grab_coord, + fanout_event_to_clients, grab_window_allows_batch, merge_dropped, + play_queued_master_pointer_event, pointer_event_fanout_to_state, xi1_batch, + xi1_device_mask_on_window, xi1_event_mask_bit, xi1_selection_filter_for_slave_grab, + xi1_window_selectors, xi1_window_selectors_with_grab_class, xi2_child_toward, xi2_evtype, + xi2_form_targets_for_source, +}; + +/// Resolved natural delivery for one attached slave ButtonPress. Xorg's +/// DeliverDeviceEvents checks XI2 and then XI1 at each window, stopping at +/// the first protocol/window with recipients; the press delivery and XI1 +/// implicit-grab activation both consume this result. +#[derive(Debug)] +pub(crate) enum SlavePressDelivery { + Xi2 { + window: ResourceId, + recipients: Vec, + }, + Xi1 { + window: ResourceId, + recipients: Vec, + }, + None, +} + +/// Route one XI 1.x device input event through grab, freeze, and selection +/// semantics. Pointer and key fanouts and the AllowDeviceEvents thaw path +/// share this entry point. Synchronous grabs re-freeze after each key/button +/// event, passive grabs auto-release on their matching release, and a delivered +/// DeviceButtonPress selection creates an implicit grab (Xorg +/// `ActivateImplicitGrab`, `../xserver/dix/events.c:2152-2196`; MPX +/// `a511c445d` postdates XTS XSelectExtensionEvent assertion 5). +pub(crate) fn xi1_route_device_event( + state: &mut ServerState, + q: crate::server::Xi1QueuedEvent, + allow_freeze: bool, + slave_press_delivery: Option<&SlavePressDelivery>, + receive: &mut ReceiveMemo, +) -> Vec { + use crate::xinput::{ + XI_DEVICE_BUTTON_PRESS_OFFSET, XI_DEVICE_BUTTON_RELEASE_OFFSET, XI_DEVICE_KEY_PRESS_OFFSET, + XI_DEVICE_KEY_RELEASE_OFFSET, + }; + let first = crate::server::XI_FIRST_EVENT; + state.xi1_last_input_time = state.xi1_last_input_time.max(q.time); + let is_press = q.evcode == first + XI_DEVICE_KEY_PRESS_OFFSET + || q.evcode == first + XI_DEVICE_BUTTON_PRESS_OFFSET; + let is_release = q.evcode == first + XI_DEVICE_KEY_RELEASE_OFFSET + || q.evcode == first + XI_DEVICE_BUTTON_RELEASE_OFFSET; + let is_button_press = q.evcode == first + XI_DEVICE_BUTTON_PRESS_OFFSET; + let is_button_release = q.evcode == first + XI_DEVICE_BUTTON_RELEASE_OFFSET; + + // 1. Frozen → queue (Xorg FreezeThaw switching processInputProc + // to the enqueue proc: NOTHING is delivered while frozen, not + // even to the grab owner). + if state + .xi1_frozen + .get(&q.deviceid) + .is_some_and(crate::server::Xi1Freeze::frozen) + { + state + .sync_pending + .push_back(crate::server::PendingSyncEvent { + device: q.deviceid, + event: crate::server::QueuedInputEvent::Xi1Routed(q), + }); + log::debug!( + "xi1_route: device {} frozen — queued evcode={} detail={}", + q.deviceid, + q.evcode, + q.detail, + ); + return Vec::new(); + } + + // Maintain the per-device axis values (Xorg `axisVal`): real + // motion writes the sprite position into axes 0/1; faked device + // motion writes its explicit payload. After the frozen check, like + // the bitmask updates below. + if q.evcode == first + crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET { + let entry = state.xi1_device_input_state.entry(q.deviceid).or_default(); + if let Some(axes) = q.axes { + for i in 0..usize::from(axes.count.min(6)) { + if let Some(slot) = entry.valuators.get_mut(usize::from(axes.first) + i) { + *slot = axes.values[i]; + } + } + } else { + entry.valuators[0] = i32::from(q.root_x); + entry.valuators[1] = i32::from(q.root_y); + } + } + + // Maintain the per-device key/button-down bitmasks consumed by + // DeviceStateNotify (Xorg `dev->key->down` / `dev->button->down`). + // After the frozen check: queued events come back through here on + // thaw, so updating at queue time would double-count them. + if is_press || is_release { + let is_key = q.evcode == first + XI_DEVICE_KEY_PRESS_OFFSET + || q.evcode == first + XI_DEVICE_KEY_RELEASE_OFFSET; + let entry = state.xi1_device_input_state.entry(q.deviceid).or_default(); + let bits = if is_key { + &mut entry.keys_down + } else { + &mut entry.buttons_down + }; + let (byte, bit) = (usize::from(q.detail) / 8, q.detail % 8); + if is_press { + bits[byte] |= 1 << bit; + } else { + bits[byte] &= !(1 << bit); + } + } + + // 2. Active grab. + if let Some(grab) = state.xi1_active_grabs.get(&q.deviceid).copied() { + // owner_events: natural delivery at the first window whose copy the + // owner receives, unless a foreign allowed copy comes first. The + // grab-window copy is its own attempt with one fresh check, made before + // the implicit device-mask gate (`dix/events.c:4388-4398`); a denial + // counts as delivered. + let natural_window = if grab.owner_events { + xi1_owner_events_window(state, &q, grab.owner, receive) + } else { + None + }; + let event_window = natural_window.unwrap_or(grab.grab_window); + let copy_allowed = natural_window.is_some() + || xi1_grab_window_copy_allowed(state, &q, grab.owner, grab.grab_window); + let targets = vec![grab.owner]; + log::debug!( + "xi1_route: evcode={} GRAB owner={} window=0x{:x} detail={}", + q.evcode, + grab.owner.0, + event_window.0, + q.detail, + ); + let deliver = copy_allowed + && (!grab.implicit || grab.device_mask & xi1_event_mask_bit(q.evcode) != 0); + let dropped = if deliver { + xi1_fan_device_event(state, &targets, event_window, &q) + } else { + Vec::new() + }; + // Sync-state transition on a delivered key/button event (Xorg + // FreezeThisEventIfNeededForSyncGrab) — the FreezeNextEvent / + // FreezeBothNextEvent armed states trip to FrozenWithEvent + // here. A plain sync grab does NOT re-freeze on every press: + // CheckGrabForSyncs froze it once at activation. + if allow_freeze && (is_press || is_release) { + xi1_freeze_this_event_if_needed(state, q.deviceid, grab.owner, &q); + } + let implicit_grab_ended = grab.implicit + && is_button_release + && state + .xi1_device_input_state + .get(&q.deviceid) + .is_none_or(|device| device.buttons_down.iter().all(|byte| *byte == 0)); + if (is_release && grab.passive_detail == Some(q.detail)) || implicit_grab_ended { + xi1_deactivate_device_grab(state, q.deviceid); + } + return dropped; + } + + // 3. Passive grab activation on press. A ReplayThisDevice + // reprocessing pass skips grabs at or above the released grab's + // window — "as though they were not present" (the replay floor). + if is_press { + let matched = xi1_matching_passive_grab(state, &q); + if let Some(g) = matched { + state.xi1_active_grabs.insert( + q.deviceid, + crate::server::Xi1ActiveGrab { + owner: g.owner, + deviceid: q.deviceid, + grab_window: g.grab_window, + owner_events: g.owner_events, + this_mode: g.this_mode, + other_mode: g.other_mode, + implicit: false, + device_mask: 0, + passive_detail: Some(q.detail), + }, + ); + state.xi1_last_grab_time = q.time; + // CheckGrabForSyncs at activation, then deliver the + // activating press; a sync grab stores it for Replay + // (FROZEN_NO_EVENT → FROZEN_WITH_EVENT, Xorg + // DeliverGrabbedEvent / ActivateGrabNoDelivery tail). + if allow_freeze { + xi1_check_grab_for_syncs( + state, + q.deviceid, + g.owner, + g.this_mode == 0, + g.other_mode == 0, + ); + } + // The activating write is a grab-window copy: one fresh check; a + // denial still activates and freezes with the stored press. + let dropped = if xi1_grab_window_copy_allowed(state, &q, g.owner, g.grab_window) { + xi1_fan_device_event(state, &[g.owner], g.grab_window, &q) + } else { + Vec::new() + }; + if allow_freeze { + let sync = state.xi1_frozen.entry(q.deviceid).or_default(); + if sync.state == crate::server::Xi1SyncState::FrozenNoEvent { + sync.state = crate::server::Xi1SyncState::FrozenWithEvent; + sync.stored = Some(crate::server::QueuedInputEvent::Xi1Routed(q)); + } + } + return dropped; + } + } + + // 4. Selection delivery, gated by the device-focus route + // (DeliverFocusedEvent for keyboard devices; plain walk for + // pointer devices). + let (selection_filter, _direct_grab_route) = + xi1_selection_filter_for_slave_grab(state, &q, receive); + let mut dropped = Vec::new(); + let hit = if is_button_press + && let Some(delivery) = slave_press_delivery + && matches!(selection_filter, Xi1SelectionFilter::Unrestricted) + { + match delivery { + SlavePressDelivery::Xi1 { window, recipients } => Some((recipients.clone(), *window)), + SlavePressDelivery::Xi2 { .. } | SlavePressDelivery::None => None, + } + } else { + match selection_filter { + Xi1SelectionFilter::Suppress => None, + Xi1SelectionFilter::Unrestricted => compute_xi1_route_targets(state, &q, Some(receive)), + // The XI2 route already decided this owner copy with the dispatch + // memo: write it at that window, no second walk. + Xi1SelectionFilter::Client(client, window) => Some((vec![client], window)), + } + }; + let xi1_implicit_press = is_button_press + && !state.xi1_active_grabs.contains_key(&q.deviceid) + && !state.xi2_pointer_grabs.contains_key(&q.deviceid) + && match slave_press_delivery { + Some(SlavePressDelivery::Xi1 { recipients, .. }) => !recipients.is_empty(), + Some(SlavePressDelivery::Xi2 { .. } | SlavePressDelivery::None) => false, + None => matches!(selection_filter, Xi1SelectionFilter::Unrestricted) && hit.is_some(), + }; + log::debug!( + "xi1_route: evcode={} target=0x{:x} route={:?} hit={:?}", + q.evcode, + q.natural_target.0, + q.focus_route, + hit.as_ref() + .map(|(t, w)| (t.iter().map(|c| c.0).collect::>(), w.0)), + ); + let xi1_dropped = hit.as_ref().map_or_else(Vec::new, |(targets, w)| { + xi1_fan_device_event(state, targets, *w, &q) + }); + merge_dropped(&mut dropped, xi1_dropped); + if xi1_implicit_press && let Some((targets, grab_window)) = hit.as_ref() { + // ../xserver/dix/events.c:2277-2310 walks every delivering node, + // including duplicate clients. The first node with ButtonGrab wins; + // otherwise the last delivering node owns the implicit grab. + let owner = xi1_window_selectors_with_grab_class(state, *grab_window, q.evcode, q.deviceid) + .iter() + .find_map(|(client, has_grab_class)| { + (*has_grab_class && targets.contains(client)).then_some(*client) + }) + .or_else(|| targets.last().copied()); + if let Some(owner) = owner { + let device_mask = xi1_device_mask_on_window(state, *grab_window, q.deviceid); + state.xi1_active_grabs.insert( + q.deviceid, + crate::server::Xi1ActiveGrab { + owner, + deviceid: q.deviceid, + grab_window: *grab_window, + owner_events: false, + this_mode: 1, + other_mode: 1, + implicit: true, + device_mask, + passive_detail: None, + }, + ); + state.xi1_last_grab_time = q.time; + } + } + // A BRIDGED core grab (no XI1 grab, but the core pointer/keyboard + // grab controls this device) must still trip an armed + // FreezeNextEvent / FreezeBothNextEvent on key/button events — + // Xorg delivers through that one grab slot and trips there. + if allow_freeze + && (is_press || is_release) + && let Some(owner) = xi1_device_grab_owner(state, q.deviceid) + { + xi1_freeze_this_event_if_needed(state, q.deviceid, owner, &q); + } + dropped +} + +/// The windows the XI1 selection walk visits, in order: unbounded walk, +/// walk bounded at the focus window, focus-window-only, or none. +pub(super) fn xi1_route_windows( + state: &ServerState, + q: &crate::server::Xi1QueuedEvent, +) -> Vec { + let stop_at = match q.focus_route { + crate::server::Xi1FocusRoute::Walk => None, + crate::server::Xi1FocusRoute::WalkUpTo(stop) => Some(stop), + crate::server::Xi1FocusRoute::WindowOnly(w) => return vec![w], + crate::server::Xi1FocusRoute::Drop => return Vec::new(), + }; + let mut windows = Vec::new(); + let mut window = q.natural_target; + loop { + windows.push(window); + if window == ROOT_WINDOW || stop_at == Some(window) { + break; + } + match state.resources.window(window).map(|w| w.parent) { + Some(parent) if parent != window => window = parent, + _ => break, + } + } + windows +} + +/// True when `client` selected this event but gets no copy of it: a synthetic +/// repeat release to a detectable-repeat client. Receive is not asked for it. +pub(super) fn xi1_gets_no_copy( + state: &ServerState, + q: &crate::server::Xi1QueuedEvent, + client: ClientId, +) -> bool { + q.synthetic_repeat + && q.evcode == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET + && state + .xkb_clients + .get(&client.0) + .is_some_and(|flags| flags.wants_detectable_auto_repeat()) +} + +/// The selectors at `window` that stop the walk there: those whose copy is +/// allowed, plus the no-copy ones (they stop it with no call). With no memo +/// every selector counts (today's selection-only walk). +pub(super) fn xi1_allowed_selectors( + state: &ServerState, + window: ResourceId, + q: &crate::server::Xi1QueuedEvent, + receive: Option<&mut ReceiveMemo>, +) -> Vec { + let mut selectors = xi1_window_selectors(state, window, q.evcode, q.deviceid); + if let Some(memo) = receive { + let batch = xi1_batch(q.evcode); + let events = EventBatch::new(&batch); + selectors.retain(|client| { + xi1_gets_no_copy(state, q, *client) + || memo.allows(state, *client, EventSubject::Window(window), &events) + }); + } + selectors +} + +/// Apply the event's [`Xi1FocusRoute`] to find selection-delivery +/// targets — the XI1 analogue of Xorg `DeliverFocusedEvent` +/// (dix/events.c:4202). A window with no allowed selector does not stop the +/// walk (a denied copy is a non-delivery); with `WindowOnly` it ends it. +pub(super) fn compute_xi1_route_targets( + state: &ServerState, + q: &crate::server::Xi1QueuedEvent, + mut receive: Option<&mut ReceiveMemo>, +) -> Option<(Vec, ResourceId)> { + xi1_route_windows(state, q).into_iter().find_map(|window| { + let targets = xi1_allowed_selectors(state, window, q, receive.as_deref_mut()); + (!targets.is_empty()).then_some((targets, window)) + }) +} + +/// owner_events grab: the window whose copy the grab owner receives naturally. +/// At each window the owner qualifies first (its copy allowed, or no copy); +/// only if it does not are the foreign selectors evaluated (no short-circuit), +/// and an allowed one sends the event to the grab window. `None` = grab window. +pub(super) fn xi1_owner_events_window( + state: &ServerState, + q: &crate::server::Xi1QueuedEvent, + owner: ClientId, + receive: &mut ReceiveMemo, +) -> Option { + let batch = xi1_batch(q.evcode); + let events = EventBatch::new(&batch); + for window in xi1_route_windows(state, q) { + let selectors = xi1_window_selectors(state, window, q.evcode, q.deviceid); + if selectors.is_empty() { + continue; + } + let mut copy_allowed = |client: ClientId| { + xi1_gets_no_copy(state, q, client) + || receive.allows(state, client, EventSubject::Window(window), &events) + }; + if selectors.contains(&owner) && copy_allowed(owner) { + return Some(window); + } + let mut rejected = false; + for client in selectors.iter().filter(|c| **c != owner) { + rejected |= copy_allowed(*client); + } + if rejected { + return None; + } + } + None +} + +/// The grab-window copy of an XI1 event is its own attempt: one fresh check in +/// the XI1 form. An owner that gets no copy is not asked. +pub(super) fn xi1_grab_window_copy_allowed( + state: &ServerState, + q: &crate::server::Xi1QueuedEvent, + owner: ClientId, + grab_window: ResourceId, +) -> bool { + !xi1_gets_no_copy(state, q, owner) + && grab_window_allows_batch(state, owner, grab_window, &xi1_batch(q.evcode)) +} + +/// The XI1 passive grab an XI1 press activates, if any (the replay floor +/// hides the grabs at or above the released one). +pub(super) fn xi1_matching_passive_grab( + state: &ServerState, + q: &crate::server::Xi1QueuedEvent, +) -> Option { + state + .xi1_passive_grabs + .iter() + .find(|g| { + g.deviceid == q.deviceid + && (g.detail == 0 || g.detail == q.detail) + && (g.modifiers == 0x8000 || g.modifiers == q.state_mask & 0x00ff) + && xi1_window_in_chain(state, q.natural_target, g.grab_window) + && !q + .replay_floor + .is_some_and(|floor| xi1_window_in_chain(state, floor, g.grab_window)) + }) + .copied() +} + +/// True when the router queues the device's XI1 events instead of delivering. +pub(super) fn xi1_device_frozen(state: &ServerState, deviceid: u16) -> bool { + state + .xi1_frozen + .get(&deviceid) + .is_some_and(crate::server::Xi1Freeze::frozen) +} + +/// Chooses the protocol of a slave press: at each window from the target up, +/// the slave XI2 selectors whose copy is allowed, else the XI1 +/// `DeviceButtonPress` selectors whose copy is allowed, else the parent. With a +/// memo, an XI2 selection counts only if its copy is allowed (the same result +/// the write reuses); `xi1_checked` says the router writes the XI1 form, so its +/// selectors are asked too. The XI1 recipients returned are decided: the router +/// writes them as they stand and picks the XI1 implicit owner among them. +pub(super) fn resolve_slave_press_delivery( + state: &ServerState, + target: ResourceId, + deviceid: u16, + xi1_evcode: u8, + receive: &mut ReceiveMemo, + xi2_checked: bool, + xi1_checked: bool, +) -> SlavePressDelivery { + let xi1_description = xi1_batch(xi1_evcode); + let xi1_events = EventBatch::new(&xi1_description); + let mut window = target; + for _ in 0..256 { + let xi2_recipients = xi2_form_targets_for_source( + state, + window, + Xi2PointerForm::Slave, + xi2_evtype(PointerEventKind::ButtonPress), + Some(deviceid), + xi2_checked.then_some(&mut *receive), + ); + if !xi2_recipients.is_empty() { + return SlavePressDelivery::Xi2 { + window, + recipients: xi2_recipients, + }; + } + + let mut xi1_recipients = xi1_window_selectors(state, window, xi1_evcode, deviceid); + if xi1_checked { + xi1_recipients.retain(|client| { + receive.allows(state, *client, EventSubject::Window(window), &xi1_events) + }); + } + if !xi1_recipients.is_empty() { + return SlavePressDelivery::Xi1 { + window, + recipients: xi1_recipients, + }; + } + + if window == ROOT_WINDOW { + break; + } + let Some(parent) = state.resources.parent_of(window) else { + break; + }; + window = parent; + } + SlavePressDelivery::None +} + +/// True when `grab_window` is `target` or one of its ancestors. +pub(super) fn xi1_window_in_chain( + state: &ServerState, + target: ResourceId, + grab_window: ResourceId, +) -> bool { + let mut window = target; + loop { + if window == grab_window { + return true; + } + if window == ROOT_WINDOW { + return false; + } + match state.resources.window(window).map(|w| w.parent) { + Some(parent) if parent != window => window = parent, + _ => return false, + } + } +} + +pub(super) fn xi1_fan_device_event( + state: &mut ServerState, + targets: &[ClientId], + event_window: ResourceId, + q: &crate::server::Xi1QueuedEvent, +) -> Vec { + // DeviceMotionNotify MUST be a MORE_EVENTS chain with a trailing + // deviceValuator: libXi's XInputWireToEvent returns DONT_ENQUEUE + // unconditionally for the leading motion event and only enqueues + // when the valuator continuation lands (XExtInt.c) — a bare motion + // event silently vanishes inside every libXi client. Key/button + // events enqueue standalone. The valuator payload mirrors the + // device's X/Y axes (the sprite position), matching Xorg's + // getValuatorEvents for a 2-axis motion. + let is_motion = + q.evcode == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET; + // Xorg FixUpEventFromWindow: coordinates relative to the event + // window's inside origin; child per FindChildForEvent from the + // sprite window (the pointer hit for pointer events, the deepest + // window under the pointer for key events). + let is_key = q.evcode + == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET + || q.evcode == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET; + let targets: Vec = if q.synthetic_repeat + && q.evcode == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET + { + targets + .iter() + .copied() + .filter(|client| !xi1_gets_no_copy(state, q, *client)) + .collect() + } else { + targets.to_vec() + }; + if targets.is_empty() { + return Vec::new(); + } + let sprite = if is_key { + crate::core_loop::key_fanout::deepest_window_at_pointer(state) + } else { + q.natural_target + }; + let child = xi2_child_toward(state, event_window, sprite); + let (ox, oy) = state.resources.window_absolute_position(event_window); + let event_x = clamp_grab_coord(q.root_x, ox); + let event_y = clamp_grab_coord(q.root_y, oy); + let mut dropped = Vec::new(); + // The general fanout deduplicates client IDs. XI1 selection delivery + // instead sends once per InputClients node (../xserver/dix/events.c:2279-2316). + for client in targets { + let failed = fanout_event_to_clients(state, &[client], |buf, seq, order| { + crate::xinput::encode_xi1_device_input_event( + buf, + order, + q.evcode, + q.detail, + seq, + q.time, + ROOT_WINDOW.0, + event_window.0, + child.0, + q.root_x, + q.root_y, + event_x, + event_y, + q.state_mask, + if is_motion { + q.deviceid | u16::from(crate::xinput::XI1_MORE_EVENTS) + } else { + q.deviceid + }, + ); + if is_motion { + // Faked motion carries its explicit axis payload; real + // motion reports the X/Y axes (= sprite position). + let (num, first_v, values) = match q.axes { + Some(a) => (a.count.min(6), a.first, a.values), + None => (2, 0, [i32::from(q.root_x), i32::from(q.root_y), 0, 0, 0, 0]), + }; + #[allow(clippy::cast_possible_truncation)] + crate::xinput::encode_xi1_device_valuator( + buf, + order, + crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_VALUATOR_OFFSET, + q.deviceid as u8, + seq, + q.state_mask, + num, + first_v, + values, + ); + } + }); + merge_dropped(&mut dropped, failed); + } + dropped +} + +/// Resolve the Xorg paired master from the requested device's current +/// attachment. Floating slaves have no paired device. +pub(crate) fn xi1_other_input_device(state: &ServerState, deviceid: u16) -> Option { + state.xi_devices.paired_master(deviceid).or_else(|| { + state + .xi2_detached_masters + .get(&deviceid) + .and_then(|master| state.xi_devices.paired_master(*master)) + }) +} + +/// Force-thaw a device: reset its sync state outright and flush. Used +/// by teardown paths (client disconnect with no grabs left) where no +/// grab semantics apply — NOT by AllowDeviceEvents, which manipulates +/// the sync state per Xorg `AllowSome` and then calls +/// [`xi1_compute_freezes`]. +pub(crate) fn xi1_thaw_device( + state: &mut ServerState, + backend: &mut dyn crate::backend::Backend, + xid_map: &HostXidMap, + deviceid: u16, +) { + if let Some(freeze) = state.xi1_frozen.get_mut(&deviceid) { + freeze.state = crate::server::Xi1SyncState::Thawed; + freeze.other = None; + } + xi1_compute_freezes(state, backend, xid_map); +} + +/// Port of Xorg `ComputeFreezes` (dix/events.c:1320) over the +/// two-device model: re-derive each device's frozen flag from its sync +/// state and flush the queued events of every no-longer-frozen device. +/// Re-freezing mid-flush (a queued press activating a sync passive +/// grab) leaves the remainder queued, exactly like Xorg's restart loop. +pub(crate) fn xi1_compute_freezes( + state: &mut ServerState, + backend: &mut dyn crate::backend::Backend, + xid_map: &HostXidMap, +) { + if state.playing_sync_events { + return; + } + // SAFETY: local guard cannot outlive this mutable ServerState borrow. + let _replay_guard = + unsafe { crate::server::SyncReplayGuard::arm(&mut state.playing_sync_events) }; + // Xorg PlayReleasedEvents: after each delivery restart the search from + // the head, because that delivery can change another device's freeze. + loop { + let index = state.sync_pending.iter().position(|pending| { + !state + .xi1_frozen + .get(&pending.device) + .is_some_and(crate::server::Xi1Freeze::frozen) + }); + let Some(index) = index else { break }; + let pending = state + .sync_pending + .remove(index) + .expect("pending index is valid"); + match pending.event { + crate::server::QueuedInputEvent::HostPointer(event) => { + let _ = pointer_event_fanout_to_state(state, backend, xid_map, event, false, false); + } + crate::server::QueuedInputEvent::HostPointerMaster(event, scroll_motion) => { + let _ = play_queued_master_pointer_event( + state, + backend, + xid_map, + event, + pending.device, + scroll_motion, + ); + } + crate::server::QueuedInputEvent::HostKey(event) => { + let _ = crate::core_loop::key_fanout::deliver_routed_key(state, event); + } + crate::server::QueuedInputEvent::HostKeyTransition( + event, + master_transition_accepted, + synthetic_repeat, + ) => { + let _ = crate::core_loop::key_fanout::deliver_routed_key_after_transition( + state, + event, + master_transition_accepted, + synthetic_repeat, + ); + } + crate::server::QueuedInputEvent::Xi1Routed(event) => { + let _ = xi1_route_device_event(state, event, true, None, &mut ReceiveMemo::new()); + } + crate::server::QueuedInputEvent::RawKey(event) => { + let _ = crate::core_loop::key_fanout::deliver_raw_key_master(state, event); + } + } + } +} + +/// End active grabs on a physical source, restore its saved attachments, +/// and replay input released by a dynamic XI2 grab's paired-device hold. +/// The caller keeps the source registered until held-state releases have +/// passed through the normal fanout path, then disables and unregisters it. +pub fn xi_cleanup_source( + state: &mut ServerState, + backend: &mut dyn crate::backend::Backend, + source: crate::xinput::InputSourceId, +) { + let device_ids: Vec = [ + state + .xi_devices + .facet(source, crate::xinput::XiFacetKind::Keyboard), + state + .xi_devices + .facet(source, crate::xinput::XiFacetKind::PointerTouch), + ] + .into_iter() + .flatten() + .collect(); + + for device_id in device_ids { + xi1_deactivate_device_grab(state, device_id); + + let pointer_grab = state.xi2_pointer_grabs.get(&device_id).copied(); + let pointer_owner = pointer_grab + .filter(|grab| !grab.implicit) + .map(|grab| grab.owner); + if pointer_grab.is_some_and(|grab| grab.implicit) { + state.remove_implicit_xi2_pointer_grab(device_id); + } else if pointer_grab.is_some() { + state.xi2_pointer_grabs.remove(&device_id); + } + let keyboard_owner = state + .xi2_keyboard_grabs + .remove(&device_id) + .map(|grab| grab.owner); + for owner in [pointer_owner, keyboard_owner].into_iter().flatten() { + if let Some(freeze) = state.xi1_frozen.get_mut(&device_id) { + freeze.state = crate::server::Xi1SyncState::Thawed; + freeze.stored = None; + } + xi1_core_grab_bridge_release(state, device_id, owner); + } + if pointer_owner.is_some() + || keyboard_owner.is_some() + || state.xi2_detached_masters.contains_key(&device_id) + { + state.reattach_xi2_slave(device_id); + } + } + + let xid_map = backend.xid_map().clone(); + xi1_compute_freezes(state, backend, &xid_map); +} + +/// Port of Xorg `CheckGrabForSyncs` (dix/events.c:1424-1450): set the +/// sync state at grab activation. A sync `this_mode` freezes the +/// grabbed device ONCE (FrozenNoEvent); a sync `other_mode` holds the +/// paired device on behalf of this grab (`sync.other`). Async modes +/// release the same-client holds. +pub(crate) fn xi1_check_grab_for_syncs( + state: &mut ServerState, + deviceid: u16, + owner: ClientId, + this_sync: bool, + other_sync: bool, +) { + { + let sync = state.xi1_frozen.entry(deviceid).or_default(); + if this_sync { + sync.state = crate::server::Xi1SyncState::FrozenNoEvent; + } else { + sync.state = crate::server::Xi1SyncState::Thawed; + if sync.other == Some(owner) { + sync.other = None; + } + } + } + // Xorg CheckGrabForSyncs only synchronizes the paired device for a + // master grab (dix/events.c:1439). Slave grabs force paired_device_mode + // to Async and never freeze their paired master. + if matches!( + state.xi_devices.role(deviceid), + Some( + crate::xinput::XiDeviceRole::MasterPointer + | crate::xinput::XiDeviceRole::MasterKeyboard + ) + ) && let Some(other_dev) = xi1_other_input_device(state, deviceid) + { + let other = state.xi1_frozen.entry(other_dev).or_default(); + if other_sync { + other.other = Some(owner); + } else if other.other == Some(owner) { + other.other = None; + } + } +} + +/// Port of Xorg `FreezeThisEventIfNeededForSyncGrab` +/// (dix/events.c:4420-4447): after a key/button event is delivered +/// through the active grab, an armed FreezeNextEvent / +/// FreezeBothNextEvent state trips to FrozenWithEvent (storing the +/// event for Replay); FreezeBothNextEvent also re-holds the paired +/// device. +pub(crate) fn xi1_freeze_this_event_if_needed( + state: &mut ServerState, + deviceid: u16, + owner: ClientId, + q: &crate::server::Xi1QueuedEvent, +) { + use crate::server::Xi1SyncState; + let st = state + .xi1_frozen + .get(&deviceid) + .map_or(Xi1SyncState::Thawed, |f| f.state); + match st { + Xi1SyncState::FreezeBothNextEvent => { + let other_dev = xi1_other_input_device(state, deviceid); + let Some(other_dev) = other_dev else { + let sync = state.xi1_frozen.entry(deviceid).or_default(); + sync.state = Xi1SyncState::FrozenWithEvent; + sync.stored = Some(crate::server::QueuedInputEvent::Xi1Routed(*q)); + return; + }; + let other_owner = xi1_device_grab_owner(state, other_dev); + let other = state.xi1_frozen.entry(other_dev).or_default(); + if other.state == Xi1SyncState::FreezeBothNextEvent && other_owner == Some(owner) { + other.state = Xi1SyncState::FrozenNoEvent; + } else { + other.other = Some(owner); + } + let sync = state.xi1_frozen.entry(deviceid).or_default(); + sync.state = Xi1SyncState::FrozenWithEvent; + sync.stored = Some(crate::server::QueuedInputEvent::Xi1Routed(*q)); + } + Xi1SyncState::FreezeNextEvent => { + let sync = state.xi1_frozen.entry(deviceid).or_default(); + sync.state = Xi1SyncState::FrozenWithEvent; + sync.stored = Some(crate::server::QueuedInputEvent::Xi1Routed(*q)); + } + _ => {} + } +} + +/// Deactivate the active XI1 grab on `deviceid` (UngrabDevice, passive +/// release auto-end, disconnect teardown): reset its sync state and +/// release a paired-device hold owned by this grab (Xorg +/// DeactivateKeyboard/PointerGrab clears only `sync.other` references to +/// the departing grab, `../xserver/dix/events.c:1698-1700,1799-1801`). +pub(crate) fn xi1_deactivate_device_grab(state: &mut ServerState, deviceid: u16) { + let Some(grab) = state.xi1_active_grabs.remove(&deviceid) else { + return; + }; + if let Some(sync) = state.xi1_frozen.get_mut(&deviceid) { + sync.state = crate::server::Xi1SyncState::Thawed; + sync.stored = None; + } + // DeviceButtonPress implicit grabs are created on slave devices with + // asynchronous paired-device mode. They never own a paired hold, so + // an `other` hold from another same-client master grab must survive. + let other_dev = (!grab.implicit) + .then(|| xi1_other_input_device(state, deviceid)) + .flatten(); + if let Some(other) = other_dev.and_then(|id| state.xi1_frozen.get_mut(&id)) + && other.other == Some(grab.owner) + { + other.other = None; + } +} + +/// Release the core-grab bridge hold on `deviceid` at GRAB +/// DEACTIVATION (core UngrabPointer / UngrabKeyboard, passive key-grab +/// auto-release): thaw the device's sync state when no XI1 grab +/// controls it and release the paired device if held on `owner`'s +/// behalf — Xorg DeactivateKeyboard/PointerGrab clears every +/// `sync.other` pointing at the dying grab. +pub(crate) fn xi1_core_grab_bridge_release( + state: &mut ServerState, + deviceid: u16, + owner: ClientId, +) { + if !state.xi1_active_grabs.contains_key(&deviceid) + && let Some(sync) = state.xi1_frozen.get_mut(&deviceid) + { + sync.state = crate::server::Xi1SyncState::Thawed; + sync.stored = None; + } + let other_dev = xi1_other_input_device(state, deviceid); + if let Some(other) = other_dev.and_then(|id| state.xi1_frozen.get_mut(&id)) + && other.other == Some(owner) + { + other.other = None; + } +} + +/// The client owning the grab that controls `deviceid`'s sync state: +/// the XI1 device grab, or the bridged core grab (core pointer grab ↔ +/// slave pointer, core keyboard grab ↔ slave keyboard) — in Xorg these +/// are one `deviceGrab.grab` slot. +pub(crate) fn xi1_device_grab_owner(state: &ServerState, deviceid: u16) -> Option { + if let Some(g) = state.xi1_active_grabs.get(&deviceid) { + return Some(g.owner); + } + if let Some(g) = state.xi2_pointer_grabs.get(&deviceid) { + return Some(g.owner); + } + if let Some(g) = state.xi2_keyboard_grabs.get(&deviceid) { + return Some(g.owner); + } + match state.xi_devices.role(deviceid)? { + crate::xinput::XiDeviceRole::MasterPointer => { + state.active_pointer_grab.as_ref().map(|grab| grab.owner) + } + crate::xinput::XiDeviceRole::SlavePointer => { + let master = state.xi_devices.attachment(deviceid)?; + (master == crate::xinput::DEVICEID_MASTER_POINTER) + .then(|| state.active_pointer_grab.as_ref().map(|grab| grab.owner)) + .flatten() + } + crate::xinput::XiDeviceRole::MasterKeyboard => { + state.active_keyboard_grab.as_ref().map(|grab| grab.owner) + } + crate::xinput::XiDeviceRole::SlaveKeyboard => { + let master = state.xi_devices.attachment(deviceid)?; + (master == crate::xinput::DEVICEID_MASTER_KEYBOARD) + .then(|| state.active_keyboard_grab.as_ref().map(|grab| grab.owner)) + .flatten() + } + } +} From 3ed4f9a67f7f1913d06b4f63afff4bfffa47c508 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Thu, 3 Dec 2026 08:38:43 -0300 Subject: [PATCH 62/72] docs(plan): access control PR 4c part 2, plan 4 (#396 review) Co-Authored-By: Claude Opus 5.5 --- .../2026-12-03-access-control-pr4c-review.md | 141 ++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 docs/superpowers/plans/2026-12-03-access-control-pr4c-review.md diff --git a/docs/superpowers/plans/2026-12-03-access-control-pr4c-review.md b/docs/superpowers/plans/2026-12-03-access-control-pr4c-review.md new file mode 100644 index 000000000..9cd55cb1c --- /dev/null +++ b/docs/superpowers/plans/2026-12-03-access-control-pr4c-review.md @@ -0,0 +1,141 @@ +# Access control PR 4c part 2, plan 4: #396 review (no-policy cost, test size) + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Answer the maintainer's review of #396. +- With no policy installed, the input path allocates no more than it did at the base. +- The four input test files shrink to about half, keeping every distinct case. + +**Architecture:** Two independent tasks. + +Task 1 changes production at three sites, without changing any decision: +- the keyboard focus walk; +- the XI1 selection walk; +- the owner-events walk. + +At each site, the no-policy path does only the work the base did, and policy-only work (event batches, descriptions, per-window copies) happens only when a memo exists. + +Task 2 is test-only. It compacts `access_input_support.rs`, `access_key_input.rs`, `access_pointer_input.rs` and `access_replay_input.rs`. + +**Tech Stack:** Rust, yserver-core (`crates/yserver-core/src/core_loop/`). + +**Spec:** `docs/superpowers/specs/2026-10-30-access-control-layer-design.md` §"Input delivery under denial" (l.353–527). With no policy, bytes and state must equal today's (l.357–359). + +**Review being answered:** joske on #396, 2026-12-03, items 1 and 2. Items 3 (PR description) and 4 (spec l.481–483 already states the crossing shadow) need no code. + +## Global Constraints + +**Behaviour must not change:** +- With no policy, and with allow-all, every row's bytes, order, grab, freeze and queue state stay as they are. +- The existing row tables are the oracle for Task 1. They must pass unchanged in Task 1, and Task 1 may not edit a test. +- Receive is asked for the same copies, in the same order, with the same subject and batch as before. Task 1 changes when work happens, never what is decided. + +**Allocations:** +- "No policy" means `state` has no access policy installed: the memo is `None`, or the policy list is empty. +- On that path, a site may not allocate per window or per client where the base did not. + - The base is `ef3bc7ac` (`git show ef3bc7ac:`). + - Per-event work that the base also did may stay. + +**Reuse first:** +- Use existing types and helpers. No new crate dependency (no `smallvec`/`arrayvec`); stack arrays or iterators are enough. +- No new `YSERVER_*` env vars. + +**Tests (Task 2):** +- Every distinct routing, grab and replay case keeps a row or a checkpoint. +- Every existing probe still compiles and is caught. Probes are in `/data/Projects/claude-scratch/access-control/pr4c-input/sdd-p3/probes.py`, replayed by `sdd-p3/replay.py`. + - A probe whose catcher row was merged is re-pointed to the surviving row. + - No probe is dropped. +- Shared outcome fragments are allowed: named consts, or a helper that builds a denied outcome from an allowed one. + - Each row must still state, or visibly derive, its frames, calls and grab facts. + - A derived denied outcome must name which copy the denial drops. +- No macro DSL, no `rustfmt::skip`, no literal frame encoders. + +**Commits:** +- signed (`-S`), with a blank line before the trailers; +- trailers `Co-Authored-By: Claude Opus 5.5 ` and `Implemented-By: codex (gpt-6-luna xhigh)`; +- no URLs. + +**Gate per task:** +- `cargo +nightly fmt --all`, then `--check`; +- `cargo clippy --workspace --all-targets -- -D warnings`; +- `cargo build --bin yserver` on its own; +- `cargo test -p yserver-core --lib`; +- `sh tools/check-layout.sh`; +- `cargo test --workspace --features xdmcp`; +- every probe replayed. + +## Review Focus + +1. A lazy path that changes Receive order: for example, the keyboard forms computed once but read in a different order, or XI1 selectors filtered before the no-copy rule. +2. An early return in the XI1 walk that skips a window whose selectors stop the walk without a copy (`xi1_gets_no_copy`). +3. The owner-events walk's known-only XI2 leg (`xi2_known_only`), and the core leg's `core_checked` rule, still behaving the same when descriptions are built lazily. +4. A compacted row that lost the frame or grab fact its mutation changes. The probe replay must still show every probe caught by a named row. +5. A runner shortcut that compares less than before: bytes per client, per-step replies, hooks, grab, freeze and queue facts. + +--- + +### Task 1: no-policy input path does the base's work only + +**Files:** +- `crates/yserver-core/src/core_loop/key_fanout.rs`: `client_key_plan` (~744), `key_xi2_forms` (~1124), and its callers (~769, ~861, ~1831). +- `crates/yserver-core/src/core_loop/pointer_fanout/xi1.rs`: + - `xi1_route_windows` (~309); + - `xi1_allowed_selectors` (~352); + - their callers in the XI1 route and the bounded fan. +- `crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs`: `owner_events_route` (~448–540). + +**Interfaces:** none change outside these modules. Signatures of private helpers may change. For example, `client_key_plan` takes the forms as `&[(u16, u16)]`, and `xi1_route_windows` may become an iterator or a walk with a visitor. + +- [ ] **Step 1: Measure the base.** The controller measures this before dispatch, in a scratch copy that is never committed. + - Use a counting `#[global_allocator]`, thread-local counters, and a single test thread. + - Count allocations per event, with no policy, for three scenarios run through the row fixtures, at the base and at the branch head: + - a focused key press over a 5-deep window chain with 3 connected clients; + - an XI1 device press over the same chain with selectors only at the root; + - a grabbed owner-events motion over the chain. + - Record the numbers in the brief. + - Step 4's pass criterion: branch ≤ base, for each scenario. +- [ ] **Step 2: Keyboard.** + - Compute `key_xi2_forms` once per event, in the function that runs the focus walk. + - Pass the slice to `client_key_plan` and to the grabbed-walk call that uses it. + - The forms' order and content must be unchanged. +- [ ] **Step 3: XI1.** + - `xi1_route_windows` no longer builds a `Vec` for the walk. The walk visits windows in the same order with the same stop rules (`Walk`, `WalkUpTo`, `WindowOnly`, `Drop`). + - `xi1_allowed_selectors`: + - with no memo, returns before building the batch; + - at a window with no selectors, returns before building anything; + - otherwise keeps the no-copy rule ahead of the Receive call. +- [ ] **Step 4: Owner-events.** + - The per-ancestor legs live on the stack. + - A leg's description batch is built only when `receive` is `Some`. + - The order (XI2, XI1, core), `known_only` and `core_checked` stay as they are. +- [ ] **Step 5: Verify.** + - The row tables pass unchanged: `cargo test -p yserver-core --lib -- access_key_input access_pointer_input access_replay_input`. + - Every probe is replayed. A probe whose anchor text moved is updated to the same mutation at its new place, and stays caught. + - The controller reruns Step 1's measurement, and the numbers go in the commit body. + - Commit `perf(access): no-policy input walks allocate as before`. + +### Task 2: compact the input tests + +**Files:** +- `crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs` (1871 lines); +- `access_key_input.rs` (931); +- `access_pointer_input.rs` (2569); +- `access_replay_input.rs` (1079); +- `sdd-p3/probes.py`, only to re-point catchers. + +Target: at most ~3200 lines in total across the four files, down from 6450. Aim for the runner well under 1000. + +- [ ] **Step 1: Inventory.** In the report, list every row and checkpoint with its case (what routing, grab or replay decision it pins) and its probes. Rows that pin the same decision with different setups are merge candidates. +- [ ] **Step 2: Runner.** + - Remove machinery no row needs. + - Fold duplicate comparison paths into one. + - Keep every check named in the Global Constraints. +- [ ] **Step 3: Tables.** + - Share repeated setups and outcome fragments. + - Merge duplicate cases, keeping each case's strongest row. + - Denied outcomes may be derived from the allowed one by naming the dropped copies. +- [ ] **Step 4: Verify.** + - Every probe is replayed; all compile, all are caught, and catchers are re-pointed where rows merged. + - Then run the gate. + - Report the line counts per file. + - Commit `test(access): compact the input row tables`. From fdf53f51025598c9785167dc60c82ce92778686e Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Thu, 3 Dec 2026 08:45:37 -0300 Subject: [PATCH 63/72] docs(plan): plan 4 review round 1 Co-Authored-By: Claude Opus 5.5 --- .../2026-12-03-access-control-pr4c-review.md | 233 +++++++++++------- 1 file changed, 150 insertions(+), 83 deletions(-) diff --git a/docs/superpowers/plans/2026-12-03-access-control-pr4c-review.md b/docs/superpowers/plans/2026-12-03-access-control-pr4c-review.md index 9cd55cb1c..447cdf815 100644 --- a/docs/superpowers/plans/2026-12-03-access-control-pr4c-review.md +++ b/docs/superpowers/plans/2026-12-03-access-control-pr4c-review.md @@ -3,52 +3,74 @@ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. **Goal:** Answer the maintainer's review of #396. -- With no policy installed, the input path allocates no more than it did at the base. -- The four input test files shrink to about half, keeping every distinct case. +- When no policy is installed, the input path allocates no more than it did at the base. +- The four input test files shrink substantially, keeping every distinct case. -**Architecture:** Two independent tasks. - -Task 1 changes production at three sites, without changing any decision: -- the keyboard focus walk; -- the XI1 selection walk; -- the owner-events walk. - -At each site, the no-policy path does only the work the base did, and policy-only work (event batches, descriptions, per-window copies) happens only when a memo exists. - -Task 2 is test-only. It compacts `access_input_support.rs`, `access_key_input.rs`, `access_pointer_input.rs` and `access_replay_input.rs`. +**Architecture:** Four tasks. +- Task 0 builds the evidence tools. It produces no commit. +- Tasks 1 and 2 change production without changing any decision: + - Task 1 covers the pointer walks. + - Task 2 covers the keyboard walk and the XI1 router. +- Task 3 is test-only. It compacts `access_input_support.rs`, `access_key_input.rs`, `access_pointer_input.rs` and `access_replay_input.rs`. **Tech Stack:** Rust, yserver-core (`crates/yserver-core/src/core_loop/`). **Spec:** `docs/superpowers/specs/2026-10-30-access-control-layer-design.md` §"Input delivery under denial" (l.353–527). With no policy, bytes and state must equal today's (l.357–359). -**Review being answered:** joske on #396, 2026-12-03, items 1 and 2. Items 3 (PR description) and 4 (spec l.481–483 already states the crossing shadow) need no code. +**Review being answered:** joske on #396, 2026-12-03, items 1 and 2. +- Item 3 (PR description) is already fixed. +- Item 4 is answered by spec l.481–483. + +**Plan review r1** (sol, `sdd-p4/plan-review-r1.md`) found: +- missing pointer sites; +- allocations left in the three named sites; +- a weak measurement; +- stale probe anchors; +- an imprecise derivation rule. + +This revision folds all of them in. ## Global Constraints -**Behaviour must not change:** -- With no policy, and with allow-all, every row's bytes, order, grab, freeze and queue state stay as they are. -- The existing row tables are the oracle for Task 1. They must pass unchanged in Task 1, and Task 1 may not edit a test. -- Receive is asked for the same copies, in the same order, with the same subject and batch as before. Task 1 changes when work happens, never what is decided. +**"No policy"** means the installed policy list is empty, which is the predicate `ReceiveMemo::allows` already tests. A memo may exist in that mode. An absent memo with an installed policy is a deliberate "this form is not checked" and keeps today's meaning. -**Allocations:** -- "No policy" means `state` has no access policy installed: the memo is `None`, or the policy list is empty. -- On that path, a site may not allocate per window or per client where the base did not. - - The base is `ef3bc7ac` (`git show ef3bc7ac:`). - - Per-event work that the base also did may stay. +**No-policy invariant.** On the no-policy path, no input-delivery site may allocate per window, per client or per form where the base `ef3bc7ac` did not. Per-event work the base also did may stay. The acceptance evidence is a per-site account (each site the series touched: base allocations, branch allocations, reason) plus Task 0's measured totals. A lower total does not excuse a new per-window allocation at another site. + +**With a policy installed, nothing changes:** +- the same Receive calls, in the same order, with the same subject and batch; +- the same recipients; +- the same frames and order; +- the same grab, freeze and queue state. + +The existing row tables are the oracle for Tasks 1–2. They pass unchanged, and Tasks 1–2 edit no test. + +**Decision rules that must survive:** +- the shadowed core subscriber stops the walk with no frame and no check; +- the no-copy XI1 selector stops the walk without a copy; +- the owner is tried in XI2, XI1, core order before any foreign selector; +- `known_only` looks up the memo and treats a missing entry as allowed; +- an unchecked core leg still takes part in selection; +- XI1 node order and multiplicity are kept; +- the focus endpoint is inclusive; +- the fresh grab-window check stays where it is, relative to the implicit device mask and the freeze transition; +- keyboard check order is client-major (one XI2 check per client's forms, then any unshadowed core check), with the grab owner before foreign clients, and the write order is core, slave XI2, master XI2. **Reuse first:** -- Use existing types and helpers. No new crate dependency (no `smallvec`/`arrayvec`); stack arrays or iterators are enough. +- Use existing types and predicates: the base's selection-only `.any()` paths still exist. +- No new crate dependency. Stack arrays, `Option` slots and iterators are enough. - No new `YSERVER_*` env vars. -**Tests (Task 2):** -- Every distinct routing, grab and replay case keeps a row or a checkpoint. -- Every existing probe still compiles and is caught. Probes are in `/data/Projects/claude-scratch/access-control/pr4c-input/sdd-p3/probes.py`, replayed by `sdd-p3/replay.py`. - - A probe whose catcher row was merged is re-pointed to the surviving row. - - No probe is dropped. -- Shared outcome fragments are allowed: named consts, or a helper that builds a denied outcome from an allowed one. - - Each row must still state, or visibly derive, its frames, calls and grab facts. - - A derived denied outcome must name which copy the denial drops. +**Probes.** Source: `/data/Projects/claude-scratch/access-control/pr4c-input/sdd-p3/probes.py` (it imports the 2b list); runner: `sdd-p3/replay.py`. +- Each task replays every probe with a fresh tag. A reused tag can load old results. +- A probe counts as caught only if the row, checkpoint or runner self-test it names fails, at the assertion its comment describes. +- A probe whose anchor moved is updated to the same mutation at its new place. +- Task 3 may update anchors inside the runner the same way. No probe is dropped. + +**Tests (Task 3):** - No macro DSL, no `rustfmt::skip`, no literal frame encoders. +- A denied outcome may be derived from the row's allowed outcome only by naming each dropped copy uniquely: client, protocol and device, window, and step or event occurrence wherever fewer fields would match more than one copy. The derivation must resolve to exactly the stated number of copies, the XI1 motion and valuator pair counting as one. Every other delta must be stated explicitly: new deliveries, a new Receive call, a different grab or freeze owner. +- Rows whose denial changes protocol, recipient, trace and grab together keep a full outcome. Examples: p14's replay, with two equal tuples, and p18's fallback. +- The runner keeps every comparison it makes today: per-client bytes and order, moved-frame placement, call order, per-step replies and errors, hooks, and grab, freeze and queue facts. **Commits:** - signed (`-S`), with a blank line before the trailers; @@ -66,76 +88,121 @@ Task 2 is test-only. It compacts `access_input_support.rs`, `access_key_input.rs ## Review Focus -1. A lazy path that changes Receive order: for example, the keyboard forms computed once but read in a different order, or XI1 selectors filtered before the no-copy rule. -2. An early return in the XI1 walk that skips a window whose selectors stop the walk without a copy (`xi1_gets_no_copy`). -3. The owner-events walk's known-only XI2 leg (`xi2_known_only`), and the core leg's `core_checked` rule, still behaving the same when descriptions are built lazily. -4. A compacted row that lost the frame or grab fact its mutation changes. The probe replay must still show every probe caught by a named row. -5. A runner shortcut that compares less than before: bytes per client, per-step replies, hooks, grab, freeze and queue facts. +1. A lazy path that changes Receive order or recipients. Examples: a lower leg's selectors skipped when an owner later fails; a no-copy XI1 selector filtered before it stops the walk; the keyboard forms read in another order. +2. A no-policy shortcut taken while a policy is installed. The shortcut must test the policy list, not the memo's presence. +3. The shadowed-subscriber rule in the core walk, once the second vector is removed. +4. A compacted row that lost the frame, call or grab fact its mutation changes. +5. A measurement that counts setup or draining, or that measures a path other than the intended one. --- -### Task 1: no-policy input path does the base's work only +### Task 0: evidence tools (no commit) + +**Files:** scratch only, under `/data/Projects/claude-scratch/access-control/pr4c-input/sdd-p4/`. `sdd-p3/probes.py` is edited in place. + +- [ ] **Step 1: Probe anchors.** + - Relocate the probe anchors that still name `pointer_fanout.rs` but now match in `pointer_fanout/xi1.rs`. The plan review counted 19 probes and 21 anchors. + - Check that every anchor matches exactly once at HEAD. + - Replay every probe with a fresh tag (`t0`). Each must be caught by the row its comment names. A probe caught by some other row is a finding to report, not a pass. +- [ ] **Step 2: Allocation harness.** One scratch test module, added to both a base tree (`ef3bc7ac`) and a HEAD tree in throwaway worktrees, using only entry points that exist in both. + - **Allocator:** a counting `#[global_allocator]` with thread-local counters. It counts allocations, zeroed allocations and reallocations, and the bytes of each; the counter and its guard allocate nothing. + - **What is counted:** only the dispatch of one event, with an empty policy list. Setup, draining and assertions stay outside the count. State is reset between samples. Outside the count, assert that the intended path ran (the frame was delivered, or the grab exists). + - **Fixture:** identical on both revisions. A 5-deep window chain under root, and 3 clients, built through requests. + - **Scenarios:** + - an ungrabbed press with two XI2 master selectors and one core subscriber at different depths; + - a press reaching a core subscriber only; + - a focused key press with an empty-selection walk; + - a focused key press with XI2 and core selectors; + - an XI1 device press with selectors only at the root; + - an XI1 press under an XI1 device grab with owner-events; + - a grabbed owner-events motion where the owner hits in XI2 at the first window while XI1 and core selectors sit lower; + - a smooth-scroll event. + - **Output:** a per-scenario table of calls and bytes for base and HEAD, in `sdd-p4/alloc-baseline.md`. + +### Task 1: pointer walks allocate as the base does with no policy **Files:** -- `crates/yserver-core/src/core_loop/key_fanout.rs`: `client_key_plan` (~744), `key_xi2_forms` (~1124), and its callers (~769, ~861, ~1831). +- `crates/yserver-core/src/core_loop/pointer_fanout.rs`: + - `xi2_route_window_for_source` (~3984) and its callers, including the per-recipient re-resolution (~2629); + - the core-walk caller (~1904); + - `xi2_form_targets_for_source`. +- `crates/yserver-core/src/core_loop/fanout.rs`: the `CoreWalk` branch of the propagation walk (~225–260). +- `crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs`: `owner_events_route` (~448–560), and its scroll caller (~202). + +Sites known so far: the plan review names these. The implementer also compares every pointer-path function the series changed against `ef3bc7ac` and lists any other per-window, per-client or per-form allocation in the report. + +- [ ] **Step 1:** Run Task 0's harness at HEAD on the pointer scenarios and record the per-site account (base, HEAD, reason) in the report. +- [ ] **Step 2: Route window.** With an empty policy list, the route-window lookup uses the selection-only predicate. With a policy, the all-selectors scan stays. +- [ ] **Step 3: Core walk.** The core walk no longer builds a second subscriber vector; the subscribers are filtered in place. The shadowed-subscriber rule and the order of the remaining checks are kept. +- [ ] **Step 4: Owner-events.** + - Owner-events no longer collects a leg's selectors, or builds its descriptions, before they are needed. + - With no policy, an owner hit in a higher leg returns before lower legs are built, as at the base. + - With a policy, the two phases (owner in XI2, XI1, core order; then every foreign selector in protocol order) are kept. +- [ ] **Step 5: Verify.** + - Run the harness: branch ≤ base for each pointer scenario, and the per-site account shows no new per-window, per-client or per-form allocation. + - The row tables pass unchanged. Replay every probe (`t1`); add one probe per changed site (for example, the shortcut taken while a policy is installed), each caught. + - Run the gate. + - Commit `perf(access): no-policy pointer walks allocate as before`, with the harness table in the body. + +### Task 2: keyboard walk and XI1 router allocate as the base does with no policy + +**Files:** +- `crates/yserver-core/src/core_loop/key_fanout.rs`: + - `client_key_plan` (~744); + - `key_xi2_forms` (~1124); + - the per-window `KeyCopies` collection (~829); + - the grabbed foreign-client checks (~1081); + - the focus-replay call (~698). - `crates/yserver-core/src/core_loop/pointer_fanout/xi1.rs`: - - `xi1_route_windows` (~309); - - `xi1_allowed_selectors` (~352); - - their callers in the XI1 route and the bounded fan. -- `crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs`: `owner_events_route` (~448–540). - -**Interfaces:** none change outside these modules. Signatures of private helpers may change. For example, `client_key_plan` takes the forms as `&[(u16, u16)]`, and `xi1_route_windows` may become an iterator or a walk with a visitor. - -- [ ] **Step 1: Measure the base.** The controller measures this before dispatch, in a scratch copy that is never committed. - - Use a counting `#[global_allocator]`, thread-local counters, and a single test thread. - - Count allocations per event, with no policy, for three scenarios run through the row fixtures, at the base and at the branch head: - - a focused key press over a 5-deep window chain with 3 connected clients; - - an XI1 device press over the same chain with selectors only at the root; - - a grabbed owner-events motion over the chain. - - Record the numbers in the brief. - - Step 4's pass criterion: branch ≤ base, for each scenario. + - `xi1_route_windows` (~309) and `xi1_allowed_selectors` (~352); + - the selection caller (~239), including the unrestricted router that always passes a memo; + - the XI1 owner-events walk (~389); + - the fresh grab-window check (~422); + - the slave-press prepass (~468). +- `owner_events.rs`: `xi1_batch` (~415), which all of the XI1 callers above use. + +- [ ] **Step 1:** Run the harness at HEAD on the keyboard and XI1 scenarios, and record the per-site account in the report. - [ ] **Step 2: Keyboard.** - - Compute `key_xi2_forms` once per event, in the function that runs the focus walk. - - Pass the slice to `client_key_plan` and to the grabbed-walk call that uses it. - - The forms' order and content must be unchanged. + - The keyboard forms (at most two) and their plan slots live on the stack. They are computed once per event and threaded through both walks and the focus-replay call. + - Intermediate ancestors use selection-only lookups; per-form recipients are materialized only at delivery, as at the base. - [ ] **Step 3: XI1.** - - `xi1_route_windows` no longer builds a `Vec` for the walk. The walk visits windows in the same order with the same stop rules (`Walk`, `WalkUpTo`, `WindowOnly`, `Drop`). - - `xi1_allowed_selectors`: - - with no memo, returns before building the batch; - - at a window with no selectors, returns before building anything; - - otherwise keeps the no-copy rule ahead of the Receive call. -- [ ] **Step 4: Owner-events.** - - The per-ancestor legs live on the stack. - - A leg's description batch is built only when `receive` is `Some`. - - The order (XI2, XI1, core), `known_only` and `core_checked` stay as they are. -- [ ] **Step 5: Verify.** - - The row tables pass unchanged: `cargo test -p yserver-core --lib -- access_key_input access_pointer_input access_replay_input`. - - Every probe is replayed. A probe whose anchor text moved is updated to the same mutation at its new place, and stays caught. - - The controller reruns Step 1's measurement, and the numbers go in the commit body. - - Commit `perf(access): no-policy input walks allocate as before`. + - `xi1_batch` returns stack storage: one description, or the ordered motion-and-valuator pair. + - The XI1 window walk is lazy, with the same stop rules (`Walk`, `WalkUpTo` inclusive, `WindowOnly`, `Drop`). + - With an empty policy list, or at a window with no selectors, no batch or selector copy is built. + - The no-copy and owner-first rules are kept. +- [ ] **Step 4: Verify.** + - Run the harness, as in Task 1. + - The row tables pass unchanged. Replay every probe (`t2`), and add one probe per changed site, each caught. + - Run the gate. + - Commit `perf(access): no-policy keyboard and XI1 walks allocate as before`. -### Task 2: compact the input tests +### Task 3: compact the input tests **Files:** - `crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs` (1871 lines); - `access_key_input.rs` (931); - `access_pointer_input.rs` (2569); - `access_replay_input.rs` (1079); -- `sdd-p3/probes.py`, only to re-point catchers. +- `sdd-p3/probes.py`, for catchers and anchors only. + +Target: a stretch goal of about half (~3200 lines across the four files, down from 6450). The mapped cases and the probe gate decide what is safe; the target does not. The report states the final counts and what blocked further cuts. -Target: at most ~3200 lines in total across the four files, down from 6450. Aim for the runner well under 1000. +- [ ] **Step 1: Inventory.** + - In the report, list every row and checkpoint (113 named entries, 14 of them checkpoints) with the decision it pins and its probes. + - Merge candidates: rows pinning the same decision with different setups. + - Checkpoints merge only where the fixture and event prefix match and the same facts are asserted at the same boundary. For example, p14's press checkpoint stays separate from its replay row, which also drives the runner's swapped-call self-test. +- [ ] **Step 2: Runner.** Reuse the runner's existing records: + - one per-step byte capture feeds the frame splitter, byte parity and step-aware checks, instead of concatenated plus per-step copies; + - one hook representation, instead of two. -- [ ] **Step 1: Inventory.** In the report, list every row and checkpoint with its case (what routing, grab or replay decision it pins) and its probes. Rows that pin the same decision with different setups are merge candidates. -- [ ] **Step 2: Runner.** - - Remove machinery no row needs. - - Fold duplicate comparison paths into one. - - Keep every check named in the Global Constraints. + Keep every comparison listed in the Global Constraints. - [ ] **Step 3: Tables.** - - Share repeated setups and outcome fragments. - - Merge duplicate cases, keeping each case's strongest row. - - Denied outcomes may be derived from the allowed one by naming the dropped copies. + - Share repeated setups. For example, the pointer and replay files share the physical-pointer fixture, keeping the replay fixture's device-ID assertion. + - Share repeated outcome fragments. + - Derive denied outcomes only under the Global Constraints' derivation rule. + - Merge duplicate cases. - [ ] **Step 4: Verify.** - - Every probe is replayed; all compile, all are caught, and catchers are re-pointed where rows merged. - - Then run the gate. + - Replay every probe (`t3`): all compile, and each is caught by its named catcher; catchers are re-pointed where rows merged. + - Run the gate. - Report the line counts per file. - Commit `test(access): compact the input row tables`. From b06dbf86f1e4a133e3a4532ac59f4e35d1d8b3b0 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Thu, 3 Dec 2026 08:52:01 -0300 Subject: [PATCH 64/72] docs(plan): plan 4 review round 2 Co-Authored-By: Claude Opus 5.5 --- .../2026-12-03-access-control-pr4c-review.md | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/docs/superpowers/plans/2026-12-03-access-control-pr4c-review.md b/docs/superpowers/plans/2026-12-03-access-control-pr4c-review.md index 447cdf815..b66173480 100644 --- a/docs/superpowers/plans/2026-12-03-access-control-pr4c-review.md +++ b/docs/superpowers/plans/2026-12-03-access-control-pr4c-review.md @@ -103,20 +103,24 @@ The existing row tables are the oracle for Tasks 1–2. They pass unchanged, and - [ ] **Step 1: Probe anchors.** - Relocate the probe anchors that still name `pointer_fanout.rs` but now match in `pointer_fanout/xi1.rs`. The plan review counted 19 probes and 21 anchors. - Check that every anchor matches exactly once at HEAD. - - Replay every probe with a fresh tag (`t0`). Each must be caught by the row its comment names. A probe caught by some other row is a finding to report, not a pass. + - Build a catcher map in `sdd-p4/catchers.md`: for each probe, the row, checkpoint or runner self-test that must fail, and the assertion (frames, trace, reply or grab fact). Take it from the probe comments and the plan 2b/3 reports and logs. A probe with two catchers (for example R2-I1: the p14 replay trace check and the repeated-press shorthand self-test) lists both, and both must stay. + - Replay every probe with a fresh tag (`t0`). Each must fail at its mapped catcher and assertion. A probe caught only elsewhere is a finding to report, not a pass. Every later replay (`t1`–`t3`) is checked against the same map. - [ ] **Step 2: Allocation harness.** One scratch test module, added to both a base tree (`ef3bc7ac`) and a HEAD tree in throwaway worktrees, using only entry points that exist in both. - **Allocator:** a counting `#[global_allocator]` with thread-local counters. It counts allocations, zeroed allocations and reallocations, and the bytes of each; the counter and its guard allocate nothing. - **What is counted:** only the dispatch of one event, with an empty policy list. Setup, draining and assertions stay outside the count. State is reset between samples. Outside the count, assert that the intended path ran (the frame was delivered, or the grab exists). - **Fixture:** identical on both revisions. A 5-deep window chain under root, and 3 clients, built through requests. - **Scenarios:** - - an ungrabbed press with two XI2 master selectors and one core subscriber at different depths; + - an ungrabbed press with two XI2 master selectors on the same window (both receive it, so each recipient's re-resolution runs) and one core subscriber on an ancestor; - a press reaching a core subscriber only; - a focused key press with an empty-selection walk; - a focused key press with XI2 and core selectors; - - an XI1 device press with selectors only at the root; + - an ungrabbed slave button press with an XI1 selection only at the root (the slave-press prepass); + - slave motion with an XI1 selection only at the root (the unrestricted XI1 walk); - an XI1 press under an XI1 device grab with owner-events; - - a grabbed owner-events motion where the owner hits in XI2 at the first window while XI1 and core selectors sit lower; - - a smooth-scroll event. + - a grabbed master owner-events motion where the owner hits in XI2 at the first window and a core selector sits on that same window; + - the same as a slave grab, with an XI1 selector on that same window; + - a smooth-scroll update from a physical slave with no grab (the p22 shape). + - Each scenario asserts, outside the count, the recipient, protocol and device, and window that show the intended route ran. - **Output:** a per-scenario table of calls and bytes for base and HEAD, in `sdd-p4/alloc-baseline.md`. ### Task 1: pointer walks allocate as the base does with no policy @@ -132,6 +136,7 @@ The existing row tables are the oracle for Tasks 1–2. They pass unchanged, and Sites known so far: the plan review names these. The implementer also compares every pointer-path function the series changed against `ef3bc7ac` and lists any other per-window, per-client or per-form allocation in the report. - [ ] **Step 1:** Run Task 0's harness at HEAD on the pointer scenarios and record the per-site account (base, HEAD, reason) in the report. +- [ ] **Step 1b: XI1 batch.** `xi1_batch` returns stack storage: one description, or the ordered motion-and-valuator pair. The slave-press prepass builds no batch before it knows a selector exists. This is in Task 1 because the pointer scenarios (wheel, press) run the prepass; Task 2 only uses it. - [ ] **Step 2: Route window.** With an empty policy list, the route-window lookup uses the selection-only predicate. With a policy, the all-selectors scan stays. - [ ] **Step 3: Core walk.** The core walk no longer builds a second subscriber vector; the subscribers are filtered in place. The shadowed-subscriber rule and the order of the remaining checks are kept. - [ ] **Step 4: Owner-events.** @@ -159,14 +164,14 @@ Sites known so far: the plan review names these. The implementer also compares e - the XI1 owner-events walk (~389); - the fresh grab-window check (~422); - the slave-press prepass (~468). -- `owner_events.rs`: `xi1_batch` (~415), which all of the XI1 callers above use. +- `xi1_batch` (`owner_events.rs` ~415) is already stack-backed by Task 1; Task 2 uses it. - [ ] **Step 1:** Run the harness at HEAD on the keyboard and XI1 scenarios, and record the per-site account in the report. - [ ] **Step 2: Keyboard.** - The keyboard forms (at most two) and their plan slots live on the stack. They are computed once per event and threaded through both walks and the focus-replay call. - - Intermediate ancestors use selection-only lookups; per-form recipients are materialized only at delivery, as at the base. + - With an empty policy list, the walk's stop test at each window uses the existing per-client selection predicate, with no per-window collection; per-form recipients are materialized only at delivery, as at the base. + - With a policy installed, the walk keeps its single client-major pass at every visited window, including a window passed over after a denial (k1: A denied on CHILD, B delivered on FOCUS). - [ ] **Step 3: XI1.** - - `xi1_batch` returns stack storage: one description, or the ordered motion-and-valuator pair. - The XI1 window walk is lazy, with the same stop rules (`Walk`, `WalkUpTo` inclusive, `WindowOnly`, `Drop`). - With an empty policy list, or at a window with no selectors, no batch or selector copy is built. - The no-copy and owner-first rules are kept. From 4a64ddd6702cb53a80e108c0f2dfbc8ba926fbd4 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Thu, 3 Dec 2026 11:52:55 -0300 Subject: [PATCH 65/72] perf(access): no-policy pointer walks allocate as before With no access policy installed, the pointer walks no longer build the recipient lists, route legs and event descriptions that only a policy check needs. Decisions and Receive order with a policy are unchanged. Allocations per event, no policy (base ef3bc7ac -> before -> after): two XI2 + core press 23 -> 29 -> 22 core only press 9 -> 10 -> 9 slave press, XI1 at root 41 -> 42 -> 41 slave motion, XI1 at root 35 -> 37 -> 35 XI1 owner-events press 38 -> 40 -> 38 master owner-events motion 11 -> 19 -> 9 slave owner-events motion 35 -> 37 -> 35 smooth scroll 37 -> 39 -> 37 Co-Authored-By: Claude Opus 5.5 Implemented-By: codex (gpt-6-luna xhigh) --- crates/yserver-core/src/core_loop/fanout.rs | 24 +- .../src/core_loop/pointer_fanout.rs | 5 +- .../core_loop/pointer_fanout/owner_events.rs | 357 ++++++++++++++---- .../src/core_loop/pointer_fanout/xi1.rs | 68 ++-- 4 files changed, 335 insertions(+), 119 deletions(-) diff --git a/crates/yserver-core/src/core_loop/fanout.rs b/crates/yserver-core/src/core_loop/fanout.rs index 9c6fe9849..1863561ff 100644 --- a/crates/yserver-core/src/core_loop/fanout.rs +++ b/crates/yserver-core/src/core_loop/fanout.rs @@ -230,7 +230,7 @@ pub(crate) fn pointer_propagation_target_by_id( return None; } } - let subs = subscribers_by_id(state, current, mask_bits); + let mut subs = subscribers_by_id(state, current, mask_bits); if !subs.is_empty() { let Some(walk) = walk.as_mut() else { return Some((current, x, y, subs, child.unwrap_or(ResourceId(0)))); @@ -241,20 +241,20 @@ pub(crate) fn pointer_propagation_target_by_id( let description = EventDescription::core(walk.event_type); let batch = EventBatch::new(std::slice::from_ref(&description)); let mut stops = false; - let mut recipients = Vec::with_capacity(subs.len()); - for sub in subs { - if walk.shadowed.contains(&sub) { + subs.retain(|sub| { + if walk.shadowed.contains(sub) { stops = true; - } else if walk - .memo - .allows(state, sub, EventSubject::Window(current), &batch) - { - stops = true; - recipients.push(sub); + false + } else { + let allowed = + walk.memo + .allows(state, *sub, EventSubject::Window(current), &batch); + stops |= allowed; + allowed } - } + }); if stops { - return Some((current, x, y, recipients, child.unwrap_or(ResourceId(0)))); + return Some((current, x, y, subs, child.unwrap_or(ResourceId(0)))); } } let window = state.resources.window(current)?; diff --git a/crates/yserver-core/src/core_loop/pointer_fanout.rs b/crates/yserver-core/src/core_loop/pointer_fanout.rs index 4cbea822a..44aaf9644 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout.rs @@ -3992,7 +3992,7 @@ fn xi2_route_window_for_source( let mut window = target; for _ in 0..256 { let selected = match receive.as_deref_mut() { - Some(memo) => !xi2_form_targets_for_source( + Some(memo) if state.policies_installed() => !xi2_form_targets_for_source( state, window, form, @@ -4004,6 +4004,9 @@ fn xi2_route_window_for_source( None => state.clients.values().any(|client| { xi2_form_selected_on_for_source(client, window, form, evtype, slave_deviceid) }), + Some(_) => state.clients.values().any(|client| { + xi2_form_selected_on_for_source(client, window, form, evtype, slave_deviceid) + }), }; if selected { return Some(window); diff --git a/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs b/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs index 2edd6d367..17df8bd44 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs @@ -3,9 +3,37 @@ use super::{ ClientId, PointerReplay, PointerXiSource, ReceiveMemo, ResourceId, ServerState, XI2_MASTER_POINTER_DEVICE_ID, Xi2PointerForm, clamp_grab_coord, xi2_child_toward, - xi2_form_targets_for_source, xi2_route_window_for_source, + xi2_form_selected_on_for_source, xi2_form_targets_for_source, xi2_route_window_for_source, }; +/// Up to two event descriptions stored inline for one input copy. +#[derive(Clone, Copy)] +pub(super) struct EventDescriptions { + entries: [crate::access::EventDescription; 2], + len: usize, +} + +impl EventDescriptions { + fn empty() -> Self { + let empty = crate::access::EventDescription::core(0); + Self { + entries: [empty; 2], + len: 0, + } + } + + fn one(description: crate::access::EventDescription) -> Self { + Self { + entries: [description; 2], + len: 1, + } + } + + pub(super) fn as_slice(&self) -> &[crate::access::EventDescription] { + &self.entries[..self.len] + } +} + /// Resolves XI1 event selectors in the shared per-window extension-entry /// order so routing and implicit-grab owner selection follow Xorg. pub(super) fn xi1_window_selectors( @@ -49,6 +77,109 @@ pub(super) fn xi1_window_selectors_with_grab_class( .collect() } +fn xi1_client_selects_on( + state: &ServerState, + window: ResourceId, + evcode: u8, + deviceid: u16, + client: ClientId, +) -> bool { + let class = (u32::from(deviceid) << 8) | u32::from(evcode); + state + .xi_input_clients + .get(&window) + .into_iter() + .flatten() + .any(|entry| { + entry.client == client + && !entry.server_owned_placeholder + && state.clients.contains_key(&entry.client.0) + && entry + .xi1_masks + .get(&deviceid) + .is_some_and(|classes| classes.contains(&class)) + }) +} + +fn xi1_has_foreign_selector( + state: &ServerState, + window: ResourceId, + evcode: u8, + deviceid: u16, + owner: ClientId, +) -> bool { + let class = (u32::from(deviceid) << 8) | u32::from(evcode); + state + .xi_input_clients + .get(&window) + .into_iter() + .flatten() + .any(|entry| { + entry.client != owner + && !entry.server_owned_placeholder + && state.clients.contains_key(&entry.client.0) + && entry + .xi1_masks + .get(&deviceid) + .is_some_and(|classes| classes.contains(&class)) + }) +} + +fn xi2_client_selects_on( + state: &ServerState, + window: ResourceId, + form: Xi2PointerForm, + evtype: u16, + slave_deviceid: Option, + client: ClientId, +) -> bool { + state.clients.get(&client.0).is_some_and(|client| { + xi2_form_selected_on_for_source(client, window, form, evtype, slave_deviceid) + }) +} + +fn xi2_has_foreign_selector( + state: &ServerState, + window: ResourceId, + form: Xi2PointerForm, + evtype: u16, + slave_deviceid: Option, + owner: ClientId, +) -> bool { + state.clients.iter().any(|(id, client)| { + *id != owner.0 + && xi2_form_selected_on_for_source(client, window, form, evtype, slave_deviceid) + }) +} + +fn core_client_selects_on( + state: &ServerState, + window: ResourceId, + mask: u32, + client: ClientId, +) -> bool { + state + .clients + .get(&client.0) + .and_then(|client| client.event_masks.get(&window)) + .is_some_and(|selected| selected & mask != 0) +} + +fn core_has_foreign_selector( + state: &ServerState, + window: ResourceId, + mask: u32, + owner: ClientId, +) -> bool { + state.clients.iter().any(|(id, client)| { + *id != owner.0 + && client + .event_masks + .get(&window) + .is_some_and(|selected| selected & mask != 0) + }) +} + /// Converts an XI1 event type into the bit used by an implicit-grab mask. pub(super) fn xi1_event_mask_bit(event_type: u8) -> u32 { let Some(offset) = event_type.checked_sub(crate::server::XI_FIRST_EVENT) else { @@ -412,22 +543,26 @@ pub(super) enum OwnerEventsRoute { /// The XI1 copy of one device event as Receive sees it: its description, and /// for `DeviceMotionNotify` the `DeviceValuator` continuation, one batch /// (`dix/eventconvert.c:369`). `evcode` is the absolute XI1 event code. -pub(super) fn xi1_batch(evcode: u8) -> Vec { +pub(super) fn xi1_batch(evcode: u8) -> EventDescriptions { let offset = evcode.saturating_sub(crate::server::XI_FIRST_EVENT); - let mut batch = vec![crate::xinput::xi1_event_description(offset)]; if offset == crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET { - batch.push(crate::xinput::xi1_event_description( - crate::xinput::XI_DEVICE_VALUATOR_OFFSET, - )); + EventDescriptions { + entries: [ + crate::xinput::xi1_event_description(offset), + crate::xinput::xi1_event_description(crate::xinput::XI_DEVICE_VALUATOR_OFFSET), + ], + len: 2, + } + } else { + EventDescriptions::one(crate::xinput::xi1_event_description(offset)) } - batch } /// One protocol's selectors at a window, with the batch their copy is checked as. struct RouteLeg { protocol: OwnerProtocol, selectors: Vec, - batch: Vec, + batch: EventDescriptions, } /// Resolve one owner-events attempt at each window in Xorg's protocol @@ -465,87 +600,149 @@ pub(super) fn owner_events_route( let mut y = start_y; let mut child: Option = None; for _ in 0..256 { - let mut legs: Vec = Vec::with_capacity(3); - if let Some(evtype) = xi2_evtype { - legs.push(RouteLeg { - protocol: OwnerProtocol::Xi2, - selectors: xi2_form_targets_for_source( - state, - current, - form, - evtype, - slave_deviceid, - None, - ), - batch: vec![crate::xinput::xi2_event_description(evtype)], - }); - } - if form == Xi2PointerForm::Slave - && let (Some(device_id), Some(class)) = (slave_deviceid, xi1_mask) - && (class >> 8) as u16 == device_id - { - let evcode = (class & 0xff) as u8; - legs.push(RouteLeg { - protocol: OwnerProtocol::Xi1, - selectors: xi1_window_selectors(state, current, evcode, device_id), - batch: xi1_batch(evcode), - }); - } - if form == Xi2PointerForm::Master && core_mask != 0 { - legs.push(RouteLeg { - protocol: OwnerProtocol::Core, - selectors: crate::core_loop::fanout::subscribers_by_id(state, current, core_mask), - // A dispatch whose core copy was not routed by the core grab - // block (an activation) leaves the core leg selection-only. - batch: xi2_evtype - .filter(|_| core_checked) - .and_then(|evtype| u8::try_from(evtype).ok()) - .map(crate::access::EventDescription::core) - .into_iter() - .collect(), - }); - } - let mut allowed = |client: ClientId, - batch: &[crate::access::EventDescription], - known_only: bool| match receive.as_deref_mut() - { - Some(memo) if !batch.is_empty() && known_only => memo - .known( - client, - crate::access::EventSubject::Window(current), - &crate::access::EventBatch::new(batch), - ) - .unwrap_or(true), - Some(memo) if !batch.is_empty() => memo.allows( - state, - client, - crate::access::EventSubject::Window(current), - &crate::access::EventBatch::new(batch), - ), - _ => true, - }; - for leg in &legs { - let known_only = xi2_known_only && matches!(leg.protocol, OwnerProtocol::Xi2); - if leg.selectors.contains(&grab_client) && allowed(grab_client, &leg.batch, known_only) + if !state.policies_installed() { + let xi1_event = if form == Xi2PointerForm::Slave + && let (Some(device_id), Some(class)) = (slave_deviceid, xi1_mask) + && (class >> 8) as u16 == device_id + { + Some((device_id, (class & 0xff) as u8)) + } else { + None + }; + + if let Some(evtype) = xi2_evtype + && xi2_client_selects_on(state, current, form, evtype, slave_deviceid, grab_client) { return OwnerEventsRoute::Natural { window: current, x, y, child: child.unwrap_or(ResourceId(0)), - protocol: leg.protocol, + protocol: OwnerProtocol::Xi2, }; } - } - let mut rejected = false; - for leg in &legs { - let known_only = xi2_known_only && matches!(leg.protocol, OwnerProtocol::Xi2); - for client in leg.selectors.iter().filter(|c| **c != grab_client) { - rejected |= allowed(*client, &leg.batch, known_only); + if let Some((device_id, evcode)) = xi1_event + && xi1_client_selects_on(state, current, evcode, device_id, grab_client) + { + return OwnerEventsRoute::Natural { + window: current, + x, + y, + child: child.unwrap_or(ResourceId(0)), + protocol: OwnerProtocol::Xi1, + }; + } + if form == Xi2PointerForm::Master + && core_mask != 0 + && core_client_selects_on(state, current, core_mask, grab_client) + { + return OwnerEventsRoute::Natural { + window: current, + x, + y, + child: child.unwrap_or(ResourceId(0)), + protocol: OwnerProtocol::Core, + }; + } + + let foreign_xi2 = xi2_evtype.is_some_and(|evtype| { + xi2_has_foreign_selector(state, current, form, evtype, slave_deviceid, grab_client) + }); + let foreign_xi1 = xi1_event.is_some_and(|(device_id, evcode)| { + xi1_has_foreign_selector(state, current, evcode, device_id, grab_client) + }); + let foreign_core = form == Xi2PointerForm::Master + && core_mask != 0 + && core_has_foreign_selector(state, current, core_mask, grab_client); + if foreign_xi2 || foreign_xi1 || foreign_core { + return OwnerEventsRoute::Fallback; + } + } else { + let mut legs: Vec = Vec::with_capacity(3); + if let Some(evtype) = xi2_evtype { + legs.push(RouteLeg { + protocol: OwnerProtocol::Xi2, + selectors: xi2_form_targets_for_source( + state, + current, + form, + evtype, + slave_deviceid, + None, + ), + batch: EventDescriptions::one(crate::xinput::xi2_event_description(evtype)), + }); + } + if form == Xi2PointerForm::Slave + && let (Some(device_id), Some(class)) = (slave_deviceid, xi1_mask) + && (class >> 8) as u16 == device_id + { + let evcode = (class & 0xff) as u8; + legs.push(RouteLeg { + protocol: OwnerProtocol::Xi1, + selectors: xi1_window_selectors(state, current, evcode, device_id), + batch: xi1_batch(evcode), + }); + } + if form == Xi2PointerForm::Master && core_mask != 0 { + legs.push(RouteLeg { + protocol: OwnerProtocol::Core, + selectors: crate::core_loop::fanout::subscribers_by_id( + state, current, core_mask, + ), + // A dispatch whose core copy was not routed by the core grab + // block (an activation) leaves the core leg selection-only. + batch: xi2_evtype + .filter(|_| core_checked) + .and_then(|evtype| u8::try_from(evtype).ok()) + .map(crate::access::EventDescription::core) + .map(EventDescriptions::one) + .unwrap_or_else(EventDescriptions::empty), + }); + } + let mut allowed = + |client: ClientId, batch: &EventDescriptions, known_only: bool| match receive + .as_deref_mut() + { + Some(memo) if !batch.as_slice().is_empty() && known_only => memo + .known( + client, + crate::access::EventSubject::Window(current), + &crate::access::EventBatch::new(batch.as_slice()), + ) + .unwrap_or(true), + Some(memo) if !batch.as_slice().is_empty() => memo.allows( + state, + client, + crate::access::EventSubject::Window(current), + &crate::access::EventBatch::new(batch.as_slice()), + ), + _ => true, + }; + for leg in &legs { + let known_only = xi2_known_only && matches!(leg.protocol, OwnerProtocol::Xi2); + if leg.selectors.contains(&grab_client) + && allowed(grab_client, &leg.batch, known_only) + { + return OwnerEventsRoute::Natural { + window: current, + x, + y, + child: child.unwrap_or(ResourceId(0)), + protocol: leg.protocol, + }; + } + } + let mut rejected = false; + for leg in &legs { + let known_only = xi2_known_only && matches!(leg.protocol, OwnerProtocol::Xi2); + for client in leg.selectors.iter().filter(|c| **c != grab_client) { + rejected |= allowed(*client, &leg.batch, known_only); + } + } + if rejected { + return OwnerEventsRoute::Fallback; } - } - if rejected { - return OwnerEventsRoute::Fallback; } let Some(window) = state.resources.window(current) else { return OwnerEventsRoute::Fallback; diff --git a/crates/yserver-core/src/core_loop/pointer_fanout/xi1.rs b/crates/yserver-core/src/core_loop/pointer_fanout/xi1.rs index a883252fc..a36ac643e 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout/xi1.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout/xi1.rs @@ -306,29 +306,44 @@ pub(crate) fn xi1_route_device_event( /// The windows the XI1 selection walk visits, in order: unbounded walk, /// walk bounded at the focus window, focus-window-only, or none. -pub(super) fn xi1_route_windows( - state: &ServerState, +pub(super) struct Xi1RouteWindows<'a> { + state: &'a ServerState, + next: Option, + stop_at: Option, +} + +impl Iterator for Xi1RouteWindows<'_> { + type Item = ResourceId; + + fn next(&mut self) -> Option { + let window = self.next?; + if window == ROOT_WINDOW || self.stop_at == Some(window) { + self.next = None; + } else { + self.next = match self.state.resources.window(window).map(|w| w.parent) { + Some(parent) if parent != window => Some(parent), + _ => None, + }; + } + Some(window) + } +} + +pub(super) fn xi1_route_windows<'a>( + state: &'a ServerState, q: &crate::server::Xi1QueuedEvent, -) -> Vec { - let stop_at = match q.focus_route { - crate::server::Xi1FocusRoute::Walk => None, - crate::server::Xi1FocusRoute::WalkUpTo(stop) => Some(stop), - crate::server::Xi1FocusRoute::WindowOnly(w) => return vec![w], - crate::server::Xi1FocusRoute::Drop => return Vec::new(), +) -> Xi1RouteWindows<'a> { + let (next, stop_at) = match q.focus_route { + crate::server::Xi1FocusRoute::Walk => (Some(q.natural_target), None), + crate::server::Xi1FocusRoute::WalkUpTo(stop) => (Some(q.natural_target), Some(stop)), + crate::server::Xi1FocusRoute::WindowOnly(window) => (Some(window), Some(window)), + crate::server::Xi1FocusRoute::Drop => (None, None), }; - let mut windows = Vec::new(); - let mut window = q.natural_target; - loop { - windows.push(window); - if window == ROOT_WINDOW || stop_at == Some(window) { - break; - } - match state.resources.window(window).map(|w| w.parent) { - Some(parent) if parent != window => window = parent, - _ => break, - } + Xi1RouteWindows { + state, + next, + stop_at, } - windows } /// True when `client` selected this event but gets no copy of it: a synthetic @@ -358,7 +373,7 @@ pub(super) fn xi1_allowed_selectors( let mut selectors = xi1_window_selectors(state, window, q.evcode, q.deviceid); if let Some(memo) = receive { let batch = xi1_batch(q.evcode); - let events = EventBatch::new(&batch); + let events = EventBatch::new(batch.as_slice()); selectors.retain(|client| { xi1_gets_no_copy(state, q, *client) || memo.allows(state, *client, EventSubject::Window(window), &events) @@ -393,7 +408,7 @@ pub(super) fn xi1_owner_events_window( receive: &mut ReceiveMemo, ) -> Option { let batch = xi1_batch(q.evcode); - let events = EventBatch::new(&batch); + let events = EventBatch::new(batch.as_slice()); for window in xi1_route_windows(state, q) { let selectors = xi1_window_selectors(state, window, q.evcode, q.deviceid); if selectors.is_empty() { @@ -425,8 +440,9 @@ pub(super) fn xi1_grab_window_copy_allowed( owner: ClientId, grab_window: ResourceId, ) -> bool { + let batch = xi1_batch(q.evcode); !xi1_gets_no_copy(state, q, owner) - && grab_window_allows_batch(state, owner, grab_window, &xi1_batch(q.evcode)) + && grab_window_allows_batch(state, owner, grab_window, batch.as_slice()) } /// The XI1 passive grab an XI1 press activates, if any (the replay floor @@ -474,8 +490,6 @@ pub(super) fn resolve_slave_press_delivery( xi2_checked: bool, xi1_checked: bool, ) -> SlavePressDelivery { - let xi1_description = xi1_batch(xi1_evcode); - let xi1_events = EventBatch::new(&xi1_description); let mut window = target; for _ in 0..256 { let xi2_recipients = xi2_form_targets_for_source( @@ -494,7 +508,9 @@ pub(super) fn resolve_slave_press_delivery( } let mut xi1_recipients = xi1_window_selectors(state, window, xi1_evcode, deviceid); - if xi1_checked { + if xi1_checked && !xi1_recipients.is_empty() { + let xi1_description = xi1_batch(xi1_evcode); + let xi1_events = EventBatch::new(xi1_description.as_slice()); xi1_recipients.retain(|client| { receive.allows(state, *client, EventSubject::Window(window), &xi1_events) }); From 5b4b526cbc7454b557f14d5be09f4f07794ef4e0 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Thu, 3 Dec 2026 12:55:02 -0300 Subject: [PATCH 66/72] perf(access): Task 1 review round, owner-events legs on the stack The owner-events walk keeps up to three legs as stack slots and visits each leg's selectors through the existing selection predicates, the owner first and every foreign selector only when the owner qualifies nowhere. No route-leg vector, selector lists or descriptions are built before a check needs them, with or without a policy. A slave owner-events grab with an XI2 owner hit now allocates 10 times per event, against 14 at ef3bc7ac. Co-Authored-By: Claude Opus 5.5 Implemented-By: codex (gpt-6-luna max) --- crates/yserver-core/src/core_loop/fanout.rs | 26 +- .../src/core_loop/pointer_fanout.rs | 31 +- .../core_loop/pointer_fanout/owner_events.rs | 472 +++++++++--------- 3 files changed, 260 insertions(+), 269 deletions(-) diff --git a/crates/yserver-core/src/core_loop/fanout.rs b/crates/yserver-core/src/core_loop/fanout.rs index 1863561ff..bce984eeb 100644 --- a/crates/yserver-core/src/core_loop/fanout.rs +++ b/crates/yserver-core/src/core_loop/fanout.rs @@ -129,18 +129,20 @@ pub(crate) fn record_outbound_telemetry(client: ClientId, order: ClientByteOrder /// follows `HashMap` iteration — already non-deterministic in the old /// path, so wire ordering is unchanged. pub fn subscribers_by_id(state: &ServerState, window: ResourceId, mask_bits: u32) -> Vec { - state - .clients - .iter() - .filter_map(|(id, c)| { - let mask = c.event_masks.get(&window).copied().unwrap_or(0); - if mask & mask_bits != 0 { - Some(ClientId(*id)) - } else { - None - } - }) - .collect() + subscribers_by_id_iter(state, window, mask_bits).collect() +} + +/// Iterate, in client-map order, over clients that selected one of the bits +/// in `mask_bits` on `window`. +pub(crate) fn subscribers_by_id_iter( + state: &ServerState, + window: ResourceId, + mask_bits: u32, +) -> impl Iterator + '_ { + state.clients.iter().filter_map(move |(id, client)| { + let mask = client.event_masks.get(&window).copied().unwrap_or(0); + (mask & mask_bits != 0).then_some(ClientId(*id)) + }) } /// XI2 device ids whose selection ABSORBS a core pointer event: the diff --git a/crates/yserver-core/src/core_loop/pointer_fanout.rs b/crates/yserver-core/src/core_loop/pointer_fanout.rs index 44aaf9644..a50149c3e 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout.rs @@ -4033,17 +4033,28 @@ fn xi2_form_targets_for_source( ) -> Vec { let description = crate::xinput::xi2_event_description(evtype); let batch = EventBatch::new(std::slice::from_ref(&description)); - let mut targets = Vec::new(); - for (id, client) in &state.clients { - if xi2_form_selected_on_for_source(client, window, form, evtype, slave_deviceid) - && receive.as_deref_mut().is_none_or(|memo| { - memo.allows(state, ClientId(*id), EventSubject::Window(window), &batch) + xi2_form_target_iter_for_source(state, window, form, evtype, slave_deviceid) + .filter(|client| { + receive.as_deref_mut().is_none_or(|memo| { + memo.allows(state, *client, EventSubject::Window(window), &batch) }) - { - targets.push(ClientId(*id)); - } - } - targets + }) + .collect() +} + +/// Iterate, in client-map order, over clients whose XI2 masks select this form +/// and event type on `window`. +fn xi2_form_target_iter_for_source( + state: &ServerState, + window: ResourceId, + form: Xi2PointerForm, + evtype: u16, + slave_deviceid: Option, +) -> impl Iterator + '_ { + state.clients.iter().filter_map(move |(id, client)| { + xi2_form_selected_on_for_source(client, window, form, evtype, slave_deviceid) + .then_some(ClientId(*id)) + }) } /// A memo and which XI2 forms of one call are checked through it. An unchecked diff --git a/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs b/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs index 17df8bd44..417d09d00 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout/owner_events.rs @@ -3,7 +3,7 @@ use super::{ ClientId, PointerReplay, PointerXiSource, ReceiveMemo, ResourceId, ServerState, XI2_MASTER_POINTER_DEVICE_ID, Xi2PointerForm, clamp_grab_coord, xi2_child_toward, - xi2_form_selected_on_for_source, xi2_form_targets_for_source, xi2_route_window_for_source, + xi2_form_target_iter_for_source, xi2_form_targets_for_source, xi2_route_window_for_source, }; /// Up to two event descriptions stored inline for one input copy. @@ -42,142 +42,59 @@ pub(super) fn xi1_window_selectors( evcode: u8, deviceid: u16, ) -> Vec { - xi1_window_selectors_with_grab_class(state, window, evcode, deviceid) - .into_iter() - .map(|(client, _)| client) - .collect() + xi1_window_selector_iter(state, window, evcode, deviceid).collect() } -/// Returns the canonical input-client entries that select an XI1 event and -/// whether that same delivering entry selects either XI1 button-grab class. -pub(super) fn xi1_window_selectors_with_grab_class( +/// Iterate selectors in XI1 input-client entry order, preserving duplicate +/// client IDs from distinct entries. +fn xi1_window_selector_iter( state: &ServerState, window: ResourceId, evcode: u8, deviceid: u16, -) -> Vec<(ClientId, bool)> { +) -> impl Iterator + '_ { let class = (u32::from(deviceid) << 8) | u32::from(evcode); state .xi_input_clients .get(&window) .into_iter() .flatten() - .filter(|entry| { + .filter(move |entry| { !entry.server_owned_placeholder && state.clients.contains_key(&entry.client.0) }) - .filter_map(|entry| { + .filter_map(move |entry| { let classes = entry.xi1_masks.get(&deviceid)?; - let selects_grab_class = classes.iter().any(|class| { - u8::try_from(*class & 0xff).is_ok_and(crate::xinput::xi1_class_is_button_grab) - }); - classes - .contains(&class) - .then_some((entry.client, selects_grab_class)) + classes.contains(&class).then_some(entry.client) }) - .collect() } -fn xi1_client_selects_on( +/// Returns the canonical input-client entries that select an XI1 event and +/// whether that same delivering entry selects either XI1 button-grab class. +pub(super) fn xi1_window_selectors_with_grab_class( state: &ServerState, window: ResourceId, evcode: u8, deviceid: u16, - client: ClientId, -) -> bool { +) -> Vec<(ClientId, bool)> { let class = (u32::from(deviceid) << 8) | u32::from(evcode); state .xi_input_clients .get(&window) .into_iter() .flatten() - .any(|entry| { - entry.client == client - && !entry.server_owned_placeholder - && state.clients.contains_key(&entry.client.0) - && entry - .xi1_masks - .get(&deviceid) - .is_some_and(|classes| classes.contains(&class)) + .filter(|entry| { + !entry.server_owned_placeholder && state.clients.contains_key(&entry.client.0) }) -} - -fn xi1_has_foreign_selector( - state: &ServerState, - window: ResourceId, - evcode: u8, - deviceid: u16, - owner: ClientId, -) -> bool { - let class = (u32::from(deviceid) << 8) | u32::from(evcode); - state - .xi_input_clients - .get(&window) - .into_iter() - .flatten() - .any(|entry| { - entry.client != owner - && !entry.server_owned_placeholder - && state.clients.contains_key(&entry.client.0) - && entry - .xi1_masks - .get(&deviceid) - .is_some_and(|classes| classes.contains(&class)) + .filter_map(|entry| { + let classes = entry.xi1_masks.get(&deviceid)?; + let selects_grab_class = classes.iter().any(|class| { + u8::try_from(*class & 0xff).is_ok_and(crate::xinput::xi1_class_is_button_grab) + }); + classes + .contains(&class) + .then_some((entry.client, selects_grab_class)) }) -} - -fn xi2_client_selects_on( - state: &ServerState, - window: ResourceId, - form: Xi2PointerForm, - evtype: u16, - slave_deviceid: Option, - client: ClientId, -) -> bool { - state.clients.get(&client.0).is_some_and(|client| { - xi2_form_selected_on_for_source(client, window, form, evtype, slave_deviceid) - }) -} - -fn xi2_has_foreign_selector( - state: &ServerState, - window: ResourceId, - form: Xi2PointerForm, - evtype: u16, - slave_deviceid: Option, - owner: ClientId, -) -> bool { - state.clients.iter().any(|(id, client)| { - *id != owner.0 - && xi2_form_selected_on_for_source(client, window, form, evtype, slave_deviceid) - }) -} - -fn core_client_selects_on( - state: &ServerState, - window: ResourceId, - mask: u32, - client: ClientId, -) -> bool { - state - .clients - .get(&client.0) - .and_then(|client| client.event_masks.get(&window)) - .is_some_and(|selected| selected & mask != 0) -} - -fn core_has_foreign_selector( - state: &ServerState, - window: ResourceId, - mask: u32, - owner: ClientId, -) -> bool { - state.clients.iter().any(|(id, client)| { - *id != owner.0 - && client - .event_masks - .get(&window) - .is_some_and(|selected| selected & mask != 0) - }) + .collect() } /// Converts an XI1 event type into the bit used by an implicit-grab mask. @@ -558,11 +475,151 @@ pub(super) fn xi1_batch(evcode: u8) -> EventDescriptions { } } -/// One protocol's selectors at a window, with the batch their copy is checked as. -struct RouteLeg { - protocol: OwnerProtocol, - selectors: Vec, - batch: EventDescriptions, +/// One enabled owner-events leg. These slots retain only the protocol and its +/// selection parameters; selector iterators and batches are created on demand. +#[derive(Clone, Copy)] +enum RouteLeg { + Xi2 { evtype: u16 }, + Xi1 { deviceid: u16, evcode: u8 }, + Core { mask: u32 }, +} + +impl RouteLeg { + fn protocol(self) -> OwnerProtocol { + match self { + Self::Xi2 { .. } => OwnerProtocol::Xi2, + Self::Xi1 { .. } => OwnerProtocol::Xi1, + Self::Core { .. } => OwnerProtocol::Core, + } + } + + fn batch(self, xi2_evtype: Option, core_checked: bool) -> EventDescriptions { + match self { + Self::Xi2 { evtype } => { + EventDescriptions::one(crate::xinput::xi2_event_description(evtype)) + } + Self::Xi1 { evcode, .. } => xi1_batch(evcode), + Self::Core { .. } => xi2_evtype + .filter(|_| core_checked) + .and_then(|evtype| u8::try_from(evtype).ok()) + .map(crate::access::EventDescription::core) + .map(EventDescriptions::one) + .unwrap_or_else(EventDescriptions::empty), + } + } +} + +fn route_leg_selects_client( + state: &ServerState, + window: ResourceId, + form: Xi2PointerForm, + slave_deviceid: Option, + leg: RouteLeg, + client: ClientId, +) -> bool { + match leg { + RouteLeg::Xi2 { evtype } => { + xi2_form_target_iter_for_source(state, window, form, evtype, slave_deviceid) + .any(|selector| selector == client) + } + RouteLeg::Xi1 { deviceid, evcode } => { + xi1_window_selector_iter(state, window, evcode, deviceid) + .any(|selector| selector == client) + } + RouteLeg::Core { mask } => { + crate::core_loop::fanout::subscribers_by_id_iter(state, window, mask) + .any(|selector| selector == client) + } + } +} + +/// Check a selected copy only when the caller has an installed policy and a +/// memo. Unchecked forms and the core activation leg keep selection-only +/// semantics without building a batch. +fn route_leg_allows( + state: &ServerState, + window: ResourceId, + client: ClientId, + leg: RouteLeg, + xi2_evtype: Option, + core_checked: bool, + known_only: bool, + receive: &mut Option<&mut ReceiveMemo>, +) -> bool { + if !state.policies_installed() { + return true; + } + let Some(memo) = receive.as_deref_mut() else { + return true; + }; + let batch = leg.batch(xi2_evtype, core_checked); + if batch.as_slice().is_empty() { + return true; + } + let subject = crate::access::EventSubject::Window(window); + let batch = crate::access::EventBatch::new(batch.as_slice()); + if known_only { + memo.known(client, subject, &batch).unwrap_or(true) + } else { + memo.allows(state, client, subject, &batch) + } +} + +/// Visit every foreign selector in this leg, preserving its native selector +/// order and evaluating every policy decision even after one allows a copy. +fn route_leg_has_allowed_foreign( + state: &ServerState, + window: ResourceId, + form: Xi2PointerForm, + slave_deviceid: Option, + owner: ClientId, + leg: RouteLeg, + xi2_evtype: Option, + core_checked: bool, + known_only: bool, + policies_installed: bool, + receive: &mut Option<&mut ReceiveMemo>, +) -> bool { + let mut rejected = false; + let mut consider = |client| { + if client != owner { + let allowed = if policies_installed { + route_leg_allows( + state, + window, + client, + leg, + xi2_evtype, + core_checked, + known_only, + receive, + ) + } else { + true + }; + rejected |= allowed; + } + }; + match leg { + RouteLeg::Xi2 { evtype } => { + for client in + xi2_form_target_iter_for_source(state, window, form, evtype, slave_deviceid) + { + consider(client); + } + } + RouteLeg::Xi1 { deviceid, evcode } => { + for client in xi1_window_selector_iter(state, window, evcode, deviceid) { + consider(client); + } + } + RouteLeg::Core { mask } => { + for client in crate::core_loop::fanout::subscribers_by_id_iter(state, window, mask) { + consider(client); + } + } + } + rejected } /// Resolve one owner-events attempt at each window in Xorg's protocol @@ -595,154 +652,75 @@ pub(super) fn owner_events_route( core_checked: bool, xi2_known_only: bool, ) -> OwnerEventsRoute { + let xi1_event = if form == Xi2PointerForm::Slave + && let (Some(device_id), Some(class)) = (slave_deviceid, xi1_mask) + && (class >> 8) as u16 == device_id + { + Some((device_id, (class & 0xff) as u8)) + } else { + None + }; + let mut legs = [None; 3]; + let mut leg_count = 0; + if let Some(evtype) = xi2_evtype { + legs[leg_count] = Some(RouteLeg::Xi2 { evtype }); + leg_count += 1; + } + if let Some((deviceid, evcode)) = xi1_event { + legs[leg_count] = Some(RouteLeg::Xi1 { deviceid, evcode }); + leg_count += 1; + } + if form == Xi2PointerForm::Master && core_mask != 0 { + legs[leg_count] = Some(RouteLeg::Core { mask: core_mask }); + leg_count += 1; + } + let policies_installed = state.policies_installed(); let mut current = start; let mut x = start_x; let mut y = start_y; let mut child: Option = None; for _ in 0..256 { - if !state.policies_installed() { - let xi1_event = if form == Xi2PointerForm::Slave - && let (Some(device_id), Some(class)) = (slave_deviceid, xi1_mask) - && (class >> 8) as u16 == device_id - { - Some((device_id, (class & 0xff) as u8)) - } else { - None - }; - - if let Some(evtype) = xi2_evtype - && xi2_client_selects_on(state, current, form, evtype, slave_deviceid, grab_client) - { - return OwnerEventsRoute::Natural { - window: current, - x, - y, - child: child.unwrap_or(ResourceId(0)), - protocol: OwnerProtocol::Xi2, - }; - } - if let Some((device_id, evcode)) = xi1_event - && xi1_client_selects_on(state, current, evcode, device_id, grab_client) - { - return OwnerEventsRoute::Natural { - window: current, - x, - y, - child: child.unwrap_or(ResourceId(0)), - protocol: OwnerProtocol::Xi1, - }; - } - if form == Xi2PointerForm::Master - && core_mask != 0 - && core_client_selects_on(state, current, core_mask, grab_client) + for leg in legs[..leg_count].iter().flatten().copied() { + if route_leg_selects_client(state, current, form, slave_deviceid, leg, grab_client) + && (!policies_installed + || route_leg_allows( + state, + current, + grab_client, + leg, + xi2_evtype, + core_checked, + xi2_known_only && matches!(leg, RouteLeg::Xi2 { .. }), + &mut receive, + )) { return OwnerEventsRoute::Natural { window: current, x, y, child: child.unwrap_or(ResourceId(0)), - protocol: OwnerProtocol::Core, + protocol: leg.protocol(), }; } - - let foreign_xi2 = xi2_evtype.is_some_and(|evtype| { - xi2_has_foreign_selector(state, current, form, evtype, slave_deviceid, grab_client) - }); - let foreign_xi1 = xi1_event.is_some_and(|(device_id, evcode)| { - xi1_has_foreign_selector(state, current, evcode, device_id, grab_client) - }); - let foreign_core = form == Xi2PointerForm::Master - && core_mask != 0 - && core_has_foreign_selector(state, current, core_mask, grab_client); - if foreign_xi2 || foreign_xi1 || foreign_core { - return OwnerEventsRoute::Fallback; - } - } else { - let mut legs: Vec = Vec::with_capacity(3); - if let Some(evtype) = xi2_evtype { - legs.push(RouteLeg { - protocol: OwnerProtocol::Xi2, - selectors: xi2_form_targets_for_source( - state, - current, - form, - evtype, - slave_deviceid, - None, - ), - batch: EventDescriptions::one(crate::xinput::xi2_event_description(evtype)), - }); - } - if form == Xi2PointerForm::Slave - && let (Some(device_id), Some(class)) = (slave_deviceid, xi1_mask) - && (class >> 8) as u16 == device_id - { - let evcode = (class & 0xff) as u8; - legs.push(RouteLeg { - protocol: OwnerProtocol::Xi1, - selectors: xi1_window_selectors(state, current, evcode, device_id), - batch: xi1_batch(evcode), - }); - } - if form == Xi2PointerForm::Master && core_mask != 0 { - legs.push(RouteLeg { - protocol: OwnerProtocol::Core, - selectors: crate::core_loop::fanout::subscribers_by_id( - state, current, core_mask, - ), - // A dispatch whose core copy was not routed by the core grab - // block (an activation) leaves the core leg selection-only. - batch: xi2_evtype - .filter(|_| core_checked) - .and_then(|evtype| u8::try_from(evtype).ok()) - .map(crate::access::EventDescription::core) - .map(EventDescriptions::one) - .unwrap_or_else(EventDescriptions::empty), - }); - } - let mut allowed = - |client: ClientId, batch: &EventDescriptions, known_only: bool| match receive - .as_deref_mut() - { - Some(memo) if !batch.as_slice().is_empty() && known_only => memo - .known( - client, - crate::access::EventSubject::Window(current), - &crate::access::EventBatch::new(batch.as_slice()), - ) - .unwrap_or(true), - Some(memo) if !batch.as_slice().is_empty() => memo.allows( - state, - client, - crate::access::EventSubject::Window(current), - &crate::access::EventBatch::new(batch.as_slice()), - ), - _ => true, - }; - for leg in &legs { - let known_only = xi2_known_only && matches!(leg.protocol, OwnerProtocol::Xi2); - if leg.selectors.contains(&grab_client) - && allowed(grab_client, &leg.batch, known_only) - { - return OwnerEventsRoute::Natural { - window: current, - x, - y, - child: child.unwrap_or(ResourceId(0)), - protocol: leg.protocol, - }; - } - } - let mut rejected = false; - for leg in &legs { - let known_only = xi2_known_only && matches!(leg.protocol, OwnerProtocol::Xi2); - for client in leg.selectors.iter().filter(|c| **c != grab_client) { - rejected |= allowed(*client, &leg.batch, known_only); - } - } - if rejected { - return OwnerEventsRoute::Fallback; - } + } + let mut rejected = false; + for leg in legs[..leg_count].iter().flatten().copied() { + rejected |= route_leg_has_allowed_foreign( + state, + current, + form, + slave_deviceid, + grab_client, + leg, + xi2_evtype, + core_checked, + xi2_known_only && matches!(leg, RouteLeg::Xi2 { .. }), + policies_installed, + &mut receive, + ); + } + if rejected { + return OwnerEventsRoute::Fallback; } let Some(window) = state.resources.window(current) else { return OwnerEventsRoute::Fallback; From 28cfd5c4694870380b997bb8e6f56e79e52d3ac1 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Thu, 3 Dec 2026 14:23:54 -0300 Subject: [PATCH 67/72] perf(access): no-policy keyboard and XI1 walks allocate as before The keyboard path builds its at-most-two XI2 forms once per event, on the stack, after key routing, and threads them through the natural, grabbed and replay walks. With an empty policy list the focus walk finds its stop window with the existing client_key_plan predicate and materialises recipients only at the delivery window; with a policy installed each window keeps its client-major pass. The XI1 selector filter, owner-events walk, fresh grab-window check and slave-press prepass skip the Receive batch when no policy is installed (policies_installed(), not memo presence). Allocation calls per event, no policy (base ef3bc7ac -> now): focused_key_empty_walk 14 -> 8, focused_key_xi2_and_core 19 -> 12; every other scenario at or below base. Co-Authored-By: Claude Opus 5.5 Implemented-By: codex (gpt-6-luna xhigh) --- .../yserver-core/src/core_loop/key_fanout.rs | 174 +++++++++++++----- .../src/core_loop/pointer_fanout/xi1.rs | 37 ++-- 2 files changed, 153 insertions(+), 58 deletions(-) diff --git a/crates/yserver-core/src/core_loop/key_fanout.rs b/crates/yserver-core/src/core_loop/key_fanout.rs index f3415f51f..683247c9b 100644 --- a/crates/yserver-core/src/core_loop/key_fanout.rs +++ b/crates/yserver-core/src/core_loop/key_fanout.rs @@ -557,12 +557,20 @@ fn deliver_routed_key_with_master_status( ); return dropped; } + let xi2_forms = key_xi2_forms(state, event.origin); let focus = current_focus(state); let mut dropped = if focus == ResourceId(0) { Vec::new() } else { - let (target, copies) = - focused_walk_target(state, focus, &event, false, false, synthetic_repeat); + let (target, copies) = focused_walk_target( + state, + focus, + &event, + &xi2_forms, + false, + false, + synthetic_repeat, + ); write_key_copies(state, &event, target, &copies, synthetic_repeat) }; merge_dropped( @@ -571,7 +579,11 @@ fn deliver_routed_key_with_master_status( ); return dropped; } - match key_route(state, &event) { + let route = key_route(state, &event); + // A matching passive-key release may reattach its slave in key_route, so + // resolve the event forms only after routing has updated device state. + let xi2_forms = key_xi2_forms(state, event.origin); + match route { // Core delivery has nowhere to go (focus on root, no grab) — // but the XI1 fanout routes by the extension keyboard's own // device focus (default PointerRoot → window under pointer), @@ -611,7 +623,14 @@ fn deliver_routed_key_with_master_status( // The activating press skips the walk: ActivatePassiveGrab // sends it to the grab window (GH #277). let natural = if owner_events && !activating { - key_grabbed_natural_target(state, &event, owner, via_xi2, synthetic_repeat) + key_grabbed_natural_target( + state, + &event, + &xi2_forms, + owner, + via_xi2, + synthetic_repeat, + ) } else { None }; @@ -659,6 +678,7 @@ fn deliver_routed_key_with_master_status( state, window, &event, + &xi2_forms, master_transition_accepted, master_transition_accepted, synthetic_repeat, @@ -691,6 +711,7 @@ pub(crate) fn replay_frozen_key_to_focus_after_transition( if !keyboard_origin_is_live(state, event.origin) { return Vec::new(); } + let xi2_forms = key_xi2_forms(state, event.origin); let focus = current_focus(state); if focus == ResourceId(0) { return Vec::new(); @@ -698,6 +719,7 @@ pub(crate) fn replay_frozen_key_to_focus_after_transition( let copies = key_copies_at( state, &event, + &xi2_forms, focus, master_transition_accepted, master_transition_accepted, @@ -716,11 +738,17 @@ pub(crate) fn replay_frozen_key_to_focus_after_transition( /// `stops` says whether the focus walk stops at this window. struct KeyCopies { core: Vec, - /// (device, source, recipients) per XI2 form, slave form before master. - xi2: Vec<(u16, u16, Vec)>, + /// Per-form recipient slots, slave form before master. + xi2: [Option; 2], stops: bool, } +struct KeyXi2Copies { + device_id: u16, + source_id: u16, + targets: Vec, +} + /// One client's decision for one key event at one window. #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct ClientKeyPlan { @@ -732,6 +760,19 @@ struct ClientKeyPlan { stops: bool, } +/// The slave-first XI2 forms one key event can carry. Their two fixed slots +/// are shared by every window and client plan for the event. +#[derive(Clone, Copy, Debug, Default)] +struct KeyXi2Forms { + forms: [Option<(u16, u16)>; 2], +} + +impl KeyXi2Forms { + fn iter(&self) -> impl Iterator { + self.forms.iter().flatten() + } +} + /// The per-selection predicate of the input routing (spec l.353–420), for one /// client at one window: whether its selections stop the focus walk, and which /// copies it gets. The focus walk takes the "any" over the window's clients, and @@ -744,6 +785,7 @@ struct ClientKeyPlan { fn client_key_plan( state: &ServerState, event: &HostKeyEvent, + forms: &KeyXi2Forms, window: ResourceId, client: ClientId, include_master_form: bool, @@ -766,7 +808,6 @@ fn client_key_plan( }; let evtype = xi2_evtype_for(event); let xi2_suppressed = synthetic_repeat && !event.pressed; - let forms = key_xi2_forms(state, event.origin); let included = |device_id: u16| include_master_form || device_id != XI2_MASTER_KEYBOARD_DEVICE_ID; let selected = |device_id: u16| key_xi2_form_selected(record, window, device_id, evtype); @@ -829,6 +870,7 @@ fn client_key_plan( fn key_copies_at( state: &ServerState, event: &HostKeyEvent, + forms: &KeyXi2Forms, window: ResourceId, include_master_form: bool, include_core_form: bool, @@ -837,12 +879,23 @@ fn key_copies_at( let subject = EventSubject::Window(window); let mut stops = false; let mut core = Vec::new(); - let mut xi2_recipients = Vec::new(); + let mut xi2 = [None, None]; + for (slot, &(device_id, source_id)) in xi2.iter_mut().zip(forms.iter()) { + if !include_master_form && device_id == XI2_MASTER_KEYBOARD_DEVICE_ID { + continue; + } + *slot = Some(KeyXi2Copies { + device_id, + source_id, + targets: Vec::new(), + }); + } for id in state.clients.keys() { let client = ClientId(*id); let plan = client_key_plan( state, event, + forms, window, client, include_master_form, @@ -854,27 +907,16 @@ fn key_copies_at( if plan.core_copy { core.push(client); } - if plan.xi2_copy { - xi2_recipients.push(client); + if plan.xi2_copy + && let Some(record) = state.clients.get(id) + { + for copies in xi2.iter_mut().flatten() { + if key_xi2_form_selected(record, window, copies.device_id, xi2_evtype_for(event)) { + copies.targets.push(client); + } + } } } - let xi2 = key_xi2_forms(state, event.origin) - .into_iter() - .filter(|(device_id, _)| include_master_form || *device_id != XI2_MASTER_KEYBOARD_DEVICE_ID) - .map(|(device_id, source_id)| { - let targets = state - .clients - .iter() - .filter_map(|(id, record)| { - let client = ClientId(*id); - (xi2_recipients.contains(&client) - && key_xi2_form_selected(record, window, device_id, xi2_evtype_for(event))) - .then_some(client) - }) - .collect(); - (device_id, source_id, targets) - }) - .collect(); KeyCopies { core, xi2, stops } } @@ -895,19 +937,19 @@ fn write_key_copies( x11::encode_key_event(buf, order, key_event_wire(event, seq, fields)); }) }; - for (device_id, source_id, targets) in &copies.xi2 { - if targets.is_empty() { + for xi2 in copies.xi2.iter().flatten() { + if xi2.targets.is_empty() { continue; } - let xi2_dropped = fanout_event_to_clients(state, targets, |buf, seq, order| { + let xi2_dropped = fanout_event_to_clients(state, &xi2.targets, |buf, seq, order| { encode_key_xi2_for_device( buf, order, seq, event, fields, - *device_id, - *source_id, + xi2.device_id, + xi2.source_id, synthetic_repeat, ); }); @@ -1081,6 +1123,7 @@ fn grab_owner_qualifies( fn foreign_selection_rejects( state: &ServerState, event: &HostKeyEvent, + forms: &KeyXi2Forms, owner: ClientId, window: ResourceId, synthetic_repeat: bool, @@ -1097,6 +1140,7 @@ fn foreign_selection_rejects( client_key_plan( state, event, + forms, window, client, true, @@ -1121,16 +1165,18 @@ fn xi2_evtype_for(event: &HostKeyEvent) -> u16 { /// Device event copies follow Xorg's slave-first mieq pass. A detached /// keyboard has only its slave form; attached sources also get a master copy. -fn key_xi2_forms(state: &ServerState, origin: crate::core_loop::InputOrigin) -> Vec<(u16, u16)> { +fn key_xi2_forms(state: &ServerState, origin: crate::core_loop::InputOrigin) -> KeyXi2Forms { let Some(source) = resolve_key_xi_source(state, origin) else { - return Vec::new(); + return KeyXi2Forms::default(); }; - let mut forms = Vec::with_capacity(2); + let mut forms = KeyXi2Forms::default(); + let mut next = 0; if let Some(slave_id) = source.slave_deviceid { - forms.push((slave_id, slave_id)); + forms.forms[next] = Some((slave_id, slave_id)); + next += 1; } if let Some(master_id) = source.attached_master { - forms.push((master_id, source.sourceid)); + forms.forms[next] = Some((master_id, source.sourceid)); } forms } @@ -1771,6 +1817,7 @@ fn focused_walk_target( state: &ServerState, focus: ResourceId, event: &HostKeyEvent, + forms: &KeyXi2Forms, include_master_form: bool, include_core_form: bool, synthetic_repeat: bool, @@ -1797,6 +1844,7 @@ fn focused_walk_target( key_copies_at( state, event, + forms, window, include_master_form, include_core_form, @@ -1806,6 +1854,29 @@ fn focused_walk_target( let Some(depth) = chain.iter().position(|w| *w == focus) else { return (focus, copies_at(focus)); }; + if !state.policies_installed() { + let target = chain[..depth] + .iter() + .copied() + .find(|window| { + state.clients.keys().any(|id| { + client_key_plan( + state, + event, + forms, + *window, + ClientId(*id), + include_master_form, + include_core_form, + synthetic_repeat, + &|_| true, + ) + .stops + }) + }) + .unwrap_or(focus); + return (target, copies_at(target)); + } for window in &chain[..depth] { let copies = copies_at(*window); if copies.stops { @@ -1823,12 +1894,12 @@ fn focused_walk_target( fn key_selectors( state: &ServerState, event: &HostKeyEvent, + forms: &KeyXi2Forms, window: ResourceId, mask_bit: u32, ) -> Vec { let mut clients = crate::core_loop::fanout::subscribers_by_id(state, window, mask_bit); let evtype = xi2_evtype_for(event); - let forms = key_xi2_forms(state, event.origin); for (id, client) in &state.clients { if !clients.contains(&ClientId(*id)) && forms @@ -1852,6 +1923,7 @@ fn key_selectors( fn key_grabbed_natural_target( state: &ServerState, event: &HostKeyEvent, + forms: &KeyXi2Forms, owner: ClientId, via_xi2: bool, synthetic_repeat: bool, @@ -1888,14 +1960,24 @@ fn key_grabbed_natural_target( }; let mut cur = start; for _ in 0..256 { - let owner_selects = key_selectors(state, event, cur, mask_bit).contains(&owner); - if owner_selects - && grab_owner_qualifies(state, event, owner, cur, via_xi2, synthetic_repeat) - { - return Some(cur); - } - if foreign_selection_rejects(state, event, owner, cur, synthetic_repeat) { - return None; + let selectors = key_selectors(state, event, forms, cur, mask_bit); + if !state.policies_installed() { + if selectors.contains(&owner) { + return Some(cur); + } + if !selectors.is_empty() { + return None; + } + } else { + let owner_selects = selectors.contains(&owner); + if owner_selects + && grab_owner_qualifies(state, event, owner, cur, via_xi2, synthetic_repeat) + { + return Some(cur); + } + if foreign_selection_rejects(state, event, forms, owner, cur, synthetic_repeat) { + return None; + } } if cur == stop { return None; diff --git a/crates/yserver-core/src/core_loop/pointer_fanout/xi1.rs b/crates/yserver-core/src/core_loop/pointer_fanout/xi1.rs index a36ac643e..333206a70 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout/xi1.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout/xi1.rs @@ -371,14 +371,18 @@ pub(super) fn xi1_allowed_selectors( receive: Option<&mut ReceiveMemo>, ) -> Vec { let mut selectors = xi1_window_selectors(state, window, q.evcode, q.deviceid); - if let Some(memo) = receive { - let batch = xi1_batch(q.evcode); - let events = EventBatch::new(batch.as_slice()); - selectors.retain(|client| { - xi1_gets_no_copy(state, q, *client) - || memo.allows(state, *client, EventSubject::Window(window), &events) - }); + if !state.policies_installed() || selectors.is_empty() { + return selectors; } + let Some(memo) = receive else { + return selectors; + }; + let batch = xi1_batch(q.evcode); + let events = EventBatch::new(batch.as_slice()); + selectors.retain(|client| { + xi1_gets_no_copy(state, q, *client) + || memo.allows(state, *client, EventSubject::Window(window), &events) + }); selectors } @@ -407,13 +411,17 @@ pub(super) fn xi1_owner_events_window( owner: ClientId, receive: &mut ReceiveMemo, ) -> Option { - let batch = xi1_batch(q.evcode); - let events = EventBatch::new(batch.as_slice()); + let policies_installed = state.policies_installed(); for window in xi1_route_windows(state, q) { let selectors = xi1_window_selectors(state, window, q.evcode, q.deviceid); if selectors.is_empty() { continue; } + if !policies_installed { + return selectors.contains(&owner).then_some(window); + } + let batch = xi1_batch(q.evcode); + let events = EventBatch::new(batch.as_slice()); let mut copy_allowed = |client: ClientId| { xi1_gets_no_copy(state, q, client) || receive.allows(state, client, EventSubject::Window(window), &events) @@ -440,9 +448,14 @@ pub(super) fn xi1_grab_window_copy_allowed( owner: ClientId, grab_window: ResourceId, ) -> bool { + if xi1_gets_no_copy(state, q, owner) { + return false; + } + if !state.policies_installed() { + return true; + } let batch = xi1_batch(q.evcode); - !xi1_gets_no_copy(state, q, owner) - && grab_window_allows_batch(state, owner, grab_window, batch.as_slice()) + grab_window_allows_batch(state, owner, grab_window, batch.as_slice()) } /// The XI1 passive grab an XI1 press activates, if any (the replay floor @@ -508,7 +521,7 @@ pub(super) fn resolve_slave_press_delivery( } let mut xi1_recipients = xi1_window_selectors(state, window, xi1_evcode, deviceid); - if xi1_checked && !xi1_recipients.is_empty() { + if xi1_checked && state.policies_installed() && !xi1_recipients.is_empty() { let xi1_description = xi1_batch(xi1_evcode); let xi1_events = EventBatch::new(xi1_description.as_slice()); xi1_recipients.retain(|client| { From 7d1b37ef3aba97ab0ed6e23fc3d590549a6b271b Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Thu, 3 Dec 2026 15:47:43 -0300 Subject: [PATCH 68/72] perf(access): Task 2 review round, smaller key planning The XI2 key forms are a plain two-slot array at fixed slave and master positions, and KeyCopies keeps one recipient vector per slot. The focus walk is one loop; with an empty policy list it skips windows where no client's client_key_plan stops before planning copies. The grabbed walk answers owner and foreign selection with the same predicate, so key_selectors is gone. With a policy installed the client-major pass, owner-then-foreign order and write order are unchanged. Co-Authored-By: Claude Opus 5.5 Implemented-By: codex (gpt-6-luna max) --- .../yserver-core/src/core_loop/key_fanout.rs | 182 +++++++----------- 1 file changed, 73 insertions(+), 109 deletions(-) diff --git a/crates/yserver-core/src/core_loop/key_fanout.rs b/crates/yserver-core/src/core_loop/key_fanout.rs index 683247c9b..dcc1b7816 100644 --- a/crates/yserver-core/src/core_loop/key_fanout.rs +++ b/crates/yserver-core/src/core_loop/key_fanout.rs @@ -571,7 +571,7 @@ fn deliver_routed_key_with_master_status( false, synthetic_repeat, ); - write_key_copies(state, &event, target, &copies, synthetic_repeat) + write_key_copies(state, &event, &xi2_forms, target, &copies, synthetic_repeat) }; merge_dropped( &mut dropped, @@ -683,7 +683,8 @@ fn deliver_routed_key_with_master_status( master_transition_accepted, synthetic_repeat, ); - let mut dropped = write_key_copies(state, &event, target, &copies, synthetic_repeat); + let mut dropped = + write_key_copies(state, &event, &xi2_forms, target, &copies, synthetic_repeat); merge_dropped( &mut dropped, deliver_xi1_focused_key(state, &event, synthetic_repeat), @@ -725,7 +726,7 @@ pub(crate) fn replay_frozen_key_to_focus_after_transition( master_transition_accepted, synthetic_repeat, ); - let mut dropped = write_key_copies(state, &event, focus, &copies, synthetic_repeat); + let mut dropped = write_key_copies(state, &event, &xi2_forms, focus, &copies, synthetic_repeat); merge_dropped( &mut dropped, deliver_xi1_focused_key(state, &event, synthetic_repeat), @@ -739,16 +740,10 @@ pub(crate) fn replay_frozen_key_to_focus_after_transition( struct KeyCopies { core: Vec, /// Per-form recipient slots, slave form before master. - xi2: [Option; 2], + xi2: [Vec; 2], stops: bool, } -struct KeyXi2Copies { - device_id: u16, - source_id: u16, - targets: Vec, -} - /// One client's decision for one key event at one window. #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct ClientKeyPlan { @@ -762,16 +757,7 @@ struct ClientKeyPlan { /// The slave-first XI2 forms one key event can carry. Their two fixed slots /// are shared by every window and client plan for the event. -#[derive(Clone, Copy, Debug, Default)] -struct KeyXi2Forms { - forms: [Option<(u16, u16)>; 2], -} - -impl KeyXi2Forms { - fn iter(&self) -> impl Iterator { - self.forms.iter().flatten() - } -} +type KeyXi2Forms = [Option<(u16, u16)>; 2]; /// The per-selection predicate of the input routing (spec l.353–420), for one /// client at one window: whether its selections stop the focus walk, and which @@ -816,6 +802,7 @@ fn client_key_plan( // An XI2 selection the include flags exclude produces no copy: it stops. if forms .iter() + .flatten() .any(|(device_id, _)| !included(*device_id) && selected(*device_id)) { stops = true; @@ -825,6 +812,7 @@ fn client_key_plan( // allowed one produces a copy and stops; a denied one neither. let selects_included_xi2 = forms .iter() + .flatten() .any(|(device_id, _)| included(*device_id) && selected(*device_id)); let xi2_copy = if !selects_included_xi2 { false @@ -879,17 +867,7 @@ fn key_copies_at( let subject = EventSubject::Window(window); let mut stops = false; let mut core = Vec::new(); - let mut xi2 = [None, None]; - for (slot, &(device_id, source_id)) in xi2.iter_mut().zip(forms.iter()) { - if !include_master_form && device_id == XI2_MASTER_KEYBOARD_DEVICE_ID { - continue; - } - *slot = Some(KeyXi2Copies { - device_id, - source_id, - targets: Vec::new(), - }); - } + let mut xi2 = [Vec::new(), Vec::new()]; for id in state.clients.keys() { let client = ClientId(*id); let plan = client_key_plan( @@ -910,9 +888,12 @@ fn key_copies_at( if plan.xi2_copy && let Some(record) = state.clients.get(id) { - for copies in xi2.iter_mut().flatten() { - if key_xi2_form_selected(record, window, copies.device_id, xi2_evtype_for(event)) { - copies.targets.push(client); + for (form, targets) in forms.iter().zip(&mut xi2) { + if let Some((device_id, _)) = form + && (include_master_form || *device_id != XI2_MASTER_KEYBOARD_DEVICE_ID) + && key_xi2_form_selected(record, window, *device_id, xi2_evtype_for(event)) + { + targets.push(client); } } } @@ -925,6 +906,7 @@ fn key_copies_at( fn write_key_copies( state: &mut ServerState, event: &HostKeyEvent, + forms: &KeyXi2Forms, window: ResourceId, copies: &KeyCopies, synthetic_repeat: bool, @@ -937,19 +919,22 @@ fn write_key_copies( x11::encode_key_event(buf, order, key_event_wire(event, seq, fields)); }) }; - for xi2 in copies.xi2.iter().flatten() { - if xi2.targets.is_empty() { + for (form, targets) in forms.iter().zip(&copies.xi2) { + let Some((device_id, source_id)) = form else { + continue; + }; + if targets.is_empty() { continue; } - let xi2_dropped = fanout_event_to_clients(state, &xi2.targets, |buf, seq, order| { + let xi2_dropped = fanout_event_to_clients(state, targets, |buf, seq, order| { encode_key_xi2_for_device( buf, order, seq, event, fields, - xi2.device_id, - xi2.source_id, + *device_id, + *source_id, synthetic_repeat, ); }); @@ -1167,18 +1152,14 @@ fn xi2_evtype_for(event: &HostKeyEvent) -> u16 { /// keyboard has only its slave form; attached sources also get a master copy. fn key_xi2_forms(state: &ServerState, origin: crate::core_loop::InputOrigin) -> KeyXi2Forms { let Some(source) = resolve_key_xi_source(state, origin) else { - return KeyXi2Forms::default(); + return [None, None]; }; - let mut forms = KeyXi2Forms::default(); - let mut next = 0; - if let Some(slave_id) = source.slave_deviceid { - forms.forms[next] = Some((slave_id, slave_id)); - next += 1; - } - if let Some(master_id) = source.attached_master { - forms.forms[next] = Some((master_id, source.sourceid)); - } - forms + [ + source.slave_deviceid.map(|slave_id| (slave_id, slave_id)), + source + .attached_master + .map(|master_id| (master_id, source.sourceid)), + ] } fn key_xi2_form_selected( @@ -1854,30 +1835,26 @@ fn focused_walk_target( let Some(depth) = chain.iter().position(|w| *w == focus) else { return (focus, copies_at(focus)); }; - if !state.policies_installed() { - let target = chain[..depth] - .iter() - .copied() - .find(|window| { - state.clients.keys().any(|id| { - client_key_plan( - state, - event, - forms, - *window, - ClientId(*id), - include_master_form, - include_core_form, - synthetic_repeat, - &|_| true, - ) - .stops - }) - }) - .unwrap_or(focus); - return (target, copies_at(target)); - } + let policies_installed = state.policies_installed(); for window in &chain[..depth] { + if !policies_installed + && !state.clients.keys().any(|id| { + client_key_plan( + state, + event, + forms, + *window, + ClientId(*id), + include_master_form, + include_core_form, + synthetic_repeat, + &|_| true, + ) + .stops + }) + { + continue; + } let copies = copies_at(*window); if copies.stops { return (*window, copies); @@ -1886,32 +1863,6 @@ fn focused_walk_target( (focus, copies_at(focus)) } -/// Clients that selected this key event on `window` in any form: the core -/// mask or the XI2 mask of one of the event's device forms. Xorg -/// `DeliverDeviceEvents` stops at the first window where -/// `EventIsDeliverable` finds any of them (dix/events.c), so a walk that -/// looks at the core masks alone runs past XI2-only selectors. -fn key_selectors( - state: &ServerState, - event: &HostKeyEvent, - forms: &KeyXi2Forms, - window: ResourceId, - mask_bit: u32, -) -> Vec { - let mut clients = crate::core_loop::fanout::subscribers_by_id(state, window, mask_bit); - let evtype = xi2_evtype_for(event); - for (id, client) in &state.clients { - if !clients.contains(&ClientId(*id)) - && forms - .iter() - .any(|(device_id, _)| key_xi2_form_selected(client, window, *device_id, evtype)) - { - clients.push(ClientId(*id)); - } - } - clients -} - /// Natural-delivery probe for an `owner_events` keyboard grab, Xorg /// `DeliverDeviceEvents` with the grab as client filter. It walks from the /// pointer window (if inside the focus subtree) or the focus up. At each window: @@ -1928,11 +1879,7 @@ fn key_grabbed_natural_target( via_xi2: bool, synthetic_repeat: bool, ) -> Option { - let mask_bit = if event.pressed { - KEY_PRESS_MASK - } else { - KEY_RELEASE_MASK - }; + let policies_installed = state.policies_installed(); let focus = current_focus(state); if focus == ResourceId(0) { return None; @@ -1960,16 +1907,33 @@ fn key_grabbed_natural_target( }; let mut cur = start; for _ in 0..256 { - let selectors = key_selectors(state, event, forms, cur, mask_bit); - if !state.policies_installed() { - if selectors.contains(&owner) { + let selects = |client| { + client_key_plan( + state, + event, + forms, + cur, + client, + true, + true, + synthetic_repeat, + &|_| true, + ) + .stops + }; + let owner_selects = selects(owner); + if !policies_installed { + if owner_selects { return Some(cur); } - if !selectors.is_empty() { + if state + .clients + .keys() + .any(|id| ClientId(*id) != owner && selects(ClientId(*id))) + { return None; } } else { - let owner_selects = selectors.contains(&owner); if owner_selects && grab_owner_qualifies(state, event, owner, cur, via_xi2, synthetic_repeat) { From d4cee920c59bbf37cd6de59b66f6867466e54697 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Thu, 3 Dec 2026 17:00:26 -0300 Subject: [PATCH 69/72] test(access): compact the input row tables The runner keeps one per-step byte capture and one hook trace instead of parallel copies. The physical-pointer fixture, the XI1 class helper and repeated outcome fragments are shared. Every row and checkpoint is kept; the four files go from 6,450 to 6,364 lines. Co-Authored-By: Claude Opus 5.5 Implemented-By: codex (gpt-6-luna xhigh) --- .../tests/access_input_support.rs | 284 +++-- .../process_request/tests/access_key_input.rs | 380 ++++--- .../tests/access_pointer_input.rs | 971 ++++++++---------- .../tests/access_replay_input.rs | 691 ++++++------- 4 files changed, 1120 insertions(+), 1206 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index ba06f2a20..d85475bb5 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -11,7 +11,7 @@ use super::{ use crate::{ access::{Decision, EventDescription, EventSubject, RequestOpcodes}, core_loop::{ - InputOrigin, client_io, + DeviceInfo, InputOrigin, client_io, key_fanout::{ RawKeyEvent, key_event_fanout_after_transition, key_event_fanout_to_state, raw_key_event_to_state, @@ -23,10 +23,13 @@ use crate::{ nested::XI2_MAJOR_OPCODE, resources::ROOT_WINDOW, server::{QueuedInputEvent, ServerState, Xi1SyncState}, - xinput::DEVICEID_XTEST_KEYBOARD, + xinput::{ + DEVICEID_MASTER_POINTER, DEVICEID_XTEST_KEYBOARD, DEVICEID_XTEST_POINTER, + InputCapabilities, InputSourceId, + }, }; use std::{cell::RefCell, collections::BTreeMap, sync::atomic::Ordering}; -use yserver_protocol::x11::{ClientByteOrder, ClientId, RequestHeader, SequenceNumber}; +use yserver_protocol::x11::{ClientByteOrder, ClientId, RequestHeader, ResourceId, SequenceNumber}; pub(super) const SEND_CLIENT: u32 = 1; /// The client that selects on the child window (A). @@ -57,6 +60,36 @@ pub(super) const XI_KEY_PRESS_AND_RELEASE: u32 = XI_KEY_PRESS | XI_KEY_RELEASE; pub(super) const XI_RAW_KEY_PRESS: u32 = 1 << 13; /// The grab window of the grab rows: the root is on no walk to FOCUS. pub(super) const ROOT: u32 = ROOT_WINDOW.0; +pub(super) const PHYSICAL_SOURCE: u64 = 0xA75_400; +pub(super) const PHYSICAL_DEVICE: u16 = 6; +pub(super) const PHYSICAL_POINTER: InputOrigin = + InputOrigin::Physical(InputSourceId(PHYSICAL_SOURCE)); + +pub(super) fn register_physical_pointer(f: &mut NotifyFixture) { + let info = DeviceInfo { + source_id: InputSourceId(PHYSICAL_SOURCE), + enabled: true, + resume_key: None, + capabilities: InputCapabilities { + keyboard: false, + pointer: true, + touch: false, + }, + name: format!("pointer source {PHYSICAL_SOURCE}"), + device_node: format!("/dev/input/event{PHYSICAL_SOURCE}"), + sysname: format!("event{PHYSICAL_SOURCE}"), + vendor_id: 1, + product_id: PHYSICAL_SOURCE as u32, + is_touchpad: false, + config: crate::core_loop::message::LibinputConfigSnapshot::default(), + }; + let ids = f.state.xi_register_source(&info); + assert_eq!(ids.first(), Some(&PHYSICAL_DEVICE), "physical pointer id"); +} + +pub(super) fn xi1_pointer_class_for(device: u16, offset: u8) -> u32 { + (u32::from(device) << 8) | u32::from(crate::server::XI_FIRST_EVENT + offset) +} thread_local! { /// Requests sent by the test helper since the runner's previous step. @@ -823,14 +856,24 @@ fn decoded_event_type(frame: &[u8], kind: Kind, order: ClientByteOrder) -> Optio } } +struct StepBytes { + bytes: Vec, + sequence: u16, +} + struct ClientBytes { client: u32, order: ClientByteOrder, - bytes: Vec, - /// Per step: the byte length after it and the client's sequence then. - steps: Vec<(usize, u16)>, - /// The bytes added for each step, for request replies and errors. - step_bytes: Vec>, + /// Bytes written and the sequence after each scenario step. + steps: Vec, +} + +fn client_frames<'a>(client: &'a ClientBytes) -> impl Iterator + 'a { + client.steps.iter().enumerate().flat_map(|(step, capture)| { + split_frames(&capture.bytes, client.order) + .into_iter() + .map(move |frame| (step, frame)) + }) } /// One fact of the grab state after a run. A row states the facts its denied @@ -869,6 +912,29 @@ pub(super) enum Grab { Queued { device: u16, held: Held }, } +pub(super) const A_ROOT_KEYBOARD_GRAB: Grab = Grab::Keyboard { + owner: A, + window: ROOT, +}; +pub(super) const A_ROOT_XI1_POINTER_GRAB: Grab = Grab::Xi1 { + device: DEVICEID_XTEST_POINTER, + owner: A, + window: ROOT, +}; +pub(super) const B_CHILD_XI1_POINTER_GRAB: Grab = Grab::Xi1 { + device: DEVICEID_XTEST_POINTER, + owner: B, + window: CHILD, +}; +pub(super) const XTEST_POINTER_DETACHED: Grab = Grab::Detached { + device: DEVICEID_XTEST_POINTER, + master: DEVICEID_MASTER_POINTER, +}; +pub(super) const PHYSICAL_POINTER_DETACHED: Grab = Grab::Detached { + device: PHYSICAL_DEVICE, + master: DEVICEID_MASTER_POINTER, +}; + /// A withheld input event: the `QueuedInputEvent` variant and the fields that /// tell the variants apart. #[derive(Clone, Copy, Debug, PartialEq)] @@ -948,13 +1014,15 @@ pub(super) struct PointerGrab { pub(super) via_xi2: bool, } +struct Hook { + step: usize, + call: RecordedExtensionCheck, +} + struct Run { clients: Vec, - calls: Vec, - /// The event types of the step that made each call, parallel to `calls`. - call_evs: Vec>, - /// Every hook, with the scenario step that caused it. - hooks: Vec<(usize, RecordedExtensionCheck)>, + /// Each recorded extension hook, with the scenario step that caused it. + hooks: Vec, /// Requests the runner's `request()` helper sent, by step: client, major /// opcode and data byte (the extension minor opcode). requests: Vec<(usize, u32, u8, u8)>, @@ -1060,14 +1128,11 @@ pub(super) fn grouped( fn delivered(name: &str, run: &Run, steps: &[Vec<(u16, u32)>]) -> Vec { let mut frames = Vec::new(); for client in &run.clients { - for frame in split_frames(&client.bytes, client.order) { + for (step, frame) in client_frames(client) { if let Some((kind, window)) = decode(frame, client.order) { - let offset = frame.as_ptr() as usize - client.bytes.as_ptr() as usize; - let step = client.steps.iter().position(|(end, _)| offset < *end); - let step = step.expect("a frame belongs to a step"); let sequence = match client.order { - ClientByteOrder::LittleEndian => client.steps[step].1.to_le_bytes(), - ClientByteOrder::BigEndian => client.steps[step].1.to_be_bytes(), + ClientByteOrder::LittleEndian => client.steps[step].sequence.to_le_bytes(), + ClientByteOrder::BigEndian => client.steps[step].sequence.to_be_bytes(), }; assert_eq!( &frame[2..4], @@ -1173,6 +1238,31 @@ pub(super) const NOTHING: Outcome = Outcome { grab: None, }; +pub(super) const fn frames_and_calls(frames: &'static [Frame], calls: &'static [Call]) -> Outcome { + Outcome { + frames, + calls, + ..NOTHING + } +} + +pub(super) const A_CORE_CHILD: Outcome = + frames_and_calls(&[(A, Kind::Core, CHILD)], &[(A, CallKind::Core, CHILD)]); + +pub(super) const fn calls_only(calls: &'static [Call]) -> Outcome { + Outcome { calls, ..NOTHING } +} + +pub(super) const fn with_moved(mut outcome: Outcome, moved: &'static [Move]) -> Outcome { + outcome.moved = moved; + outcome +} + +pub(super) const fn with_grab(mut outcome: Outcome, grab: &'static [Grab]) -> Outcome { + outcome.grab = Some(grab); + outcome +} + /// A setup, the steps run after it, and the allow-all outcome. Rows that share /// a scenario differ in what they deny. pub(super) struct Scenario { @@ -1238,12 +1328,9 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run .map(|client| ClientBytes { client, order: f.state.clients[&client].byte_order, - bytes: Vec::new(), steps: Vec::new(), - step_bytes: Vec::new(), }) .collect(); - let mut call_evs = Vec::new(); let mut seen_calls = 0; let mut call_steps = Vec::new(); let mut requests = Vec::new(); @@ -1264,17 +1351,14 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run .map(|(client, major, data)| (index, client, major, data)), ); for client in &mut clients { - let step_bytes = f.drain(ClientId(client.client)); - client.bytes.extend_from_slice(&step_bytes); - client.step_bytes.push(step_bytes); + let bytes = f.drain(ClientId(client.client)); let sequence = f.state.clients[&client.client] .last_sequence .load(Ordering::Relaxed); - client.steps.push((client.bytes.len(), sequence)); + client.steps.push(StepBytes { bytes, sequence }); } if let Some(recorder) = &recorder { let total = recorder.lock().unwrap().len(); - call_evs.extend((seen_calls..total).map(|_| step_evs[index].clone())); call_steps.extend((seen_calls..total).map(|_| index)); seen_calls = total; } @@ -1292,49 +1376,20 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run .iter() .cloned() .zip(call_steps) - .map(|(call, step)| (step, call)) + .map(|(call, step)| Hook { step, call }) .collect() }) .unwrap_or_default(); - // Keep the named Receive calls, with the event type of the step that made - // each. Other hooks are checked separately against the request step. - let (calls, call_evs) = recorder - .map(|recorder| { - recorder - .lock() - .unwrap() - .iter() - .zip(call_evs) - .filter(|(call, _)| call.hook == ExtensionHook::Receive) - .filter_map(|(call, ev)| { - let EventSubject::Window(window) = call.receive? else { - panic!("{name}: Receive subject {:?}", call.receive); - }; - let seen = (call.client.0, names_of(call.events.as_deref()?)?, window.0); - Some((seen, ev)) - }) - .unzip() - }) - .unwrap_or_default(); let replies = clients .iter() .flat_map(|client| { - client - .step_bytes - .iter() - .enumerate() - .flat_map(move |(step, bytes)| { - split_frames(bytes, client.order) - .into_iter() - .filter(|frame| matches!(frame[0], 0 | 1)) - .map(move |frame| (step, client.client, frame[0])) - }) + client_frames(client) + .filter(|(_, frame)| matches!(frame[0], 0 | 1)) + .map(move |(step, frame)| (step, client.client, frame[0])) }) .collect(); Run { clients, - calls, - call_evs, hooks, requests, replies, @@ -1377,12 +1432,13 @@ fn moved_frames(name: &str, allow: &Run, denied: &Run) -> Vec<(u32, Move)> { .iter() .find(|c| c.client == got.client) .expect("allow-all stream for the client"); - let allowed_frames: Vec<_> = split_frames(&allowed.bytes, allowed.order) - .into_iter() - .filter_map(|frame| decode(frame, allowed.order).map(|(k, w)| (k, w, frame))) + let allowed_frames: Vec<_> = client_frames(allowed) + .filter_map(|(_, frame)| { + decode(frame, allowed.order).map(|(kind, window)| (kind, window, frame)) + }) .collect(); let mut seen: Vec<(Kind, u32)> = Vec::new(); - for frame in split_frames(&got.bytes, got.order) { + for (_, frame) in client_frames(got) { let Some((kind, window)) = decode(frame, got.order) else { continue; }; @@ -1437,13 +1493,33 @@ fn canonical_call(call: &Call) -> Seen { expected_call(call, 0) } +fn receive_calls(name: &str, scenario: &Scenario, run: &Run) -> Vec<(usize, Seen, Vec)> { + let events = step_events(scenario); + run.hooks + .iter() + .enumerate() + .filter_map(|(index, hook)| { + let call = &hook.call; + if call.hook != ExtensionHook::Receive { + return None; + } + let EventSubject::Window(window) = call.receive? else { + panic!("{name}: Receive subject {:?}", call.receive); + }; + let names = names_of(call.events.as_deref()?)?; + let event_types = events[hook.step].iter().map(|event| event.ev()).collect(); + Some((index, (call.client.0, names, window.0), event_types)) + }) + .collect() +} + fn check_hooks(name: &str, mode: &str, scenario: &Scenario, run: &Run) { for (step_index, step) in scenario.steps.iter().enumerate() { let actual: Vec<_> = run .hooks .iter() - .filter(|(index, call)| *index == step_index && call.hook != ExtensionHook::Receive) - .map(|(_, call)| call) + .filter(|hook| hook.step == step_index && hook.call.hook != ExtensionHook::Receive) + .map(|hook| &hook.call) .collect(); let request = run .requests @@ -1493,11 +1569,9 @@ fn check_hooks(name: &str, mode: &str, scenario: &Scenario, run: &Run) { /// call names the event of the step that made it (`Core(0)` below). fn check_outcome(name: &str, mode: &str, scenario: &Scenario, run: &Run, want: &Outcome) { check_hooks(name, mode, scenario, run); - let got: Vec = run - .calls + let got: Vec = receive_calls(name, scenario, run) .iter() - .zip(&run.call_evs) - .map(|(call, evs)| canonical_seen(call, evs)) + .map(|(_, call, evs)| canonical_seen(call, evs)) .collect(); let calls: Vec = want.calls.iter().map(canonical_call).collect(); let calls_match = match scenario.order { @@ -1585,16 +1659,17 @@ pub(super) fn assert_swapped_request_calls_fail( ) { let run = play(name, scenario, Some(&[])); check_outcome(name, "allow-all", scenario, &run, &scenario.allow); + let calls = receive_calls(name, scenario, &run); let call_index = |event| { - run.calls + calls .iter() - .zip(&run.call_evs) - .position(|(call, evs)| { + .find(|(_, call, evs)| { call.0 == client && call.1.as_slice() == [Named::Xi2(event)] && call.2 == window && evs.as_slice() == request_events }) + .map(|(index, _, _)| *index) .unwrap_or_else(|| panic!("{name}: request recorded the XI2 event {event}")) }; let first = call_index(first_event); @@ -1605,7 +1680,11 @@ pub(super) fn assert_swapped_request_calls_fail( ); let mut swapped = run; - swapped.calls.swap(first, second); + let (before_second, second_and_after) = swapped.hooks.split_at_mut(second); + std::mem::swap( + &mut before_second[first].call, + &mut second_and_after[0].call, + ); let rejected = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { check_outcome(name, "allow-all", scenario, &swapped, &scenario.allow); })); @@ -1632,7 +1711,16 @@ fn check_input_row(row: &InputRow) { let bytes = |run: &Run| { run.clients .iter() - .map(|c| c.bytes.clone()) + .map(|c| { + ( + c.client, + c.order, + c.steps + .iter() + .flat_map(|step| step.bytes.iter().copied()) + .collect::>(), + ) + }) .collect::>() }; assert_eq!( @@ -1704,6 +1792,29 @@ mod batch_naming { fn no_request(_: &mut NotifyFixture) {} + fn receive_check(event: u16) -> RecordedExtensionCheck { + RecordedExtensionCheck { + hook: ExtensionHook::Receive, + client: ClientId(A), + extension: "XInputExtension".to_owned(), + request: None, + peer: None, + admission: None, + target: None, + property: None, + mode: None, + send: None, + receive: Some(EventSubject::Window(ResourceId(CHILD))), + events: Some(vec![EventDescription::extension( + 35, + XI2_MAJOR_OPCODE, + event, + )]), + owner: None, + target_owner: None, + } + } + fn run_with_xi2_frame(evtype: u16, detail: u32) -> Run { let order = ClientByteOrder::BigEndian; let mut frame = [0_u8; 32]; @@ -1717,12 +1828,11 @@ mod batch_naming { clients: vec![ClientBytes { client: A, order, - bytes: frame.to_vec(), - steps: vec![(frame.len(), 0)], - step_bytes: vec![frame.to_vec()], + steps: vec![StepBytes { + bytes: frame.to_vec(), + sequence: 0, + }], }], - calls: Vec::new(), - call_evs: Vec::new(), hooks: Vec::new(), requests: Vec::new(), replies: Vec::new(), @@ -1818,12 +1928,18 @@ mod batch_naming { }, order: CallOrder::Total, }; - let one_press_call = (A, vec![Named::Xi2(4)], CHILD); let run = Run { clients: Vec::new(), - calls: vec![one_press_call.clone(), one_press_call], - call_evs: vec![vec![4, 4], vec![4, 4]], - hooks: Vec::new(), + hooks: vec![ + Hook { + step: 0, + call: receive_check(4), + }, + Hook { + step: 0, + call: receive_check(4), + }, + ], requests: vec![(0, A, 35, 0)], replies: Vec::new(), state: String::new(), diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs index 531b219c5..a37db9585 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -299,47 +299,35 @@ const A_GRABS_SLAVE: &[Grab] = &[ ]; /// The grab facts of an active core keyboard grab by A on the root. -const A_GRABS_ROOT: &[Grab] = &[Grab::Keyboard { - owner: A, - window: ROOT, -}]; - -/// A press delivered by an allow-all policy to A at CHILD by a core selection. -const A_AT_CHILD: Outcome = Outcome { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - ..NOTHING -}; +const A_GRABS_ROOT: &[Grab] = &[A_ROOT_KEYBOARD_GRAB]; const K1_SCENARIO: Scenario = Scenario { setup: setup_k1, steps: &[PRESS], - allow: A_AT_CHILD, + allow: A_CORE_CHILD, order: CallOrder::Total, }; const K3_SCENARIO: Scenario = Scenario { setup: setup_k3, steps: &[PRESS], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - ..NOTHING - }, + allow: frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), CHILD)], + &[(A, CallKind::Xi2, CHILD)], + ), order: CallOrder::Total, }; const K4_SCENARIO: Scenario = Scenario { setup: setup_k4, steps: &[XTEST_PRESS], - allow: Outcome { - frames: &[ + allow: frames_and_calls( + &[ (A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD), (A, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), CHILD), ], - calls: &[(A, CallKind::Xi2, CHILD)], - ..NOTHING - }, + &[(A, CallKind::Xi2, CHILD)], + ), order: CallOrder::Total, }; @@ -362,11 +350,10 @@ const K5_DETECTABLE_SCENARIO: Scenario = Scenario { const K5B_SCENARIO: Scenario = Scenario { setup: setup_k5b, steps: &[SLAVE_PRESS], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - ..NOTHING - }, + allow: frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD)], + &[(A, CallKind::Xi2, CHILD)], + ), order: CallOrder::Total, }; @@ -380,23 +367,23 @@ const K5B_MASTER_SCENARIO: Scenario = Scenario { const K5C_GRAB_SCENARIO: Scenario = Scenario { setup: setup_k5c_grab, steps: &[SLAVE_PRESS], - allow: Outcome { - grab: Some(A_GRABS_SLAVE), - frames: &[(A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), FOCUS)], - calls: &[(A, CallKind::Xi2, FOCUS)], - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), FOCUS)], + &[(A, CallKind::Xi2, FOCUS)], + ), + A_GRABS_SLAVE, + ), order: CallOrder::Total, }; const K5C_FOCUS_SCENARIO: Scenario = Scenario { setup: setup_k5c_focus, steps: &[SLAVE_PRESS], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - ..NOTHING - }, + allow: frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD)], + &[(A, CallKind::Xi2, CHILD)], + ), order: CallOrder::Total, }; @@ -405,7 +392,7 @@ const K7_SCENARIO: Scenario = Scenario { steps: &[PRESS], allow: Outcome { grab: Some(A_GRABS_ROOT), - ..A_AT_CHILD + ..A_CORE_CHILD }, order: CallOrder::Total, }; @@ -415,7 +402,7 @@ const K8_SCENARIO: Scenario = Scenario { steps: &[PRESS], allow: Outcome { grab: Some(A_GRABS_ROOT), - ..A_AT_CHILD + ..A_CORE_CHILD }, order: CallOrder::PerClient, }; @@ -423,29 +410,22 @@ const K8_SCENARIO: Scenario = Scenario { const K10_SCENARIO: Scenario = Scenario { setup: setup_k10, steps: &[SYNTH_RELEASE], - allow: Outcome { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(A, CallKind::Core, ROOT)], - grab: Some(A_GRABS_ROOT), - ..NOTHING - }, + allow: with_grab( + frames_and_calls(&[(A, Kind::Core, ROOT)], &[(A, CallKind::Core, ROOT)]), + A_GRABS_ROOT, + ), order: CallOrder::Total, }; -const A_ROOT_COPY: Outcome = Outcome { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(A, CallKind::Core, ROOT)], - grab: Some(A_GRABS_ROOT), - ..NOTHING -}; +const A_ROOT_COPY: Outcome = with_grab( + frames_and_calls(&[(A, Kind::Core, ROOT)], &[(A, CallKind::Core, ROOT)]), + A_GRABS_ROOT, +); /// A holds the activating sync grab: the press freezes the master keyboard /// with the press stored. const K12_GRABS: &[Grab] = &[ - Grab::Keyboard { - owner: A, - window: ROOT, - }, + A_ROOT_KEYBOARD_GRAB, Grab::Freeze { device: DEVICEID_MASTER_KEYBOARD, state: Xi1SyncState::FrozenWithEvent, @@ -462,19 +442,18 @@ const K12_GRABS: &[Grab] = &[ const K13_RAW_SCENARIO: Scenario = Scenario { setup: setup_k13_raw, steps: &[XTEST_RAW_PRESS], - allow: Outcome { - frames: &[ + allow: frames_and_calls( + &[ (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), (B, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), (SEND_CLIENT, Kind::Raw(DEVICEID_XTEST_KEYBOARD), ROOT), ], - calls: &[ + &[ (SEND_CLIENT, CallKind::Raw, ROOT), (A, CallKind::Raw, ROOT), (B, CallKind::Raw, ROOT), ], - ..NOTHING - }, + ), order: CallOrder::PerClient, }; @@ -485,15 +464,16 @@ const K14_GRABS: &[Grab] = &[Grab::Keyboard { owner: A, window: CHILD, }]; -const K14_ALLOW: Outcome = Outcome { - frames: &[ - (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), - (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), - ], - calls: &[(A, CallKind::Raw, ROOT), (A, CallKind::Raw, ROOT)], - grab: Some(K14_GRABS), - ..NOTHING -}; +const K14_ALLOW: Outcome = with_grab( + frames_and_calls( + &[ + (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + ], + &[(A, CallKind::Raw, ROOT), (A, CallKind::Raw, ROOT)], + ), + K14_GRABS, +); // ---- rows ---------------------------------------------------------------- @@ -502,57 +482,58 @@ const ROWS: &[InputRow] = &[ name: "k1_denied_pointer_window_selector_advances_the_focus_walk", scenario: &K1_SCENARIO, deny: &[(A, CallKind::Core, CHILD)], - denied: Outcome { - frames: &[(B, Kind::Core, FOCUS)], - moved: &[moved(B, Kind::Core, FOCUS, CHILD, (20, 20))], - calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, FOCUS)], - ..NOTHING - }, + denied: with_moved( + frames_and_calls( + &[(B, Kind::Core, FOCUS)], + &[(A, CallKind::Core, CHILD), (B, CallKind::Core, FOCUS)], + ), + &[moved(B, Kind::Core, FOCUS, CHILD, (20, 20))], + ), }, InputRow { name: "k2_one_allowed_selector_stops_the_walk", scenario: &Scenario { setup: setup_k2, steps: &[PRESS], - allow: Outcome { - frames: &[(A, Kind::Core, CHILD), (B, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, CHILD)], - ..NOTHING - }, + allow: frames_and_calls( + &[(A, Kind::Core, CHILD), (B, Kind::Core, CHILD)], + &[(A, CallKind::Core, CHILD), (B, CallKind::Core, CHILD)], + ), order: CallOrder::PerClient, }, deny: &[(A, CallKind::Core, CHILD)], - denied: Outcome { - frames: &[(B, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, CHILD)], - ..NOTHING - }, + denied: frames_and_calls( + &[(B, Kind::Core, CHILD)], + &[(A, CallKind::Core, CHILD), (B, CallKind::Core, CHILD)], + ), }, InputRow { name: "k3_denied_xi2_copy_reopens_core_for_that_client", scenario: &K3_SCENARIO, deny: &[(A, CallKind::Xi2, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Core, CHILD)], - moved: &[moved(A, Kind::Core, CHILD, 0, (10, 10))], - calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], - ..NOTHING - }, + denied: with_moved( + frames_and_calls( + &[(A, Kind::Core, CHILD)], + &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], + ), + &[moved(A, Kind::Core, CHILD, 0, (10, 10))], + ), }, InputRow { name: "k3_both_denied_walks_on_to_the_focus", scenario: &K3_SCENARIO, deny: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], - denied: Outcome { - frames: &[(B, Kind::Core, FOCUS)], - moved: &[moved(B, Kind::Core, FOCUS, CHILD, (20, 20))], - calls: &[ - (A, CallKind::Xi2, CHILD), - (A, CallKind::Core, CHILD), - (B, CallKind::Core, FOCUS), - ], - ..NOTHING - }, + denied: with_moved( + frames_and_calls( + &[(B, Kind::Core, FOCUS)], + &[ + (A, CallKind::Xi2, CHILD), + (A, CallKind::Core, CHILD), + (B, CallKind::Core, FOCUS), + ], + ), + &[moved(B, Kind::Core, FOCUS, CHILD, (20, 20))], + ), }, // The XI2 forms of one key share one check. With that check allowed the // denial list is empty, so the allowed row is this scenario's allow run. @@ -560,12 +541,13 @@ const ROWS: &[InputRow] = &[ name: "k4_xi2_forms_share_one_check_denied_reopens_core", scenario: &K4_SCENARIO, deny: &[(A, CallKind::Xi2, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Core, CHILD)], - moved: &[moved(A, Kind::Core, CHILD, 0, (10, 10))], - calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], - ..NOTHING - }, + denied: with_moved( + frames_and_calls( + &[(A, Kind::Core, CHILD)], + &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], + ), + &[moved(A, Kind::Core, CHILD, 0, (10, 10))], + ), }, InputRow { name: "k5_suppressed_xi2_release_stops_without_a_check", @@ -583,10 +565,7 @@ const ROWS: &[InputRow] = &[ name: "k5b_form_excluded_by_the_include_flags_still_stops", scenario: &K5B_SCENARIO, deny: &[(A, CallKind::Xi2, CHILD)], - denied: Outcome { - calls: &[(A, CallKind::Xi2, CHILD)], - ..NOTHING - }, + denied: calls_only(&[(A, CallKind::Xi2, CHILD)]), }, InputRow { name: "k5b_excluded_master_form_still_stops", @@ -598,100 +577,96 @@ const ROWS: &[InputRow] = &[ name: "k5c_slave_grab_write_is_checked", scenario: &K5C_GRAB_SCENARIO, deny: &[(A, CallKind::Xi2, FOCUS)], - denied: Outcome { - calls: &[(A, CallKind::Xi2, FOCUS)], - ..NOTHING - }, + denied: calls_only(&[(A, CallKind::Xi2, FOCUS)]), }, InputRow { name: "k5c_slave_focus_path_is_checked", scenario: &K5C_FOCUS_SCENARIO, deny: &[(A, CallKind::Xi2, CHILD)], - denied: Outcome { - calls: &[(A, CallKind::Xi2, CHILD)], - ..NOTHING - }, + denied: calls_only(&[(A, CallKind::Xi2, CHILD)]), }, InputRow { name: "k6_all_denied_lands_on_focus_with_a_stopping_focus_selector", scenario: &Scenario { setup: setup_k6a, steps: &[PRESS], - allow: A_AT_CHILD, + allow: A_CORE_CHILD, order: CallOrder::PerClient, }, deny: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - denied: Outcome { - frames: &[(B, Kind::Core, FOCUS)], - moved: &[moved(B, Kind::Core, FOCUS, CHILD, (20, 20))], - calls: &[ - (A, CallKind::Core, CHILD), - (A, CallKind::Core, FOCUS), - (B, CallKind::Core, FOCUS), - ], - ..NOTHING - }, + denied: with_moved( + frames_and_calls( + &[(B, Kind::Core, FOCUS)], + &[ + (A, CallKind::Core, CHILD), + (A, CallKind::Core, FOCUS), + (B, CallKind::Core, FOCUS), + ], + ), + &[moved(B, Kind::Core, FOCUS, CHILD, (20, 20))], + ), }, InputRow { name: "k6_only_selector_denied_lands_on_focus_and_writes_nothing", scenario: &Scenario { setup: setup_k6b, steps: &[PRESS], - allow: A_AT_CHILD, + allow: A_CORE_CHILD, order: CallOrder::Total, }, deny: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - denied: Outcome { - calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - ..NOTHING - }, + denied: calls_only(&[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)]), }, InputRow { name: "k7_denied_owner_copy_continues_the_natural_walk", scenario: &K7_SCENARIO, deny: &[(A, CallKind::Core, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Core, FOCUS)], - moved: &[moved(A, Kind::Core, FOCUS, CHILD, (20, 20))], - calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - ..NOTHING - }, + denied: with_moved( + frames_and_calls( + &[(A, Kind::Core, FOCUS)], + &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + ), + &[moved(A, Kind::Core, FOCUS, CHILD, (20, 20))], + ), }, InputRow { name: "k8_denied_owner_with_allowed_foreign_falls_back", scenario: &K8_SCENARIO, deny: &[(A, CallKind::Core, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Core, ROOT)], - moved: &[moved(A, Kind::Core, ROOT, FOCUS, (120, 120))], - calls: &[ - (A, CallKind::Core, CHILD), - (B, CallKind::Core, CHILD), - (A, CallKind::Core, ROOT), - ], - ..NOTHING - }, + denied: with_moved( + frames_and_calls( + &[(A, Kind::Core, ROOT)], + &[ + (A, CallKind::Core, CHILD), + (B, CallKind::Core, CHILD), + (A, CallKind::Core, ROOT), + ], + ), + &[moved(A, Kind::Core, ROOT, FOCUS, (120, 120))], + ), }, InputRow { name: "k9_denied_foreign_selector_does_not_reject", scenario: &Scenario { setup: setup_k9, steps: &[PRESS], - allow: Outcome { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, ROOT)], - grab: Some(A_GRABS_ROOT), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[(A, Kind::Core, ROOT)], + &[(B, CallKind::Core, CHILD), (A, CallKind::Core, ROOT)], + ), + A_GRABS_ROOT, + ), order: CallOrder::Total, }, deny: &[(B, CallKind::Core, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Core, FOCUS)], - moved: &[moved(A, Kind::Core, FOCUS, CHILD, (20, 20))], - calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - ..NOTHING - }, + denied: with_moved( + frames_and_calls( + &[(A, Kind::Core, FOCUS)], + &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + ), + &[moved(A, Kind::Core, FOCUS, CHILD, (20, 20))], + ), }, // A and B both select on CHILD and B is denied. A qualifies first, so the // walk stops at CHILD and no check is made for B. @@ -708,22 +683,23 @@ const ROWS: &[InputRow] = &[ steps: &[PRESS], allow: Outcome { grab: Some(A_GRABS_ROOT), - ..A_AT_CHILD + ..A_CORE_CHILD }, order: CallOrder::PerClient, }, deny: &[(A, CallKind::Core, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Core, ROOT)], - moved: &[moved(A, Kind::Core, ROOT, FOCUS, (120, 120))], - calls: &[ - (A, CallKind::Core, CHILD), - (B, CallKind::Core, CHILD), - (SEND_CLIENT, CallKind::Core, CHILD), - (A, CallKind::Core, ROOT), - ], - ..NOTHING - }, + denied: with_moved( + frames_and_calls( + &[(A, Kind::Core, ROOT)], + &[ + (A, CallKind::Core, CHILD), + (B, CallKind::Core, CHILD), + (SEND_CLIENT, CallKind::Core, CHILD), + (A, CallKind::Core, ROOT), + ], + ), + &[moved(A, Kind::Core, ROOT, FOCUS, (120, 120))], + ), }, InputRow { name: "k10_suppressed_foreign_selector_still_rejects", @@ -742,10 +718,7 @@ const ROWS: &[InputRow] = &[ order: CallOrder::Total, }, deny: &[(A, CallKind::Core, ROOT)], - denied: Outcome { - calls: &[(A, CallKind::Core, ROOT)], - ..NOTHING - }, + denied: calls_only(&[(A, CallKind::Core, ROOT)]), }, // The activating press is denied to A: the grab still activates and // freezes with the press stored. @@ -761,10 +734,7 @@ const ROWS: &[InputRow] = &[ order: CallOrder::Total, }, deny: &[(A, CallKind::Core, ROOT)], - denied: Outcome { - calls: &[(A, CallKind::Core, ROOT)], - ..NOTHING - }, + denied: calls_only(&[(A, CallKind::Core, ROOT)]), }, // A holds the slave keyboard's exact XI2 grab on FOCUS (owner_events // false): the synthetic XI2 release is suppressed in the grab's protocol. @@ -846,15 +816,14 @@ const ROWS: &[InputRow] = &[ order: CallOrder::Total, }, deny: &[(A, CallKind::Raw, ROOT)], - denied: Outcome { - frames: &[(A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT)], - calls: &[ + denied: frames_and_calls( + &[(A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT)], + &[ (A, CallKind::Raw, ROOT), (A, CallKind::Raw, CHILD), (A, CallKind::Raw, ROOT), ], - ..NOTHING - }, + ), }, // Without RawKeyPress in the grab mask nothing falls back, so the owner // gets no copy when its root copy is denied. @@ -867,10 +836,7 @@ const ROWS: &[InputRow] = &[ order: CallOrder::Total, }, deny: &[(A, CallKind::Raw, ROOT)], - denied: Outcome { - calls: K14_ALLOW.calls, - ..NOTHING - }, + denied: calls_only(K14_ALLOW.calls), }, // X selects the XI1 `DeviceKeyPress` on C (the pointer window, under focus // F), Y on F. X's copy is denied: the focus walk goes on and Y gets it at F. @@ -880,29 +846,29 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_k16, steps: &[XTEST_PRESS], - allow: Outcome { - frames: &[(A, Kind::Xi1Key(DEVICEID_XTEST_KEYBOARD), CHILD)], - calls: &[(A, XI1_KEY_PRESS_CALL, CHILD)], - ..NOTHING - }, + allow: frames_and_calls( + &[(A, Kind::Xi1Key(DEVICEID_XTEST_KEYBOARD), CHILD)], + &[(A, XI1_KEY_PRESS_CALL, CHILD)], + ), order: CallOrder::Total, }, deny: &[(A, XI1_KEY_PRESS_CALL, CHILD)], - denied: Outcome { - frames: &[(B, Kind::Xi1Key(DEVICEID_XTEST_KEYBOARD), FOCUS)], - moved: &[moved( + denied: with_moved( + frames_and_calls( + &[(B, Kind::Xi1Key(DEVICEID_XTEST_KEYBOARD), FOCUS)], + &[ + (A, XI1_KEY_PRESS_CALL, CHILD), + (B, XI1_KEY_PRESS_CALL, FOCUS), + ], + ), + &[moved( B, Kind::Xi1Key(DEVICEID_XTEST_KEYBOARD), FOCUS, CHILD, (20, 20), )], - calls: &[ - (A, XI1_KEY_PRESS_CALL, CHILD), - (B, XI1_KEY_PRESS_CALL, FOCUS), - ], - ..NOTHING - }, + ), }, // A synthetic repeat release to a detectable-repeat client gets no copy but // stops the walk: nothing is written, X is not asked, Y is not reached. diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index 42ea33365..1f89f3cbe 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -14,10 +14,10 @@ use super::{ access_input_support::*, access_notify_support::NotifyFixture, access_xi_notify::xi1_class, }; use crate::{ - core_loop::{DeviceInfo, InputOrigin}, + core_loop::InputOrigin, host_x11::PointerEventKind, server::Xi1SyncState, - xinput::{DEVICEID_MASTER_POINTER, DEVICEID_XTEST_POINTER, InputCapabilities, InputSourceId}, + xinput::{DEVICEID_MASTER_POINTER, DEVICEID_XTEST_POINTER}, }; use yserver_protocol::x11::{ClientId, ResourceId}; @@ -33,12 +33,8 @@ const XI_RAW_BUTTON_PRESS: u32 = 1 << 15; /// XIAllDevices, the device id that selects every device. const XI_ALL_DEVICES: u16 = 0; /// The source id of the physical pointer, and the device id the registry gives it. -const PHYSICAL_SOURCE: u64 = 0xA75_400; -const PHYSICAL_DEVICE: u16 = 6; - const XTEST_MASTER: InputOrigin = InputOrigin::XTest(DEVICEID_MASTER_POINTER); const XTEST_SLAVE: InputOrigin = InputOrigin::XTest(DEVICEID_XTEST_POINTER); -const PHYSICAL: InputOrigin = InputOrigin::Physical(InputSourceId(PHYSICAL_SOURCE)); const fn button(origin: InputOrigin, kind: PointerEventKind, to: (i16, i16)) -> Step { Step::Event(Drive::Pointer { @@ -74,7 +70,7 @@ const fn motion(origin: InputOrigin) -> Step { /// A physical wheel press (button 4) at C. const WHEEL_PRESS: Step = Step::Event(Drive::Pointer { - origin: PHYSICAL, + origin: PHYSICAL_POINTER, kind: PointerEventKind::ButtonPress, button: 4, to: POINTER, @@ -83,7 +79,7 @@ const WHEEL_PRESS: Step = Step::Event(Drive::Pointer { /// The two-Motion smooth-scroll stop of the physical pointer. const SCROLL_STOP: Step = Step::Event(Drive::ScrollStop { - origin: PHYSICAL, + origin: PHYSICAL_POINTER, at: POINTER, }); @@ -100,28 +96,6 @@ const MOTION_EVENT_AT_P: (i16, i16) = (MOTION_TO.0 - P_ORIGIN.0, MOTION_TO.1 - P // ---- setup helpers ------------------------------------------------------- -/// Registers a physical pointer source with the XI registry. -fn register_physical_pointer(f: &mut NotifyFixture) { - let info = DeviceInfo { - source_id: InputSourceId(PHYSICAL_SOURCE), - enabled: true, - resume_key: None, - capabilities: InputCapabilities { - keyboard: false, - pointer: true, - touch: false, - }, - name: format!("pointer source {PHYSICAL_SOURCE}"), - device_node: format!("/dev/input/event{PHYSICAL_SOURCE}"), - sysname: format!("event{PHYSICAL_SOURCE}"), - vendor_id: 1, - product_id: PHYSICAL_SOURCE as u32, - is_touchpad: false, - config: crate::core_loop::message::LibinputConfigSnapshot::default(), - }; - let _ = f.state.xi_register_source(&info); -} - /// Moves the sprite to the root position `at` before the row's event, so the /// slave pass starts from the window under it as it does in a session (Xorg /// delivers slave motion to the window the sprite left). Nothing is selected @@ -361,7 +335,7 @@ fn setup_p7(f: &mut NotifyFixture) { drive( f, Drive::Pointer { - origin: PHYSICAL, + origin: PHYSICAL_POINTER, kind: PointerEventKind::ButtonPress, button: 1, to: POINTER, @@ -816,11 +790,10 @@ const SLAVE_PASSIVE_GRAB: Grab = Grab::SlavePointer { }; /// A selects core on C, XI2 (master) on P; B selects core on P. -const P5B_ALLOW: Outcome = Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], - calls: &[(A, CallKind::Xi2, FOCUS)], - ..NOTHING -}; +const P5B_ALLOW: Outcome = frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], + &[(A, CallKind::Xi2, FOCUS)], +); const P5B: Scenario = Scenario { setup: setup_p5b, steps: &[press(XTEST_MASTER)], @@ -831,21 +804,20 @@ const P5B: Scenario = Scenario { const P15_PRESS: Scenario = Scenario { setup: setup_p15, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - grab: Some(&[implicit(A, CHILD, false)]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls(&[(A, Kind::Core, CHILD)], &[(A, CallKind::Core, CHILD)]), + &[implicit(A, CHILD, false)], + ), order: CallOrder::Total, }; -const P20B_ALLOW: Outcome = Outcome { - frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], - calls: &[(B, XI1_PRESS_CALL, FOCUS)], - grab: Some(&[xi1_implicit(B, FOCUS)]), - ..NOTHING -}; +const P20B_ALLOW: Outcome = with_grab( + frames_and_calls( + &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], + &[(B, XI1_PRESS_CALL, FOCUS)], + ), + &[xi1_implicit(B, FOCUS)], +); const P20B: Scenario = Scenario { setup: setup_p20b, steps: &[press(XTEST_SLAVE)], @@ -856,23 +828,23 @@ const P20B: Scenario = Scenario { const P22_GRAB: Scenario = Scenario { setup: setup_p22_grab, steps: &[WHEEL_PRESS], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], - calls: &[(A, CallKind::Xi2, ROOT), (A, SCROLL_MOTION_CALL, ROOT)], - ..NOTHING - }, + allow: frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], + &[(A, CallKind::Xi2, ROOT), (A, SCROLL_MOTION_CALL, ROOT)], + ), order: CallOrder::Total, }; const P26_OWNER_EVENTS: Scenario = Scenario { setup: setup_p26::, steps: &[press(XTEST_SLAVE)], - allow: Outcome { - frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[(A, XI1_PRESS_CALL, CHILD)], - grab: Some(&[xi1_implicit(A, ROOT)]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + &[(A, XI1_PRESS_CALL, CHILD)], + ), + &[xi1_implicit(A, ROOT)], + ), order: CallOrder::Total, }; /// A denied on C and B allowed there: A gets the press at G, after one fresh @@ -913,107 +885,91 @@ const P28_ACTIVATED: &[Grab] = &[ const P28_PRESS: Scenario = Scenario { setup: setup_p28, steps: &[press(XTEST_SLAVE)], - allow: Outcome { - frames: &[(SEND_CLIENT, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], - calls: &[(SEND_CLIENT, XI1_PRESS_CALL, FOCUS)], - grab: Some(P28_ACTIVATED), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[(SEND_CLIENT, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], + &[(SEND_CLIENT, XI1_PRESS_CALL, FOCUS)], + ), + P28_ACTIVATED, + ), order: CallOrder::PerClient, }; /// The allow-all outcomes several scenarios share, and the denied outcome that /// only asks (nothing written). -const A_XI2_AT_CHILD: Outcome = Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - ..NOTHING -}; -const A_CORE_AT_CHILD: Outcome = Outcome { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - ..NOTHING -}; -const B_XI2_AT_CHILD: Outcome = Outcome { - frames: &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(B, CallKind::Xi2, CHILD)], - ..NOTHING -}; +const A_XI2_AT_CHILD: Outcome = frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + &[(A, CallKind::Xi2, CHILD)], +); +const B_XI2_AT_CHILD: Outcome = frames_and_calls( + &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + &[(B, CallKind::Xi2, CHILD)], +); /// B gets the slave and the master form at C from one check. -const B_BOTH_FORMS_AT_CHILD: Outcome = Outcome { - frames: &[ +const B_BOTH_FORMS_AT_CHILD: Outcome = frames_and_calls( + &[ (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), ], - calls: &[(B, CallKind::Xi2, CHILD)], - ..NOTHING -}; + &[(B, CallKind::Xi2, CHILD)], +); /// A gets the slave motion and its valuator continuation at C from one check. -const A_XI1_MOTION_AT_CHILD: Outcome = Outcome { - frames: &[ +const A_XI1_MOTION_AT_CHILD: Outcome = frames_and_calls( + &[ (A, Kind::Xi1Motion(DEVICEID_XTEST_POINTER), CHILD), (A, Kind::Xi1Valuator(DEVICEID_XTEST_POINTER), 0), ], - calls: &[(A, XI1_MOTION_CALL, CHILD)], - ..NOTHING -}; -const ASKED_A_CORE_ROOT: Outcome = Outcome { - calls: &[(A, CallKind::Core, ROOT)], - ..NOTHING -}; -const ASKED_A_XI2_ROOT: Outcome = Outcome { - calls: &[(A, CallKind::Xi2, ROOT)], - ..NOTHING -}; -const ASKED_A_XI2_CHILD: Outcome = Outcome { - calls: &[(A, CallKind::Xi2, CHILD)], - ..NOTHING -}; + &[(A, XI1_MOTION_CALL, CHILD)], +); +const ASKED_A_CORE_ROOT: Outcome = calls_only(&[(A, CallKind::Core, ROOT)]); +const ASKED_A_XI2_ROOT: Outcome = calls_only(&[(A, CallKind::Xi2, ROOT)]); +const ASKED_A_XI2_CHILD: Outcome = calls_only(&[(A, CallKind::Xi2, CHILD)]); /// The p14 scenarios up to the activating press; the rows with more steps build /// on them with `..PREFIX`. const P14_CORE: Scenario = Scenario { setup: setup_p14_core, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(A, CallKind::Core, ROOT)], - grab: Some(&[passive(ROOT, false), FROZEN_BY_PRESS]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls(&[(A, Kind::Core, ROOT)], &[(A, CallKind::Core, ROOT)]), + &[passive(ROOT, false), FROZEN_BY_PRESS], + ), order: CallOrder::Total, }; const P14_FROM_SLAVE: Scenario = Scenario { setup: setup_p14_xi2_master_from_slave, steps: &[press(XTEST_SLAVE)], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], - calls: &[(A, CallKind::Xi2, ROOT)], - grab: Some(&[passive(ROOT, true), FROZEN_BY_PRESS]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], + &[(A, CallKind::Xi2, ROOT)], + ), + &[passive(ROOT, true), FROZEN_BY_PRESS], + ), order: CallOrder::Total, }; const P14_FROM_MASTER: Scenario = Scenario { setup: setup_p14_xi2_master_origin, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - grab: Some(&[passive(ROOT, true), FROZEN_BY_PRESS]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + &[(A, CallKind::Xi2, CHILD)], + ), + &[passive(ROOT, true), FROZEN_BY_PRESS], + ), order: CallOrder::Total, }; const P14_OWNER_EVENTS: Scenario = Scenario { setup: setup_p14_owner_events_from_slave, steps: &[press(XTEST_SLAVE)], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], - calls: &[(A, CallKind::Xi2, ROOT)], - grab: Some(&[passive(ROOT, true), FROZEN_BY_PRESS]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], + &[(A, CallKind::Xi2, ROOT)], + ), + &[passive(ROOT, true), FROZEN_BY_PRESS], + ), order: CallOrder::Total, }; @@ -1023,28 +979,31 @@ const P27_THAWED_XI1_FILTER: Scenario = Scenario { press(XTEST_SLAVE), Step::Request(allow_slave::, &[]), ], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], - calls: &[(A, CallKind::Xi2, ROOT)], - grab: Some(&[ + allow: with_grab( + frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], + &[(A, CallKind::Xi2, ROOT)], + ), + &[ Grab::Detached { device: DEVICEID_XTEST_POINTER, master: DEVICEID_MASTER_POINTER, }, SLAVE_PASSIVE_GRAB, - ]), - ..NOTHING - }, + ], + ), order: CallOrder::Total, }; const P27_THAWED_XI1_FILTER_PRESS: Scenario = Scenario { setup: setup_p27_thawed_xi1_filter, steps: &[press(XTEST_SLAVE)], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], - calls: &[(A, CallKind::Xi2, ROOT)], - grab: Some(&[ + allow: with_grab( + frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], + &[(A, CallKind::Xi2, ROOT)], + ), + &[ Grab::Detached { device: DEVICEID_XTEST_POINTER, master: DEVICEID_MASTER_POINTER, @@ -1067,9 +1026,8 @@ const P27_THAWED_XI1_FILTER_PRESS: Scenario = Scenario { detail: 1, }, }, - ]), - ..NOTHING - }, + ], + ), order: CallOrder::Total, }; @@ -1079,21 +1037,22 @@ const P27_THAWED_XI1_DELIVERY: Scenario = Scenario { press(XTEST_SLAVE), Step::Request(allow_slave::, &[]), ], - allow: Outcome { - frames: &[ - (A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT), - (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), - ], - calls: &[(A, CallKind::Xi2, ROOT), (A, XI1_PRESS_CALL, CHILD)], - grab: Some(&[ + allow: with_grab( + frames_and_calls( + &[ + (A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT), + (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + ], + &[(A, CallKind::Xi2, ROOT), (A, XI1_PRESS_CALL, CHILD)], + ), + &[ Grab::Detached { device: DEVICEID_XTEST_POINTER, master: DEVICEID_MASTER_POINTER, }, SLAVE_PASSIVE_GRAB, - ]), - ..NOTHING - }, + ], + ), order: CallOrder::Total, }; @@ -1108,22 +1067,20 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p1, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(B, Kind::Core, CHILD)], - calls: &[(B, CallKind::Core, CHILD)], - ..NOTHING - }, + allow: frames_and_calls(&[(B, Kind::Core, CHILD)], &[(B, CallKind::Core, CHILD)]), order: CallOrder::Total, }, deny: &[(B, CallKind::Core, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Core, FOCUS)], - moved: &[moved(A, Kind::Core, FOCUS, CHILD, P_EVENT)], - calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - grab: Some(&[implicit(A, FOCUS, false)]), - - ..NOTHING - }, + denied: with_grab( + with_moved( + frames_and_calls( + &[(A, Kind::Core, FOCUS)], + &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + ), + &[moved(A, Kind::Core, FOCUS, CHILD, P_EVENT)], + ), + &[implicit(A, FOCUS, false)], + ), }, // Mutation: an XI2 selection absorbs the walk whether or not its copy is // allowed (selection-only absorption), or the denied XI2 copy is checked twice. @@ -1136,14 +1093,16 @@ const ROWS: &[InputRow] = &[ order: CallOrder::Total, }, deny: &[(B, CallKind::Xi2, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Core, FOCUS)], - moved: &[moved(A, Kind::Core, FOCUS, CHILD, P_EVENT)], - calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Core, FOCUS)], - grab: Some(&[implicit(A, FOCUS, false)]), - - ..NOTHING - }, + denied: with_grab( + with_moved( + frames_and_calls( + &[(A, Kind::Core, FOCUS)], + &[(B, CallKind::Xi2, CHILD), (A, CallKind::Core, FOCUS)], + ), + &[moved(A, Kind::Core, FOCUS, CHILD, P_EVENT)], + ), + &[implicit(A, FOCUS, false)], + ), }, // Mutation: the XI2 route window is the first window with a selection rather // than the first with an allowed one, so the denied copy at C ends the walk. @@ -1156,20 +1115,22 @@ const ROWS: &[InputRow] = &[ order: CallOrder::Total, }, deny: &[(B, CallKind::Xi2, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], - moved: &[moved( - A, - Kind::Xi2(DEVICEID_MASTER_POINTER), - FOCUS, - CHILD, - P_EVENT, - )], - calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], - grab: Some(&[implicit(A, FOCUS, true)]), - - ..NOTHING - }, + denied: with_grab( + with_moved( + frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], + &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], + ), + &[moved( + A, + Kind::Xi2(DEVICEID_MASTER_POINTER), + FOCUS, + CHILD, + P_EVENT, + )], + ), + &[implicit(A, FOCUS, true)], + ), }, // B's slave and master forms at C come from one check. Denied: B gets // neither, and A's master form at P is the only copy. @@ -1231,11 +1192,7 @@ const ROWS: &[InputRow] = &[ order: CallOrder::Total, }, deny: &[(B, CallKind::Xi2, CHILD)], - denied: Outcome { - calls: &[(B, CallKind::Xi2, CHILD)], - grab: Some(&[]), - ..NOTHING - }, + denied: with_grab(calls_only(&[(B, CallKind::Xi2, CHILD)]), &[]), }, // A's master XI2 copy shadows its core copy at C. Denied: A's XI2 copy is // refused, so its core copy at C is delivered. @@ -1250,14 +1207,16 @@ const ROWS: &[InputRow] = &[ order: CallOrder::Total, }, deny: &[(A, CallKind::Xi2, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Core, CHILD)], - moved: &[moved(A, Kind::Core, CHILD, 0, C_EVENT)], - calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], - grab: Some(&[implicit(A, CHILD, false)]), - - ..NOTHING - }, + denied: with_grab( + with_moved( + frames_and_calls( + &[(A, Kind::Core, CHILD)], + &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], + ), + &[moved(A, Kind::Core, CHILD, 0, C_EVENT)], + ), + &[implicit(A, CHILD, false)], + ), }, // Denying A's core copy at C changes nothing: a shadowed core copy is not // checked, and the walk stops at C as it does with allow-all. @@ -1276,14 +1235,16 @@ const ROWS: &[InputRow] = &[ name: "p5b_shadow_follows_the_master_copy_anywhere", scenario: &P5B, deny: &[(A, CallKind::Xi2, FOCUS)], - denied: Outcome { - frames: &[(A, Kind::Core, CHILD)], - moved: &[moved(A, Kind::Core, CHILD, 0, C_EVENT)], - calls: &[(A, CallKind::Xi2, FOCUS), (A, CallKind::Core, CHILD)], - grab: Some(&[implicit(A, CHILD, false)]), - - ..NOTHING - }, + denied: with_grab( + with_moved( + frames_and_calls( + &[(A, Kind::Core, CHILD)], + &[(A, CallKind::Xi2, FOCUS), (A, CallKind::Core, CHILD)], + ), + &[moved(A, Kind::Core, CHILD, 0, C_EVENT)], + ), + &[implicit(A, CHILD, false)], + ), }, // Denied: the master route is P (A's master copy), so A's core copy at C is // shadowed and A gets its slave and master forms at P, with no core copy. @@ -1296,14 +1257,13 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p5c, steps: &[motion(XTEST_SLAVE)], - allow: Outcome { - frames: &[ + allow: frames_and_calls( + &[ (A, Kind::Xi2(DEVICEID_XTEST_POINTER), FOCUS), (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), ], - calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], - ..NOTHING - }, + &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], + ), order: CallOrder::Total, }, deny: &[(B, CallKind::Xi2, CHILD)], @@ -1334,24 +1294,26 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p6, steps: &[press(XTEST_SLAVE)], - allow: Outcome { - frames: &[ - (A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), - (A, Kind::Core, CHILD), - ], - calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Xi2, CHILD)], - grab: Some(&[implicit(A, CHILD, false), SLAVE_GRAB]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[ + (A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), + (A, Kind::Core, CHILD), + ], + &[(A, CallKind::Core, CHILD), (A, CallKind::Xi2, CHILD)], + ), + &[implicit(A, CHILD, false), SLAVE_GRAB], + ), order: CallOrder::Total, }, deny: &[(A, CallKind::Core, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Xi2, CHILD)], - grab: Some(&[SLAVE_GRAB]), - ..NOTHING - }, + denied: with_grab( + frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD)], + &[(A, CallKind::Core, CHILD), (A, CallKind::Xi2, CHILD)], + ), + &[SLAVE_GRAB], + ), }, // A and B select master XI2 on P; denied A also selects core on C. // Mutation: build the shadow list from selection-only recipients at P, so @@ -1362,14 +1324,13 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p5d, steps: &[motion(XTEST_MASTER)], - allow: Outcome { - frames: &[ + allow: frames_and_calls( + &[ (A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS), (B, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS), ], - calls: &[(A, CallKind::Xi2, FOCUS), (B, CallKind::Xi2, FOCUS)], - ..NOTHING - }, + &[(A, CallKind::Xi2, FOCUS), (B, CallKind::Xi2, FOCUS)], + ), order: CallOrder::PerClient, }, deny: &[(A, CallKind::Xi2, FOCUS)], @@ -1412,7 +1373,7 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p8, steps: &[press(XTEST_MASTER)], - allow: A_CORE_AT_CHILD, + allow: A_CORE_CHILD, order: CallOrder::Total, }, deny: &[(A, CallKind::Core, CHILD)], @@ -1456,18 +1417,15 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p9_core_same_window, steps: &[press(XTEST_MASTER)], - allow: A_CORE_AT_CHILD, + allow: A_CORE_CHILD, order: CallOrder::Total, }, deny: &[(A, CallKind::Core, CHILD)], - denied: Outcome { - calls: &[ - (A, CallKind::Core, CHILD), - (B, CallKind::Xi2, CHILD), - (A, CallKind::Core, CHILD), - ], - ..NOTHING - }, + denied: calls_only(&[ + (A, CallKind::Core, CHILD), + (B, CallKind::Xi2, CHILD), + (A, CallKind::Core, CHILD), + ]), }, // Mutation: a foreign selector rejects the walk by selection (the denied // selector at C sends A to the grab window instead of on to P). @@ -1476,11 +1434,10 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p10, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, ROOT)], - ..NOTHING - }, + allow: frames_and_calls( + &[(A, Kind::Core, ROOT)], + &[(B, CallKind::Core, CHILD), (A, CallKind::Core, ROOT)], + ), order: CallOrder::Total, }, deny: &[(B, CallKind::Core, CHILD)], @@ -1501,7 +1458,7 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p11, steps: &[press(XTEST_MASTER)], - allow: A_CORE_AT_CHILD, + allow: A_CORE_CHILD, order: CallOrder::Total, }, deny: &[(A, CallKind::Core, CHILD)], @@ -1545,11 +1502,7 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p12::, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(A, CallKind::Core, ROOT)], - ..NOTHING - }, + allow: frames_and_calls(&[(A, Kind::Core, ROOT)], &[(A, CallKind::Core, ROOT)]), order: CallOrder::Total, }, deny: &[(A, CallKind::Core, ROOT)], @@ -1561,10 +1514,7 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p12::, steps: &[press(XTEST_MASTER)], - allow: Outcome { - calls: &[(A, CallKind::Core, ROOT)], - ..NOTHING - }, + allow: calls_only(&[(A, CallKind::Core, ROOT)]), order: CallOrder::Total, }, deny: &[(A, CallKind::Core, ROOT)], @@ -1576,11 +1526,10 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p12_xi2, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], - calls: &[(A, CallKind::Xi2, ROOT)], - ..NOTHING - }, + allow: frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], + &[(A, CallKind::Xi2, ROOT)], + ), order: CallOrder::Total, }, deny: &[(A, CallKind::Xi2, ROOT)], @@ -1627,14 +1576,11 @@ const ROWS: &[InputRow] = &[ order: CallOrder::Total, }, deny: &[(A, CallKind::Xi2, CHILD)], - denied: Outcome { - calls: &[ - (A, CallKind::Xi2, CHILD), - (B, CallKind::Xi2, CHILD), - (A, CallKind::Xi2, CHILD), - ], - ..NOTHING - }, + denied: calls_only(&[ + (A, CallKind::Xi2, CHILD), + (B, CallKind::Xi2, CHILD), + (A, CallKind::Xi2, CHILD), + ]), }, // A sync `GrabButton` on G: the activating press is denied to its owner, and // the grab still activates, freezes and stores the press; the next motion is @@ -1695,22 +1641,20 @@ const ROWS: &[InputRow] = &[ motion(XTEST_SLAVE), Step::Request(allow_master::, &[]), ], - allow: Outcome { - frames: &[ - (A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT), - (A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT), - ], - calls: &[(A, CallKind::Xi2, ROOT), (A, CallKind::Xi2, ROOT)], - grab: Some(&[passive(ROOT, true)]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[ + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT), + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT), + ], + &[(A, CallKind::Xi2, ROOT), (A, CallKind::Xi2, ROOT)], + ), + &[passive(ROOT, true)], + ), ..P14_FROM_SLAVE }, deny: &[(A, CallKind::Xi2, ROOT)], - denied: Outcome { - calls: &[(A, CallKind::Xi2, ROOT), (A, CallKind::Xi2, ROOT)], - ..NOTHING - }, + denied: calls_only(&[(A, CallKind::Xi2, ROOT), (A, CallKind::Xi2, ROOT)]), }, // The same grab from a master origin (`xi2_grab_delivery`): A also selects the // master XI2 press on C, which is the window its copy is routed to. Denying @@ -1755,11 +1699,10 @@ const ROWS: &[InputRow] = &[ ..P14_FROM_MASTER }, deny: &[(A, CallKind::Xi2, CHILD)], - denied: Outcome { - calls: &[(A, CallKind::Xi2, CHILD), (A, XI2_PRESS_CALL, CHILD)], - grab: Some(&[]), - ..NOTHING - }, + denied: with_grab( + calls_only(&[(A, CallKind::Xi2, CHILD), (A, XI2_PRESS_CALL, CHILD)]), + &[], + ), }, InputRow { name: "p14_denied_xi2_activating_press_from_a_master_origin_still_freezes", @@ -1808,19 +1751,11 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_activation_owner_events, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(A, CallKind::Core, ROOT)], - ..NOTHING - }, + allow: frames_and_calls(&[(A, Kind::Core, ROOT)], &[(A, CallKind::Core, ROOT)]), order: CallOrder::Total, }, deny: &[(A, CallKind::Core, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(A, CallKind::Core, ROOT)], - ..NOTHING - }, + denied: frames_and_calls(&[(A, Kind::Core, ROOT)], &[(A, CallKind::Core, ROOT)]), }, // A denied on C: B on P gets the press and owns the implicit grab. // Mutation (the core candidate): the candidate is any walk recipient, denied @@ -1829,26 +1764,29 @@ const ROWS: &[InputRow] = &[ name: "p15_denied_candidate_is_not_the_implicit_owner@press", scenario: &P15_PRESS, deny: &[(A, CallKind::Core, CHILD)], - denied: Outcome { - frames: &[(B, Kind::Core, FOCUS)], - moved: &[moved(B, Kind::Core, FOCUS, CHILD, P_EVENT)], - calls: &[(A, CallKind::Core, CHILD), (B, CallKind::Core, FOCUS)], - grab: Some(&[implicit(B, FOCUS, false)]), - - ..NOTHING - }, + denied: with_grab( + with_moved( + frames_and_calls( + &[(B, Kind::Core, FOCUS)], + &[(A, CallKind::Core, CHILD), (B, CallKind::Core, FOCUS)], + ), + &[moved(B, Kind::Core, FOCUS, CHILD, P_EVENT)], + ), + &[implicit(B, FOCUS, false)], + ), }, // The release, with the pointer still over C, goes to B at P. InputRow { name: "p15_denied_candidate_is_not_the_implicit_owner", scenario: &Scenario { steps: &[press(XTEST_MASTER), release(XTEST_MASTER)], - allow: Outcome { - frames: &[(A, Kind::Core, CHILD), (A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, CHILD)], - grab: Some(&[]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[(A, Kind::Core, CHILD), (A, Kind::Core, CHILD)], + &[(A, CallKind::Core, CHILD), (A, CallKind::Core, CHILD)], + ), + &[], + ), ..P15_PRESS }, deny: &[(A, CallKind::Core, CHILD)], @@ -1877,20 +1815,14 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p16, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[(A, Kind::Core, CHILD)], - calls: &[(A, CallKind::Core, CHILD)], - grab: Some(&[implicit(A, CHILD, false)]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls(&[(A, Kind::Core, CHILD)], &[(A, CallKind::Core, CHILD)]), + &[implicit(A, CHILD, false)], + ), order: CallOrder::Total, }, deny: &[(A, CallKind::Core, CHILD)], - denied: Outcome { - calls: &[(A, CallKind::Core, CHILD)], - grab: Some(&[]), - ..NOTHING - }, + denied: with_grab(calls_only(&[(A, CallKind::Core, CHILD)]), &[]), }, // Both select the master pointer's XI2 press on C; A is the window's owner and // wins with allow-all, and with A denied B owns the grab. (The mutation that a @@ -1900,24 +1832,26 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p17, steps: &[press(XTEST_MASTER)], - allow: Outcome { - frames: &[ - (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - ], - calls: &[(A, CallKind::Xi2, CHILD), (B, CallKind::Xi2, CHILD)], - grab: Some(&[implicit(A, CHILD, true)]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[ + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + &[(A, CallKind::Xi2, CHILD), (B, CallKind::Xi2, CHILD)], + ), + &[implicit(A, CHILD, true)], + ), order: CallOrder::PerClient, }, deny: &[(A, CallKind::Xi2, CHILD)], - denied: Outcome { - frames: &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD), (B, CallKind::Xi2, CHILD)], - grab: Some(&[implicit(B, CHILD, true)]), - ..NOTHING - }, + denied: with_grab( + frames_and_calls( + &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + &[(A, CallKind::Xi2, CHILD), (B, CallKind::Xi2, CHILD)], + ), + &[implicit(B, CHILD, true)], + ), }, // Slave origin; A selects the slave's XI2 press on C, B its XI1 press on C. A // denied: B gets the XI1 form at C and owns the XI1 implicit grab, with one @@ -1929,29 +1863,32 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p18, steps: &[press(XTEST_SLAVE)], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - grab: Some(&[SLAVE_GRAB]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD)], + &[(A, CallKind::Xi2, CHILD)], + ), + &[SLAVE_GRAB], + ), order: CallOrder::Total, }, deny: &[(A, CallKind::Xi2, CHILD)], - denied: Outcome { - frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], - moved: &[moved( - B, - Kind::Xi1(DEVICEID_XTEST_POINTER), - CHILD, - 0, - C_EVENT, - )], - calls: &[(A, CallKind::Xi2, CHILD), (B, XI1_PRESS_CALL, CHILD)], - grab: Some(&[xi1_implicit(B, CHILD)]), - - ..NOTHING - }, + denied: with_grab( + with_moved( + frames_and_calls( + &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + &[(A, CallKind::Xi2, CHILD), (B, XI1_PRESS_CALL, CHILD)], + ), + &[moved( + B, + Kind::Xi1(DEVICEID_XTEST_POINTER), + CHILD, + 0, + C_EVENT, + )], + ), + &[xi1_implicit(B, CHILD)], + ), }, // A's XI1 press selector on C is denied, B's on P is not: the walk continues // and B gets the press at P. @@ -1962,29 +1899,32 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p19, steps: &[press(XTEST_SLAVE)], - allow: Outcome { - frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[(A, XI1_PRESS_CALL, CHILD)], - grab: Some(&[xi1_implicit(A, CHILD)]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + &[(A, XI1_PRESS_CALL, CHILD)], + ), + &[xi1_implicit(A, CHILD)], + ), order: CallOrder::Total, }, deny: &[(A, XI1_PRESS_CALL, CHILD)], - denied: Outcome { - frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], - moved: &[moved( - B, - Kind::Xi1(DEVICEID_XTEST_POINTER), - FOCUS, - CHILD, - P_EVENT, - )], - calls: &[(A, XI1_PRESS_CALL, CHILD), (B, XI1_PRESS_CALL, FOCUS)], - grab: Some(&[xi1_implicit(B, FOCUS)]), - - ..NOTHING - }, + denied: with_grab( + with_moved( + frames_and_calls( + &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], + &[(A, XI1_PRESS_CALL, CHILD), (B, XI1_PRESS_CALL, FOCUS)], + ), + &[moved( + B, + Kind::Xi1(DEVICEID_XTEST_POINTER), + FOCUS, + CHILD, + P_EVENT, + )], + ), + &[xi1_implicit(B, FOCUS)], + ), }, // Two XI1 press selectors on C, the one that also selected the button grab // class is denied: the other owns the XI1 implicit grab (allow-all: the grab @@ -1996,24 +1936,26 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p20, steps: &[press(XTEST_SLAVE)], - allow: Outcome { - frames: &[ - (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), - (B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), - ], - calls: &[(A, XI1_PRESS_CALL, CHILD), (B, XI1_PRESS_CALL, CHILD)], - grab: Some(&[xi1_implicit(B, CHILD)]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[ + (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + (B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + ], + &[(A, XI1_PRESS_CALL, CHILD), (B, XI1_PRESS_CALL, CHILD)], + ), + &[xi1_implicit(B, CHILD)], + ), order: CallOrder::PerClient, }, deny: &[(B, XI1_PRESS_CALL, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[(A, XI1_PRESS_CALL, CHILD), (B, XI1_PRESS_CALL, CHILD)], - grab: Some(&[xi1_implicit(A, CHILD)]), - ..NOTHING - }, + denied: with_grab( + frames_and_calls( + &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + &[(A, XI1_PRESS_CALL, CHILD), (B, XI1_PRESS_CALL, CHILD)], + ), + &[xi1_implicit(A, CHILD)], + ), }, // An XI1 passive grab takes the slave press, so the router never reaches the // selection walk: A's selector copy is not written and Receive is not asked @@ -2032,10 +1974,7 @@ const ROWS: &[InputRow] = &[ name: "p20b_xi1_passive_activation_owner_denied", scenario: &P20B, deny: &[(B, XI1_PRESS_CALL, FOCUS)], - denied: Outcome { - calls: &[(B, XI1_PRESS_CALL, FOCUS)], - ..NOTHING - }, + denied: calls_only(&[(B, XI1_PRESS_CALL, FOCUS)]), }, // A selects the slave's XI2 press on the root, B its XI1 press, and the press // is over the bare root: no XI2 copy is written, so Receive is not asked for @@ -2069,23 +2008,23 @@ const ROWS: &[InputRow] = &[ PointerEventKind::ButtonPress, BARE_ROOT, )], - allow: Outcome { - frames: &[ + allow: frames_and_calls( + &[ (A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT), (B, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT), ], - calls: &[(A, XI1_PRESS_CALL, ROOT), (B, XI1_PRESS_CALL, ROOT)], - ..NOTHING - }, + &[(A, XI1_PRESS_CALL, ROOT), (B, XI1_PRESS_CALL, ROOT)], + ), order: CallOrder::PerClient, }, deny: &[(A, XI1_PRESS_CALL, ROOT)], - denied: Outcome { - frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT)], - calls: &[(A, XI1_PRESS_CALL, ROOT), (B, XI1_PRESS_CALL, ROOT)], - grab: Some(&[xi1_implicit(B, ROOT)]), - ..NOTHING - }, + denied: with_grab( + frames_and_calls( + &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT)], + &[(A, XI1_PRESS_CALL, ROOT), (B, XI1_PRESS_CALL, ROOT)], + ), + &[xi1_implicit(B, ROOT)], + ), }, // A and B select the master raw press on the root, the requester the slave's; // A is denied: only A's copy goes, B and the requester keep theirs. @@ -2096,19 +2035,18 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p21, steps: &[press(XTEST_SLAVE)], - allow: Outcome { - frames: &[ + allow: frames_and_calls( + &[ (SEND_CLIENT, Kind::Raw(DEVICEID_XTEST_POINTER), ROOT), (A, Kind::Raw(DEVICEID_MASTER_POINTER), ROOT), (B, Kind::Raw(DEVICEID_MASTER_POINTER), ROOT), ], - calls: &[ + &[ (SEND_CLIENT, RAW_BUTTON_PRESS_CALL, ROOT), (A, RAW_BUTTON_PRESS_CALL, ROOT), (B, RAW_BUTTON_PRESS_CALL, ROOT), ], - ..NOTHING - }, + ), order: CallOrder::PerClient, }, deny: &[(A, RAW_BUTTON_PRESS_CALL, ROOT)], @@ -2134,11 +2072,10 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_scroll_walk, steps: &[WHEEL_PRESS], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - calls: &[(A, SCROLL_MOTION_CALL, CHILD)], - ..NOTHING - }, + allow: frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + &[(A, SCROLL_MOTION_CALL, CHILD)], + ), order: CallOrder::Total, }, deny: &[(A, SCROLL_MOTION_CALL, CHILD)], @@ -2170,21 +2107,17 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_scroll_walk, steps: &[SCROLL_STOP], - allow: Outcome { - frames: &[ + allow: frames_and_calls( + &[ (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), ], - calls: &[(A, STOP_BATCH, CHILD)], - ..NOTHING - }, + &[(A, STOP_BATCH, CHILD)], + ), order: CallOrder::Total, }, deny: &[(A, STOP_BATCH, CHILD)], - denied: Outcome { - calls: &[(A, STOP_BATCH, CHILD)], - ..NOTHING - }, + denied: calls_only(&[(A, STOP_BATCH, CHILD)]), }, // A client with both device forms on one window is asked once for both forms' // four events. @@ -2194,23 +2127,19 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_scroll_stop_two_forms, steps: &[SCROLL_STOP], - allow: Outcome { - frames: &[ + allow: frames_and_calls( + &[ (A, Kind::Xi2(PHYSICAL_DEVICE), CHILD), (A, Kind::Xi2(PHYSICAL_DEVICE), CHILD), (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), ], - calls: &[(A, STOP_BATCH, CHILD)], - ..NOTHING - }, + &[(A, STOP_BATCH, CHILD)], + ), order: CallOrder::Total, }, deny: &[(A, STOP_BATCH, CHILD)], - denied: Outcome { - calls: &[(A, STOP_BATCH, CHILD)], - ..NOTHING - }, + denied: calls_only(&[(A, STOP_BATCH, CHILD)]), }, // The scroll Motion of an XI2 grab with owner_events false is a grab-window // copy of its own: one fresh check, whatever the press's check at that @@ -2229,10 +2158,7 @@ const ROWS: &[InputRow] = &[ name: "p22_scroll_motion_grab_window_has_its_own_check_motion_denied", scenario: &P22_GRAB, deny: &[(A, SCROLL_MOTION_CALL, ROOT)], - denied: Outcome { - calls: P22_GRAB.allow.calls, - ..NOTHING - }, + denied: calls_only(P22_GRAB.allow.calls), }, // Slave motion over C: A selects XI1 `DeviceMotionNotify` on C, B on P. A's // copy denied: the walk goes on and B gets it at P. @@ -2279,10 +2205,7 @@ const ROWS: &[InputRow] = &[ order: CallOrder::Total, }, deny: &[(A, XI1_MOTION_CALL, CHILD)], - denied: Outcome { - calls: &[(A, XI1_MOTION_CALL, CHILD)], - ..NOTHING - }, + denied: calls_only(&[(A, XI1_MOTION_CALL, CHILD)]), }, // Slave origin, XI1 `GrabDevice` by A on G with `owner_events`: with A's own // copy on C allowed A gets it at C and the foreign selector B is not asked @@ -2304,19 +2227,17 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p26::, steps: &[press(XTEST_SLAVE)], - allow: Outcome { - frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT)], - calls: &[(A, XI1_PRESS_CALL, ROOT)], - grab: Some(&[xi1_implicit(A, ROOT)]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT)], + &[(A, XI1_PRESS_CALL, ROOT)], + ), + &[xi1_implicit(A, ROOT)], + ), order: CallOrder::Total, }, deny: &[(A, XI1_PRESS_CALL, ROOT)], - denied: Outcome { - calls: &[(A, XI1_PRESS_CALL, ROOT)], - ..NOTHING - }, + denied: calls_only(&[(A, XI1_PRESS_CALL, ROOT)]), }, // A denied on C, B allowed on C: B's copy rejects the walk, so A does not // reach its own selector on P: it gets the event at G. @@ -2339,21 +2260,23 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p26_implicit_device_mask, steps: &[press(XTEST_SLAVE), motion(XTEST_SLAVE)], - allow: Outcome { - frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[(A, XI1_PRESS_CALL, CHILD), (A, XI1_MOTION_CALL, CHILD)], - grab: Some(&[xi1_implicit(A, CHILD)]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + &[(A, XI1_PRESS_CALL, CHILD), (A, XI1_MOTION_CALL, CHILD)], + ), + &[xi1_implicit(A, CHILD)], + ), order: CallOrder::Total, }, deny: &[(A, XI1_MOTION_CALL, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[(A, XI1_PRESS_CALL, CHILD), (A, XI1_MOTION_CALL, CHILD)], - grab: Some(&[xi1_implicit(A, CHILD)]), - ..NOTHING - }, + denied: with_grab( + frames_and_calls( + &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + &[(A, XI1_PRESS_CALL, CHILD), (A, XI1_MOTION_CALL, CHILD)], + ), + &[xi1_implicit(A, CHILD)], + ), }, // An XIGrabDevice on the slave with `owner_events` and ButtonPress in its // mask; A selects the XI1 press on C. A's XI1 copy denied: the XI2 route @@ -2366,11 +2289,10 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p27, steps: &[press(XTEST_SLAVE)], - allow: Outcome { - frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[(A, XI1_PRESS_CALL, CHILD)], - ..NOTHING - }, + allow: frames_and_calls( + &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + &[(A, XI1_PRESS_CALL, CHILD)], + ), order: CallOrder::Total, }, deny: &[(A, XI1_PRESS_CALL, CHILD)], @@ -2399,11 +2321,10 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p27_later_window, steps: &[press(XTEST_SLAVE)], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], - calls: &[(B, XI1_PRESS_CALL, CHILD), (A, CallKind::Xi2, ROOT)], - ..NOTHING - }, + allow: frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], + &[(B, XI1_PRESS_CALL, CHILD), (A, CallKind::Xi2, ROOT)], + ), order: CallOrder::Total, }, deny: &[(B, XI1_PRESS_CALL, CHILD)], @@ -2437,18 +2358,19 @@ const ROWS: &[InputRow] = &[ name: "p27_thawed_xi1_press_filter_asks_no_xi2_copy", scenario: &P27_THAWED_XI1_FILTER, deny: &[(A, XI2_PRESS_CALL, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], - calls: &[(A, CallKind::Xi2, ROOT)], - grab: Some(&[ + denied: with_grab( + frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], + &[(A, CallKind::Xi2, ROOT)], + ), + &[ Grab::Detached { device: DEVICEID_XTEST_POINTER, master: DEVICEID_MASTER_POINTER, }, SLAVE_PASSIVE_GRAB, - ]), - ..NOTHING - }, + ], + ), }, // This sibling leaves XI2 unselected on C while retaining the sync slave // passive grab and XI1 selection. The queued Xi1Routed press then produces @@ -2458,18 +2380,19 @@ const ROWS: &[InputRow] = &[ name: "p27_thawed_xi1_routed_entry_delivers_xi1_copy", scenario: &P27_THAWED_XI1_DELIVERY, deny: &[(A, XI1_PRESS_CALL, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], - calls: &[(A, CallKind::Xi2, ROOT), (A, XI1_PRESS_CALL, CHILD)], - grab: Some(&[ + denied: with_grab( + frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], + &[(A, CallKind::Xi2, ROOT), (A, XI1_PRESS_CALL, CHILD)], + ), + &[ Grab::Detached { device: DEVICEID_XTEST_POINTER, master: DEVICEID_MASTER_POINTER, }, SLAVE_PASSIVE_GRAB, - ]), - ..NOTHING - }, + ], + ), }, // The live filter follows the slave XI2 route's decision in their shared // memo: when that XI2 copy is denied, A's selected XI1 copy is written. @@ -2480,26 +2403,26 @@ const ROWS: &[InputRow] = &[ scenario: &Scenario { setup: setup_p27_live_filter, steps: &[press(XTEST_SLAVE)], - allow: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[(A, CallKind::Xi2, CHILD)], - ..NOTHING - }, + allow: frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD)], + &[(A, CallKind::Xi2, CHILD)], + ), order: CallOrder::Total, }, deny: &[(A, XI2_PRESS_CALL, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], - moved: &[moved( + denied: with_moved( + frames_and_calls( + &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + &[(A, CallKind::Xi2, CHILD), (A, XI1_PRESS_CALL, CHILD)], + ), + &[moved( A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD, 0, C_EVENT, )], - calls: &[(A, CallKind::Xi2, CHILD), (A, XI1_PRESS_CALL, CHILD)], - ..NOTHING - }, + ), }, // A sync `GrabDeviceButton` by the requester on P activates on the press and // stores it (the activating write is one fresh check). @@ -2519,36 +2442,38 @@ const ROWS: &[InputRow] = &[ name: "p28_thawed_xi1_press_picks_the_owner_from_allowed", scenario: &Scenario { steps: &[press(XTEST_SLAVE), Step::Request(replay_slave, &[])], - allow: Outcome { - frames: &[ + allow: with_grab( + frames_and_calls( + &[ + (SEND_CLIENT, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS), + (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + (B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + ], + &[ + (SEND_CLIENT, XI1_PRESS_CALL, FOCUS), + (A, XI1_PRESS_CALL, CHILD), + (B, XI1_PRESS_CALL, CHILD), + ], + ), + &[xi1_implicit(B, CHILD)], + ), + ..P28_PRESS + }, + deny: &[(B, XI1_PRESS_CALL, CHILD)], + denied: with_grab( + frames_and_calls( + &[ (SEND_CLIENT, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS), (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), - (B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), ], - calls: &[ + &[ (SEND_CLIENT, XI1_PRESS_CALL, FOCUS), (A, XI1_PRESS_CALL, CHILD), (B, XI1_PRESS_CALL, CHILD), ], - grab: Some(&[xi1_implicit(B, CHILD)]), - ..NOTHING - }, - ..P28_PRESS - }, - deny: &[(B, XI1_PRESS_CALL, CHILD)], - denied: Outcome { - frames: &[ - (SEND_CLIENT, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS), - (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), - ], - calls: &[ - (SEND_CLIENT, XI1_PRESS_CALL, FOCUS), - (A, XI1_PRESS_CALL, CHILD), - (B, XI1_PRESS_CALL, CHILD), - ], - grab: Some(&[xi1_implicit(A, CHILD)]), - ..NOTHING - }, + ), + &[xi1_implicit(A, CHILD)], + ), }, ]; diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs index 922b9776f..516a555af 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs @@ -6,12 +6,12 @@ use super::{access_input_support::*, access_notify_support::NotifyFixture}; use crate::{ - core_loop::{DeviceInfo, InputOrigin}, + core_loop::InputOrigin, host_x11::PointerEventKind, server::Xi1SyncState, xinput::{ DEVICEID_MASTER_KEYBOARD, DEVICEID_MASTER_POINTER, DEVICEID_XTEST_KEYBOARD, - DEVICEID_XTEST_POINTER, InputCapabilities, InputSourceId, XI_DEVICE_BUTTON_PRESS_OFFSET, + DEVICEID_XTEST_POINTER, XI_DEVICE_BUTTON_PRESS_OFFSET, }, }; use yserver_protocol::x11::ClientId; @@ -20,9 +20,6 @@ const XTEST_MASTER_POINTER: InputOrigin = InputOrigin::XTest(DEVICEID_MASTER_POI const XTEST_SLAVE_POINTER: InputOrigin = InputOrigin::XTest(DEVICEID_XTEST_POINTER); const XTEST_MASTER_KEYBOARD: InputOrigin = InputOrigin::XTest(DEVICEID_MASTER_KEYBOARD); const XTEST_SLAVE_KEYBOARD: InputOrigin = InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD); -const PHYSICAL_SOURCE: u64 = 0xA75_400; -const PHYSICAL_DEVICE: u16 = 6; -const PHYSICAL_POINTER: InputOrigin = InputOrigin::Physical(InputSourceId(PHYSICAL_SOURCE)); const CORE_BUTTON_PRESS: u32 = 1 << 2; const CORE_MOTION: u32 = 1 << 6; const XI_BUTTON_PRESS: u32 = 1 << 4; @@ -76,36 +73,10 @@ const fn raw_key_press(origin: InputOrigin) -> Step { }) } -fn xi1_pointer_class_for(device: u16, offset: u8) -> u32 { - (u32::from(device) << 8) | u32::from(crate::server::XI_FIRST_EVENT + offset) -} - fn xi1_pointer_class(offset: u8) -> u32 { xi1_pointer_class_for(DEVICEID_XTEST_POINTER, offset) } -fn register_physical_pointer(f: &mut NotifyFixture) { - let info = DeviceInfo { - source_id: InputSourceId(PHYSICAL_SOURCE), - enabled: true, - resume_key: None, - capabilities: InputCapabilities { - keyboard: false, - pointer: true, - touch: false, - }, - name: format!("pointer source {PHYSICAL_SOURCE}"), - device_node: format!("/dev/input/event{PHYSICAL_SOURCE}"), - sysname: format!("event{PHYSICAL_SOURCE}"), - vendor_id: 1, - product_id: PHYSICAL_SOURCE as u32, - is_touchpad: false, - config: crate::core_loop::message::LibinputConfigSnapshot::default(), - }; - let ids = f.state.xi_register_source(&info); - assert_eq!(ids.first(), Some(&PHYSICAL_DEVICE), "physical pointer id"); -} - fn xi2_passive_button_grab(f: &mut NotifyFixture, device: u16) { const XI_PASSIVE_GRAB_DEVICE: u8 = 54; let mut body = Vec::with_capacity(36); @@ -316,12 +287,13 @@ const XI1_KEYBOARD_QUEUE: Grab = Grab::Freeze { const R4_PRESS: Scenario = Scenario { setup: setup_r4_replay_pointer, steps: &[button_press(XTEST_MASTER_POINTER)], - allow: Outcome { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], - grab: Some(&[PASSIVE_CORE_POINTER, CORE_POINTER_PRESS_FROZEN]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[(A, Kind::Core, ROOT)], + &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], + ), + &[PASSIVE_CORE_POINTER, CORE_POINTER_PRESS_FROZEN], + ), order: CallOrder::Total, }; @@ -334,21 +306,22 @@ const R4_REPLAY: Scenario = Scenario { &[button_press(XTEST_MASTER_POINTER)], ), ], - allow: Outcome { - frames: &[(A, Kind::Core, ROOT), (B, Kind::Core, CHILD)], - calls: &[ - (A, CORE_BUTTON_PRESS_CALL, ROOT), - (B, CORE_BUTTON_PRESS_CALL, CHILD), - ], - grab: Some(&[Grab::Pointer(PointerGrab { + allow: with_grab( + frames_and_calls( + &[(A, Kind::Core, ROOT), (B, Kind::Core, CHILD)], + &[ + (A, CORE_BUTTON_PRESS_CALL, ROOT), + (B, CORE_BUTTON_PRESS_CALL, CHILD), + ], + ), + &[Grab::Pointer(PointerGrab { owner: B, window: CHILD, implicit: true, passive: false, via_xi2: false, - })]), - ..NOTHING - }, + })], + ), order: CallOrder::Total, }; @@ -358,33 +331,26 @@ const R5_REPLAY: Scenario = Scenario { key_press(XTEST_MASTER_KEYBOARD), Step::Request(allow_core_events::<5>, &[key_press(XTEST_MASTER_KEYBOARD)]), ], - allow: Outcome { - frames: &[(A, Kind::Core, ROOT), (B, Kind::Core, FOCUS)], - calls: &[ - (A, CORE_KEY_PRESS_CALL, ROOT), - (B, CORE_KEY_PRESS_CALL, FOCUS), - ], - grab: Some(&[]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[(A, Kind::Core, ROOT), (B, Kind::Core, FOCUS)], + &[ + (A, CORE_KEY_PRESS_CALL, ROOT), + (B, CORE_KEY_PRESS_CALL, FOCUS), + ], + ), + &[], + ), order: CallOrder::Total, }; const R5_PRESS: Scenario = Scenario { setup: setup_r5_replay_keyboard, steps: &[key_press(XTEST_MASTER_KEYBOARD)], - allow: Outcome { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(A, CORE_KEY_PRESS_CALL, ROOT)], - grab: Some(&[ - Grab::Keyboard { - owner: A, - window: ROOT, - }, - MASTER_KEY_PRESS_FROZEN, - ]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls(&[(A, Kind::Core, ROOT)], &[(A, CORE_KEY_PRESS_CALL, ROOT)]), + &[A_ROOT_KEYBOARD_GRAB, MASTER_KEY_PRESS_FROZEN], + ), order: CallOrder::Total, }; @@ -394,20 +360,21 @@ const R5_CONTINUATION: Scenario = Scenario { key_press(XTEST_MASTER_KEYBOARD), Step::Request(allow_core_events::<5>, &[key_press(XTEST_MASTER_KEYBOARD)]), ], - allow: Outcome { - frames: &[ - (A, Kind::Core, ROOT), - (A, Kind::Core, FOCUS), - (B, Kind::Core, FOCUS), - ], - calls: &[ - (A, CORE_KEY_PRESS_CALL, ROOT), - (A, CORE_KEY_PRESS_CALL, FOCUS), - (B, CORE_KEY_PRESS_CALL, FOCUS), - ], - grab: Some(&[]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[ + (A, Kind::Core, ROOT), + (A, Kind::Core, FOCUS), + (B, Kind::Core, FOCUS), + ], + &[ + (A, CORE_KEY_PRESS_CALL, ROOT), + (A, CORE_KEY_PRESS_CALL, FOCUS), + (B, CORE_KEY_PRESS_CALL, FOCUS), + ], + ), + &[], + ), order: CallOrder::PerClient, }; @@ -417,25 +384,18 @@ const R1_XI1_QUEUE: Scenario = Scenario { button_press(XTEST_SLAVE_POINTER), button_press(PHYSICAL_POINTER), ], - allow: Outcome { - frames: &[ - (A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT), - (A, Kind::Xi2(PHYSICAL_DEVICE), ROOT), - ], - calls: &[(A, CallKind::Xi2, ROOT), (A, CallKind::Xi2, ROOT)], - grab: Some(&[ - Grab::Keyboard { - owner: A, - window: ROOT, - }, - Grab::Detached { - device: DEVICEID_XTEST_POINTER, - master: DEVICEID_MASTER_POINTER, - }, - Grab::Detached { - device: PHYSICAL_DEVICE, - master: DEVICEID_MASTER_POINTER, - }, + allow: with_grab( + frames_and_calls( + &[ + (A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT), + (A, Kind::Xi2(PHYSICAL_DEVICE), ROOT), + ], + &[(A, CallKind::Xi2, ROOT), (A, CallKind::Xi2, ROOT)], + ), + &[ + A_ROOT_KEYBOARD_GRAB, + XTEST_POINTER_DETACHED, + PHYSICAL_POINTER_DETACHED, R1_XTEST_PASSIVE_GRAB, R1_PHYSICAL_PASSIVE_GRAB, Grab::Freeze { @@ -448,9 +408,8 @@ const R1_XI1_QUEUE: Scenario = Scenario { PHYSICAL_POINTER_PRESS_STORED, R1_XTEST_XI1_QUEUED, R1_PHYSICAL_XI1_QUEUED, - ]), - ..NOTHING - }, + ], + ), order: CallOrder::Total, }; @@ -461,37 +420,29 @@ const R1_XI1_THAW: Scenario = Scenario { button_press(PHYSICAL_POINTER), Step::Request(allow_core_events::<6>, &[]), ], - allow: Outcome { - frames: &[ - (A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT), - (A, Kind::Xi2(PHYSICAL_DEVICE), ROOT), - (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), - (A, Kind::Xi1(PHYSICAL_DEVICE), CHILD), - ], - calls: &[ - (A, CallKind::Xi2, ROOT), - (A, CallKind::Xi2, ROOT), - (A, XI1_BUTTON_PRESS_CALL, CHILD), - (A, XI1_BUTTON_PRESS_CALL, CHILD), - ], - grab: Some(&[ - Grab::Keyboard { - owner: A, - window: ROOT, - }, - Grab::Detached { - device: DEVICEID_XTEST_POINTER, - master: DEVICEID_MASTER_POINTER, - }, - Grab::Detached { - device: PHYSICAL_DEVICE, - master: DEVICEID_MASTER_POINTER, - }, + allow: with_grab( + frames_and_calls( + &[ + (A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT), + (A, Kind::Xi2(PHYSICAL_DEVICE), ROOT), + (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + (A, Kind::Xi1(PHYSICAL_DEVICE), CHILD), + ], + &[ + (A, CallKind::Xi2, ROOT), + (A, CallKind::Xi2, ROOT), + (A, XI1_BUTTON_PRESS_CALL, CHILD), + (A, XI1_BUTTON_PRESS_CALL, CHILD), + ], + ), + &[ + A_ROOT_KEYBOARD_GRAB, + XTEST_POINTER_DETACHED, + PHYSICAL_POINTER_DETACHED, R1_XTEST_PASSIVE_GRAB, R1_PHYSICAL_PASSIVE_GRAB, - ]), - ..NOTHING - }, + ], + ), order: CallOrder::Total, }; @@ -501,16 +452,17 @@ const R6_QUEUE: Scenario = Scenario { button_press(XTEST_MASTER_POINTER), motion(XTEST_MASTER_POINTER), ], - allow: Outcome { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], - grab: Some(&[ + allow: with_grab( + frames_and_calls( + &[(A, Kind::Core, ROOT)], + &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], + ), + &[ PASSIVE_CORE_POINTER, CORE_POINTER_PRESS_FROZEN, MASTER_POINTER_MOTION_QUEUED, - ]), - ..NOTHING - }, + ], + ), order: CallOrder::Total, }; @@ -521,15 +473,16 @@ const R6_THAW: Scenario = Scenario { motion(XTEST_MASTER_POINTER), Step::Request(allow_core_events::<0>, &[]), ], - allow: Outcome { - frames: &[(A, Kind::Core, ROOT), (A, Kind::Core, CHILD)], - calls: &[ - (A, CORE_BUTTON_PRESS_CALL, ROOT), - (A, CORE_MOTION_CALL, CHILD), - ], - grab: Some(&[PASSIVE_CORE_POINTER]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[(A, Kind::Core, ROOT), (A, Kind::Core, CHILD)], + &[ + (A, CORE_BUTTON_PRESS_CALL, ROOT), + (A, CORE_MOTION_CALL, CHILD), + ], + ), + &[PASSIVE_CORE_POINTER], + ), order: CallOrder::Total, }; @@ -541,10 +494,7 @@ const R7_QUEUE: Scenario = Scenario { ], allow: Outcome { grab: Some(&[ - Grab::Keyboard { - owner: A, - window: ROOT, - }, + A_ROOT_KEYBOARD_GRAB, XI1_KEYBOARD_QUEUE, Grab::Queued { device: DEVICEID_MASTER_KEYBOARD, @@ -581,21 +531,19 @@ const R7_THAW: Scenario = Scenario { ], ), ], - allow: Outcome { - frames: &[ - (B, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), - (A, Kind::Core, CHILD), - ], - calls: &[ - (B, CallKind::Batch(&[Named::Raw(13)]), ROOT), - (A, CallKind::Batch(&[Named::Core(2)]), CHILD), - ], - grab: Some(&[Grab::Keyboard { - owner: A, - window: ROOT, - }]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[ + (B, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + (A, Kind::Core, CHILD), + ], + &[ + (B, CallKind::Batch(&[Named::Raw(13)]), ROOT), + (A, CallKind::Batch(&[Named::Core(2)]), CHILD), + ], + ), + &[A_ROOT_KEYBOARD_GRAB], + ), order: CallOrder::Total, }; @@ -608,41 +556,32 @@ const R8_REPLAY: Scenario = Scenario { &[button_press(XTEST_SLAVE_POINTER)], ), ], - allow: Outcome { - frames: &[ - (A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT), - (B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), - ], - calls: &[ - (A, XI1_BUTTON_PRESS_CALL, ROOT), - (B, XI1_BUTTON_PRESS_CALL, CHILD), - ], - grab: Some(&[Grab::Xi1 { - device: DEVICEID_XTEST_POINTER, - owner: B, - window: CHILD, - }]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[ + (A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT), + (B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + ], + &[ + (A, XI1_BUTTON_PRESS_CALL, ROOT), + (B, XI1_BUTTON_PRESS_CALL, CHILD), + ], + ), + &[B_CHILD_XI1_POINTER_GRAB], + ), order: CallOrder::Total, }; const R9_XI1_FREEZE: Scenario = Scenario { setup: setup_r9_xi1_freeze_next, steps: &[button_press(XTEST_SLAVE_POINTER)], - allow: Outcome { - frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT)], - calls: &[(A, XI1_BUTTON_PRESS_CALL, ROOT)], - grab: Some(&[ - Grab::Xi1 { - device: DEVICEID_XTEST_POINTER, - owner: A, - window: ROOT, - }, - XI1_POINTER_PRESS_STORED, - ]), - ..NOTHING - }, + allow: with_grab( + frames_and_calls( + &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT)], + &[(A, XI1_BUTTON_PRESS_CALL, ROOT)], + ), + &[A_ROOT_XI1_POINTER_GRAB, XI1_POINTER_PRESS_STORED], + ), order: CallOrder::Total, }; @@ -654,25 +593,18 @@ const ROWS: &[InputRow] = &[ name: "r1_equal_key_xi1_routed_entries_share_freeze_pass@queue", scenario: &R1_XI1_QUEUE, deny: &[], - denied: Outcome { - frames: &[ - (A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT), - (A, Kind::Xi2(PHYSICAL_DEVICE), ROOT), - ], - calls: &[(A, CallKind::Xi2, ROOT), (A, CallKind::Xi2, ROOT)], - grab: Some(&[ - Grab::Keyboard { - owner: A, - window: ROOT, - }, - Grab::Detached { - device: DEVICEID_XTEST_POINTER, - master: DEVICEID_MASTER_POINTER, - }, - Grab::Detached { - device: PHYSICAL_DEVICE, - master: DEVICEID_MASTER_POINTER, - }, + denied: with_grab( + frames_and_calls( + &[ + (A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT), + (A, Kind::Xi2(PHYSICAL_DEVICE), ROOT), + ], + &[(A, CallKind::Xi2, ROOT), (A, CallKind::Xi2, ROOT)], + ), + &[ + A_ROOT_KEYBOARD_GRAB, + XTEST_POINTER_DETACHED, + PHYSICAL_POINTER_DETACHED, R1_XTEST_PASSIVE_GRAB, R1_PHYSICAL_PASSIVE_GRAB, Grab::Freeze { @@ -685,45 +617,36 @@ const ROWS: &[InputRow] = &[ PHYSICAL_POINTER_PRESS_STORED, R1_XTEST_XI1_QUEUED, R1_PHYSICAL_XI1_QUEUED, - ]), - ..NOTHING - }, + ], + ), }, InputRow { name: "r1_equal_key_xi1_routed_entries_share_freeze_pass", scenario: &R1_XI1_THAW, deny: &[], - denied: Outcome { - frames: &[ - (A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT), - (A, Kind::Xi2(PHYSICAL_DEVICE), ROOT), - (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), - (A, Kind::Xi1(PHYSICAL_DEVICE), CHILD), - ], - calls: &[ - (A, CallKind::Xi2, ROOT), - (A, CallKind::Xi2, ROOT), - (A, XI1_BUTTON_PRESS_CALL, CHILD), - (A, XI1_BUTTON_PRESS_CALL, CHILD), - ], - grab: Some(&[ - Grab::Keyboard { - owner: A, - window: ROOT, - }, - Grab::Detached { - device: DEVICEID_XTEST_POINTER, - master: DEVICEID_MASTER_POINTER, - }, - Grab::Detached { - device: PHYSICAL_DEVICE, - master: DEVICEID_MASTER_POINTER, - }, + denied: with_grab( + frames_and_calls( + &[ + (A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT), + (A, Kind::Xi2(PHYSICAL_DEVICE), ROOT), + (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + (A, Kind::Xi1(PHYSICAL_DEVICE), CHILD), + ], + &[ + (A, CallKind::Xi2, ROOT), + (A, CallKind::Xi2, ROOT), + (A, XI1_BUTTON_PRESS_CALL, CHILD), + (A, XI1_BUTTON_PRESS_CALL, CHILD), + ], + ), + &[ + A_ROOT_KEYBOARD_GRAB, + XTEST_POINTER_DETACHED, + PHYSICAL_POINTER_DETACHED, R1_XTEST_PASSIVE_GRAB, R1_PHYSICAL_PASSIVE_GRAB, - ]), - ..NOTHING - }, + ], + ), }, // Mutation: gate passive storage on the original activating write's // Receive result. Denying A@ROOT must still leave ReplayPointer able to @@ -733,11 +656,10 @@ const ROWS: &[InputRow] = &[ name: "r4_replay_pointer_rechecks_the_natural_target@press", scenario: &R4_PRESS, deny: &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], - denied: Outcome { - calls: &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], - grab: Some(&[PASSIVE_CORE_POINTER, CORE_POINTER_PRESS_FROZEN]), - ..NOTHING - }, + denied: with_grab( + calls_only(&[(A, CORE_BUTTON_PRESS_CALL, ROOT)]), + &[PASSIVE_CORE_POINTER, CORE_POINTER_PRESS_FROZEN], + ), }, // Mutation: make the replay's core selection route selection-only. B's // denial must let A at FOCUS receive the press; Xorg 21.1.24 replay @@ -748,21 +670,22 @@ const ROWS: &[InputRow] = &[ name: "r4_replay_pointer_rechecks_the_natural_target", scenario: &R4_REPLAY, deny: &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], - denied: Outcome { - frames: &[(B, Kind::Core, CHILD)], - calls: &[ - (A, CORE_BUTTON_PRESS_CALL, ROOT), - (B, CORE_BUTTON_PRESS_CALL, CHILD), - ], - grab: Some(&[Grab::Pointer(PointerGrab { + denied: with_grab( + frames_and_calls( + &[(B, Kind::Core, CHILD)], + &[ + (A, CORE_BUTTON_PRESS_CALL, ROOT), + (B, CORE_BUTTON_PRESS_CALL, CHILD), + ], + ), + &[Grab::Pointer(PointerGrab { owner: B, window: CHILD, implicit: true, passive: false, via_xi2: false, - })]), - ..NOTHING - }, + })], + ), }, InputRow { name: "r4_replay_pointer_rechecks_the_natural_target_denied_at_B", @@ -771,23 +694,26 @@ const ROWS: &[InputRow] = &[ (A, CORE_BUTTON_PRESS_CALL, ROOT), (B, CORE_BUTTON_PRESS_CALL, CHILD), ], - denied: Outcome { - frames: &[(A, Kind::Core, FOCUS)], - moved: &[moved(A, Kind::Core, FOCUS, CHILD, FOCUS_EVENT)], - calls: &[ - (A, CORE_BUTTON_PRESS_CALL, ROOT), - (B, CORE_BUTTON_PRESS_CALL, CHILD), - (A, CORE_BUTTON_PRESS_CALL, FOCUS), - ], - grab: Some(&[Grab::Pointer(PointerGrab { + denied: with_grab( + with_moved( + frames_and_calls( + &[(A, Kind::Core, FOCUS)], + &[ + (A, CORE_BUTTON_PRESS_CALL, ROOT), + (B, CORE_BUTTON_PRESS_CALL, CHILD), + (A, CORE_BUTTON_PRESS_CALL, FOCUS), + ], + ), + &[moved(A, Kind::Core, FOCUS, CHILD, FOCUS_EVENT)], + ), + &[Grab::Pointer(PointerGrab { owner: A, window: FOCUS, implicit: true, passive: false, via_xi2: false, - })]), - ..NOTHING - }, + })], + ), }, // Mutation: gate activation storage on the original denied write. The // checkpoint still requires A's active grab and stored transition, with @@ -796,17 +722,10 @@ const ROWS: &[InputRow] = &[ name: "r5_replay_keyboard_rechecks_the_focus@press", scenario: &R5_PRESS, deny: &[(A, CORE_KEY_PRESS_CALL, ROOT)], - denied: Outcome { - calls: &[(A, CORE_KEY_PRESS_CALL, ROOT)], - grab: Some(&[ - Grab::Keyboard { - owner: A, - window: ROOT, - }, - MASTER_KEY_PRESS_FROZEN, - ]), - ..NOTHING - }, + denied: with_grab( + calls_only(&[(A, CORE_KEY_PRESS_CALL, ROOT)]), + &[A_ROOT_KEYBOARD_GRAB, MASTER_KEY_PRESS_FROZEN], + ), }, // Mutation: gate the stored activating transition on its original // Receive result. ReplayKeyboard must still hand a denied A copy to B. @@ -815,15 +734,16 @@ const ROWS: &[InputRow] = &[ name: "r5_replay_keyboard_rechecks_the_focus_denied_activation", scenario: &R5_REPLAY, deny: &[(A, CORE_KEY_PRESS_CALL, ROOT)], - denied: Outcome { - frames: &[(B, Kind::Core, FOCUS)], - calls: &[ - (A, CORE_KEY_PRESS_CALL, ROOT), - (B, CORE_KEY_PRESS_CALL, FOCUS), - ], - grab: Some(&[]), - ..NOTHING - }, + denied: with_grab( + frames_and_calls( + &[(B, Kind::Core, FOCUS)], + &[ + (A, CORE_KEY_PRESS_CALL, ROOT), + (B, CORE_KEY_PRESS_CALL, FOCUS), + ], + ), + &[], + ), }, // Mutation: a denied selector at the focused window vetoes another // client's allowed copy. Kill probe: `t3r1-r5-key-denial-does-not-veto`. @@ -834,16 +754,17 @@ const ROWS: &[InputRow] = &[ (A, CORE_KEY_PRESS_CALL, ROOT), (B, CORE_KEY_PRESS_CALL, FOCUS), ], - denied: Outcome { - frames: &[(A, Kind::Core, FOCUS)], - calls: &[ - (A, CORE_KEY_PRESS_CALL, ROOT), - (A, CORE_KEY_PRESS_CALL, FOCUS), - (B, CORE_KEY_PRESS_CALL, FOCUS), - ], - grab: Some(&[]), - ..NOTHING - }, + denied: with_grab( + frames_and_calls( + &[(A, Kind::Core, FOCUS)], + &[ + (A, CORE_KEY_PRESS_CALL, ROOT), + (A, CORE_KEY_PRESS_CALL, FOCUS), + (B, CORE_KEY_PRESS_CALL, FOCUS), + ], + ), + &[], + ), }, // Mutation: skip Receive for the replayed key's focus write. A denied // focus copy must be dropped; Xorg 21.1.24 replays to focus at `dix/events.c:1360`. @@ -854,14 +775,13 @@ const ROWS: &[InputRow] = &[ (A, CORE_KEY_PRESS_CALL, ROOT), (B, CORE_KEY_PRESS_CALL, FOCUS), ], - denied: Outcome { - calls: &[ + denied: with_grab( + calls_only(&[ (A, CORE_KEY_PRESS_CALL, ROOT), (B, CORE_KEY_PRESS_CALL, FOCUS), - ], - grab: Some(&[]), - ..NOTHING - }, + ]), + &[], + ), }, // Pin only: queueing the motion makes no Receive call and preserves it; // Xorg `ComputeFreezes` queues without a Receive hook (`dix/events.c:1320`). @@ -869,16 +789,17 @@ const ROWS: &[InputRow] = &[ name: "r6_thawed_queued_motion_is_checked_at_its_write@queue", scenario: &R6_QUEUE, deny: &[], - denied: Outcome { - frames: &[(A, Kind::Core, ROOT)], - calls: &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], - grab: Some(&[ + denied: with_grab( + frames_and_calls( + &[(A, Kind::Core, ROOT)], + &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], + ), + &[ PASSIVE_CORE_POINTER, CORE_POINTER_PRESS_FROZEN, MASTER_POINTER_MOTION_QUEUED, - ]), - ..NOTHING - }, + ], + ), }, // Mutation: bypass `fanout::receive_allows` while // `state.playing_sync_events` in the thawed pointer write. The denied @@ -888,17 +809,20 @@ const ROWS: &[InputRow] = &[ name: "r6_thawed_queued_motion_is_checked_at_its_write", scenario: &R6_THAW, deny: &[(A, CallKind::Batch(&[Named::Core(6)]), CHILD)], - denied: Outcome { - frames: &[(A, Kind::Core, ROOT), (A, Kind::Core, ROOT)], - moved: &[moved(A, Kind::Core, ROOT, FOCUS, MOTION_TO)], - calls: &[ - (A, CORE_BUTTON_PRESS_CALL, ROOT), - (A, CORE_MOTION_CALL, CHILD), - (A, CORE_MOTION_CALL, ROOT), - ], - grab: Some(&[PASSIVE_CORE_POINTER]), - ..NOTHING - }, + denied: with_grab( + with_moved( + frames_and_calls( + &[(A, Kind::Core, ROOT), (A, Kind::Core, ROOT)], + &[ + (A, CORE_BUTTON_PRESS_CALL, ROOT), + (A, CORE_MOTION_CALL, CHILD), + (A, CORE_MOTION_CALL, ROOT), + ], + ), + &[moved(A, Kind::Core, ROOT, FOCUS, MOTION_TO)], + ), + &[PASSIVE_CORE_POINTER], + ), }, InputRow { name: "r6_thawed_queued_motion_denied_at_both_writes_stays_grabbed", @@ -926,10 +850,7 @@ const ROWS: &[InputRow] = &[ deny: &[], denied: Outcome { grab: Some(&[ - Grab::Keyboard { - owner: A, - window: ROOT, - }, + A_ROOT_KEYBOARD_GRAB, XI1_KEYBOARD_QUEUE, Grab::Queued { device: DEVICEID_MASTER_KEYBOARD, @@ -961,20 +882,20 @@ const ROWS: &[InputRow] = &[ (B, RAW_KEY_PRESS_CALL, ROOT), (A, CORE_KEY_PRESS_CALL, CHILD), ], - denied: Outcome { - frames: &[(A, Kind::Core, ROOT)], - moved: &[moved(A, Kind::Core, ROOT, FOCUS, (120, 120))], - calls: &[ - (B, CallKind::Batch(&[Named::Raw(13)]), ROOT), - (A, CallKind::Batch(&[Named::Core(2)]), CHILD), - (A, CallKind::Batch(&[Named::Core(2)]), ROOT), - ], - grab: Some(&[Grab::Keyboard { - owner: A, - window: ROOT, - }]), - ..NOTHING - }, + denied: with_grab( + with_moved( + frames_and_calls( + &[(A, Kind::Core, ROOT)], + &[ + (B, CallKind::Batch(&[Named::Raw(13)]), ROOT), + (A, CallKind::Batch(&[Named::Core(2)]), CHILD), + (A, CallKind::Batch(&[Named::Core(2)]), ROOT), + ], + ), + &[moved(A, Kind::Core, ROOT, FOCUS, (120, 120))], + ), + &[A_ROOT_KEYBOARD_GRAB], + ), }, // Mutation: playback calls Receive for the ROOT fallback but discards its // denial. Kill probe: `t4-r7-playback-discards-root-receive-denial`. @@ -986,19 +907,14 @@ const ROWS: &[InputRow] = &[ (A, CORE_KEY_PRESS_CALL, CHILD), (A, CORE_KEY_PRESS_CALL, ROOT), ], - denied: Outcome { - frames: &[], - calls: &[ + denied: with_grab( + calls_only(&[ (B, CallKind::Batch(&[Named::Raw(13)]), ROOT), (A, CallKind::Batch(&[Named::Core(2)]), CHILD), (A, CallKind::Batch(&[Named::Core(2)]), ROOT), - ], - grab: Some(&[Grab::Keyboard { - owner: A, - window: ROOT, - }]), - ..NOTHING - }, + ]), + &[A_ROOT_KEYBOARD_GRAB], + ), }, // Mutation: gate XI1 activation storage on the original write's Receive // result. A denied activation still stores it for ReplayThisDevice; @@ -1014,11 +930,7 @@ const ROWS: &[InputRow] = &[ (A, XI1_BUTTON_PRESS_CALL, ROOT), (B, XI1_BUTTON_PRESS_CALL, CHILD), ], - grab: Some(&[Grab::Xi1 { - device: DEVICEID_XTEST_POINTER, - owner: B, - window: CHILD, - }]), + grab: Some(&[B_CHILD_XI1_POINTER_GRAB]), ..NOTHING }, }, @@ -1029,27 +941,30 @@ const ROWS: &[InputRow] = &[ (A, XI1_BUTTON_PRESS_CALL, ROOT), (B, XI1_BUTTON_PRESS_CALL, CHILD), ], - denied: Outcome { - frames: &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], - moved: &[moved( - A, - Kind::Xi1(DEVICEID_XTEST_POINTER), - FOCUS, - CHILD, - FOCUS_EVENT, - )], - calls: &[ - (A, XI1_BUTTON_PRESS_CALL, ROOT), - (B, XI1_BUTTON_PRESS_CALL, CHILD), - (A, XI1_BUTTON_PRESS_CALL, FOCUS), - ], - grab: Some(&[Grab::Xi1 { + denied: with_grab( + with_moved( + frames_and_calls( + &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], + &[ + (A, XI1_BUTTON_PRESS_CALL, ROOT), + (B, XI1_BUTTON_PRESS_CALL, CHILD), + (A, XI1_BUTTON_PRESS_CALL, FOCUS), + ], + ), + &[moved( + A, + Kind::Xi1(DEVICEID_XTEST_POINTER), + FOCUS, + CHILD, + FOCUS_EVENT, + )], + ), + &[Grab::Xi1 { device: DEVICEID_XTEST_POINTER, owner: A, window: FOCUS, - }]), - ..NOTHING - }, + }], + ), }, // Mutation: gate `xi1_freeze_this_event_if_needed` on `deliver`. A denied // grab-window write must still trip FreezeNextEvent and store the press; @@ -1058,18 +973,10 @@ const ROWS: &[InputRow] = &[ name: "r9_denied_xi1_grab_window_write_trips_freeze_next", scenario: &R9_XI1_FREEZE, deny: &[(A, XI1_BUTTON_PRESS_CALL, ROOT)], - denied: Outcome { - calls: &[(A, XI1_BUTTON_PRESS_CALL, ROOT)], - grab: Some(&[ - Grab::Xi1 { - device: DEVICEID_XTEST_POINTER, - owner: A, - window: ROOT, - }, - XI1_POINTER_PRESS_STORED, - ]), - ..NOTHING - }, + denied: with_grab( + calls_only(&[(A, XI1_BUTTON_PRESS_CALL, ROOT)]), + &[A_ROOT_XI1_POINTER_GRAB, XI1_POINTER_PRESS_STORED], + ), }, ]; From 1f927529dae23c08d396d131ec90e063731ce65c Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Thu, 3 Dec 2026 18:33:20 -0300 Subject: [PATCH 70/72] test(access): prune input rows to the ones that pin a distinct decision Keep the rows that alone catch a mutation of the input routing, a small cover of the rest, one row for each spec routing rule not otherwise pinned, and the k1, p14 replay and p18 fallback rows: 48 of 113. Self-tests that a kept row now exercises are gone. The four files go from 6,364 to 4,268 lines; every one of the 117 mutation probes is still caught at a kept assertion. Co-Authored-By: Claude Opus 5.5 Implemented-By: codex (gpt-6-luna max) --- .../tests/access_input_support.rs | 76 -- .../process_request/tests/access_key_input.rs | 407 ------ .../tests/access_pointer_input.rs | 1204 +---------------- .../tests/access_replay_input.rs | 487 ------- 4 files changed, 39 insertions(+), 2135 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index d85475bb5..07dae3670 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -1815,82 +1815,6 @@ mod batch_naming { } } - fn run_with_xi2_frame(evtype: u16, detail: u32) -> Run { - let order = ClientByteOrder::BigEndian; - let mut frame = [0_u8; 32]; - frame[0] = 35; - frame[1] = XI2_MAJOR_OPCODE; - frame[8..10].copy_from_slice(&evtype.to_be_bytes()); - frame[10..12].copy_from_slice(&crate::xinput::DEVICEID_MASTER_POINTER.to_be_bytes()); - frame[16..20].copy_from_slice(&detail.to_be_bytes()); - frame[24..28].copy_from_slice(&CHILD.to_be_bytes()); - Run { - clients: vec![ClientBytes { - client: A, - order, - steps: vec![StepBytes { - bytes: frame.to_vec(), - sequence: 0, - }], - }], - hooks: Vec::new(), - requests: Vec::new(), - replies: Vec::new(), - state: String::new(), - grab: Vec::new(), - } - } - - /// Mutation: a replayed XI2 ButtonPress is encoded with detail zero. It - /// must not borrow zero from the Motion in the same request step. - #[test] - fn multi_event_frame_detail_is_checked_against_its_own_event_type() { - let bad_press = run_with_xi2_frame(4, 0); - let panic = std::panic::catch_unwind(|| { - delivered("multi-event detail", &bad_press, &[vec![(4, 1), (6, 0)]]) - }) - .expect_err("ButtonPress detail 0 must not borrow Motion detail 0"); - let message = panic - .downcast_ref::() - .map(String::as_str) - .or_else(|| panic.downcast_ref::<&str>().copied()) - .unwrap_or_default(); - assert!( - message.contains("frame event Some(4) detail Some(0)"), - "ButtonPress detail mismatch must be the rejected condition, got {message:?}" - ); - } - - #[test] - fn multi_event_motion_keeps_its_zero_detail() { - let motion = run_with_xi2_frame(6, 0); - assert_eq!( - delivered("multi-event detail", &motion, &[vec![(4, 1), (6, 0)]]), - vec![(A, Kind::Xi2(crate::xinput::DEVICEID_MASTER_POINTER), CHILD)] - ); - } - - /// Mutation: a batch is traced by its first description, or the shorthand - /// names a description with another event type than the row drives. The - /// list order and each description's own numbering are what decide and the - /// trace compare. - #[test] - fn a_batch_call_is_traced_as_its_ordered_list() { - const SMOOTH_STOP: &[Named] = &[Named::Xi2(6), Named::Xi2(6)]; - let batch: Call = (A, CallKind::Batch(SMOOTH_STOP), CHILD); - assert_eq!( - expected_call(&batch, 4), - (A, vec![Named::Xi2(6), Named::Xi2(6)], CHILD) - ); - let shorthand: Call = (A, CallKind::Xi2, CHILD); - assert_eq!( - expected_call(&shorthand, 6), - (A, vec![Named::Xi2(6)], CHILD) - ); - let xi1: Call = (B, CallKind::Batch(&[Named::Xi1(6)]), FOCUS); - assert_eq!(expected_call(&xi1, 4), (B, vec![Named::Xi1(6)], FOCUS)); - } - /// A shorthand names the event of the step that made the call: the same /// recorded call is the shorthand under its own step's event and an /// explicit name under another step's. diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs index a37db9585..dcf33f2f9 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -31,14 +31,6 @@ fn setup_k2(f: &mut NotifyFixture) { select_core(f, SEND_CLIENT, FOCUS, KEY_PRESS); } -/// A selects XI2 (master) and core on CHILD; B selects core on FOCUS. -fn setup_k3(f: &mut NotifyFixture) { - tree(f); - select_core(f, A, CHILD, KEY_PRESS); - select_xi2(f, A, CHILD, DEVICEID_MASTER_KEYBOARD, XI_KEY_PRESS); - select_core(f, B, FOCUS, KEY_PRESS); -} - /// A selects XI2 on the master (3) and slave (5) keyboards and core on CHILD. fn setup_k4(f: &mut NotifyFixture) { tree(f); @@ -48,21 +40,6 @@ fn setup_k4(f: &mut NotifyFixture) { } } -/// Synthetic release: A selects only XI2 KeyRelease on CHILD; B core on FOCUS. -fn setup_k5_xi2_release(f: &mut NotifyFixture) { - tree(f); - select_xi2(f, A, CHILD, DEVICEID_MASTER_KEYBOARD, XI_KEY_RELEASE); - select_core(f, B, FOCUS, KEY_RELEASE); -} - -/// Synthetic release with a detectable-repeat core selector on CHILD. -fn setup_k5_detectable(f: &mut NotifyFixture) { - tree(f); - select_core(f, A, CHILD, KEY_RELEASE); - select_core(f, B, FOCUS, KEY_RELEASE); - set_detectable_repeat(f, A); -} - /// Slave origin with the master transition rejected: the core form is excluded /// on this path. A selects slave XI2 and core on CHILD; B slave XI2 on FOCUS. fn setup_k5b(f: &mut NotifyFixture) { @@ -87,38 +64,8 @@ fn setup_k5c_grab(f: &mut NotifyFixture) { grab_slave_keyboard(f, A, FOCUS); } -/// The slave origin through the slave focus path, with no grab. -fn setup_k5c_focus(f: &mut NotifyFixture) { - tree(f); - select_xi2(f, A, CHILD, DEVICEID_XTEST_KEYBOARD, XI_KEY_PRESS); -} - -/// A selects core on CHILD and FOCUS; B selects core on FOCUS. -fn setup_k6a(f: &mut NotifyFixture) { - tree(f); - select_core(f, A, CHILD, KEY_PRESS); - select_core(f, A, FOCUS, KEY_PRESS); - select_core(f, B, FOCUS, KEY_PRESS); -} - -/// Only A selects, on CHILD and FOCUS. -fn setup_k6b(f: &mut NotifyFixture) { - tree(f); - select_core(f, A, CHILD, KEY_PRESS); - select_core(f, A, FOCUS, KEY_PRESS); -} - // Grabbed rows: A is the grab owner, B the foreign selector. -/// A grabs the keyboard with owner_events on the root and selects core presses -/// on CHILD (the pointer window) and FOCUS. -fn setup_k7(f: &mut NotifyFixture) { - tree(f); - grab_keyboard(f, A, ROOT, true); - select_core(f, A, CHILD, KEY_PRESS); - select_core(f, A, FOCUS, KEY_PRESS); -} - /// A grabs with owner_events on the root and selects core on CHILD; B selects /// core on CHILD too. With A denied at CHILD, B's allowed copy is the foreign /// rejection and the grab window gets the key (k8); with B denied, A qualifies @@ -130,15 +77,6 @@ fn setup_k8(f: &mut NotifyFixture) { select_core(f, B, CHILD, KEY_PRESS); } -/// B alone selects core on CHILD and is denied there, so it does not reject; -/// A selects core on FOCUS, which is allowed. -fn setup_k9(f: &mut NotifyFixture) { - tree(f); - grab_keyboard(f, A, ROOT, true); - select_core(f, B, CHILD, KEY_PRESS); - select_core(f, A, FOCUS, KEY_PRESS); -} - /// A grabs with owner_events on the root. A, B and SEND_CLIENT select core /// press on CHILD. A is denied there; B and SEND_CLIENT are allowed. Every /// foreign selector is asked, and A falls back to the root grab window. @@ -160,13 +98,6 @@ fn setup_k10(f: &mut NotifyFixture) { select_xi2(f, B, CHILD, DEVICEID_MASTER_KEYBOARD, XI_KEY_RELEASE); } -/// A grabs with owner_events false on the root; B selects core press on FOCUS. -fn setup_k11(f: &mut NotifyFixture) { - tree(f); - grab_keyboard(f, A, ROOT, false); - select_core(f, B, FOCUS, KEY_PRESS); -} - /// A holds a synchronous passive GrabKey on the root (owner_events false) and /// B selects core press on FOCUS. fn setup_k12(f: &mut NotifyFixture) { @@ -175,14 +106,6 @@ fn setup_k12(f: &mut NotifyFixture) { select_core(f, B, FOCUS, KEY_PRESS); } -/// A holds a core keyboard grab on the root (owner_events false) and has -/// detectable repeat. -fn setup_k13_detectable(f: &mut NotifyFixture) { - tree(f); - grab_keyboard(f, A, ROOT, false); - set_detectable_repeat(f, A); -} - /// A grabs with owner_events on the root and has detectable repeat. A selects /// core release on CHILD and B selects core release on FOCUS. fn setup_k13_natural(f: &mut NotifyFixture) { @@ -193,22 +116,6 @@ fn setup_k13_natural(f: &mut NotifyFixture) { select_core(f, B, FOCUS, KEY_RELEASE); } -/// A and B select RawKeyPress on the root for the master keyboard. SEND_CLIENT -/// (the slave-form selector) selects it for the slave keyboard. -fn setup_k13_raw(f: &mut NotifyFixture) { - tree(f); - for client in [A, B] { - select_xi2(f, client, ROOT, DEVICEID_MASTER_KEYBOARD, XI_RAW_KEY_PRESS); - } - select_xi2( - f, - SEND_CLIENT, - ROOT, - DEVICEID_XTEST_KEYBOARD, - XI_RAW_KEY_PRESS, - ); -} - /// A holds the master keyboard's XI2 grab on CHILD with owner_events, the grab /// mask selects RawKeyPress, and focus is PointerRoot. A selects RawKeyPress on /// the root for the master keyboard, so the natural walk reaches it. @@ -216,11 +123,6 @@ fn setup_k14(f: &mut NotifyFixture) { setup_k14_with_mask(f, XI_KEY_PRESS | XI_RAW_KEY_PRESS); } -/// The same without RawKeyPress in the grab mask. -fn setup_k14_without_raw_bit(f: &mut NotifyFixture) { - setup_k14_with_mask(f, XI_KEY_PRESS); -} - fn setup_k14_with_mask(f: &mut NotifyFixture, mask: u32) { tree(f); set_focus_pointer_root(f); @@ -228,8 +130,6 @@ fn setup_k14_with_mask(f: &mut NotifyFixture, mask: u32) { select_xi2(f, A, ROOT, DEVICEID_MASTER_KEYBOARD, XI_RAW_KEY_PRESS); } -const XI1_KEY_PRESS_CALL: CallKind = - CallKind::Batch(&[Named::Xi1(crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET as u16)]); const XI1_KEY_RELEASE_CALL: CallKind = CallKind::Batch(&[Named::Xi1( crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET as u16, )]); @@ -238,14 +138,6 @@ fn xi1_key_class(offset: u8) -> u32 { (u32::from(DEVICEID_XTEST_KEYBOARD) << 8) | u32::from(crate::server::XI_FIRST_EVENT + offset) } -/// A selects the XI1 `DeviceKeyPress` of the slave keyboard on CHILD, B on FOCUS. -fn setup_k16(f: &mut NotifyFixture) { - tree(f); - let class = xi1_key_class(crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET); - select_xi1(f, A, CHILD, &[class]); - select_xi1(f, B, FOCUS, &[class]); -} - /// The same for `DeviceKeyRelease`, with A on detectable repeat. fn setup_k17(f: &mut NotifyFixture) { tree(f); @@ -308,16 +200,6 @@ const K1_SCENARIO: Scenario = Scenario { order: CallOrder::Total, }; -const K3_SCENARIO: Scenario = Scenario { - setup: setup_k3, - steps: &[PRESS], - allow: frames_and_calls( - &[(A, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), CHILD)], - &[(A, CallKind::Xi2, CHILD)], - ), - order: CallOrder::Total, -}; - const K4_SCENARIO: Scenario = Scenario { setup: setup_k4, steps: &[XTEST_PRESS], @@ -331,22 +213,6 @@ const K4_SCENARIO: Scenario = Scenario { order: CallOrder::Total, }; -/// A selector the walk stops at without a copy or a check: nothing is written -/// or asked, whatever the denial says. -const SUPPRESSED: Scenario = Scenario { - setup: setup_k5_xi2_release, - steps: &[SYNTH_RELEASE], - allow: NOTHING, - order: CallOrder::Total, -}; - -const K5_DETECTABLE_SCENARIO: Scenario = Scenario { - setup: setup_k5_detectable, - steps: &[SYNTH_RELEASE], - allow: NOTHING, - order: CallOrder::Total, -}; - const K5B_SCENARIO: Scenario = Scenario { setup: setup_k5b, steps: &[SLAVE_PRESS], @@ -364,39 +230,6 @@ const K5B_MASTER_SCENARIO: Scenario = Scenario { order: CallOrder::Total, }; -const K5C_GRAB_SCENARIO: Scenario = Scenario { - setup: setup_k5c_grab, - steps: &[SLAVE_PRESS], - allow: with_grab( - frames_and_calls( - &[(A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), FOCUS)], - &[(A, CallKind::Xi2, FOCUS)], - ), - A_GRABS_SLAVE, - ), - order: CallOrder::Total, -}; - -const K5C_FOCUS_SCENARIO: Scenario = Scenario { - setup: setup_k5c_focus, - steps: &[SLAVE_PRESS], - allow: frames_and_calls( - &[(A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD)], - &[(A, CallKind::Xi2, CHILD)], - ), - order: CallOrder::Total, -}; - -const K7_SCENARIO: Scenario = Scenario { - setup: setup_k7, - steps: &[PRESS], - allow: Outcome { - grab: Some(A_GRABS_ROOT), - ..A_CORE_CHILD - }, - order: CallOrder::Total, -}; - const K8_SCENARIO: Scenario = Scenario { setup: setup_k8, steps: &[PRESS], @@ -439,24 +272,6 @@ const K12_GRABS: &[Grab] = &[ }, ]; -const K13_RAW_SCENARIO: Scenario = Scenario { - setup: setup_k13_raw, - steps: &[XTEST_RAW_PRESS], - allow: frames_and_calls( - &[ - (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), - (B, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), - (SEND_CLIENT, Kind::Raw(DEVICEID_XTEST_KEYBOARD), ROOT), - ], - &[ - (SEND_CLIENT, CallKind::Raw, ROOT), - (A, CallKind::Raw, ROOT), - (B, CallKind::Raw, ROOT), - ], - ), - order: CallOrder::PerClient, -}; - /// The grab owner's raw copies: the natural copy at the root and the grab /// leg's copy, which the root fanout repeats. An allowed natural copy is the /// only grab-leg copy; the grab window is never asked. @@ -507,34 +322,6 @@ const ROWS: &[InputRow] = &[ &[(A, CallKind::Core, CHILD), (B, CallKind::Core, CHILD)], ), }, - InputRow { - name: "k3_denied_xi2_copy_reopens_core_for_that_client", - scenario: &K3_SCENARIO, - deny: &[(A, CallKind::Xi2, CHILD)], - denied: with_moved( - frames_and_calls( - &[(A, Kind::Core, CHILD)], - &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], - ), - &[moved(A, Kind::Core, CHILD, 0, (10, 10))], - ), - }, - InputRow { - name: "k3_both_denied_walks_on_to_the_focus", - scenario: &K3_SCENARIO, - deny: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], - denied: with_moved( - frames_and_calls( - &[(B, Kind::Core, FOCUS)], - &[ - (A, CallKind::Xi2, CHILD), - (A, CallKind::Core, CHILD), - (B, CallKind::Core, FOCUS), - ], - ), - &[moved(B, Kind::Core, FOCUS, CHILD, (20, 20))], - ), - }, // The XI2 forms of one key share one check. With that check allowed the // denial list is empty, so the allowed row is this scenario's allow run. InputRow { @@ -549,18 +336,6 @@ const ROWS: &[InputRow] = &[ &[moved(A, Kind::Core, CHILD, 0, (10, 10))], ), }, - InputRow { - name: "k5_suppressed_xi2_release_stops_without_a_check", - scenario: &SUPPRESSED, - deny: &[(A, CallKind::Xi2, CHILD)], - denied: NOTHING, - }, - InputRow { - name: "k5_suppressed_detectable_core_release_stops_without_a_check", - scenario: &K5_DETECTABLE_SCENARIO, - deny: &[(A, CallKind::Core, CHILD)], - denied: NOTHING, - }, InputRow { name: "k5b_form_excluded_by_the_include_flags_still_stops", scenario: &K5B_SCENARIO, @@ -573,101 +348,6 @@ const ROWS: &[InputRow] = &[ deny: &[(A, CallKind::Xi2, CHILD)], denied: NOTHING, }, - InputRow { - name: "k5c_slave_grab_write_is_checked", - scenario: &K5C_GRAB_SCENARIO, - deny: &[(A, CallKind::Xi2, FOCUS)], - denied: calls_only(&[(A, CallKind::Xi2, FOCUS)]), - }, - InputRow { - name: "k5c_slave_focus_path_is_checked", - scenario: &K5C_FOCUS_SCENARIO, - deny: &[(A, CallKind::Xi2, CHILD)], - denied: calls_only(&[(A, CallKind::Xi2, CHILD)]), - }, - InputRow { - name: "k6_all_denied_lands_on_focus_with_a_stopping_focus_selector", - scenario: &Scenario { - setup: setup_k6a, - steps: &[PRESS], - allow: A_CORE_CHILD, - order: CallOrder::PerClient, - }, - deny: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - denied: with_moved( - frames_and_calls( - &[(B, Kind::Core, FOCUS)], - &[ - (A, CallKind::Core, CHILD), - (A, CallKind::Core, FOCUS), - (B, CallKind::Core, FOCUS), - ], - ), - &[moved(B, Kind::Core, FOCUS, CHILD, (20, 20))], - ), - }, - InputRow { - name: "k6_only_selector_denied_lands_on_focus_and_writes_nothing", - scenario: &Scenario { - setup: setup_k6b, - steps: &[PRESS], - allow: A_CORE_CHILD, - order: CallOrder::Total, - }, - deny: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - denied: calls_only(&[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)]), - }, - InputRow { - name: "k7_denied_owner_copy_continues_the_natural_walk", - scenario: &K7_SCENARIO, - deny: &[(A, CallKind::Core, CHILD)], - denied: with_moved( - frames_and_calls( - &[(A, Kind::Core, FOCUS)], - &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - ), - &[moved(A, Kind::Core, FOCUS, CHILD, (20, 20))], - ), - }, - InputRow { - name: "k8_denied_owner_with_allowed_foreign_falls_back", - scenario: &K8_SCENARIO, - deny: &[(A, CallKind::Core, CHILD)], - denied: with_moved( - frames_and_calls( - &[(A, Kind::Core, ROOT)], - &[ - (A, CallKind::Core, CHILD), - (B, CallKind::Core, CHILD), - (A, CallKind::Core, ROOT), - ], - ), - &[moved(A, Kind::Core, ROOT, FOCUS, (120, 120))], - ), - }, - InputRow { - name: "k9_denied_foreign_selector_does_not_reject", - scenario: &Scenario { - setup: setup_k9, - steps: &[PRESS], - allow: with_grab( - frames_and_calls( - &[(A, Kind::Core, ROOT)], - &[(B, CallKind::Core, CHILD), (A, CallKind::Core, ROOT)], - ), - A_GRABS_ROOT, - ), - order: CallOrder::Total, - }, - deny: &[(B, CallKind::Core, CHILD)], - denied: with_moved( - frames_and_calls( - &[(A, Kind::Core, FOCUS)], - &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - ), - &[moved(A, Kind::Core, FOCUS, CHILD, (20, 20))], - ), - }, // A and B both select on CHILD and B is denied. A qualifies first, so the // walk stops at CHILD and no check is made for B. InputRow { @@ -707,19 +387,6 @@ const ROWS: &[InputRow] = &[ deny: &[], denied: K10_SCENARIO.allow, }, - // The grab-window copy is denied: no bytes, and B gets nothing, but the - // keyboard grab stays active. - InputRow { - name: "k11_denied_grab_window_copy_is_delivered", - scenario: &Scenario { - setup: setup_k11, - steps: &[PRESS], - allow: A_ROOT_COPY, - order: CallOrder::Total, - }, - deny: &[(A, CallKind::Core, ROOT)], - denied: calls_only(&[(A, CallKind::Core, ROOT)]), - }, // The activating press is denied to A: the grab still activates and // freezes with the press stored. InputRow { @@ -757,20 +424,6 @@ const ROWS: &[InputRow] = &[ deny: &[], denied: NOTHING, }, - InputRow { - name: "k13_synthetic_detectable_core_release_to_a_grab_owner_is_suppressed", - scenario: &Scenario { - setup: setup_k13_detectable, - steps: &[SYNTH_RELEASE], - allow: Outcome { - grab: Some(A_GRABS_ROOT), - ..NOTHING - }, - order: CallOrder::Total, - }, - deny: &[], - denied: NOTHING, - }, // The synthetic release is suppressed for A, so A qualifies at CHILD with // no Receive call and nothing is written; denying A at CHILD changes // nothing, because no copy is checked. @@ -788,21 +441,6 @@ const ROWS: &[InputRow] = &[ deny: &[(A, CallKind::Core, CHILD)], denied: NOTHING, }, - // The slave-form copy goes first (slave pass), then the master copies of A - // and B. Denying A's master root copy drops only A's copy. - InputRow { - name: "k13_denied_raw_root_copy_drops_only_that_copy", - scenario: &K13_RAW_SCENARIO, - deny: &[(A, CallKind::Raw, ROOT)], - denied: Outcome { - frames: &[ - (B, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), - (SEND_CLIENT, Kind::Raw(DEVICEID_XTEST_KEYBOARD), ROOT), - ], - calls: K13_RAW_SCENARIO.allow.calls, - ..NOTHING - }, - }, // Denying A's root copy: the natural copy falls back to the grab window (a // fresh check with CHILD as subject), and the root fanout is denied too. // This row's allow run is also the allowed natural raw leg: the grab @@ -825,51 +463,6 @@ const ROWS: &[InputRow] = &[ ], ), }, - // Without RawKeyPress in the grab mask nothing falls back, so the owner - // gets no copy when its root copy is denied. - InputRow { - name: "k14b_denied_raw_owner_without_raw_grab_bit_gets_nothing", - scenario: &Scenario { - setup: setup_k14_without_raw_bit, - steps: &[XTEST_RAW_PRESS], - allow: K14_ALLOW, - order: CallOrder::Total, - }, - deny: &[(A, CallKind::Raw, ROOT)], - denied: calls_only(K14_ALLOW.calls), - }, - // X selects the XI1 `DeviceKeyPress` on C (the pointer window, under focus - // F), Y on F. X's copy is denied: the focus walk goes on and Y gets it at F. - // Mutation: a denied XI1 selector stops the walk. - InputRow { - name: "k16_xi1_focused_key_denial_advances_the_focus_walk", - scenario: &Scenario { - setup: setup_k16, - steps: &[XTEST_PRESS], - allow: frames_and_calls( - &[(A, Kind::Xi1Key(DEVICEID_XTEST_KEYBOARD), CHILD)], - &[(A, XI1_KEY_PRESS_CALL, CHILD)], - ), - order: CallOrder::Total, - }, - deny: &[(A, XI1_KEY_PRESS_CALL, CHILD)], - denied: with_moved( - frames_and_calls( - &[(B, Kind::Xi1Key(DEVICEID_XTEST_KEYBOARD), FOCUS)], - &[ - (A, XI1_KEY_PRESS_CALL, CHILD), - (B, XI1_KEY_PRESS_CALL, FOCUS), - ], - ), - &[moved( - B, - Kind::Xi1Key(DEVICEID_XTEST_KEYBOARD), - FOCUS, - CHILD, - (20, 20), - )], - ), - }, // A synthetic repeat release to a detectable-repeat client gets no copy but // stops the walk: nothing is written, X is not asked, Y is not reached. // Mutation: X is asked (a call) or the walk goes past it (Y gets a frame). diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index 1f89f3cbe..8919a38fd 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -23,7 +23,6 @@ use yserver_protocol::x11::{ClientId, ResourceId}; /// Core ButtonPressMask, ButtonReleaseMask and MotionNotify mask bits. const CORE_BUTTON_PRESS: u32 = 1 << 2; -const CORE_BUTTON_RELEASE: u32 = 1 << 3; const CORE_MOTION: u32 = 1 << 6; /// XI2 mask bits, one per event type: ButtonPress (4), Motion (6), raw /// ButtonPress (15). @@ -50,10 +49,6 @@ const fn press(origin: InputOrigin) -> Step { button(origin, PointerEventKind::ButtonPress, POINTER) } -const fn release(origin: InputOrigin) -> Step { - button(origin, PointerEventKind::ButtonRelease, POINTER) -} - /// The root position of the motion rows: still over C. const MOTION_TO: (i16, i16) = (125, 125); @@ -121,7 +116,6 @@ const CORE_GRAB_POINTER: u8 = 26; const CORE_GRAB_BUTTON: u8 = 28; const XI_PASSIVE_GRAB_DEVICE: u8 = 54; const XI_ALLOW_EVENTS: u8 = 53; -const XI_ALLOW_DEVICE_EVENTS_XI1: u8 = 19; const XI_GRAB_DEVICE_XI1: u8 = 13; /// `GrabPointer` by `owner` on `window`, asynchronous, with the core event mask. @@ -192,24 +186,6 @@ fn xi1_grab_device(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: assert_eq!((reply[0], reply[8]), (1, 0), "GrabDevice replies Success"); } -/// A `GrabDeviceButton` of the slave by `owner` on `window`, any button and -/// modifier, installed directly. -fn xi1_passive_grab(f: &mut NotifyFixture, owner: u32, window: u32, sync: bool) { - f.state - .xi1_passive_grabs - .push(crate::server::Xi1PassiveGrab { - owner: ClientId(owner), - deviceid: DEVICEID_XTEST_POINTER, - grab_window: ResourceId(window), - detail: 0, - modifiers: 0x8000, - owner_events: false, - this_mode: u8::from(!sync), - other_mode: 1, - is_key: false, - }); -} - /// The requests of the p14 and p28 step lists: `XIAllowEvents` of the master /// pointer by A with mode `MODE`, and the XI1 `AllowDeviceEvents(ReplayThisDevice)` /// of the slave by the requester. Both use `request`, not `send`: a thaw may @@ -234,44 +210,11 @@ fn allow_slave(f: &mut NotifyFixture) { request(f, A, XI_MAJOR, XI_ALLOW_EVENTS, &body); } -fn replay_slave(f: &mut NotifyFixture) { - let mut body = Vec::new(); - body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime - body.extend_from_slice(&[2, DEVICEID_XTEST_POINTER as u8, 0, 0]); // ReplayThisDevice - request(f, SEND_CLIENT, XI_MAJOR, XI_ALLOW_DEVICE_EVENTS_XI1, &body); -} - // ---- setups -------------------------------------------------------------- // // A is the grab owner and B the foreign selector in the grab rows; the grab // window G is the root unless a row says otherwise: it is on no selection. -/// A selects core on FOCUS, B on CHILD. -fn setup_p1(f: &mut NotifyFixture) { - tree(f); - select_core(f, B, CHILD, CORE_BUTTON_PRESS); - select_core(f, A, FOCUS, CORE_BUTTON_PRESS); -} - -fn setup_p2(f: &mut NotifyFixture) { - tree(f); - select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); - select_core(f, A, FOCUS, CORE_BUTTON_PRESS); -} - -fn setup_p3(f: &mut NotifyFixture) { - tree(f); - select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); - select_xi2(f, A, FOCUS, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); -} - -fn setup_p4(f: &mut NotifyFixture) { - tree(f); - park_pointer(f); - select_xi2(f, B, CHILD, XI_ALL_DEVICES, XI_MOTION); - select_xi2(f, A, FOCUS, DEVICEID_MASTER_POINTER, XI_MOTION); -} - /// The pointer sits on P outside C, so the slave pass starts from P while the /// live target is C. const OUTSIDE_C: (i16, i16) = (105, 105); @@ -282,33 +225,12 @@ fn setup_p4b(f: &mut NotifyFixture) { select_xi2(f, B, CHILD, DEVICEID_XTEST_POINTER, XI_MOTION); } -fn setup_p4c(f: &mut NotifyFixture) { - tree(f); - select_xi2(f, B, CHILD, XI_ALL_DEVICES, XI_BUTTON_PRESS); -} - fn setup_p5(f: &mut NotifyFixture) { tree(f); select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); select_core(f, A, CHILD, CORE_BUTTON_PRESS); } -fn setup_p5b(f: &mut NotifyFixture) { - tree(f); - select_core(f, A, CHILD, CORE_BUTTON_PRESS); - select_xi2(f, A, FOCUS, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); - select_core(f, B, FOCUS, CORE_BUTTON_PRESS); -} - -fn setup_p5c(f: &mut NotifyFixture) { - tree(f); - park_pointer(f); - select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_MOTION); - select_core(f, A, CHILD, CORE_MOTION); - select_xi2(f, A, FOCUS, DEVICEID_MASTER_POINTER, XI_MOTION); - select_xi2(f, A, FOCUS, DEVICEID_XTEST_POINTER, XI_MOTION); -} - /// A and B select the master copy on P; A also selects core on C. Denying /// A's master copy must leave A eligible for the core copy on the walk. fn setup_p5d(f: &mut NotifyFixture) { @@ -345,24 +267,6 @@ fn setup_p7(f: &mut NotifyFixture) { select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); } -fn setup_p8(f: &mut NotifyFixture) { - tree(f); - select_core(f, A, CHILD, CORE_BUTTON_PRESS); - select_core(f, A, FOCUS, CORE_BUTTON_PRESS); - grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); -} - -/// A selects the master XI2 press on C, B the core press on C (a core -/// ButtonPress selection is exclusive per window, so the two cannot both be core). -fn setup_p9(f: &mut NotifyFixture) { - tree(f); - select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); - // A also selects on P: a walk the denial did not reject would end there. - select_xi2(f, A, FOCUS, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); - select_core(f, B, CHILD, CORE_BUTTON_PRESS); - grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); -} - /// The core grab window is C itself: A core on C (denied), B master XI2 on C /// (allowed). The core fallback is a distinct attempt, so A is asked at C again. fn setup_p9_core_same_window(f: &mut NotifyFixture) { @@ -372,13 +276,6 @@ fn setup_p9_core_same_window(f: &mut NotifyFixture) { grab_pointer(f, A, CHILD, true, CORE_BUTTON_PRESS); } -fn setup_p10(f: &mut NotifyFixture) { - tree(f); - select_core(f, B, CHILD, CORE_BUTTON_PRESS); - select_core(f, A, FOCUS, CORE_BUTTON_PRESS); - grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); -} - fn setup_p11(f: &mut NotifyFixture) { tree(f); select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); @@ -386,13 +283,6 @@ fn setup_p11(f: &mut NotifyFixture) { grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); } -/// A selects the master XI2 press (denied) and the core press (allowed) on C: -/// it qualifies through the later protocol. -fn setup_p11_own_protocols(f: &mut NotifyFixture) { - setup_p5(f); - grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); -} - /// B selects the core press on C; A grabs the pointer on G with `mask` /// (without owner_events). With a mask lacking ButtonPress there is no frame in /// any mode, but the check still comes first, so the trace has the call at G. @@ -402,30 +292,6 @@ fn setup_p12(f: &mut NotifyFixture) { grab_pointer(f, A, ROOT, false, MASK); } -/// An XI2 master grab with owner_events false: the grab-window copy is the -/// only call; B's master XI2 selector on C is never asked. -fn setup_p12_xi2(f: &mut NotifyFixture) { - tree(f); - select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); - xi_grab_device(f, A, DEVICEID_MASTER_POINTER, ROOT, false, XI_BUTTON_PRESS); -} - -/// A and B select the master XI2 press on C; A grabs the master pointer with -/// owner_events on `GRAB`. With `GRAB` = C the fallback is a distinct attempt, -/// so A is asked a second time at C (and denied again), not served from the memo. -fn setup_p13(f: &mut NotifyFixture) { - tree(f); - select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); - select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); - xi_grab_device(f, A, DEVICEID_MASTER_POINTER, GRAB, true, XI_BUTTON_PRESS); -} - -/// A sync `GrabButton` on G. -fn setup_p14_core(f: &mut NotifyFixture) { - tree(f); - grab_button(f, A, ROOT, false, true); -} - /// A sync `XIPassiveGrabDevice` on the master, to be activated from an attached /// slave origin. fn setup_p14_xi2_master_from_slave(f: &mut NotifyFixture) { @@ -482,13 +348,6 @@ fn xi1_slave_motion() -> u32 { ) } -/// A and B select press and release on different windows: A on C, B on P. -fn setup_p15(f: &mut NotifyFixture) { - tree(f); - select_core(f, A, CHILD, CORE_BUTTON_PRESS | CORE_BUTTON_RELEASE); - select_core(f, B, FOCUS, CORE_BUTTON_PRESS | CORE_BUTTON_RELEASE); -} - fn setup_p16(f: &mut NotifyFixture) { tree(f); select_core(f, A, CHILD, CORE_BUTTON_PRESS); @@ -512,12 +371,6 @@ fn setup_p18(f: &mut NotifyFixture) { select_xi1(f, B, CHILD, &[xi1_slave_press()]); } -fn setup_p19(f: &mut NotifyFixture) { - tree(f); - select_xi1(f, A, CHILD, &[xi1_slave_press()]); - select_xi1(f, B, FOCUS, &[xi1_slave_press()]); -} - /// Two XI1 press selectors on C; B also selected the button grab class. fn setup_p20(f: &mut NotifyFixture) { tree(f); @@ -530,46 +383,6 @@ fn setup_p20(f: &mut NotifyFixture) { ); } -/// B holds an async XI1 passive grab on P. -fn setup_p20b(f: &mut NotifyFixture) { - tree(f); - select_xi1(f, A, CHILD, &[xi1_slave_press()]); - xi1_passive_grab(f, B, FOCUS, false); -} - -/// The press over a root that nothing can hit (unmapped, as `unhit_root` -/// makes it): there is no top level, so the XI2 fanout does not run while the -/// XI1 router still does. A real server always has a mapped root, so this -/// state cannot occur there; the rows pin the ask/write rule (XI2 not asked -/// without a top level, XI1 selectors checked) for the code path that would see it. -const BARE_ROOT: (i16, i16) = (10, 10); - -fn unhit_root(f: &mut NotifyFixture) { - f.state - .resources - .window_mut(ResourceId(ROOT)) - .expect("root") - .map_state = crate::resources::MapState::Unmapped; -} - -fn bare_root_tree(f: &mut NotifyFixture) { - tree(f); - park_pointer_at(f, BARE_ROOT); - unhit_root(f); -} - -fn setup_i1a(f: &mut NotifyFixture) { - bare_root_tree(f); - select_xi2(f, A, ROOT, DEVICEID_XTEST_POINTER, XI_BUTTON_PRESS); - select_xi1(f, B, ROOT, &[xi1_slave_press()]); -} - -fn setup_i1b(f: &mut NotifyFixture) { - bare_root_tree(f); - select_xi1(f, A, ROOT, &[xi1_slave_press()]); - select_xi1(f, B, ROOT, &[xi1_slave_press()]); -} - fn setup_p21(f: &mut NotifyFixture) { tree(f); select_xi2(f, A, ROOT, DEVICEID_MASTER_POINTER, XI_RAW_BUTTON_PRESS); @@ -597,15 +410,6 @@ fn setup_scroll_stop_two_forms(f: &mut NotifyFixture) { select_xi2(f, A, CHILD, XI_ALL_DEVICES, XI_MOTION); } -/// A's XIGrabDevice on the master pointer at the root, owner_events false, -/// selecting Motion only: a wheel press writes A the scroll Motion at the grab -/// window and no button event. -fn setup_p22_grab(f: &mut NotifyFixture) { - tree(f); - register_physical_pointer(f); - xi_grab_device(f, A, DEVICEID_MASTER_POINTER, ROOT, false, XI_MOTION); -} - fn setup_p25(f: &mut NotifyFixture) { tree(f); park_pointer(f); @@ -638,12 +442,6 @@ fn setup_p26_implicit_device_mask(f: &mut NotifyFixture) { select_xi1(f, A, CHILD, &[xi1_slave_press()]); } -fn setup_p27(f: &mut NotifyFixture) { - tree(f); - select_xi1(f, A, CHILD, &[xi1_slave_press()]); - xi_grab_device(f, A, DEVICEID_XTEST_POINTER, ROOT, true, XI_BUTTON_PRESS); -} - fn setup_p27_later_window(f: &mut NotifyFixture) { tree(f); select_xi1(f, B, CHILD, &[xi1_slave_press()]); @@ -660,14 +458,6 @@ fn setup_p27_thawed_xi1_filter(f: &mut NotifyFixture) { xi_passive_grab_device(f, A, DEVICEID_XTEST_POINTER, true, XI_BUTTON_PRESS); } -/// The thaw fixture without A's XI2 selection on C: the queued XI1 press is -/// observable at thaw, while the same slave passive grab still freezes it. -fn setup_p27_thawed_xi1_delivery(f: &mut NotifyFixture) { - tree(f); - select_xi1(f, A, CHILD, &[xi1_slave_press()]); - xi_passive_grab_device(f, A, DEVICEID_XTEST_POINTER, true, XI_BUTTON_PRESS); -} - /// The same selections as the thaw case, under an already active asynchronous /// slave XI2 grab, so the XI1 filter shares the live dispatch's ReceiveMemo. fn setup_p27_live_filter(f: &mut NotifyFixture) { @@ -677,13 +467,6 @@ fn setup_p27_live_filter(f: &mut NotifyFixture) { xi_grab_device(f, A, DEVICEID_XTEST_POINTER, ROOT, true, XI_BUTTON_PRESS); } -/// A sync `GrabDeviceButton` by the requester on P, plus two XI1 press -/// selectors on C, of which B also selected the grab class. -fn setup_p28(f: &mut NotifyFixture) { - setup_p20(f); - xi1_passive_grab(f, SEND_CLIENT, FOCUS, true); -} - // ---- calls and grab facts ------------------------------------------------ /// The Receive batch of an XI1 `DeviceButtonPress` copy. @@ -749,14 +532,6 @@ const FROZEN_BY_PRESS: Grab = Grab::Freeze { }), }; -/// A motion withheld behind the freeze, whole, or as its deferred master part. -const MOTION_QUEUED: Grab = Grab::Queued { - device: DEVICEID_MASTER_POINTER, - held: Held::HostPointer { - kind: PointerEventKind::MotionNotify, - detail: 0, - }, -}; const MASTER_PART_QUEUED: Grab = Grab::Queued { device: DEVICEID_MASTER_POINTER, held: Held::HostPointerMaster { @@ -789,52 +564,6 @@ const SLAVE_PASSIVE_GRAB: Grab = Grab::SlavePointer { }, }; -/// A selects core on C, XI2 (master) on P; B selects core on P. -const P5B_ALLOW: Outcome = frames_and_calls( - &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], - &[(A, CallKind::Xi2, FOCUS)], -); -const P5B: Scenario = Scenario { - setup: setup_p5b, - steps: &[press(XTEST_MASTER)], - allow: P5B_ALLOW, - order: CallOrder::Total, -}; - -const P15_PRESS: Scenario = Scenario { - setup: setup_p15, - steps: &[press(XTEST_MASTER)], - allow: with_grab( - frames_and_calls(&[(A, Kind::Core, CHILD)], &[(A, CallKind::Core, CHILD)]), - &[implicit(A, CHILD, false)], - ), - order: CallOrder::Total, -}; - -const P20B_ALLOW: Outcome = with_grab( - frames_and_calls( - &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], - &[(B, XI1_PRESS_CALL, FOCUS)], - ), - &[xi1_implicit(B, FOCUS)], -); -const P20B: Scenario = Scenario { - setup: setup_p20b, - steps: &[press(XTEST_SLAVE)], - allow: P20B_ALLOW, - order: CallOrder::Total, -}; - -const P22_GRAB: Scenario = Scenario { - setup: setup_p22_grab, - steps: &[WHEEL_PRESS], - allow: frames_and_calls( - &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], - &[(A, CallKind::Xi2, ROOT), (A, SCROLL_MOTION_CALL, ROOT)], - ), - order: CallOrder::Total, -}; - const P26_OWNER_EVENTS: Scenario = Scenario { setup: setup_p26::, steps: &[press(XTEST_SLAVE)], @@ -868,51 +597,12 @@ const P26_FALLS_TO_ROOT: Outcome = Outcome { ..NOTHING }; -/// The requester's sync grab on P holds the slave frozen with the routed press. -const P28_ACTIVATED: &[Grab] = &[ - xi1_implicit(SEND_CLIENT, FOCUS), - Grab::Freeze { - device: DEVICEID_XTEST_POINTER, - state: Xi1SyncState::FrozenWithEvent, - other: None, - stored: Some(Held::Xi1Routed { - evcode: crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET, - detail: 1, - }), - }, -]; - -const P28_PRESS: Scenario = Scenario { - setup: setup_p28, - steps: &[press(XTEST_SLAVE)], - allow: with_grab( - frames_and_calls( - &[(SEND_CLIENT, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], - &[(SEND_CLIENT, XI1_PRESS_CALL, FOCUS)], - ), - P28_ACTIVATED, - ), - order: CallOrder::PerClient, -}; - /// The allow-all outcomes several scenarios share, and the denied outcome that /// only asks (nothing written). const A_XI2_AT_CHILD: Outcome = frames_and_calls( &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], &[(A, CallKind::Xi2, CHILD)], ); -const B_XI2_AT_CHILD: Outcome = frames_and_calls( - &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], - &[(B, CallKind::Xi2, CHILD)], -); -/// B gets the slave and the master form at C from one check. -const B_BOTH_FORMS_AT_CHILD: Outcome = frames_and_calls( - &[ - (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), - (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - ], - &[(B, CallKind::Xi2, CHILD)], -); /// A gets the slave motion and its valuator continuation at C from one check. const A_XI1_MOTION_AT_CHILD: Outcome = frames_and_calls( &[ @@ -925,17 +615,6 @@ const ASKED_A_CORE_ROOT: Outcome = calls_only(&[(A, CallKind::Core, ROOT)]); const ASKED_A_XI2_ROOT: Outcome = calls_only(&[(A, CallKind::Xi2, ROOT)]); const ASKED_A_XI2_CHILD: Outcome = calls_only(&[(A, CallKind::Xi2, CHILD)]); -/// The p14 scenarios up to the activating press; the rows with more steps build -/// on them with `..PREFIX`. -const P14_CORE: Scenario = Scenario { - setup: setup_p14_core, - steps: &[press(XTEST_MASTER)], - allow: with_grab( - frames_and_calls(&[(A, Kind::Core, ROOT)], &[(A, CallKind::Core, ROOT)]), - &[passive(ROOT, false), FROZEN_BY_PRESS], - ), - order: CallOrder::Total, -}; const P14_FROM_SLAVE: Scenario = Scenario { setup: setup_p14_xi2_master_from_slave, steps: &[press(XTEST_SLAVE)], @@ -995,314 +674,69 @@ const P27_THAWED_XI1_FILTER: Scenario = Scenario { order: CallOrder::Total, }; -const P27_THAWED_XI1_FILTER_PRESS: Scenario = Scenario { - setup: setup_p27_thawed_xi1_filter, - steps: &[press(XTEST_SLAVE)], - allow: with_grab( - frames_and_calls( - &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], - &[(A, CallKind::Xi2, ROOT)], - ), - &[ - Grab::Detached { - device: DEVICEID_XTEST_POINTER, - master: DEVICEID_MASTER_POINTER, - }, - SLAVE_PASSIVE_GRAB, - Grab::Freeze { - device: DEVICEID_XTEST_POINTER, - state: Xi1SyncState::FrozenWithEvent, - other: None, - stored: Some(Held::HostPointer { - kind: PointerEventKind::ButtonPress, - detail: 1, - }), - }, - Grab::Queued { - device: DEVICEID_XTEST_POINTER, - held: Held::Xi1Routed { - evcode: crate::server::XI_FIRST_EVENT - + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET, - detail: 1, - }, - }, - ], - ), - order: CallOrder::Total, -}; - -const P27_THAWED_XI1_DELIVERY: Scenario = Scenario { - setup: setup_p27_thawed_xi1_delivery, - steps: &[ - press(XTEST_SLAVE), - Step::Request(allow_slave::, &[]), - ], - allow: with_grab( - frames_and_calls( - &[ - (A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT), - (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), - ], - &[(A, CallKind::Xi2, ROOT), (A, XI1_PRESS_CALL, CHILD)], - ), - &[ - Grab::Detached { - device: DEVICEID_XTEST_POINTER, - master: DEVICEID_MASTER_POINTER, - }, - SLAVE_PASSIVE_GRAB, - ], - ), - order: CallOrder::Total, -}; - // ---- rows ---------------------------------------------------------------- const ROWS: &[InputRow] = &[ - // A selects P, B selects C: B's denied copy does not stop the core walk. - // Mutation: the core walk stops at any window with a core selector, without - // asking Receive (selection-only stop). A then never sees the press. + // A slave motion moves the sprite from P into C. B selects the slave form on C + // only, so the slave form (routed from P) has no recipient and B gets nothing, + // in every mode. The route from the live target C writes no slave copy, so it + // asks nothing. + // Mutation: the slave form's route from the live target (not the earlier + // window) goes through the memo (`slave_form_checked` there), so B's selection + // on C is asked although no copy of it is ever written. InputRow { - name: "p1_denied_core_selector_does_not_stop_the_core_walk", + name: "p4b_no_check_for_the_slave_route_from_the_live_target", scenario: &Scenario { - setup: setup_p1, - steps: &[press(XTEST_MASTER)], - allow: frames_and_calls(&[(B, Kind::Core, CHILD)], &[(B, CallKind::Core, CHILD)]), + setup: setup_p4b, + steps: &[motion(XTEST_SLAVE)], + allow: NOTHING, order: CallOrder::Total, }, - deny: &[(B, CallKind::Core, CHILD)], - denied: with_grab( - with_moved( - frames_and_calls( - &[(A, Kind::Core, FOCUS)], - &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - ), - &[moved(A, Kind::Core, FOCUS, CHILD, P_EVENT)], - ), - &[implicit(A, FOCUS, false)], - ), + deny: &[(B, CallKind::Xi2, CHILD)], + denied: NOTHING, }, - // Mutation: an XI2 selection absorbs the walk whether or not its copy is - // allowed (selection-only absorption), or the denied XI2 copy is checked twice. + // A's master XI2 copy shadows its core copy at C. Denied: A's XI2 copy is + // refused, so its core copy at C is delivered. + // Mutation: A's core copy is shadowed by its XI2 selection, not by the copy + // that is allowed, so the denied XI2 still hides the core copy at C. InputRow { - name: "p2_denied_xi2_selector_does_not_absorb_core", + name: "p5_denied_xi2_reopens_that_clients_core", scenario: &Scenario { - setup: setup_p2, + setup: setup_p5, steps: &[press(XTEST_MASTER)], - allow: B_XI2_AT_CHILD, + allow: A_XI2_AT_CHILD, order: CallOrder::Total, }, - deny: &[(B, CallKind::Xi2, CHILD)], + deny: &[(A, CallKind::Xi2, CHILD)], denied: with_grab( with_moved( frames_and_calls( - &[(A, Kind::Core, FOCUS)], - &[(B, CallKind::Xi2, CHILD), (A, CallKind::Core, FOCUS)], + &[(A, Kind::Core, CHILD)], + &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], ), - &[moved(A, Kind::Core, FOCUS, CHILD, P_EVENT)], + &[moved(A, Kind::Core, CHILD, 0, C_EVENT)], ), - &[implicit(A, FOCUS, false)], + &[implicit(A, CHILD, false)], ), }, - // Mutation: the XI2 route window is the first window with a selection rather - // than the first with an allowed one, so the denied copy at C ends the walk. + // A slave press: A's core copy is deferred behind the slave pass. Denying it + // drops that copy at admission, after the slave XI2 copy was written. + // Mutation: the deferred core copy is checked again at the flush (two calls), + // or never checked (the copy is written with no call). InputRow { - name: "p3_xi2_walk_skips_a_denied_window", + name: "p6_deferred_core_copy_is_checked_at_admission", scenario: &Scenario { - setup: setup_p3, - steps: &[press(XTEST_MASTER)], - allow: B_XI2_AT_CHILD, - order: CallOrder::Total, - }, - deny: &[(B, CallKind::Xi2, CHILD)], - denied: with_grab( - with_moved( + setup: setup_p6, + steps: &[press(XTEST_SLAVE)], + allow: with_grab( frames_and_calls( - &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], - &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], + &[ + (A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), + (A, Kind::Core, CHILD), + ], + &[(A, CallKind::Core, CHILD), (A, CallKind::Xi2, CHILD)], ), - &[moved( - A, - Kind::Xi2(DEVICEID_MASTER_POINTER), - FOCUS, - CHILD, - P_EVENT, - )], - ), - &[implicit(A, FOCUS, true)], - ), - }, - // B's slave and master forms at C come from one check. Denied: B gets - // neither, and A's master form at P is the only copy. - // Mutation: the slave and master forms each ask Receive (two calls for B), - // or the master form is checked at the slave pass's window. - InputRow { - name: "p4_slave_and_master_forms_share_one_check", - scenario: &Scenario { - setup: setup_p4, - steps: &[motion(XTEST_SLAVE)], - allow: B_BOTH_FORMS_AT_CHILD, - order: CallOrder::Total, - }, - deny: &[(B, CallKind::Xi2, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], - moved: &[moved( - A, - Kind::Xi2(DEVICEID_MASTER_POINTER), - FOCUS, - CHILD, - MOTION_EVENT_AT_P, - )], - calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], - grab: None, - - ..NOTHING - }, - }, - // A slave motion moves the sprite from P into C. B selects the slave form on C - // only, so the slave form (routed from P) has no recipient and B gets nothing, - // in every mode. The route from the live target C writes no slave copy, so it - // asks nothing. - // Mutation: the slave form's route from the live target (not the earlier - // window) goes through the memo (`slave_form_checked` there), so B's selection - // on C is asked although no copy of it is ever written. - InputRow { - name: "p4b_no_check_for_the_slave_route_from_the_live_target", - scenario: &Scenario { - setup: setup_p4b, - steps: &[motion(XTEST_SLAVE)], - allow: NOTHING, - order: CallOrder::Total, - }, - deny: &[(B, CallKind::Xi2, CHILD)], - denied: NOTHING, - }, - // B's slave press copy (routed by the slave press route) and its master copy - // at C share the one check the master route made. Denied: neither form is - // written, and the one call is not repeated. - // Mutation: the slave press copy (not a grab attempt) takes a fresh - // `receive_allows` instead of the dispatch memo, so B is asked twice. - InputRow { - name: "p4c_slave_press_and_master_forms_share_one_check", - scenario: &Scenario { - setup: setup_p4c, - steps: &[press(XTEST_SLAVE)], - allow: B_BOTH_FORMS_AT_CHILD, - order: CallOrder::Total, - }, - deny: &[(B, CallKind::Xi2, CHILD)], - denied: with_grab(calls_only(&[(B, CallKind::Xi2, CHILD)]), &[]), - }, - // A's master XI2 copy shadows its core copy at C. Denied: A's XI2 copy is - // refused, so its core copy at C is delivered. - // Mutation: A's core copy is shadowed by its XI2 selection, not by the copy - // that is allowed, so the denied XI2 still hides the core copy at C. - InputRow { - name: "p5_denied_xi2_reopens_that_clients_core", - scenario: &Scenario { - setup: setup_p5, - steps: &[press(XTEST_MASTER)], - allow: A_XI2_AT_CHILD, - order: CallOrder::Total, - }, - deny: &[(A, CallKind::Xi2, CHILD)], - denied: with_grab( - with_moved( - frames_and_calls( - &[(A, Kind::Core, CHILD)], - &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], - ), - &[moved(A, Kind::Core, CHILD, 0, C_EVENT)], - ), - &[implicit(A, CHILD, false)], - ), - }, - // Denying A's core copy at C changes nothing: a shadowed core copy is not - // checked, and the walk stops at C as it does with allow-all. - // Mutation: a shadowed core copy is still checked before the walk stops. - InputRow { - name: "p5b_shadow_follows_the_master_copy_anywhere_core_denied", - scenario: &P5B, - deny: &[(A, CallKind::Core, CHILD)], - denied: P5B.allow, - }, - // Denying A's master XI2 copy at P reopens A's core copy at C, and the walk - // stops there, so B at P gets nothing. - // Mutation: a shadow that only applies at the same window (the core copy at C - // is checked and then deduplicated). - InputRow { - name: "p5b_shadow_follows_the_master_copy_anywhere", - scenario: &P5B, - deny: &[(A, CallKind::Xi2, FOCUS)], - denied: with_grab( - with_moved( - frames_and_calls( - &[(A, Kind::Core, CHILD)], - &[(A, CallKind::Xi2, FOCUS), (A, CallKind::Core, CHILD)], - ), - &[moved(A, Kind::Core, CHILD, 0, C_EVENT)], - ), - &[implicit(A, CHILD, false)], - ), - }, - // Denied: the master route is P (A's master copy), so A's core copy at C is - // shadowed and A gets its slave and master forms at P, with no core copy. - // Mutation: the shadow uses the selection-only master route, which ends at C - // (B's selection); A then keeps its core copy at C and gets no XI2 at P. - // Open gap: this selection-only mutation (P-5c) is not caught by any row; the - // row does catch P-5 (both routes selection-only). - InputRow { - name: "p5c_shadow_uses_the_allowed_master_route", - scenario: &Scenario { - setup: setup_p5c, - steps: &[motion(XTEST_SLAVE)], - allow: frames_and_calls( - &[ - (A, Kind::Xi2(DEVICEID_XTEST_POINTER), FOCUS), - (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - ], - &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], - ), - order: CallOrder::Total, - }, - deny: &[(B, CallKind::Xi2, CHILD)], - denied: Outcome { - frames: &[ - (A, Kind::Xi2(DEVICEID_XTEST_POINTER), FOCUS), - (A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS), - ], - moved: &[moved( - A, - Kind::Xi2(DEVICEID_MASTER_POINTER), - FOCUS, - CHILD, - MOTION_EVENT_AT_P, - )], - calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], - grab: None, - - ..NOTHING - }, - }, - // A slave press: A's core copy is deferred behind the slave pass. Denying it - // drops that copy at admission, after the slave XI2 copy was written. - // Mutation: the deferred core copy is checked again at the flush (two calls), - // or never checked (the copy is written with no call). - InputRow { - name: "p6_deferred_core_copy_is_checked_at_admission", - scenario: &Scenario { - setup: setup_p6, - steps: &[press(XTEST_SLAVE)], - allow: with_grab( - frames_and_calls( - &[ - (A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), - (A, Kind::Core, CHILD), - ], - &[(A, CallKind::Core, CHILD), (A, CallKind::Xi2, CHILD)], - ), - &[implicit(A, CHILD, false), SLAVE_GRAB], + &[implicit(A, CHILD, false), SLAVE_GRAB], ), order: CallOrder::Total, }, @@ -1365,51 +799,6 @@ const ROWS: &[InputRow] = &[ ..NOTHING }, }, - // Mutation: the owner qualifies by selection (the route returns C although the - // copy there is denied, so nothing is written), or the natural core write asks - // again (a second call for A at C when allowed). - InputRow { - name: "p8_denied_owner_copy_continues_the_natural_walk", - scenario: &Scenario { - setup: setup_p8, - steps: &[press(XTEST_MASTER)], - allow: A_CORE_CHILD, - order: CallOrder::Total, - }, - deny: &[(A, CallKind::Core, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Core, FOCUS)], - moved: &[moved(A, Kind::Core, FOCUS, CHILD, P_EVENT)], - calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - grab: None, - - ..NOTHING - }, - }, - // Mutation: the denied owner keeps walking (or is dropped) although an allowed - // foreign selector rejects the walk, so the grab window gets no copy. - InputRow { - name: "p9_denied_owner_with_allowed_foreign_falls_back", - scenario: &Scenario { - setup: setup_p9, - steps: &[press(XTEST_MASTER)], - allow: A_XI2_AT_CHILD, - order: CallOrder::Total, - }, - deny: &[(A, CallKind::Xi2, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Core, ROOT)], - moved: &[moved(A, Kind::Core, ROOT, FOCUS, POINTER)], - calls: &[ - (A, CallKind::Xi2, CHILD), - (B, CallKind::Core, CHILD), - (A, CallKind::Core, ROOT), - ], - grab: None, - - ..NOTHING - }, - }, // Mutation: the core fallback takes the memo's result for (A, G, core) // instead of a fresh check (this row then has one call for A, not two). InputRow { @@ -1427,29 +816,6 @@ const ROWS: &[InputRow] = &[ (A, CallKind::Core, CHILD), ]), }, - // Mutation: a foreign selector rejects the walk by selection (the denied - // selector at C sends A to the grab window instead of on to P). - InputRow { - name: "p10_denied_foreign_selector_does_not_reject", - scenario: &Scenario { - setup: setup_p10, - steps: &[press(XTEST_MASTER)], - allow: frames_and_calls( - &[(A, Kind::Core, ROOT)], - &[(B, CallKind::Core, CHILD), (A, CallKind::Core, ROOT)], - ), - order: CallOrder::Total, - }, - deny: &[(B, CallKind::Core, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Core, FOCUS)], - moved: &[moved(A, Kind::Core, FOCUS, CHILD, P_EVENT)], - calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], - grab: None, - - ..NOTHING - }, - }, // Mutation: the foreign selectors are evaluated before the owner (an extra // call for B when A qualifies), B's master XI2 copy is asked under the // grab-owned master form (a call for B in the allowed run). @@ -1475,39 +841,6 @@ const ROWS: &[InputRow] = &[ ..NOTHING }, }, - // Mutation: the owner qualifies only through the first protocol it selected - // (this row then falls back to the grab window). - InputRow { - name: "p11_owner_qualifies_in_a_later_protocol_own_protocols", - scenario: &Scenario { - setup: setup_p11_own_protocols, - steps: &[press(XTEST_MASTER)], - allow: A_XI2_AT_CHILD, - order: CallOrder::Total, - }, - deny: &[(A, CallKind::Xi2, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Core, CHILD)], - moved: &[moved(A, Kind::Core, CHILD, 0, C_EVENT)], - calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], - grab: None, - - ..NOTHING - }, - }, - // A denial at the grab window is a delivery: C's selectors get nothing. - // Mutation: the denial is not a delivery (C's selectors get the press). - InputRow { - name: "p12_grab_window_denial_counts_as_delivered", - scenario: &Scenario { - setup: setup_p12::, - steps: &[press(XTEST_MASTER)], - allow: frames_and_calls(&[(A, Kind::Core, ROOT)], &[(A, CallKind::Core, ROOT)]), - order: CallOrder::Total, - }, - deny: &[(A, CallKind::Core, ROOT)], - denied: ASKED_A_CORE_ROOT, - }, // Mutation: the check moves behind the grab mask (no call here). InputRow { name: "p12_grab_window_denial_counts_as_delivered_mask", @@ -1520,119 +853,6 @@ const ROWS: &[InputRow] = &[ deny: &[(A, CallKind::Core, ROOT)], denied: ASKED_A_CORE_ROOT, }, - // Mutation: the XI2 grab asks B's selector (a call for B). - InputRow { - name: "p12_grab_window_denial_counts_as_delivered_xi2", - scenario: &Scenario { - setup: setup_p12_xi2, - steps: &[press(XTEST_MASTER)], - allow: frames_and_calls( - &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], - &[(A, CallKind::Xi2, ROOT)], - ), - order: CallOrder::Total, - }, - deny: &[(A, CallKind::Xi2, ROOT)], - denied: ASKED_A_XI2_ROOT, - }, - // Mutation: the XI2 owner qualifies by selection (nothing is written at C), - // or the natural XI2 write asks again (two calls for A at C when allowed). - InputRow { - name: "p13_xi2_owner_events_fallback_is_fresh", - scenario: &Scenario { - setup: setup_p13::, - steps: &[press(XTEST_MASTER)], - allow: A_XI2_AT_CHILD, - order: CallOrder::Total, - }, - deny: &[(A, CallKind::Xi2, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), ROOT)], - moved: &[moved( - A, - Kind::Xi2(DEVICEID_MASTER_POINTER), - ROOT, - FOCUS, - POINTER, - )], - calls: &[ - (A, CallKind::Xi2, CHILD), - (B, CallKind::Xi2, CHILD), - (A, CallKind::Xi2, ROOT), - ], - grab: None, - - ..NOTHING - }, - }, - // The fallback reuses the memo for G (one call for A at C here): no probe - // replays this edit. - InputRow { - name: "p13_xi2_owner_events_fallback_is_fresh_same_window", - scenario: &Scenario { - setup: setup_p13::, - steps: &[press(XTEST_MASTER)], - allow: A_XI2_AT_CHILD, - order: CallOrder::Total, - }, - deny: &[(A, CallKind::Xi2, CHILD)], - denied: calls_only(&[ - (A, CallKind::Xi2, CHILD), - (B, CallKind::Xi2, CHILD), - (A, CallKind::Xi2, CHILD), - ]), - }, - // A sync `GrabButton` on G: the activating press is denied to its owner, and - // the grab still activates, freezes and stores the press; the next motion is - // queued behind the freeze. - // Mutation: the passive core activating write is unchecked (p14 core rows and - // the activation row). - InputRow { - name: "p14_denied_activating_press_still_activates_and_freezes@press", - scenario: &P14_CORE, - deny: &[(A, CallKind::Core, ROOT)], - denied: ASKED_A_CORE_ROOT, - }, - InputRow { - name: "p14_denied_activating_press_still_activates_and_freezes", - scenario: &Scenario { - steps: &[press(XTEST_MASTER), motion(XTEST_MASTER)], - allow: Outcome { - grab: Some(&[passive(ROOT, false), FROZEN_BY_PRESS, MOTION_QUEUED]), - ..P14_CORE.allow - }, - ..P14_CORE - }, - deny: &[(A, CallKind::Core, ROOT)], - denied: ASKED_A_CORE_ROOT, - }, - // A sync `XIPassiveGrabDevice` on the master from an attached slave origin: - // A's copy on G is denied, nobody else gets the press, and the grab still - // freezes with the press stored. The next motion delivers its slave part and - // defers the master part behind the freeze; thawing runs the master part, - // which is the one attempt, asked once. - // Mutation: the grab-window result is ignored, or the XI2 master block asks - // for the grab window without the emitted-form gate (a phantom call after the - // motion, and a second one at the thaw); the slave rows catch both. - InputRow { - name: "p14_denied_xi2_activating_press_still_freezes_from_a_slave_origin@press", - scenario: &P14_FROM_SLAVE, - deny: &[(A, CallKind::Xi2, ROOT)], - denied: ASKED_A_XI2_ROOT, - }, - InputRow { - name: "p14_denied_xi2_activating_press_still_freezes_from_a_slave_origin@motion", - scenario: &Scenario { - steps: &[press(XTEST_SLAVE), motion(XTEST_SLAVE)], - allow: Outcome { - grab: Some(&[passive(ROOT, true), FROZEN_BY_PRESS, MASTER_PART_QUEUED]), - ..P14_FROM_SLAVE.allow - }, - ..P14_FROM_SLAVE - }, - deny: &[(A, CallKind::Xi2, ROOT)], - denied: ASKED_A_XI2_ROOT, - }, InputRow { name: "p14_denied_xi2_activating_press_still_freezes_from_a_slave_origin", scenario: &Scenario { @@ -1704,28 +924,6 @@ const ROWS: &[InputRow] = &[ &[], ), }, - InputRow { - name: "p14_denied_xi2_activating_press_from_a_master_origin_still_freezes", - scenario: &Scenario { - steps: &[press(XTEST_MASTER), motion(XTEST_MASTER)], - allow: Outcome { - grab: Some(&[passive(ROOT, true), FROZEN_BY_PRESS, MOTION_QUEUED]), - ..P14_FROM_MASTER.allow - }, - ..P14_FROM_MASTER - }, - deny: &[(A, CallKind::Xi2, CHILD)], - denied: ASKED_A_XI2_CHILD, - }, - // The same sync master grab with owner_events, and A selecting the master XI2 - // motion on C: the follow-up slave motion defers its master part, so the - // route that would ask A@C for that copy must not ask yet. - InputRow { - name: "p14_deferred_master_part_asks_nothing_in_the_route@press", - scenario: &P14_OWNER_EVENTS, - deny: &[(A, CallKind::Xi2, ROOT)], - denied: ASKED_A_XI2_ROOT, - }, // Mutation: the master block's route takes the memo although the master form // is not emitted in this dispatch (a phantom A@C call, after the motion). InputRow { @@ -1757,55 +955,6 @@ const ROWS: &[InputRow] = &[ deny: &[(A, CallKind::Core, CHILD)], denied: frames_and_calls(&[(A, Kind::Core, ROOT)], &[(A, CallKind::Core, ROOT)]), }, - // A denied on C: B on P gets the press and owns the implicit grab. - // Mutation (the core candidate): the candidate is any walk recipient, denied - // or not, so A owns the grab and the release goes to A at C. - InputRow { - name: "p15_denied_candidate_is_not_the_implicit_owner@press", - scenario: &P15_PRESS, - deny: &[(A, CallKind::Core, CHILD)], - denied: with_grab( - with_moved( - frames_and_calls( - &[(B, Kind::Core, FOCUS)], - &[(A, CallKind::Core, CHILD), (B, CallKind::Core, FOCUS)], - ), - &[moved(B, Kind::Core, FOCUS, CHILD, P_EVENT)], - ), - &[implicit(B, FOCUS, false)], - ), - }, - // The release, with the pointer still over C, goes to B at P. - InputRow { - name: "p15_denied_candidate_is_not_the_implicit_owner", - scenario: &Scenario { - steps: &[press(XTEST_MASTER), release(XTEST_MASTER)], - allow: with_grab( - frames_and_calls( - &[(A, Kind::Core, CHILD), (A, Kind::Core, CHILD)], - &[(A, CallKind::Core, CHILD), (A, CallKind::Core, CHILD)], - ), - &[], - ), - ..P15_PRESS - }, - deny: &[(A, CallKind::Core, CHILD)], - denied: Outcome { - frames: &[(B, Kind::Core, FOCUS), (B, Kind::Core, FOCUS)], - moved: &[ - moved(B, Kind::Core, FOCUS, CHILD, P_EVENT), - moved(B, Kind::Core, FOCUS, CHILD, P_EVENT), - ], - calls: &[ - (A, CallKind::Core, CHILD), - (B, CallKind::Core, FOCUS), - (B, CallKind::Core, FOCUS), - ], - grab: None, - - ..NOTHING - }, - }, // A alone on C, denied: nobody receives the press and no pointer grab is // active afterwards. // Mutation (the core candidate): the denied recipient still qualifies, so A @@ -1890,42 +1039,6 @@ const ROWS: &[InputRow] = &[ &[xi1_implicit(B, CHILD)], ), }, - // A's XI1 press selector on C is denied, B's on P is not: the walk continues - // and B gets the press at P. - // Mutation: a denied XI1 selector stops the walk (selection decides the - // window), so B gets nothing. - InputRow { - name: "p19_denied_xi1_press_continues", - scenario: &Scenario { - setup: setup_p19, - steps: &[press(XTEST_SLAVE)], - allow: with_grab( - frames_and_calls( - &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], - &[(A, XI1_PRESS_CALL, CHILD)], - ), - &[xi1_implicit(A, CHILD)], - ), - order: CallOrder::Total, - }, - deny: &[(A, XI1_PRESS_CALL, CHILD)], - denied: with_grab( - with_moved( - frames_and_calls( - &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], - &[(A, XI1_PRESS_CALL, CHILD), (B, XI1_PRESS_CALL, FOCUS)], - ), - &[moved( - B, - Kind::Xi1(DEVICEID_XTEST_POINTER), - FOCUS, - CHILD, - P_EVENT, - )], - ), - &[xi1_implicit(B, FOCUS)], - ), - }, // Two XI1 press selectors on C, the one that also selected the button grab // class is denied: the other owns the XI1 implicit grab (allow-all: the grab // class holder). @@ -1957,75 +1070,6 @@ const ROWS: &[InputRow] = &[ &[xi1_implicit(A, CHILD)], ), }, - // An XI1 passive grab takes the slave press, so the router never reaches the - // selection walk: A's selector copy is not written and Receive is not asked - // (the activating write is the grab owner's one fresh check). - // Mutation: the route asks the XI1 selectors although a passive grab matches - // (`xi1_routed` ignores it). - InputRow { - name: "p20b_xi1_passive_activation_asks_no_selector", - scenario: &P20B, - deny: &[(A, XI1_PRESS_CALL, CHILD)], - denied: P20B.allow, - }, - // With the owner denied the grab still activates and nobody gets the press. - // Mutation: the activating write is unchecked. - InputRow { - name: "p20b_xi1_passive_activation_owner_denied", - scenario: &P20B, - deny: &[(B, XI1_PRESS_CALL, FOCUS)], - denied: calls_only(&[(B, XI1_PRESS_CALL, FOCUS)]), - }, - // A selects the slave's XI2 press on the root, B its XI1 press, and the press - // is over the bare root: no XI2 copy is written, so Receive is not asked for - // A's, and a denial must not hand the press to B (nor give B an XI1 grab). - // Mutation: the XI2 leg is asked without the top-level condition. - InputRow { - name: "i1a_bare_root_slave_xi2_is_not_asked", - scenario: &Scenario { - setup: setup_i1a, - steps: &[button( - XTEST_SLAVE, - PointerEventKind::ButtonPress, - BARE_ROOT, - )], - allow: NOTHING, - order: CallOrder::Total, - }, - deny: &[(A, CallKind::Xi2, ROOT)], - denied: NOTHING, - }, - // Only XI1 selectors on the root, the press over the bare root: the router - // writes the XI1 form, so each selector is asked once and the denied one gets - // nothing. - // Mutation: the XI1 check is gated on the XI2 flag (here false). - InputRow { - name: "i1b_bare_root_xi1_selectors_are_checked", - scenario: &Scenario { - setup: setup_i1b, - steps: &[button( - XTEST_SLAVE, - PointerEventKind::ButtonPress, - BARE_ROOT, - )], - allow: frames_and_calls( - &[ - (A, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT), - (B, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT), - ], - &[(A, XI1_PRESS_CALL, ROOT), (B, XI1_PRESS_CALL, ROOT)], - ), - order: CallOrder::PerClient, - }, - deny: &[(A, XI1_PRESS_CALL, ROOT)], - denied: with_grab( - frames_and_calls( - &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), ROOT)], - &[(A, XI1_PRESS_CALL, ROOT), (B, XI1_PRESS_CALL, ROOT)], - ), - &[xi1_implicit(B, ROOT)], - ), - }, // A and B select the master raw press on the root, the requester the slave's; // A is denied: only A's copy goes, B and the requester keep theirs. // Mutation: the raw copies are written unchecked (every denied-run assertion @@ -2097,28 +1141,6 @@ const ROWS: &[InputRow] = &[ ..NOTHING }, }, - // The stop routes from its own probe hit. A's denied batch on C drops A's two - // Motions and the walk does not resume (B at P gets nothing and is not - // asked); allowed, A gets both. - // Mutations: the stop routes through the memo (B gets it at P and is asked); - // one check per event (two calls for A). - InputRow { - name: "p23_scroll_stop_is_not_rerouted", - scenario: &Scenario { - setup: setup_scroll_walk, - steps: &[SCROLL_STOP], - allow: frames_and_calls( - &[ - (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - (A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), - ], - &[(A, STOP_BATCH, CHILD)], - ), - order: CallOrder::Total, - }, - deny: &[(A, STOP_BATCH, CHILD)], - denied: calls_only(&[(A, STOP_BATCH, CHILD)]), - }, // A client with both device forms on one window is asked once for both forms' // four events. // Mutation: one check per form (two calls here). @@ -2141,25 +1163,6 @@ const ROWS: &[InputRow] = &[ deny: &[(A, STOP_BATCH, CHILD)], denied: calls_only(&[(A, STOP_BATCH, CHILD)]), }, - // The scroll Motion of an XI2 grab with owner_events false is a grab-window - // copy of its own: one fresh check, whatever the press's check at that - // window said. Denying the press check leaves the Motion written. - // Mutation: the Motion reuses the press's grab-window result (this row then - // drops the Motion). - InputRow { - name: "p22_scroll_motion_grab_window_has_its_own_check_press_denied", - scenario: &P22_GRAB, - deny: &[(A, CallKind::Xi2, ROOT)], - denied: P22_GRAB.allow, - }, - // Denying the Motion check drops it. - // Mutation: the Motion is written unchecked (this row writes it). - InputRow { - name: "p22_scroll_motion_grab_window_has_its_own_check_motion_denied", - scenario: &P22_GRAB, - deny: &[(A, SCROLL_MOTION_CALL, ROOT)], - denied: calls_only(P22_GRAB.allow.calls), - }, // Slave motion over C: A selects XI1 `DeviceMotionNotify` on C, B on P. A's // copy denied: the walk goes on and B gets it at P. // Mutation: a denied XI1 selector stops the walk (selection decides the @@ -2207,18 +1210,6 @@ const ROWS: &[InputRow] = &[ deny: &[(A, XI1_MOTION_CALL, CHILD)], denied: calls_only(&[(A, XI1_MOTION_CALL, CHILD)]), }, - // Slave origin, XI1 `GrabDevice` by A on G with `owner_events`: with A's own - // copy on C allowed A gets it at C and the foreign selector B is not asked - // (the allow-all run). With A denied, B (allowed) sends the event to G: A - // gets one fresh check there. - // Mutations: the owner copy is not checked in the route (selection decides); - // the grab-window copy is written unchecked (the three p26 rows). - InputRow { - name: "p26_xi1_grab_owner_denied_falls_to_the_grab_window", - scenario: &P26_OWNER_EVENTS, - deny: &[(A, XI1_PRESS_CALL, CHILD)], - denied: P26_FALLS_TO_ROOT, - }, // Without `owner_events` the natural walk is not checked at all: only A's // copy at G, and a denial there is a delivery (the grab stays). // Mutation: the natural walk is asked without `owner_events`. @@ -2278,39 +1269,6 @@ const ROWS: &[InputRow] = &[ &[xi1_implicit(A, CHILD)], ), }, - // An XIGrabDevice on the slave with `owner_events` and ButtonPress in its - // mask; A selects the XI1 press on C. A's XI1 copy denied: the XI2 route - // falls back to the grab window and the XI1 selection path delivers nothing - // to A (one XI1 call, one XI2 grab-window call). - // Mutation: the filter is selection-only (A also gets the XI1 copy at C: - // double delivery), or the router asks again. - InputRow { - name: "p27_xi1_slave_grab_filter_agrees_with_the_xi2_route", - scenario: &Scenario { - setup: setup_p27, - steps: &[press(XTEST_SLAVE)], - allow: frames_and_calls( - &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], - &[(A, XI1_PRESS_CALL, CHILD)], - ), - order: CallOrder::Total, - }, - deny: &[(A, XI1_PRESS_CALL, CHILD)], - denied: Outcome { - frames: &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], - moved: &[moved( - A, - Kind::Xi2(DEVICEID_XTEST_POINTER), - ROOT, - FOCUS, - POINTER, - )], - calls: &[(A, XI1_PRESS_CALL, CHILD), (A, CallKind::Xi2, ROOT)], - grab: None, - - ..NOTHING - }, - }, // B's foreign XI1 copy on C is denied, A's own is on P. Allow-all: B's copy // rejects the walk, A gets the XI2 grab-window copy. Denied: the route reaches // A's selector on P and the router writes it there, though a selection-only @@ -2343,17 +1301,6 @@ const ROWS: &[InputRow] = &[ ..NOTHING }, }, - // The activating press queues its XI1 route behind the sync slave grab; - // AsyncDevice re-enters the XI1 filter with a fresh memo. The filter must - // not ask Receive for the slave XI2 copy that this thaw does not write. - // Mutation: pass xi2_known_only=false from the thaw filter, adding its - // phantom XI2 call to the thaw trace. - InputRow { - name: "p27_thawed_xi1_press_filter_asks_no_xi2_copy@press", - scenario: &P27_THAWED_XI1_FILTER_PRESS, - deny: &[(A, XI2_PRESS_CALL, CHILD)], - denied: P27_THAWED_XI1_FILTER_PRESS.allow, - }, InputRow { name: "p27_thawed_xi1_press_filter_asks_no_xi2_copy", scenario: &P27_THAWED_XI1_FILTER, @@ -2372,28 +1319,6 @@ const ROWS: &[InputRow] = &[ ], ), }, - // This sibling leaves XI2 unselected on C while retaining the sync slave - // passive grab and XI1 selection. The queued Xi1Routed press then produces - // an observable XI1 copy at thaw. Mutation: drop the dequeued Xi1Routed - // entry in xi1_compute_freezes without routing it. - InputRow { - name: "p27_thawed_xi1_routed_entry_delivers_xi1_copy", - scenario: &P27_THAWED_XI1_DELIVERY, - deny: &[(A, XI1_PRESS_CALL, CHILD)], - denied: with_grab( - frames_and_calls( - &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT)], - &[(A, CallKind::Xi2, ROOT), (A, XI1_PRESS_CALL, CHILD)], - ), - &[ - Grab::Detached { - device: DEVICEID_XTEST_POINTER, - master: DEVICEID_MASTER_POINTER, - }, - SLAVE_PASSIVE_GRAB, - ], - ), - }, // The live filter follows the slave XI2 route's decision in their shared // memo: when that XI2 copy is denied, A's selected XI1 copy is written. // Mutation: make a known-only XI2 selector count as allowed in the filter, @@ -2424,57 +1349,6 @@ const ROWS: &[InputRow] = &[ )], ), }, - // A sync `GrabDeviceButton` by the requester on P activates on the press and - // stores it (the activating write is one fresh check). - InputRow { - name: "p28_thawed_xi1_press_picks_the_owner_from_allowed@press", - scenario: &P28_PRESS, - deny: &[(B, XI1_PRESS_CALL, CHILD)], - denied: P28_PRESS.allow, - }, - // Its `AllowDeviceEvents(ReplayThisDevice)` re-routes the press through the - // thaw with no decided delivery. Two XI1 press selectors on C; the one that - // also selected the grab class (B) is denied: the other (A) owns the XI1 - // implicit grab. Allow-all: B, the grab class holder. - // Mutation: the implicit owner is chosen among the selectors (the denied B - // owns the grab), or the replay walk is unchecked (B gets the copy). - InputRow { - name: "p28_thawed_xi1_press_picks_the_owner_from_allowed", - scenario: &Scenario { - steps: &[press(XTEST_SLAVE), Step::Request(replay_slave, &[])], - allow: with_grab( - frames_and_calls( - &[ - (SEND_CLIENT, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS), - (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), - (B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), - ], - &[ - (SEND_CLIENT, XI1_PRESS_CALL, FOCUS), - (A, XI1_PRESS_CALL, CHILD), - (B, XI1_PRESS_CALL, CHILD), - ], - ), - &[xi1_implicit(B, CHILD)], - ), - ..P28_PRESS - }, - deny: &[(B, XI1_PRESS_CALL, CHILD)], - denied: with_grab( - frames_and_calls( - &[ - (SEND_CLIENT, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS), - (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), - ], - &[ - (SEND_CLIENT, XI1_PRESS_CALL, FOCUS), - (A, XI1_PRESS_CALL, CHILD), - (B, XI1_PRESS_CALL, CHILD), - ], - ), - &[xi1_implicit(A, CHILD)], - ), - }, ]; #[test] diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs index 516a555af..aa9cd6e83 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs @@ -21,14 +21,11 @@ const XTEST_SLAVE_POINTER: InputOrigin = InputOrigin::XTest(DEVICEID_XTEST_POINT const XTEST_MASTER_KEYBOARD: InputOrigin = InputOrigin::XTest(DEVICEID_MASTER_KEYBOARD); const XTEST_SLAVE_KEYBOARD: InputOrigin = InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD); const CORE_BUTTON_PRESS: u32 = 1 << 2; -const CORE_MOTION: u32 = 1 << 6; const XI_BUTTON_PRESS: u32 = 1 << 4; const XI_RAW_KEY_PRESS: u32 = 1 << 13; -const MOTION_TO: (i16, i16) = (125, 125); const FOCUS_EVENT: (i16, i16) = (20, 20); const CORE_BUTTON_PRESS_CALL: CallKind = CallKind::Core; -const CORE_MOTION_CALL: CallKind = CallKind::Core; const CORE_KEY_PRESS_CALL: CallKind = CallKind::Core; const XI1_BUTTON_PRESS_CALL: CallKind = CallKind::Batch(&[Named::Xi1(XI_DEVICE_BUTTON_PRESS_OFFSET as u16)]); @@ -55,10 +52,6 @@ const fn button_press(origin: InputOrigin) -> Step { pointer_event(origin, PointerEventKind::ButtonPress, POINTER) } -const fn motion(origin: InputOrigin) -> Step { - pointer_event(origin, PointerEventKind::MotionNotify, MOTION_TO) -} - const fn key_press(origin: InputOrigin) -> Step { Step::Event(Drive::Entry { origin, @@ -107,13 +100,6 @@ fn setup_r5_replay_keyboard(f: &mut NotifyFixture) { grab_key(f, A, ROOT, false, true); } -fn setup_r5_replay_keyboard_continuation(f: &mut NotifyFixture) { - tree(f); - select_core(f, A, FOCUS, KEY_PRESS); - select_core(f, B, FOCUS, KEY_PRESS); - grab_key(f, A, ROOT, false, true); -} - fn setup_r1_equal_key_xi1_queue(f: &mut NotifyFixture) { tree(f); register_physical_pointer(f); @@ -131,12 +117,6 @@ fn setup_r1_equal_key_xi1_queue(f: &mut NotifyFixture) { xi2_passive_button_grab(f, PHYSICAL_DEVICE); } -fn setup_r6_queued_motion(f: &mut NotifyFixture) { - tree(f); - select_core(f, A, CHILD, CORE_MOTION); - grab_core_button(f, A, ROOT, true, 0); // synchronous passive GrabButton -} - fn setup_r7_queued_key(f: &mut NotifyFixture) { tree(f); select_core(f, A, CHILD, KEY_PRESS); @@ -171,32 +151,6 @@ fn setup_r9_xi1_freeze_next(f: &mut NotifyFixture) { ); } -const PASSIVE_CORE_POINTER: Grab = Grab::Pointer(PointerGrab { - owner: A, - window: ROOT, - implicit: false, - passive: true, - via_xi2: false, -}); - -const CORE_POINTER_PRESS_FROZEN: Grab = Grab::Freeze { - device: DEVICEID_MASTER_POINTER, - state: Xi1SyncState::FrozenWithEvent, - other: None, - stored: Some(Held::HostPointer { - kind: PointerEventKind::ButtonPress, - detail: 1, - }), -}; - -const MASTER_POINTER_MOTION_QUEUED: Grab = Grab::Queued { - device: DEVICEID_MASTER_POINTER, - held: Held::HostPointer { - kind: PointerEventKind::MotionNotify, - detail: 0, - }, -}; - const XI1_POINTER_PRESS_STORED: Grab = Grab::Freeze { device: DEVICEID_XTEST_POINTER, state: Xi1SyncState::FrozenWithEvent, @@ -207,38 +161,6 @@ const XI1_POINTER_PRESS_STORED: Grab = Grab::Freeze { }), }; -const MASTER_KEY_PRESS_FROZEN: Grab = Grab::Freeze { - device: DEVICEID_MASTER_KEYBOARD, - state: Xi1SyncState::FrozenWithEvent, - other: None, - stored: Some(Held::HostKeyTransition { - pressed: true, - keycode: KEYCODE, - master: true, - synthetic: false, - }), -}; - -const PHYSICAL_POINTER_PRESS_STORED: Grab = Grab::Freeze { - device: PHYSICAL_DEVICE, - state: Xi1SyncState::FrozenWithEvent, - other: None, - stored: Some(Held::HostPointer { - kind: PointerEventKind::ButtonPress, - detail: 1, - }), -}; - -const R1_XTEST_PRESS_STORED: Grab = Grab::Freeze { - device: DEVICEID_XTEST_POINTER, - state: Xi1SyncState::FrozenWithEvent, - other: None, - stored: Some(Held::HostPointer { - kind: PointerEventKind::ButtonPress, - detail: 1, - }), -}; - const R1_XTEST_PASSIVE_GRAB: Grab = Grab::SlavePointer { device: DEVICEID_XTEST_POINTER, grab: PointerGrab { @@ -261,42 +183,6 @@ const R1_PHYSICAL_PASSIVE_GRAB: Grab = Grab::SlavePointer { }, }; -const R1_XTEST_XI1_QUEUED: Grab = Grab::Queued { - device: DEVICEID_XTEST_POINTER, - held: Held::Xi1Routed { - evcode: crate::server::XI_FIRST_EVENT + XI_DEVICE_BUTTON_PRESS_OFFSET, - detail: 1, - }, -}; - -const R1_PHYSICAL_XI1_QUEUED: Grab = Grab::Queued { - device: PHYSICAL_DEVICE, - held: Held::Xi1Routed { - evcode: crate::server::XI_FIRST_EVENT + XI_DEVICE_BUTTON_PRESS_OFFSET, - detail: 1, - }, -}; - -const XI1_KEYBOARD_QUEUE: Grab = Grab::Freeze { - device: DEVICEID_MASTER_KEYBOARD, - state: Xi1SyncState::FrozenNoEvent, - other: None, - stored: None, -}; - -const R4_PRESS: Scenario = Scenario { - setup: setup_r4_replay_pointer, - steps: &[button_press(XTEST_MASTER_POINTER)], - allow: with_grab( - frames_and_calls( - &[(A, Kind::Core, ROOT)], - &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], - ), - &[PASSIVE_CORE_POINTER, CORE_POINTER_PRESS_FROZEN], - ), - order: CallOrder::Total, -}; - const R4_REPLAY: Scenario = Scenario { setup: setup_r4_replay_pointer, steps: &[ @@ -344,75 +230,6 @@ const R5_REPLAY: Scenario = Scenario { order: CallOrder::Total, }; -const R5_PRESS: Scenario = Scenario { - setup: setup_r5_replay_keyboard, - steps: &[key_press(XTEST_MASTER_KEYBOARD)], - allow: with_grab( - frames_and_calls(&[(A, Kind::Core, ROOT)], &[(A, CORE_KEY_PRESS_CALL, ROOT)]), - &[A_ROOT_KEYBOARD_GRAB, MASTER_KEY_PRESS_FROZEN], - ), - order: CallOrder::Total, -}; - -const R5_CONTINUATION: Scenario = Scenario { - setup: setup_r5_replay_keyboard_continuation, - steps: &[ - key_press(XTEST_MASTER_KEYBOARD), - Step::Request(allow_core_events::<5>, &[key_press(XTEST_MASTER_KEYBOARD)]), - ], - allow: with_grab( - frames_and_calls( - &[ - (A, Kind::Core, ROOT), - (A, Kind::Core, FOCUS), - (B, Kind::Core, FOCUS), - ], - &[ - (A, CORE_KEY_PRESS_CALL, ROOT), - (A, CORE_KEY_PRESS_CALL, FOCUS), - (B, CORE_KEY_PRESS_CALL, FOCUS), - ], - ), - &[], - ), - order: CallOrder::PerClient, -}; - -const R1_XI1_QUEUE: Scenario = Scenario { - setup: setup_r1_equal_key_xi1_queue, - steps: &[ - button_press(XTEST_SLAVE_POINTER), - button_press(PHYSICAL_POINTER), - ], - allow: with_grab( - frames_and_calls( - &[ - (A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT), - (A, Kind::Xi2(PHYSICAL_DEVICE), ROOT), - ], - &[(A, CallKind::Xi2, ROOT), (A, CallKind::Xi2, ROOT)], - ), - &[ - A_ROOT_KEYBOARD_GRAB, - XTEST_POINTER_DETACHED, - PHYSICAL_POINTER_DETACHED, - R1_XTEST_PASSIVE_GRAB, - R1_PHYSICAL_PASSIVE_GRAB, - Grab::Freeze { - device: DEVICEID_MASTER_KEYBOARD, - state: Xi1SyncState::FrozenNoEvent, - other: None, - stored: None, - }, - R1_XTEST_PRESS_STORED, - PHYSICAL_POINTER_PRESS_STORED, - R1_XTEST_XI1_QUEUED, - R1_PHYSICAL_XI1_QUEUED, - ], - ), - order: CallOrder::Total, -}; - const R1_XI1_THAW: Scenario = Scenario { setup: setup_r1_equal_key_xi1_queue, steps: &[ @@ -446,78 +263,6 @@ const R1_XI1_THAW: Scenario = Scenario { order: CallOrder::Total, }; -const R6_QUEUE: Scenario = Scenario { - setup: setup_r6_queued_motion, - steps: &[ - button_press(XTEST_MASTER_POINTER), - motion(XTEST_MASTER_POINTER), - ], - allow: with_grab( - frames_and_calls( - &[(A, Kind::Core, ROOT)], - &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], - ), - &[ - PASSIVE_CORE_POINTER, - CORE_POINTER_PRESS_FROZEN, - MASTER_POINTER_MOTION_QUEUED, - ], - ), - order: CallOrder::Total, -}; - -const R6_THAW: Scenario = Scenario { - setup: setup_r6_queued_motion, - steps: &[ - button_press(XTEST_MASTER_POINTER), - motion(XTEST_MASTER_POINTER), - Step::Request(allow_core_events::<0>, &[]), - ], - allow: with_grab( - frames_and_calls( - &[(A, Kind::Core, ROOT), (A, Kind::Core, CHILD)], - &[ - (A, CORE_BUTTON_PRESS_CALL, ROOT), - (A, CORE_MOTION_CALL, CHILD), - ], - ), - &[PASSIVE_CORE_POINTER], - ), - order: CallOrder::Total, -}; - -const R7_QUEUE: Scenario = Scenario { - setup: setup_r7_queued_key, - steps: &[ - raw_key_press(XTEST_SLAVE_KEYBOARD), - key_press(XTEST_SLAVE_KEYBOARD), - ], - allow: Outcome { - grab: Some(&[ - A_ROOT_KEYBOARD_GRAB, - XI1_KEYBOARD_QUEUE, - Grab::Queued { - device: DEVICEID_MASTER_KEYBOARD, - held: Held::RawKey { - pressed: true, - keycode: KEYCODE, - }, - }, - Grab::Queued { - device: DEVICEID_MASTER_KEYBOARD, - held: Held::HostKeyTransition { - pressed: true, - keycode: KEYCODE, - master: true, - synthetic: false, - }, - }, - ]), - ..NOTHING - }, - order: CallOrder::Total, -}; - const R7_THAW: Scenario = Scenario { setup: setup_r7_queued_key, steps: &[ @@ -586,40 +331,6 @@ const R9_XI1_FREEZE: Scenario = Scenario { }; const ROWS: &[InputRow] = &[ - // Mutation: hoist ReceiveMemo out of `xi1_compute_freezes`' per-entry - // router call. The different devices have the same client/window/batch - // key, so thaw must still ask Receive once for each queued write. - InputRow { - name: "r1_equal_key_xi1_routed_entries_share_freeze_pass@queue", - scenario: &R1_XI1_QUEUE, - deny: &[], - denied: with_grab( - frames_and_calls( - &[ - (A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT), - (A, Kind::Xi2(PHYSICAL_DEVICE), ROOT), - ], - &[(A, CallKind::Xi2, ROOT), (A, CallKind::Xi2, ROOT)], - ), - &[ - A_ROOT_KEYBOARD_GRAB, - XTEST_POINTER_DETACHED, - PHYSICAL_POINTER_DETACHED, - R1_XTEST_PASSIVE_GRAB, - R1_PHYSICAL_PASSIVE_GRAB, - Grab::Freeze { - device: DEVICEID_MASTER_KEYBOARD, - state: Xi1SyncState::FrozenNoEvent, - other: None, - stored: None, - }, - R1_XTEST_PRESS_STORED, - PHYSICAL_POINTER_PRESS_STORED, - R1_XTEST_XI1_QUEUED, - R1_PHYSICAL_XI1_QUEUED, - ], - ), - }, InputRow { name: "r1_equal_key_xi1_routed_entries_share_freeze_pass", scenario: &R1_XI1_THAW, @@ -648,45 +359,6 @@ const ROWS: &[InputRow] = &[ ], ), }, - // Mutation: gate passive storage on the original activating write's - // Receive result. Denying A@ROOT must still leave ReplayPointer able to - // deliver the press; Xorg 21.1.24 `dix/events.c:3833-3919` stores it. - // Kill probe: `t3r1-r4-passive-store-gated-on-original-write-check`. - InputRow { - name: "r4_replay_pointer_rechecks_the_natural_target@press", - scenario: &R4_PRESS, - deny: &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], - denied: with_grab( - calls_only(&[(A, CORE_BUTTON_PRESS_CALL, ROOT)]), - &[PASSIVE_CORE_POINTER, CORE_POINTER_PRESS_FROZEN], - ), - }, - // Mutation: make the replay's core selection route selection-only. B's - // denial must let A at FOCUS receive the press; Xorg 21.1.24 replay - // rematches below the released grab (`dix/events.c:1318-1371`). - // Kill probe: `t4-r4-extra-receive-on-replay-choice` rejects a check made - // when AllowEvents chooses the stored press. - InputRow { - name: "r4_replay_pointer_rechecks_the_natural_target", - scenario: &R4_REPLAY, - deny: &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], - denied: with_grab( - frames_and_calls( - &[(B, Kind::Core, CHILD)], - &[ - (A, CORE_BUTTON_PRESS_CALL, ROOT), - (B, CORE_BUTTON_PRESS_CALL, CHILD), - ], - ), - &[Grab::Pointer(PointerGrab { - owner: B, - window: CHILD, - implicit: true, - passive: false, - via_xi2: false, - })], - ), - }, InputRow { name: "r4_replay_pointer_rechecks_the_natural_target_denied_at_B", scenario: &R4_REPLAY, @@ -715,18 +387,6 @@ const ROWS: &[InputRow] = &[ })], ), }, - // Mutation: gate activation storage on the original denied write. The - // checkpoint still requires A's active grab and stored transition, with - // no B call. Kill probe: `t3r1-r5-key-store-gated-on-activation-check`. - InputRow { - name: "r5_replay_keyboard_rechecks_the_focus@press", - scenario: &R5_PRESS, - deny: &[(A, CORE_KEY_PRESS_CALL, ROOT)], - denied: with_grab( - calls_only(&[(A, CORE_KEY_PRESS_CALL, ROOT)]), - &[A_ROOT_KEYBOARD_GRAB, MASTER_KEY_PRESS_FROZEN], - ), - }, // Mutation: gate the stored activating transition on its original // Receive result. ReplayKeyboard must still hand a denied A copy to B. // Kill probe: `t3r1-r5-key-store-gated-on-activation-check`. @@ -745,27 +405,6 @@ const ROWS: &[InputRow] = &[ &[], ), }, - // Mutation: a denied selector at the focused window vetoes another - // client's allowed copy. Kill probe: `t3r1-r5-key-denial-does-not-veto`. - InputRow { - name: "r5_replay_keyboard_rechecks_the_focus_denied_selector_continues", - scenario: &R5_CONTINUATION, - deny: &[ - (A, CORE_KEY_PRESS_CALL, ROOT), - (B, CORE_KEY_PRESS_CALL, FOCUS), - ], - denied: with_grab( - frames_and_calls( - &[(A, Kind::Core, FOCUS)], - &[ - (A, CORE_KEY_PRESS_CALL, ROOT), - (A, CORE_KEY_PRESS_CALL, FOCUS), - (B, CORE_KEY_PRESS_CALL, FOCUS), - ], - ), - &[], - ), - }, // Mutation: skip Receive for the replayed key's focus write. A denied // focus copy must be dropped; Xorg 21.1.24 replays to focus at `dix/events.c:1360`. InputRow { @@ -783,95 +422,6 @@ const ROWS: &[InputRow] = &[ &[], ), }, - // Pin only: queueing the motion makes no Receive call and preserves it; - // Xorg `ComputeFreezes` queues without a Receive hook (`dix/events.c:1320`). - InputRow { - name: "r6_thawed_queued_motion_is_checked_at_its_write@queue", - scenario: &R6_QUEUE, - deny: &[], - denied: with_grab( - frames_and_calls( - &[(A, Kind::Core, ROOT)], - &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], - ), - &[ - PASSIVE_CORE_POINTER, - CORE_POINTER_PRESS_FROZEN, - MASTER_POINTER_MOTION_QUEUED, - ], - ), - }, - // Mutation: bypass `fanout::receive_allows` while - // `state.playing_sync_events` in the thawed pointer write. The denied - // natural owner copy must fall back to a fresh grab-window check, per - // Xorg 21.1.24 `dix/events.c:4388-4398`. - InputRow { - name: "r6_thawed_queued_motion_is_checked_at_its_write", - scenario: &R6_THAW, - deny: &[(A, CallKind::Batch(&[Named::Core(6)]), CHILD)], - denied: with_grab( - with_moved( - frames_and_calls( - &[(A, Kind::Core, ROOT), (A, Kind::Core, ROOT)], - &[ - (A, CORE_BUTTON_PRESS_CALL, ROOT), - (A, CORE_MOTION_CALL, CHILD), - (A, CORE_MOTION_CALL, ROOT), - ], - ), - &[moved(A, Kind::Core, ROOT, FOCUS, MOTION_TO)], - ), - &[PASSIVE_CORE_POINTER], - ), - }, - InputRow { - name: "r6_thawed_queued_motion_denied_at_both_writes_stays_grabbed", - scenario: &R6_THAW, - deny: &[ - (A, CallKind::Batch(&[Named::Core(6)]), CHILD), - (A, CallKind::Batch(&[Named::Core(6)]), ROOT), - ], - denied: Outcome { - frames: &[(A, Kind::Core, ROOT)], - calls: &[ - (A, CORE_BUTTON_PRESS_CALL, ROOT), - (A, CORE_MOTION_CALL, CHILD), - (A, CORE_MOTION_CALL, ROOT), - ], - grab: Some(&[PASSIVE_CORE_POINTER]), - ..NOTHING - }, - }, - // Pin only: queueing the raw and cooked key makes no Receive call; Xorg - // queues during `ComputeFreezes` without a Receive hook (`dix/events.c:1320`). - InputRow { - name: "r7_thawed_queued_key_is_checked_at_its_write@queue", - scenario: &R7_QUEUE, - deny: &[], - denied: Outcome { - grab: Some(&[ - A_ROOT_KEYBOARD_GRAB, - XI1_KEYBOARD_QUEUE, - Grab::Queued { - device: DEVICEID_MASTER_KEYBOARD, - held: Held::RawKey { - pressed: true, - keycode: KEYCODE, - }, - }, - Grab::Queued { - device: DEVICEID_MASTER_KEYBOARD, - held: Held::HostKeyTransition { - pressed: true, - keycode: KEYCODE, - master: true, - synthetic: false, - }, - }, - ]), - ..NOTHING - }, - }, // Mutation: skip Receive during `playing_sync_events`. Both the queued // RawKey root copy and HostKeyTransition natural copy are fresh writes; // Xorg 21.1.24 routes each on thaw at `dix/events.c:1320-1371`. @@ -897,43 +447,6 @@ const ROWS: &[InputRow] = &[ &[A_ROOT_KEYBOARD_GRAB], ), }, - // Mutation: playback calls Receive for the ROOT fallback but discards its - // denial. Kill probe: `t4-r7-playback-discards-root-receive-denial`. - InputRow { - name: "r7_thawed_queued_key_denied_at_child_and_root_stays_grabbed", - scenario: &R7_THAW, - deny: &[ - (B, RAW_KEY_PRESS_CALL, ROOT), - (A, CORE_KEY_PRESS_CALL, CHILD), - (A, CORE_KEY_PRESS_CALL, ROOT), - ], - denied: with_grab( - calls_only(&[ - (B, CallKind::Batch(&[Named::Raw(13)]), ROOT), - (A, CallKind::Batch(&[Named::Core(2)]), CHILD), - (A, CallKind::Batch(&[Named::Core(2)]), ROOT), - ]), - &[A_ROOT_KEYBOARD_GRAB], - ), - }, - // Mutation: gate XI1 activation storage on the original write's Receive - // result. A denied activation still stores it for ReplayThisDevice; - // Xorg 21.1.24 `dix/events.c:3833-3919` keeps activation independent. - // Kill probe: `t3r1-r8-xi1-store-gated-on-original-write-check`. - InputRow { - name: "r8_denied_xi1_activating_write_still_replays", - scenario: &R8_REPLAY, - deny: &[(A, XI1_BUTTON_PRESS_CALL, ROOT)], - denied: Outcome { - frames: &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], - calls: &[ - (A, XI1_BUTTON_PRESS_CALL, ROOT), - (B, XI1_BUTTON_PRESS_CALL, CHILD), - ], - grab: Some(&[B_CHILD_XI1_POINTER_GRAB]), - ..NOTHING - }, - }, InputRow { name: "r8_denied_xi1_activating_write_rechecks_the_replayed_selector", scenario: &R8_REPLAY, From 442b8f4761f73a04df46b210b4c97b008bfec578 Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Thu, 3 Dec 2026 20:06:25 -0300 Subject: [PATCH 71/72] test(access): Task 3 review round, restore the rows that pin a distinct decision The review found rows that pruning removed although no kept row pins their decision: owner-events keyboard continuation (k7, k9), the exhausted focus walk (k6), the owner's own protocol precedence (p11), slave/master check sharing (p4, p4c), the fresh XI2 fallback (p13), write-time and thaw denials (p12, r6, r7), the XI1 press prepass (p19), and the k13, k14b, k16 and p3 boundaries. They are back, and the two-form scroll stop row gains an ancestor selector so a resumed walk shows. Probe catchers point at the row whose assertion the probe describes. The runner captures and decodes each step once, keeps the frame-detail negative control, and builds XI1 frames with the existing encoders. Co-Authored-By: Claude Opus 5.5 Implemented-By: codex (gpt-6-luna max) --- .../tests/access_input_support.rs | 700 ++++++++++-------- .../process_request/tests/access_key_input.rs | 181 +++++ .../tests/access_pointer_input.rs | 212 +++++- .../tests/access_replay_input.rs | 77 ++ 4 files changed, 838 insertions(+), 332 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index 07dae3670..84c2ab8ff 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -485,14 +485,7 @@ pub(super) fn set_focus_pointer_root(f: &mut NotifyFixture) { /// The core GrabKeyboard request by `owner` on `window`, asynchronous pointer /// mode, with `owner_events`. The reply must be Success. pub(super) fn grab_keyboard(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: bool) { - const CORE_GRAB_KEYBOARD: u8 = 31; - let mut body = Vec::with_capacity(12); - body.extend_from_slice(&window.to_le_bytes()); - body.extend_from_slice(&[0; 4]); // CurrentTime - body.extend_from_slice(&[1, 1, 0, 0]); // async pointer, async keyboard - let bytes = send_with_reply(f, owner, CORE_GRAB_KEYBOARD, u8::from(owner_events), &body); - let reply = &bytes[bytes.len() - 32..]; - assert_eq!((reply[0], reply[1]), (1, 0), "GrabKeyboard replies Success"); + grab_keyboard_modes(f, owner, window, owner_events, 1, 1); } /// A core `GrabKeyboard` with independently chosen pointer and keyboard modes. @@ -540,13 +533,31 @@ pub(super) fn grab_xi1_device( window: u32, device: u16, synchronous: bool, +) { + send_xi1_grab_device(f, owner, window, device, false, u8::from(!synchronous), 1); +} + +/// XI1 `GrabDevice` with explicit owner-events and device/keyboard modes. +pub(super) fn send_xi1_grab_device( + f: &mut NotifyFixture, + owner: u32, + window: u32, + device: u16, + owner_events: bool, + pointer_mode: u8, + keyboard_mode: u8, ) { const XI1_GRAB_DEVICE: u8 = 13; let mut body = Vec::with_capacity(16); body.extend_from_slice(&window.to_le_bytes()); body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime body.extend_from_slice(&0_u16.to_le_bytes()); // no event classes - body.extend_from_slice(&[u8::from(!synchronous), 1, 0, device as u8]); + body.extend_from_slice(&[ + pointer_mode, + keyboard_mode, + u8::from(owner_events), + device as u8, + ]); body.extend_from_slice(&[0, 0]); // pad let bytes = send_with_reply(f, owner, XI_MAJOR, XI1_GRAB_DEVICE, &body); let reply = &bytes[bytes.len() - 32..]; @@ -748,134 +759,150 @@ pub(super) fn decide(denied: &[Call], evs: &[u16], call: &RecordedExtensionCheck if hit { DENY } else { Decision::Allow } } -/// Decodes a frame the walks write: a core key, button or motion event (event -/// window at byte 12), an XI2 key, button or motion GenericEvent (device at -/// byte 10, event window at byte 24) or a raw XI2 input GenericEvent (device at -/// byte 10, always the root), or an XI1 device event. `None` for a frame that is no -/// input event (a reply, a crossing, a mapping notify...); an XI1 event frame or -/// an XI2 touch frame with no `Kind` panics, so it is never skipped. -pub(super) fn decode(frame: &[u8], order: ClientByteOrder) -> Option<(Kind, u32)> { - match frame[0] & 0x7f { - 2..=6 => Some((Kind::Core, dec32(&frame[12..16], order))), - code if code - == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET - || code - == crate::server::XI_FIRST_EVENT - + crate::xinput::XI_DEVICE_BUTTON_RELEASE_OFFSET => - { - Some(( - Kind::Xi1(u16::from(frame[31] & 0x7f)), - dec32(&frame[12..16], order), - )) - } - code if code - == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET - || code - == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET => - { - Some(( - Kind::Xi1Key(u16::from(frame[31] & 0x7f)), - dec32(&frame[12..16], order), - )) - } - code if code - == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET => - { - Some(( - Kind::Xi1Motion(u16::from(frame[31] & 0x7f)), - dec32(&frame[12..16], order), - )) - } - code if code - == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_VALUATOR_OFFSET => - { - Some((Kind::Xi1Valuator(u16::from(frame[1])), 0)) - } - 35 if frame[1] == XI2_MAJOR_OPCODE => match dec16(&frame[8..10], order) { - 2..=6 => Some(( - Kind::Xi2(dec16(&frame[10..12], order)), - dec32(&frame[24..28], order), - )), - 13..=17 => Some((Kind::Raw(dec16(&frame[10..12], order)), ROOT)), - touch @ 18..=24 => panic!("undecoded XI2 touch frame {touch}: add a Kind"), - _ => None, - }, - code if (crate::server::XI_FIRST_EVENT - ..=crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_PROPERTY_NOTIFY_OFFSET) - .contains(&code) => - { - panic!("undecoded XI1 frame {code}: add a Kind") - } - _ => None, - } +struct InputFrame { + kind: Kind, + window: u32, + sequence: u16, + event_type: Option, + detail: Option, + placement: (u32, (i16, i16)), } -/// The event number a frame carries, normalized to the corresponding core/XI2 -/// input type. XI1's event code carries the same distinction in its code. -fn decoded_event_type(frame: &[u8], kind: Kind, order: ClientByteOrder) -> Option { - match kind { - Kind::Core => Some(u16::from(frame[0] & 0x7f)), - Kind::Xi1(_) => match frame[0] & 0x7f { - code if code - == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET => - { - Some(4) - } - code if code - == crate::server::XI_FIRST_EVENT - + crate::xinput::XI_DEVICE_BUTTON_RELEASE_OFFSET => - { - Some(5) - } - _ => unreachable!("decoded XI1 button frame has an unexpected event code"), - }, - Kind::Xi1Key(_) => match frame[0] & 0x7f { - code if code - == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET => - { - Some(2) - } - code if code - == crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET => - { - Some(3) - } - _ => unreachable!("decoded XI1 key frame has an unexpected event code"), - }, - Kind::Xi1Motion(_) => Some(6), - Kind::Xi1Valuator(_) => None, - Kind::Xi2(_) => Some(dec16(&frame[8..10], order)), - Kind::Raw(_) => match dec16(&frame[8..10], order) { - 13 => Some(2), - 14 => Some(3), - 15 => Some(4), - 16 => Some(5), - 17 => Some(6), - _ => unreachable!("decoded XI2 raw frame has an unexpected event type"), - }, - } +struct FrameRecord { + start: usize, + len: usize, + first_byte: u8, + input: Option, } struct StepBytes { bytes: Vec, sequence: u16, + frames: Vec, } struct ClientBytes { client: u32, order: ClientByteOrder, - /// Bytes written and the sequence after each scenario step. + /// Captured bytes, sequence and decoded frames after each scenario step. steps: Vec, } -fn client_frames<'a>(client: &'a ClientBytes) -> impl Iterator + 'a { +fn client_frames<'a>( + client: &'a ClientBytes, +) -> impl Iterator + 'a { client.steps.iter().enumerate().flat_map(|(step, capture)| { - split_frames(&capture.bytes, client.order) - .into_iter() - .map(move |frame| (step, frame)) + capture + .frames + .iter() + .map(move |frame| (step, capture, frame)) }) } +fn frame_bytes<'a>(capture: &'a StepBytes, frame: &FrameRecord) -> &'a [u8] { + &capture.bytes[frame.start..frame.start + frame.len] +} + +/// Decodes one frame the walks write: a core key, button or motion event (event +/// window at byte 12), an XI2 key, button or motion GenericEvent (device at +/// byte 10, event window at byte 24) or a raw XI2 input GenericEvent (device at +/// byte 10, always the root), or an XI1 device event. `None` for a frame that is +/// no input event (a reply, a crossing, a mapping notify...); an XI1 event frame +/// or an XI2 touch frame with no `Kind` panics, so it is never skipped. +fn decode(frame: &[u8], order: ClientByteOrder) -> Option { + let code = frame[0] & 0x7f; + if (crate::server::XI_FIRST_EVENT + ..=crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_PROPERTY_NOTIFY_OFFSET) + .contains(&code) + { + let device = u16::from(frame[31] & 0x7f); + let (kind, window, event_type, detail) = match code - crate::server::XI_FIRST_EVENT { + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET => ( + Kind::Xi1(device), + dec32(&frame[12..16], order), + Some(4), + Some(u32::from(frame[1])), + ), + crate::xinput::XI_DEVICE_BUTTON_RELEASE_OFFSET => ( + Kind::Xi1(device), + dec32(&frame[12..16], order), + Some(5), + Some(u32::from(frame[1])), + ), + crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET => ( + Kind::Xi1Key(device), + dec32(&frame[12..16], order), + Some(2), + Some(u32::from(frame[1])), + ), + crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET => ( + Kind::Xi1Key(device), + dec32(&frame[12..16], order), + Some(3), + Some(u32::from(frame[1])), + ), + crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET => ( + Kind::Xi1Motion(device), + dec32(&frame[12..16], order), + Some(6), + Some(u32::from(frame[1])), + ), + crate::xinput::XI_DEVICE_VALUATOR_OFFSET => { + (Kind::Xi1Valuator(u16::from(frame[1])), 0, None, None) + } + _ => panic!("undecoded XI1 frame {code}: add a Kind"), + }; + return Some(input_frame(frame, order, kind, window, event_type, detail)); + } + let (kind, window, event_type, detail) = match code { + 2..=6 => ( + Kind::Core, + dec32(&frame[12..16], order), + Some(u16::from(code)), + Some(u32::from(frame[1])), + ), + 35 if frame[1] == XI2_MAJOR_OPCODE => { + let evtype = dec16(&frame[8..10], order); + match evtype { + 2..=6 => ( + Kind::Xi2(dec16(&frame[10..12], order)), + dec32(&frame[24..28], order), + Some(evtype), + Some(dec32(&frame[16..20], order)), + ), + 13..=17 => ( + Kind::Raw(dec16(&frame[10..12], order)), + ROOT, + Some(evtype - 11), + Some(dec32(&frame[16..20], order)), + ), + touch @ 18..=24 => panic!("undecoded XI2 touch frame {touch}: add a Kind"), + _ => return None, + } + } + _ => return None, + }; + Some(input_frame(frame, order, kind, window, event_type, detail)) +} + +fn input_frame( + frame: &[u8], + order: ClientByteOrder, + kind: Kind, + window: u32, + event_type: Option, + detail: Option, +) -> InputFrame { + InputFrame { + kind, + window, + sequence: dec16(&frame[2..4], order), + event_type, + detail, + placement: placement(frame, kind, order), + } +} + /// One fact of the grab state after a run. A row states the facts its denied /// run must have; the no-policy and allow-all runs must have the same list. #[derive(Clone, Copy, Debug, PartialEq)] @@ -1014,20 +1041,17 @@ pub(super) struct PointerGrab { pub(super) via_xi2: bool, } -struct Hook { - step: usize, - call: RecordedExtensionCheck, +struct StepRun { + events: Vec, + request: Option<(u32, u8, u8)>, + hooks: Vec, + replies: Vec<(u32, u8)>, } struct Run { clients: Vec, - /// Each recorded extension hook, with the scenario step that caused it. - hooks: Vec, - /// Requests the runner's `request()` helper sent, by step: client, major - /// opcode and data byte (the extension minor opcode). - requests: Vec<(usize, u32, u8, u8)>, - /// Reply and X error frames from every fixture client at every step. - replies: Vec<(usize, u32, u8)>, + /// Each step carries its request, ordered hooks and reply/error frames. + steps: Vec, state: String, grab: Vec, } @@ -1128,39 +1152,28 @@ pub(super) fn grouped( fn delivered(name: &str, run: &Run, steps: &[Vec<(u16, u32)>]) -> Vec { let mut frames = Vec::new(); for client in &run.clients { - for (step, frame) in client_frames(client) { - if let Some((kind, window)) = decode(frame, client.order) { - let sequence = match client.order { - ClientByteOrder::LittleEndian => client.steps[step].sequence.to_le_bytes(), - ClientByteOrder::BigEndian => client.steps[step].sequence.to_be_bytes(), - }; - assert_eq!( - &frame[2..4], - sequence.as_slice(), - "{name}: client {} step {step} frame sequence", - client.client - ); - // The valuator continuation has no detail byte (byte 1 is the - // device). - let detail = match kind { - Kind::Core | Kind::Xi1(_) | Kind::Xi1Key(_) | Kind::Xi1Motion(_) => { - Some(u32::from(frame[1])) - } - Kind::Xi1Valuator(_) => None, - Kind::Xi2(_) | Kind::Raw(_) => Some(dec32(&frame[16..20], client.order)), - }; - let event_type = decoded_event_type(frame, kind, client.order); - assert!( - detail.is_none_or(|detail| { - event_type - .is_some_and(|event_type| steps[step].contains(&(event_type, detail))) - }), - "{name}: client {} step {step} frame event {event_type:?} detail {detail:?} is none of {:?}", - client.client, - steps[step] - ); - frames.push((client.client, kind, window)); - } + for (step, capture, frame) in client_frames(client) { + let Some(input) = &frame.input else { + continue; + }; + assert_eq!( + input.sequence, capture.sequence, + "{name}: client {} step {step} frame sequence", + client.client + ); + assert!( + input.detail.is_none_or(|detail| { + input + .event_type + .is_some_and(|event_type| steps[step].contains(&(event_type, detail))) + }), + "{name}: client {} step {step} frame event {:?} detail {:?} is none of {:?}", + client.client, + input.event_type, + input.detail, + steps[step] + ); + frames.push((client.client, input.kind, input.window)); } } frames @@ -1224,8 +1237,6 @@ pub(super) struct Outcome { pub(super) frames: &'static [Frame], pub(super) moved: &'static [Move], pub(super) calls: &'static [Call], - /// Requester replies and X errors: (step, client, first byte). - pub(super) replies: &'static [(usize, u32, u8)], pub(super) grab: Option<&'static [Grab]>, } @@ -1234,7 +1245,6 @@ pub(super) const NOTHING: Outcome = Outcome { frames: &[], moved: &[], calls: &[], - replies: &[], grab: None, }; @@ -1315,7 +1325,8 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run f.drain(ClientId(client)); } take_sent_requests(); - let step_evs: Vec> = step_events(scenario) + let step_drives = step_events(scenario); + let step_evs: Vec> = step_drives .iter() .map(|drives| drives.iter().map(|drive| drive.ev()).collect()) .collect(); @@ -1331,11 +1342,12 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run steps: Vec::new(), }) .collect(); - let mut seen_calls = 0; - let mut call_steps = Vec::new(); - let mut requests = Vec::new(); + let mut step_runs = Vec::with_capacity(scenario.steps.len()); for (index, step) in scenario.steps.iter().enumerate() { take_sent_requests(); + let hook_start = recorder + .as_ref() + .map_or(0, |recorder| recorder.lock().unwrap().len()); match step { Step::Event(event) => drive(&mut f, *event), Step::Request(request, _) => request(&mut f), @@ -1346,53 +1358,36 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run usize::from(matches!(step, Step::Request(..))), "{name}: step {index} sent the expected number of requests" ); - requests.extend( - sent.into_iter() - .map(|(client, major, data)| (index, client, major, data)), - ); + let request = sent.first().copied(); + let mut replies = Vec::new(); for client in &mut clients { let bytes = f.drain(ClientId(client.client)); let sequence = f.state.clients[&client.client] .last_sequence .load(Ordering::Relaxed); - client.steps.push(StepBytes { bytes, sequence }); - } - if let Some(recorder) = &recorder { - let total = recorder.lock().unwrap().len(); - call_steps.extend((seen_calls..total).map(|_| index)); - seen_calls = total; + let capture = capture_step_bytes(bytes, sequence, client.order); + replies.extend(capture.frames.iter().filter_map(|frame| { + matches!(frame.first_byte, 0 | 1).then_some((client.client, frame.first_byte)) + })); + client.steps.push(capture); } + let hooks = recorder.as_ref().map_or_else(Vec::new, |recorder| { + recorder.lock().unwrap()[hook_start..].to_vec() + }); + step_runs.push(StepRun { + events: step_drives[index].clone(), + request, + hooks, + replies, + }); } assert!( client_io::failed_writers(&f.state.clients).is_empty(), "{name}: delivery queued a disconnect" ); - let hooks = recorder - .as_ref() - .map(|recorder| { - recorder - .lock() - .unwrap() - .iter() - .cloned() - .zip(call_steps) - .map(|(call, step)| Hook { step, call }) - .collect() - }) - .unwrap_or_default(); - let replies = clients - .iter() - .flat_map(|client| { - client_frames(client) - .filter(|(_, frame)| matches!(frame[0], 0 | 1)) - .map(move |(step, frame)| (step, client.client, frame[0])) - }) - .collect(); Run { clients, - hooks, - requests, - replies, + steps: step_runs, state: format!("{:?}", (f.state.core_focus.raw, f.state.keys_down)), grab: grab_facts(&f.state), } @@ -1420,6 +1415,28 @@ fn placement(frame: &[u8], kind: Kind, order: ClientByteOrder) -> (u32, (i16, i1 } } +/// Captures and decodes one client's frames once after a scenario step. +fn capture_step_bytes(bytes: Vec, sequence: u16, order: ClientByteOrder) -> StepBytes { + let mut frames = Vec::new(); + let mut start = 0; + for frame in split_frames(&bytes, order) { + let len = frame.len(); + let input = decode(frame, order); + frames.push(FrameRecord { + start, + len, + first_byte: frame[0], + input, + }); + start += len; + } + StepBytes { + bytes, + sequence, + frames, + } +} + /// The frames the denied run writes that the allow-all run does not: a denied /// frame is paired with the allow-all frame of the same kind and window at the /// same position among those, and must equal it byte for byte. An unpaired @@ -1433,15 +1450,19 @@ fn moved_frames(name: &str, allow: &Run, denied: &Run) -> Vec<(u32, Move)> { .find(|c| c.client == got.client) .expect("allow-all stream for the client"); let allowed_frames: Vec<_> = client_frames(allowed) - .filter_map(|(_, frame)| { - decode(frame, allowed.order).map(|(kind, window)| (kind, window, frame)) + .filter_map(|(_, capture, frame)| { + frame + .input + .as_ref() + .map(|input| (input.kind, input.window, frame_bytes(capture, frame))) }) .collect(); let mut seen: Vec<(Kind, u32)> = Vec::new(); - for (_, frame) in client_frames(got) { - let Some((kind, window)) = decode(frame, got.order) else { + for (_, capture, frame) in client_frames(got) { + let Some(input) = &frame.input else { continue; }; + let (kind, window) = (input.kind, input.window); let nth = seen.iter().filter(|s| **s == (kind, window)).count(); seen.push((kind, window)); let same = allowed_frames @@ -1450,12 +1471,12 @@ fn moved_frames(name: &str, allow: &Run, denied: &Run) -> Vec<(u32, Move)> { .nth(nth); if let Some((.., same)) = same { assert_eq!( - frame, *same, + frame_bytes(capture, frame), + *same, "{name}: client {} {kind:?} @{window:#x} bytes under denial", got.client ); } else if !matches!(kind, Kind::Xi1Valuator(_)) { - let (child, event) = placement(frame, kind, got.order); let client = got.client; moved.push(( client, @@ -1463,8 +1484,8 @@ fn moved_frames(name: &str, allow: &Run, denied: &Run) -> Vec<(u32, Move)> { client, kind, window, - child, - event, + child: input.placement.0, + event: input.placement.1, }, )); } @@ -1493,51 +1514,50 @@ fn canonical_call(call: &Call) -> Seen { expected_call(call, 0) } -fn receive_calls(name: &str, scenario: &Scenario, run: &Run) -> Vec<(usize, Seen, Vec)> { - let events = step_events(scenario); - run.hooks +fn receive_calls(name: &str, run: &Run) -> Vec<((usize, usize), Seen, Vec)> { + run.steps .iter() .enumerate() - .filter_map(|(index, hook)| { - let call = &hook.call; - if call.hook != ExtensionHook::Receive { - return None; - } - let EventSubject::Window(window) = call.receive? else { - panic!("{name}: Receive subject {:?}", call.receive); - }; - let names = names_of(call.events.as_deref()?)?; - let event_types = events[hook.step].iter().map(|event| event.ev()).collect(); - Some((index, (call.client.0, names, window.0), event_types)) + .flat_map(|(step, record)| { + let events = &record.events; + record + .hooks + .iter() + .enumerate() + .filter_map(move |(hook_index, call)| { + if call.hook != ExtensionHook::Receive { + return None; + } + let EventSubject::Window(window) = call.receive? else { + panic!("{name}: Receive subject {:?}", call.receive); + }; + let names = names_of(call.events.as_deref()?)?; + let event_types = events.iter().map(|event| event.ev()).collect(); + Some(( + (step, hook_index), + (call.client.0, names, window.0), + event_types, + )) + }) }) .collect() } fn check_hooks(name: &str, mode: &str, scenario: &Scenario, run: &Run) { for (step_index, step) in scenario.steps.iter().enumerate() { - let actual: Vec<_> = run + let step_run = &run.steps[step_index]; + let actual: Vec<_> = step_run .hooks .iter() - .filter(|hook| hook.step == step_index && hook.call.hook != ExtensionHook::Receive) - .map(|hook| &hook.call) + .filter(|hook| hook.hook != ExtensionHook::Receive) .collect(); - let request = run - .requests - .iter() - .find(|(index, _, _, _)| *index == step_index); let expected_dispatch = match step { Step::Event(_) => None, Step::Request(..) => { - let (_, client, major, data) = request.unwrap_or_else(|| { + let (client, major, data) = step_run.request.unwrap_or_else(|| { panic!("{name} [{mode}]: request step {step_index} did not record its request") }); - (*major >= 128).then_some(( - *client, - RequestOpcodes { - major: *major, - minor: if *major < 128 { 0 } else { *data }, - }, - )) + (major >= 128).then_some((client, RequestOpcodes { major, minor: data })) } }; assert_eq!( @@ -1569,7 +1589,7 @@ fn check_hooks(name: &str, mode: &str, scenario: &Scenario, run: &Run) { /// call names the event of the step that made it (`Core(0)` below). fn check_outcome(name: &str, mode: &str, scenario: &Scenario, run: &Run, want: &Outcome) { check_hooks(name, mode, scenario, run); - let got: Vec = receive_calls(name, scenario, run) + let got: Vec = receive_calls(name, run) .iter() .map(|(_, call, evs)| canonical_seen(call, evs)) .collect(); @@ -1586,41 +1606,26 @@ fn check_outcome(name: &str, mode: &str, scenario: &Scenario, run: &Run, want: & "{name} [{mode}]: Receive calls ({:?}) differ\n got: {got:?}\n want: {calls:?}", scenario.order ); - for &(step, client, first_byte) in want.replies { - assert!( - matches!(first_byte, 0 | 1), - "{name} [{mode}]: stated reply frame type is 0 or 1" - ); - assert!( - matches!(scenario.steps.get(step), Some(Step::Request(..))), - "{name} [{mode}]: stated reply is on request step {step}" - ); - let requester = run - .requests - .iter() - .find(|(request_step, _, _, _)| *request_step == step) - .map(|(_, requester, _, _)| *requester); - assert_eq!( - requester, - Some(client), - "{name} [{mode}]: stated reply belongs to that step's requester" - ); - } - let grouped_replies = |replies: &[(usize, u32, u8)]| { - let mut grouped = BTreeMap::<(usize, u32), Vec>::new(); - for &(step, client, first_byte) in replies { - grouped.entry((step, client)).or_default().push(first_byte); - } - grouped - }; - assert_eq!( - grouped_replies(&run.replies), - grouped_replies(want.replies), - "{name} [{mode}]: reply and error frames by step and client" + let unexpected_replies: Vec<_> = run + .steps + .iter() + .enumerate() + .flat_map(|(step, record)| { + record + .replies + .iter() + .map(move |&(client, first_byte)| (step, client, first_byte)) + }) + .collect(); + assert!( + unexpected_replies.is_empty(), + "{name} [{mode}]: unexpected reply or error frames by step and client: {unexpected_replies:?}" ); - let steps: Vec> = step_events(scenario) + let steps: Vec> = run + .steps .iter() - .map(|drives| { + .map(|step| { + let drives = &step.events; drives .iter() .flat_map(|drive| { @@ -1659,8 +1664,8 @@ pub(super) fn assert_swapped_request_calls_fail( ) { let run = play(name, scenario, Some(&[])); check_outcome(name, "allow-all", scenario, &run, &scenario.allow); - let calls = receive_calls(name, scenario, &run); - let call_index = |event| { + let calls = receive_calls(name, &run); + let call_position = |event| { calls .iter() .find(|(_, call, evs)| { @@ -1669,22 +1674,21 @@ pub(super) fn assert_swapped_request_calls_fail( && call.2 == window && evs.as_slice() == request_events }) - .map(|(index, _, _)| *index) + .map(|(position, _, _)| *position) .unwrap_or_else(|| panic!("{name}: request recorded the XI2 event {event}")) }; - let first = call_index(first_event); - let second = call_index(second_event); + let first = call_position(first_event); + let second = call_position(second_event); assert!( first < second, "{name}: request checks events in stated order" ); let mut swapped = run; - let (before_second, second_and_after) = swapped.hooks.split_at_mut(second); - std::mem::swap( - &mut before_second[first].call, - &mut second_and_after[0].call, - ); + assert_eq!(first.0, second.0, "{name}: request checks share one step"); + let hooks = &mut swapped.steps[first.0].hooks; + let (before_second, second_and_after) = hooks.split_at_mut(second.1); + std::mem::swap(&mut before_second[first.1], &mut second_and_after[0]); let rejected = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { check_outcome(name, "allow-all", scenario, &swapped, &scenario.allow); })); @@ -1815,6 +1819,47 @@ mod batch_naming { } } + fn run_with_xi2_frame(evtype: u16, detail: u32) -> Run { + let order = ClientByteOrder::LittleEndian; + let mut bytes = Vec::new(); + yserver_protocol::x11::encode_xi2_device_event( + &mut bytes, + order, + SequenceNumber(0), + XI2_MAJOR_OPCODE, + evtype, + crate::xinput::DEVICEID_MASTER_POINTER, + TIME, + ResourceId(ROOT), + ResourceId(CHILD), + ResourceId(0), + 0, + 0, + 0, + 0, + 0, + detail, + crate::xinput::DEVICEID_MASTER_POINTER, + 0, + None, + ); + Run { + clients: vec![ClientBytes { + client: A, + order, + steps: vec![capture_step_bytes(bytes, 0, order)], + }], + steps: vec![StepRun { + events: Vec::new(), + request: None, + hooks: Vec::new(), + replies: Vec::new(), + }], + state: String::new(), + grab: Vec::new(), + } + } + /// A shorthand names the event of the step that made the call: the same /// recorded call is the shorthand under its own step's event and an /// explicit name under another step's. @@ -1828,17 +1873,38 @@ mod batch_naming { assert_eq!(canonical_seen(&recorded, &[4]), canonical_call(&explicit)); } + /// A ButtonPress must match its own detail even when a Motion in the same + /// request step legitimately carries detail zero. + #[test] + fn multi_event_frame_detail_is_checked_against_its_own_event_type() { + let bad_press = run_with_xi2_frame(4, 0); + let panic = std::panic::catch_unwind(|| { + delivered("multi-event detail", &bad_press, &[vec![(4, 1), (6, 0)]]) + }) + .expect_err("ButtonPress detail 0 must not borrow Motion detail 0"); + let message = panic + .downcast_ref::() + .map(String::as_str) + .or_else(|| panic.downcast_ref::<&str>().copied()) + .unwrap_or_default(); + assert!( + message.contains("frame event Some(4) detail Some(0)"), + "ButtonPress detail mismatch must be the rejected condition, got {message:?}" + ); + } + /// A two-press request step cannot make two explicit XI2 checks match two /// shorthand expectations just because both presses have the same type. #[test] fn two_press_request_rejects_shorthand_expectations() { - const PRESS: Step = Step::Event(Drive::Pointer { + const PRESS_DRIVE: Drive = Drive::Pointer { origin: InputOrigin::XTest(crate::xinput::DEVICEID_MASTER_POINTER), kind: PointerEventKind::ButtonPress, button: 1, to: POINTER, delta: (0, 0), - }); + }; + const PRESS: Step = Step::Event(PRESS_DRIVE); const REQUEST_EVENTS: &[Step] = &[PRESS, PRESS]; const REQUEST_STEP: &[Step] = &[Step::Request(no_request, REQUEST_EVENTS)]; const SHORTHAND: &[Call] = &[(A, CallKind::Xi2, CHILD), (A, CallKind::Xi2, CHILD)]; @@ -1854,18 +1920,12 @@ mod batch_naming { }; let run = Run { clients: Vec::new(), - hooks: vec![ - Hook { - step: 0, - call: receive_check(4), - }, - Hook { - step: 0, - call: receive_check(4), - }, - ], - requests: vec![(0, A, 35, 0)], - replies: Vec::new(), + steps: vec![StepRun { + events: vec![PRESS_DRIVE, PRESS_DRIVE], + request: Some((A, 35, 0)), + hooks: vec![receive_check(4), receive_check(4)], + replies: Vec::new(), + }], state: String::new(), grab: Vec::new(), }; @@ -1894,18 +1954,42 @@ mod batch_naming { /// the runner has no `Kind` for fails instead of being skipped. #[test] fn xi1_releases_decode_and_unknown_xi1_frames_fail() { - let frame = |offset: u8| { - let mut frame = [0_u8; 32]; - frame[0] = crate::server::XI_FIRST_EVENT + offset; - frame[1] = 1; - frame[12..16].copy_from_slice(&CHILD.to_le_bytes()); - frame[31] = 4; - frame - }; let order = ClientByteOrder::LittleEndian; - let release = frame(crate::xinput::XI_DEVICE_BUTTON_RELEASE_OFFSET); - assert_eq!(decode(&release, order), Some((Kind::Xi1(4), CHILD))); - let focus = frame(crate::xinput::XI_DEVICE_FOCUS_IN_OFFSET); + let mut release = Vec::new(); + crate::xinput::encode_xi1_device_input_event( + &mut release, + order, + crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_RELEASE_OFFSET, + 1, + SequenceNumber(0), + TIME, + ROOT, + CHILD, + 0, + 0, + 0, + 0, + 0, + 0, + 4, + ); + let decoded = decode(&release, order).expect("button release is an input frame"); + assert_eq!( + (decoded.kind, decoded.window, decoded.event_type), + (Kind::Xi1(4), CHILD, Some(5)) + ); + let mut focus = Vec::new(); + crate::xinput::encode_xi1_device_focus_event( + &mut focus, + order, + crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_FOCUS_IN_OFFSET, + 0, + SequenceNumber(0), + TIME, + CHILD, + 0, + 4, + ); assert!(std::panic::catch_unwind(|| decode(&focus, order)).is_err()); } } diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs index dcf33f2f9..f5e2b6266 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -64,8 +64,23 @@ fn setup_k5c_grab(f: &mut NotifyFixture) { grab_slave_keyboard(f, A, FOCUS); } +/// Only A selects core on CHILD and FOCUS, so denial exhausts the bounded walk. +fn setup_k6b(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, CHILD, KEY_PRESS); + select_core(f, A, FOCUS, KEY_PRESS); +} + // Grabbed rows: A is the grab owner, B the foreign selector. +/// A grabs with owner_events on the root and selects core on CHILD and FOCUS. +fn setup_k7(f: &mut NotifyFixture) { + tree(f); + grab_keyboard(f, A, ROOT, true); + select_core(f, A, CHILD, KEY_PRESS); + select_core(f, A, FOCUS, KEY_PRESS); +} + /// A grabs with owner_events on the root and selects core on CHILD; B selects /// core on CHILD too. With A denied at CHILD, B's allowed copy is the foreign /// rejection and the grab window gets the key (k8); with B denied, A qualifies @@ -77,6 +92,15 @@ fn setup_k8(f: &mut NotifyFixture) { select_core(f, B, CHILD, KEY_PRESS); } +/// B selects core on CHILD and is denied; A's core selection on FOCUS remains +/// eligible and does not fall back to the grab window. +fn setup_k9(f: &mut NotifyFixture) { + tree(f); + grab_keyboard(f, A, ROOT, true); + select_core(f, B, CHILD, KEY_PRESS); + select_core(f, A, FOCUS, KEY_PRESS); +} + /// A grabs with owner_events on the root. A, B and SEND_CLIENT select core /// press on CHILD. A is denied there; B and SEND_CLIENT are allowed. Every /// foreign selector is asked, and A falls back to the root grab window. @@ -116,6 +140,22 @@ fn setup_k13_natural(f: &mut NotifyFixture) { select_core(f, B, FOCUS, KEY_RELEASE); } +/// A and B select master RawKeyPress on ROOT; SEND_CLIENT selects the slave +/// raw form there. +fn setup_k13_raw(f: &mut NotifyFixture) { + tree(f); + for client in [A, B] { + select_xi2(f, client, ROOT, DEVICEID_MASTER_KEYBOARD, XI_RAW_KEY_PRESS); + } + select_xi2( + f, + SEND_CLIENT, + ROOT, + DEVICEID_XTEST_KEYBOARD, + XI_RAW_KEY_PRESS, + ); +} + /// A holds the master keyboard's XI2 grab on CHILD with owner_events, the grab /// mask selects RawKeyPress, and focus is PointerRoot. A selects RawKeyPress on /// the root for the master keyboard, so the natural walk reaches it. @@ -123,6 +163,10 @@ fn setup_k14(f: &mut NotifyFixture) { setup_k14_with_mask(f, XI_KEY_PRESS | XI_RAW_KEY_PRESS); } +fn setup_k14_without_raw_bit(f: &mut NotifyFixture) { + setup_k14_with_mask(f, XI_KEY_PRESS); +} + fn setup_k14_with_mask(f: &mut NotifyFixture, mask: u32) { tree(f); set_focus_pointer_root(f); @@ -133,11 +177,21 @@ fn setup_k14_with_mask(f: &mut NotifyFixture, mask: u32) { const XI1_KEY_RELEASE_CALL: CallKind = CallKind::Batch(&[Named::Xi1( crate::xinput::XI_DEVICE_KEY_RELEASE_OFFSET as u16, )]); +const XI1_KEY_PRESS_CALL: CallKind = + CallKind::Batch(&[Named::Xi1(crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET as u16)]); fn xi1_key_class(offset: u8) -> u32 { (u32::from(DEVICEID_XTEST_KEYBOARD) << 8) | u32::from(crate::server::XI_FIRST_EVENT + offset) } +/// A selects the slave key-press class on CHILD; B selects it on FOCUS. +fn setup_k16(f: &mut NotifyFixture) { + tree(f); + let class = xi1_key_class(crate::xinput::XI_DEVICE_KEY_PRESS_OFFSET); + select_xi1(f, A, CHILD, &[class]); + select_xi1(f, B, FOCUS, &[class]); +} + /// The same for `DeviceKeyRelease`, with A on detectable repeat. fn setup_k17(f: &mut NotifyFixture) { tree(f); @@ -240,6 +294,34 @@ const K8_SCENARIO: Scenario = Scenario { order: CallOrder::PerClient, }; +const K7_SCENARIO: Scenario = Scenario { + setup: setup_k7, + steps: &[PRESS], + allow: Outcome { + grab: Some(A_GRABS_ROOT), + ..A_CORE_CHILD + }, + order: CallOrder::Total, +}; + +const K13_RAW_SCENARIO: Scenario = Scenario { + setup: setup_k13_raw, + steps: &[XTEST_RAW_PRESS], + allow: frames_and_calls( + &[ + (A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + (B, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + (SEND_CLIENT, Kind::Raw(DEVICEID_XTEST_KEYBOARD), ROOT), + ], + &[ + (SEND_CLIENT, CallKind::Raw, ROOT), + (A, CallKind::Raw, ROOT), + (B, CallKind::Raw, ROOT), + ], + ), + order: CallOrder::PerClient, +}; + const K10_SCENARIO: Scenario = Scenario { setup: setup_k10, steps: &[SYNTH_RELEASE], @@ -348,6 +430,29 @@ const ROWS: &[InputRow] = &[ deny: &[(A, CallKind::Xi2, CHILD)], denied: NOTHING, }, + InputRow { + name: "k6_only_selector_denied_lands_on_focus_and_writes_nothing", + scenario: &Scenario { + setup: setup_k6b, + steps: &[PRESS], + allow: A_CORE_CHILD, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + denied: calls_only(&[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)]), + }, + InputRow { + name: "k7_denied_owner_copy_continues_the_natural_walk", + scenario: &K7_SCENARIO, + deny: &[(A, CallKind::Core, CHILD)], + denied: with_moved( + frames_and_calls( + &[(A, Kind::Core, FOCUS)], + &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + ), + &[moved(A, Kind::Core, FOCUS, CHILD, (20, 20))], + ), + }, // A and B both select on CHILD and B is denied. A qualifies first, so the // walk stops at CHILD and no check is made for B. InputRow { @@ -356,6 +461,29 @@ const ROWS: &[InputRow] = &[ deny: &[(B, CallKind::Core, CHILD)], denied: K8_SCENARIO.allow, }, + InputRow { + name: "k9_denied_foreign_selector_does_not_reject", + scenario: &Scenario { + setup: setup_k9, + steps: &[PRESS], + allow: with_grab( + frames_and_calls( + &[(A, Kind::Core, ROOT)], + &[(B, CallKind::Core, CHILD), (A, CallKind::Core, ROOT)], + ), + A_GRABS_ROOT, + ), + order: CallOrder::Total, + }, + deny: &[(B, CallKind::Core, CHILD)], + denied: with_moved( + frames_and_calls( + &[(A, Kind::Core, FOCUS)], + &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + ), + &[moved(A, Kind::Core, FOCUS, CHILD, (20, 20))], + ), + }, InputRow { name: "k9b_every_foreign_selector_is_checked", scenario: &Scenario { @@ -463,6 +591,59 @@ const ROWS: &[InputRow] = &[ ], ), }, + InputRow { + name: "k13_denied_raw_root_copy_drops_only_that_copy", + scenario: &K13_RAW_SCENARIO, + deny: &[(A, CallKind::Raw, ROOT)], + denied: Outcome { + frames: &[ + (B, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT), + (SEND_CLIENT, Kind::Raw(DEVICEID_XTEST_KEYBOARD), ROOT), + ], + calls: K13_RAW_SCENARIO.allow.calls, + ..NOTHING + }, + }, + InputRow { + name: "k14b_denied_raw_owner_without_raw_grab_bit_gets_nothing", + scenario: &Scenario { + setup: setup_k14_without_raw_bit, + steps: &[XTEST_RAW_PRESS], + allow: K14_ALLOW, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Raw, ROOT)], + denied: calls_only(K14_ALLOW.calls), + }, + InputRow { + name: "k16_xi1_focused_key_denial_advances_the_focus_walk", + scenario: &Scenario { + setup: setup_k16, + steps: &[XTEST_PRESS], + allow: frames_and_calls( + &[(A, Kind::Xi1Key(DEVICEID_XTEST_KEYBOARD), CHILD)], + &[(A, XI1_KEY_PRESS_CALL, CHILD)], + ), + order: CallOrder::Total, + }, + deny: &[(A, XI1_KEY_PRESS_CALL, CHILD)], + denied: with_moved( + frames_and_calls( + &[(B, Kind::Xi1Key(DEVICEID_XTEST_KEYBOARD), FOCUS)], + &[ + (A, XI1_KEY_PRESS_CALL, CHILD), + (B, XI1_KEY_PRESS_CALL, FOCUS), + ], + ), + &[moved( + B, + Kind::Xi1Key(DEVICEID_XTEST_KEYBOARD), + FOCUS, + CHILD, + (20, 20), + )], + ), + }, // A synthetic repeat release to a detectable-repeat client gets no copy but // stops the walk: nothing is written, X is not asked, Y is not reached. // Mutation: X is asked (a call) or the walk goes past it (Y gets a frame). diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index 8919a38fd..29b096f55 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -116,7 +116,6 @@ const CORE_GRAB_POINTER: u8 = 26; const CORE_GRAB_BUTTON: u8 = 28; const XI_PASSIVE_GRAB_DEVICE: u8 = 54; const XI_ALLOW_EVENTS: u8 = 53; -const XI_GRAB_DEVICE_XI1: u8 = 13; /// `GrabPointer` by `owner` on `window`, asynchronous, with the core event mask. fn grab_pointer(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: bool, mask: u32) { @@ -174,16 +173,7 @@ fn xi_passive_grab_device( /// The XI1 `GrabDevice` of the slave pointer by `owner` on `window`. fn xi1_grab_device(f: &mut NotifyFixture, owner: u32, window: u32, owner_events: bool) { - let mut body = Vec::with_capacity(16); - body.extend_from_slice(&window.to_le_bytes()); - body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime - body.extend_from_slice(&0_u16.to_le_bytes()); // no event classes - body.extend_from_slice(&[1, 1, u8::from(owner_events)]); // async modes - body.push(DEVICEID_XTEST_POINTER as u8); - body.extend_from_slice(&[0, 0]); - let bytes = send_with_reply(f, owner, XI_MAJOR, XI_GRAB_DEVICE_XI1, &body); - let reply = &bytes[bytes.len() - 32..]; - assert_eq!((reply[0], reply[8]), (1, 0), "GrabDevice replies Success"); + send_xi1_grab_device(f, owner, window, DEVICEID_XTEST_POINTER, owner_events, 1, 1); } /// The requests of the p14 and p28 step lists: `XIAllowEvents` of the master @@ -219,12 +209,30 @@ fn allow_slave(f: &mut NotifyFixture) { /// live target is C. const OUTSIDE_C: (i16, i16) = (105, 105); +fn setup_p3(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + select_xi2(f, A, FOCUS, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); +} + +fn setup_p4(f: &mut NotifyFixture) { + tree(f); + park_pointer(f); + select_xi2(f, B, CHILD, XI_ALL_DEVICES, XI_MOTION); + select_xi2(f, A, FOCUS, DEVICEID_MASTER_POINTER, XI_MOTION); +} + fn setup_p4b(f: &mut NotifyFixture) { tree(f); park_pointer_at(f, OUTSIDE_C); select_xi2(f, B, CHILD, DEVICEID_XTEST_POINTER, XI_MOTION); } +fn setup_p4c(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, B, CHILD, XI_ALL_DEVICES, XI_BUTTON_PRESS); +} + fn setup_p5(f: &mut NotifyFixture) { tree(f); select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); @@ -283,6 +291,13 @@ fn setup_p11(f: &mut NotifyFixture) { grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); } +/// A selects the master XI2 and core press on C; the denied XI2 leg leaves its +/// core leg eligible at the same window. +fn setup_p11_own_protocols(f: &mut NotifyFixture) { + setup_p5(f); + grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); +} + /// B selects the core press on C; A grabs the pointer on G with `mask` /// (without owner_events). With a mask lacking ButtonPress there is no frame in /// any mode, but the check still comes first, so the trace has the call at G. @@ -292,6 +307,15 @@ fn setup_p12(f: &mut NotifyFixture) { grab_pointer(f, A, ROOT, false, MASK); } +/// A and B select the master XI2 press on C; A's owner-events grab window is +/// parameterized so the fallback can share or miss the natural memo key. +fn setup_p13(f: &mut NotifyFixture) { + tree(f); + select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + xi_grab_device(f, A, DEVICEID_MASTER_POINTER, GRAB, true, XI_BUTTON_PRESS); +} + /// A sync `XIPassiveGrabDevice` on the master, to be activated from an attached /// slave origin. fn setup_p14_xi2_master_from_slave(f: &mut NotifyFixture) { @@ -371,6 +395,12 @@ fn setup_p18(f: &mut NotifyFixture) { select_xi1(f, B, CHILD, &[xi1_slave_press()]); } +fn setup_p19(f: &mut NotifyFixture) { + tree(f); + select_xi1(f, A, CHILD, &[xi1_slave_press()]); + select_xi1(f, B, FOCUS, &[xi1_slave_press()]); +} + /// Two XI1 press selectors on C; B also selected the button grab class. fn setup_p20(f: &mut NotifyFixture) { tree(f); @@ -408,6 +438,7 @@ fn setup_scroll_stop_two_forms(f: &mut NotifyFixture) { tree(f); register_physical_pointer(f); select_xi2(f, A, CHILD, XI_ALL_DEVICES, XI_MOTION); + select_xi2(f, B, FOCUS, DEVICEID_MASTER_POINTER, XI_MOTION); } fn setup_p25(f: &mut NotifyFixture) { @@ -593,8 +624,6 @@ const P26_FALLS_TO_ROOT: Outcome = Outcome { (A, XI1_PRESS_CALL, ROOT), ], grab: None, - - ..NOTHING }; /// The allow-all outcomes several scenarios share, and the denied outcome that @@ -603,6 +632,17 @@ const A_XI2_AT_CHILD: Outcome = frames_and_calls( &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], &[(A, CallKind::Xi2, CHILD)], ); +const B_XI2_AT_CHILD: Outcome = frames_and_calls( + &[(B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + &[(B, CallKind::Xi2, CHILD)], +); +const B_BOTH_FORMS_AT_CHILD: Outcome = frames_and_calls( + &[ + (B, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD), + (B, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD), + ], + &[(B, CallKind::Xi2, CHILD)], +); /// A gets the slave motion and its valuator continuation at C from one check. const A_XI1_MOTION_AT_CHILD: Outcome = frames_and_calls( &[ @@ -677,6 +717,65 @@ const P27_THAWED_XI1_FILTER: Scenario = Scenario { // ---- rows ---------------------------------------------------------------- const ROWS: &[InputRow] = &[ + InputRow { + name: "p3_xi2_walk_skips_a_denied_window", + scenario: &Scenario { + setup: setup_p3, + steps: &[press(XTEST_MASTER)], + allow: B_XI2_AT_CHILD, + order: CallOrder::Total, + }, + deny: &[(B, CallKind::Xi2, CHILD)], + denied: with_grab( + with_moved( + frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], + &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], + ), + &[moved( + A, + Kind::Xi2(DEVICEID_MASTER_POINTER), + FOCUS, + CHILD, + P_EVENT, + )], + ), + &[implicit(A, FOCUS, true)], + ), + }, + InputRow { + name: "p4_slave_and_master_forms_share_one_check", + scenario: &Scenario { + setup: setup_p4, + steps: &[motion(XTEST_SLAVE)], + allow: B_BOTH_FORMS_AT_CHILD, + order: CallOrder::Total, + }, + deny: &[(B, CallKind::Xi2, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS)], + moved: &[moved( + A, + Kind::Xi2(DEVICEID_MASTER_POINTER), + FOCUS, + CHILD, + MOTION_EVENT_AT_P, + )], + calls: &[(B, CallKind::Xi2, CHILD), (A, CallKind::Xi2, FOCUS)], + grab: None, + }, + }, + InputRow { + name: "p4c_slave_press_and_master_forms_share_one_check", + scenario: &Scenario { + setup: setup_p4c, + steps: &[press(XTEST_SLAVE)], + allow: B_BOTH_FORMS_AT_CHILD, + order: CallOrder::Total, + }, + deny: &[(B, CallKind::Xi2, CHILD)], + denied: with_grab(calls_only(&[(B, CallKind::Xi2, CHILD)]), &[]), + }, // A slave motion moves the sprite from P into C. B selects the slave form on C // only, so the slave form (routed from P) has no recipient and B gets nothing, // in every mode. The route from the live target C writes no slave copy, so it @@ -780,7 +879,6 @@ const ROWS: &[InputRow] = &[ (A, CallKind::Core, CHILD), ], grab: None, - ..NOTHING }, }, // Guard: a master form that is not written asks nothing, so denying B's copy @@ -837,10 +935,35 @@ const ROWS: &[InputRow] = &[ (A, CallKind::Core, ROOT), ], grab: None, - - ..NOTHING }, }, + InputRow { + name: "p11_owner_qualifies_in_a_later_protocol_own_protocols", + scenario: &Scenario { + setup: setup_p11_own_protocols, + steps: &[press(XTEST_MASTER)], + allow: A_XI2_AT_CHILD, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Core, CHILD)], + moved: &[moved(A, Kind::Core, CHILD, 0, C_EVENT)], + calls: &[(A, CallKind::Xi2, CHILD), (A, CallKind::Core, CHILD)], + grab: None, + }, + }, + InputRow { + name: "p12_grab_window_denial_counts_as_delivered", + scenario: &Scenario { + setup: setup_p12::, + steps: &[press(XTEST_MASTER)], + allow: frames_and_calls(&[(A, Kind::Core, ROOT)], &[(A, CallKind::Core, ROOT)]), + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, ROOT)], + denied: ASKED_A_CORE_ROOT, + }, // Mutation: the check moves behind the grab mask (no call here). InputRow { name: "p12_grab_window_denial_counts_as_delivered_mask", @@ -853,6 +976,21 @@ const ROWS: &[InputRow] = &[ deny: &[(A, CallKind::Core, ROOT)], denied: ASKED_A_CORE_ROOT, }, + InputRow { + name: "p13_xi2_owner_events_fallback_is_fresh_same_window", + scenario: &Scenario { + setup: setup_p13::, + steps: &[press(XTEST_MASTER)], + allow: A_XI2_AT_CHILD, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: calls_only(&[ + (A, CallKind::Xi2, CHILD), + (B, CallKind::Xi2, CHILD), + (A, CallKind::Xi2, CHILD), + ]), + }, InputRow { name: "p14_denied_xi2_activating_press_still_freezes_from_a_slave_origin", scenario: &Scenario { @@ -1039,6 +1177,38 @@ const ROWS: &[InputRow] = &[ &[xi1_implicit(B, CHILD)], ), }, + InputRow { + name: "p19_denied_xi1_press_continues", + scenario: &Scenario { + setup: setup_p19, + steps: &[press(XTEST_SLAVE)], + allow: with_grab( + frames_and_calls( + &[(A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD)], + &[(A, XI1_PRESS_CALL, CHILD)], + ), + &[xi1_implicit(A, CHILD)], + ), + order: CallOrder::Total, + }, + deny: &[(A, XI1_PRESS_CALL, CHILD)], + denied: with_grab( + with_moved( + frames_and_calls( + &[(B, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], + &[(A, XI1_PRESS_CALL, CHILD), (B, XI1_PRESS_CALL, FOCUS)], + ), + &[moved( + B, + Kind::Xi1(DEVICEID_XTEST_POINTER), + FOCUS, + CHILD, + P_EVENT, + )], + ), + &[xi1_implicit(B, FOCUS)], + ), + }, // Two XI1 press selectors on C, the one that also selected the button grab // class is denied: the other owns the XI1 implicit grab (allow-all: the grab // class holder). @@ -1137,12 +1307,10 @@ const ROWS: &[InputRow] = &[ (B, SCROLL_MOTION_CALL, FOCUS), ], grab: None, - - ..NOTHING }, }, - // A client with both device forms on one window is asked once for both forms' - // four events. + // A client with both device forms on C is asked once for all four stop events. + // B's XI2 selector on P makes a resumed walk observable under denial. // Mutation: one check per form (two calls here). InputRow { name: "p23_scroll_stop_is_not_rerouted_two_forms_denied", @@ -1190,8 +1358,6 @@ const ROWS: &[InputRow] = &[ )], calls: &[(A, XI1_MOTION_CALL, CHILD), (B, XI1_MOTION_CALL, FOCUS)], grab: None, - - ..NOTHING }, }, // The motion event and its valuator continuation are decided by one call with @@ -1297,8 +1463,6 @@ const ROWS: &[InputRow] = &[ )], calls: &[(B, XI1_PRESS_CALL, CHILD), (A, XI1_PRESS_CALL, FOCUS)], grab: None, - - ..NOTHING }, }, InputRow { diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs index aa9cd6e83..5f5ca921a 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs @@ -21,11 +21,14 @@ const XTEST_SLAVE_POINTER: InputOrigin = InputOrigin::XTest(DEVICEID_XTEST_POINT const XTEST_MASTER_KEYBOARD: InputOrigin = InputOrigin::XTest(DEVICEID_MASTER_KEYBOARD); const XTEST_SLAVE_KEYBOARD: InputOrigin = InputOrigin::XTest(DEVICEID_XTEST_KEYBOARD); const CORE_BUTTON_PRESS: u32 = 1 << 2; +const CORE_MOTION: u32 = 1 << 6; const XI_BUTTON_PRESS: u32 = 1 << 4; const XI_RAW_KEY_PRESS: u32 = 1 << 13; +const MOTION_TO: (i16, i16) = (125, 125); const FOCUS_EVENT: (i16, i16) = (20, 20); const CORE_BUTTON_PRESS_CALL: CallKind = CallKind::Core; +const CORE_MOTION_CALL: CallKind = CallKind::Core; const CORE_KEY_PRESS_CALL: CallKind = CallKind::Core; const XI1_BUTTON_PRESS_CALL: CallKind = CallKind::Batch(&[Named::Xi1(XI_DEVICE_BUTTON_PRESS_OFFSET as u16)]); @@ -52,6 +55,10 @@ const fn button_press(origin: InputOrigin) -> Step { pointer_event(origin, PointerEventKind::ButtonPress, POINTER) } +const fn motion(origin: InputOrigin) -> Step { + pointer_event(origin, PointerEventKind::MotionNotify, MOTION_TO) +} + const fn key_press(origin: InputOrigin) -> Step { Step::Event(Drive::Entry { origin, @@ -117,6 +124,12 @@ fn setup_r1_equal_key_xi1_queue(f: &mut NotifyFixture) { xi2_passive_button_grab(f, PHYSICAL_DEVICE); } +fn setup_r6_queued_motion(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, CHILD, CORE_MOTION); + grab_core_button(f, A, ROOT, true, 0); +} + fn setup_r7_queued_key(f: &mut NotifyFixture) { tree(f); select_core(f, A, CHILD, KEY_PRESS); @@ -161,6 +174,14 @@ const XI1_POINTER_PRESS_STORED: Grab = Grab::Freeze { }), }; +const PASSIVE_CORE_POINTER: Grab = Grab::Pointer(PointerGrab { + owner: A, + window: ROOT, + implicit: false, + passive: true, + via_xi2: false, +}); + const R1_XTEST_PASSIVE_GRAB: Grab = Grab::SlavePointer { device: DEVICEID_XTEST_POINTER, grab: PointerGrab { @@ -292,6 +313,26 @@ const R7_THAW: Scenario = Scenario { order: CallOrder::Total, }; +const R6_THAW: Scenario = Scenario { + setup: setup_r6_queued_motion, + steps: &[ + button_press(XTEST_MASTER_POINTER), + motion(XTEST_MASTER_POINTER), + Step::Request(allow_core_events::<0>, &[]), + ], + allow: with_grab( + frames_and_calls( + &[(A, Kind::Core, ROOT), (A, Kind::Core, CHILD)], + &[ + (A, CORE_BUTTON_PRESS_CALL, ROOT), + (A, CORE_MOTION_CALL, CHILD), + ], + ), + &[PASSIVE_CORE_POINTER], + ), + order: CallOrder::Total, +}; + const R8_REPLAY: Scenario = Scenario { setup: setup_r8_xi1_replay, steps: &[ @@ -422,6 +463,25 @@ const ROWS: &[InputRow] = &[ &[], ), }, + InputRow { + name: "r6_thawed_queued_motion_is_checked_at_its_write", + scenario: &R6_THAW, + deny: &[(A, CallKind::Batch(&[Named::Core(6)]), CHILD)], + denied: with_grab( + with_moved( + frames_and_calls( + &[(A, Kind::Core, ROOT), (A, Kind::Core, ROOT)], + &[ + (A, CORE_BUTTON_PRESS_CALL, ROOT), + (A, CORE_MOTION_CALL, CHILD), + (A, CORE_MOTION_CALL, ROOT), + ], + ), + &[moved(A, Kind::Core, ROOT, FOCUS, MOTION_TO)], + ), + &[PASSIVE_CORE_POINTER], + ), + }, // Mutation: skip Receive during `playing_sync_events`. Both the queued // RawKey root copy and HostKeyTransition natural copy are fresh writes; // Xorg 21.1.24 routes each on thaw at `dix/events.c:1320-1371`. @@ -447,6 +507,23 @@ const ROWS: &[InputRow] = &[ &[A_ROOT_KEYBOARD_GRAB], ), }, + InputRow { + name: "r7_thawed_queued_key_denied_at_child_and_root_stays_grabbed", + scenario: &R7_THAW, + deny: &[ + (B, RAW_KEY_PRESS_CALL, ROOT), + (A, CORE_KEY_PRESS_CALL, CHILD), + (A, CORE_KEY_PRESS_CALL, ROOT), + ], + denied: with_grab( + calls_only(&[ + (B, CallKind::Batch(&[Named::Raw(13)]), ROOT), + (A, CallKind::Batch(&[Named::Core(2)]), CHILD), + (A, CallKind::Batch(&[Named::Core(2)]), ROOT), + ]), + &[A_ROOT_KEYBOARD_GRAB], + ), + }, InputRow { name: "r8_denied_xi1_activating_write_rechecks_the_replayed_selector", scenario: &R8_REPLAY, From f82fcd19bcb36db997c76803befa9006f69075bf Mon Sep 17 00:00:00 2001 From: Ariel Santangelo Date: Thu, 3 Dec 2026 21:05:39 -0300 Subject: [PATCH 72/72] test(access): final review round, pin the decisions only pruned rows held Restore the focused suppressed-release stops (k5), the pointer owner-events continuations after a denied owner or foreign core copy (p8, p10) and the XI1 replay grab-class competition (p28). R1, R6 and R7 check the frozen boundary before the thaw: queue contents and order, freeze state and no early copies or checks. R5 selects the master XI2 form at the focus, so a lost XI2 form in the replay handoff fails in the suite. Each of these fails under a one-line mutation of the decision it pins. Co-Authored-By: Claude Opus 5.5 Implemented-By: codex (gpt-6-luna max) --- .../tests/access_input_support.rs | 117 ++++++++++++-- .../process_request/tests/access_key_input.rs | 44 +++++ .../tests/access_pointer_input.rs | 153 ++++++++++++++++++ .../tests/access_replay_input.rs | 142 +++++++++++++++- 4 files changed, 438 insertions(+), 18 deletions(-) diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs index 84c2ab8ff..36c9a984d 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -1046,6 +1046,7 @@ struct StepRun { request: Option<(u32, u8, u8)>, hooks: Vec, replies: Vec<(u32, u8)>, + grab: Vec, } struct Run { @@ -1190,6 +1191,9 @@ pub(super) enum Step { /// writes the stored ones, not necessarily the previous step's); none means /// the previous step's event. Request(fn(&mut NotifyFixture), &'static [Step]), + /// Compare cumulative output, Receive calls and grab/freeze/queue facts at + /// this boundary in the scenario, before a later thaw or replay. + Checkpoint(Outcome), } /// How a scenario's Receive trace is compared: in total order, or in order per @@ -1295,7 +1299,7 @@ pub(super) struct InputRow { fn step_events(scenario: &Scenario) -> Vec> { let event = |step: &Step| match step { Step::Event(drive) => Some(*drive), - Step::Request(..) => None, + Step::Request(..) | Step::Checkpoint(..) => None, }; let mut current = scenario.steps.iter().find_map(event); scenario @@ -1306,6 +1310,7 @@ fn step_events(scenario: &Scenario) -> Vec> { current = Some(*drive); vec![*drive] } + Step::Checkpoint(..) => Vec::new(), Step::Request(_, []) => { vec![current.expect("a scenario drives at least one event")] } @@ -1317,7 +1322,7 @@ fn step_events(scenario: &Scenario) -> Vec> { /// Runs a scenario from a fresh fixture. `policy` is `None` for no policy, or /// the calls to deny under a recording policy. Frames and Receive calls are /// attributed to the step that made them. -fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run { +fn play(name: &str, mode: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run { let mut f = NotifyFixture::new(); (scenario.setup)(&mut f); f.state.clients.get_mut(&A).expect("client A").byte_order = ClientByteOrder::BigEndian; @@ -1351,6 +1356,7 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run match step { Step::Event(event) => drive(&mut f, *event), Step::Request(request, _) => request(&mut f), + Step::Checkpoint(_) => {} } let sent = take_sent_requests(); assert_eq!( @@ -1379,7 +1385,20 @@ fn play(name: &str, scenario: &Scenario, policy: Option<&'static [Call]>) -> Run request, hooks, replies, + grab: grab_facts(&f.state), }); + if let Step::Checkpoint(want) = step { + check_checkpoint( + name, + mode, + scenario, + &clients, + &step_runs, + index, + want, + mode != "no-policy", + ); + } } assert!( client_io::failed_writers(&f.state.clients).is_empty(), @@ -1514,8 +1533,8 @@ fn canonical_call(call: &Call) -> Seen { expected_call(call, 0) } -fn receive_calls(name: &str, run: &Run) -> Vec<((usize, usize), Seen, Vec)> { - run.steps +fn receive_calls(name: &str, steps: &[StepRun]) -> Vec<((usize, usize), Seen, Vec)> { + steps .iter() .enumerate() .flat_map(|(step, record)| { @@ -1553,6 +1572,7 @@ fn check_hooks(name: &str, mode: &str, scenario: &Scenario, run: &Run) { .collect(); let expected_dispatch = match step { Step::Event(_) => None, + Step::Checkpoint(..) => None, Step::Request(..) => { let (client, major, data) = step_run.request.unwrap_or_else(|| { panic!("{name} [{mode}]: request step {step_index} did not record its request") @@ -1589,7 +1609,7 @@ fn check_hooks(name: &str, mode: &str, scenario: &Scenario, run: &Run) { /// call names the event of the step that made it (`Core(0)` below). fn check_outcome(name: &str, mode: &str, scenario: &Scenario, run: &Run, want: &Outcome) { check_hooks(name, mode, scenario, run); - let got: Vec = receive_calls(name, run) + let got: Vec = receive_calls(name, &run.steps) .iter() .map(|(_, call, evs)| canonical_seen(call, evs)) .collect(); @@ -1651,6 +1671,81 @@ fn check_outcome(name: &str, mode: &str, scenario: &Scenario, run: &Run, want: & ); } +fn check_checkpoint( + name: &str, + mode: &str, + scenario: &Scenario, + clients: &[ClientBytes], + steps: &[StepRun], + boundary: usize, + want: &Outcome, + check_calls: bool, +) { + let mut got_frames = Vec::new(); + for client in clients { + for (step, _, frame) in client_frames(client) { + if step <= boundary + && let Some(input) = &frame.input + { + got_frames.push((client.client, input.kind, input.window)); + } + } + } + assert_eq!( + grouped( + got_frames + .into_iter() + .map(|(client, kind, window)| (client, (kind, window))) + ), + grouped( + want.frames + .iter() + .map(|&(client, kind, window)| (client, (kind, window))) + ), + "{name} [{mode}]: checkpoint after step {boundary} frames per client" + ); + + if check_calls { + let got_calls: Vec = receive_calls(name, steps) + .into_iter() + .filter(|((step, _), _, _)| *step <= boundary) + .map(|(_, call, events)| canonical_seen(&call, &events)) + .collect(); + let expected_calls: Vec = want.calls.iter().map(canonical_call).collect(); + let calls_match = match scenario.order { + CallOrder::Total => got_calls == expected_calls, + CallOrder::PerClient => { + grouped( + got_calls + .iter() + .map(|(client, names, window)| (*client, (names.clone(), *window))), + ) == grouped( + expected_calls + .iter() + .map(|(client, names, window)| (*client, (names.clone(), *window))), + ) + } + }; + assert!( + calls_match, + "{name} [{mode}]: checkpoint after step {boundary} Receive calls ({:?}) differ\n got: {got_calls:?}\n want: {expected_calls:?}", + scenario.order + ); + } + + let expected_grab = want.grab.unwrap_or_else(|| { + panic!("{name}: checkpoint after step {boundary} must state grab and queue facts") + }); + assert_eq!( + steps[boundary].grab, expected_grab, + "{name} [{mode}]: checkpoint after step {boundary} grab, freeze and queue facts" + ); + assert!( + want.moved.is_empty(), + "{name}: a checkpoint has no moved frames" + ); +} + /// Exercises the real runner and verifies its stated outcome rejects a swap /// between two named events produced by one multi-event request step. pub(super) fn assert_swapped_request_calls_fail( @@ -1662,9 +1757,9 @@ pub(super) fn assert_swapped_request_calls_fail( first_event: u16, second_event: u16, ) { - let run = play(name, scenario, Some(&[])); + let run = play(name, "allow-all", scenario, Some(&[])); check_outcome(name, "allow-all", scenario, &run, &scenario.allow); - let calls = receive_calls(name, &run); + let calls = receive_calls(name, &run.steps); let call_position = |event| { calls .iter() @@ -1710,8 +1805,8 @@ pub(super) fn assert_swapped_request_calls_fail( /// freeze facts are compared exactly. fn check_input_row(row: &InputRow) { let (name, scenario) = (row.name, row.scenario); - let plain = play(name, scenario, None); - let allow = play(name, scenario, Some(&[])); + let plain = play(name, "no-policy", scenario, None); + let allow = play(name, "allow-all", scenario, Some(&[])); let bytes = |run: &Run| { run.clients .iter() @@ -1746,7 +1841,7 @@ fn check_input_row(row: &InputRow) { assert_eq!(allow.grab, facts, "{name}: allow-all grab and freeze state"); } - let denied = play(name, scenario, Some(row.deny)); + let denied = play(name, "denial", scenario, Some(row.deny)); check_outcome(name, "denial", scenario, &denied, &row.denied); assert_eq!(denied.state, allow.state, "{name}: denial changed state"); let expected_grab = row @@ -1854,6 +1949,7 @@ mod batch_naming { request: None, hooks: Vec::new(), replies: Vec::new(), + grab: Vec::new(), }], state: String::new(), grab: Vec::new(), @@ -1925,6 +2021,7 @@ mod batch_naming { request: Some((A, 35, 0)), hooks: vec![receive_check(4), receive_check(4)], replies: Vec::new(), + grab: Vec::new(), }], state: String::new(), grab: Vec::new(), diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs index f5e2b6266..75f11cf34 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -40,6 +40,24 @@ fn setup_k4(f: &mut NotifyFixture) { } } +/// Shared focused-release fixture: the legacy selector at FOCUS makes a +/// suppressed selection at CHILD observable if it incorrectly continues. +fn setup_k5_suppressed_base(f: &mut NotifyFixture) { + tree(f); + select_core(f, B, FOCUS, KEY_RELEASE); +} + +fn setup_k5_xi2_release(f: &mut NotifyFixture) { + setup_k5_suppressed_base(f); + select_xi2(f, A, CHILD, DEVICEID_MASTER_KEYBOARD, XI_KEY_RELEASE); +} + +fn setup_k5_detectable(f: &mut NotifyFixture) { + setup_k5_suppressed_base(f); + select_core(f, A, CHILD, KEY_RELEASE); + set_detectable_repeat(f, A); +} + /// Slave origin with the master transition rejected: the core form is excluded /// on this path. A selects slave XI2 and core on CHILD; B slave XI2 on FOCUS. fn setup_k5b(f: &mut NotifyFixture) { @@ -267,6 +285,20 @@ const K4_SCENARIO: Scenario = Scenario { order: CallOrder::Total, }; +const K5_XI2_SUPPRESSED_SCENARIO: Scenario = Scenario { + setup: setup_k5_xi2_release, + steps: &[SYNTH_RELEASE], + allow: NOTHING, + order: CallOrder::Total, +}; + +const K5_DETECTABLE_SCENARIO: Scenario = Scenario { + setup: setup_k5_detectable, + steps: &[SYNTH_RELEASE], + allow: NOTHING, + order: CallOrder::Total, +}; + const K5B_SCENARIO: Scenario = Scenario { setup: setup_k5b, steps: &[SLAVE_PRESS], @@ -418,6 +450,18 @@ const ROWS: &[InputRow] = &[ &[moved(A, Kind::Core, CHILD, 0, (10, 10))], ), }, + InputRow { + name: "k5_suppressed_xi2_release_stops_without_a_check", + scenario: &K5_XI2_SUPPRESSED_SCENARIO, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: NOTHING, + }, + InputRow { + name: "k5_suppressed_detectable_core_release_stops_without_a_check", + scenario: &K5_DETECTABLE_SCENARIO, + deny: &[(A, CallKind::Core, CHILD)], + denied: NOTHING, + }, InputRow { name: "k5b_form_excluded_by_the_include_flags_still_stops", scenario: &K5B_SCENARIO, diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs index 29b096f55..193e61936 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -200,6 +200,32 @@ fn allow_slave(f: &mut NotifyFixture) { request(f, A, XI_MAJOR, XI_ALLOW_EVENTS, &body); } +fn replay_slave(f: &mut NotifyFixture) { + const XI1_ALLOW_DEVICE_EVENTS: u8 = 19; + let mut body = Vec::new(); + body.extend_from_slice(&0_u32.to_le_bytes()); // CurrentTime + body.extend_from_slice(&[XI_REPLAY_DEVICE, DEVICEID_XTEST_POINTER as u8, 0, 0]); + request(f, SEND_CLIENT, XI_MAJOR, XI1_ALLOW_DEVICE_EVENTS, &body); +} + +/// A synchronous XI1 `GrabDeviceButton` by `owner` on `window`, any button +/// and modifier, installed directly for the replay fixture. +fn xi1_passive_grab(f: &mut NotifyFixture, owner: u32, window: u32, sync: bool) { + f.state + .xi1_passive_grabs + .push(crate::server::Xi1PassiveGrab { + owner: ClientId(owner), + deviceid: DEVICEID_XTEST_POINTER, + grab_window: ResourceId(window), + detail: 0, + modifiers: 0x8000, + owner_events: false, + this_mode: u8::from(!sync), + other_mode: 1, + is_key: false, + }); +} + // ---- setups -------------------------------------------------------------- // // A is the grab owner and B the foreign selector in the grab rows; the grab @@ -275,6 +301,24 @@ fn setup_p7(f: &mut NotifyFixture) { select_xi2(f, B, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); } +/// Shared owner-events fixture with A's eligible natural copy at the +/// ancestor. The p8 and p10 variants differ only in who selects on CHILD. +fn setup_p8_p10_ancestor(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, FOCUS, CORE_BUTTON_PRESS); + grab_pointer(f, A, ROOT, true, CORE_BUTTON_PRESS); +} + +fn setup_p8(f: &mut NotifyFixture) { + setup_p8_p10_ancestor(f); + select_core(f, A, CHILD, CORE_BUTTON_PRESS); +} + +fn setup_p10(f: &mut NotifyFixture) { + setup_p8_p10_ancestor(f); + select_core(f, B, CHILD, CORE_BUTTON_PRESS); +} + /// The core grab window is C itself: A core on C (denied), B master XI2 on C /// (allowed). The core fallback is a distinct attempt, so A is asked at C again. fn setup_p9_core_same_window(f: &mut NotifyFixture) { @@ -413,6 +457,13 @@ fn setup_p20(f: &mut NotifyFixture) { ); } +/// The replay competition shares p20's selectors; the requester owns a sync +/// passive grab on FOCUS so ReplayThisDevice re-runs the CHILD selection walk. +fn setup_p28(f: &mut NotifyFixture) { + setup_p20(f); + xi1_passive_grab(f, SEND_CLIENT, FOCUS, true); +} + fn setup_p21(f: &mut NotifyFixture) { tree(f); select_xi2(f, A, ROOT, DEVICEID_MASTER_POINTER, XI_RAW_BUTTON_PRESS); @@ -552,6 +603,52 @@ const fn xi1_implicit(owner: u32, window: u32) -> Grab { } } +const P28_ACTIVATED: &[Grab] = &[ + xi1_implicit(SEND_CLIENT, FOCUS), + Grab::Freeze { + device: DEVICEID_XTEST_POINTER, + state: Xi1SyncState::FrozenWithEvent, + other: None, + stored: Some(Held::Xi1Routed { + evcode: crate::server::XI_FIRST_EVENT + crate::xinput::XI_DEVICE_BUTTON_PRESS_OFFSET, + detail: 1, + }), + }, +]; + +const P28_PRESS: Scenario = Scenario { + setup: setup_p28, + steps: &[press(XTEST_SLAVE)], + allow: with_grab( + frames_and_calls( + &[(SEND_CLIENT, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS)], + &[(SEND_CLIENT, XI1_PRESS_CALL, FOCUS)], + ), + P28_ACTIVATED, + ), + order: CallOrder::PerClient, +}; + +const P28_REPLAY: Scenario = Scenario { + steps: &[press(XTEST_SLAVE), Step::Request(replay_slave, &[])], + allow: with_grab( + frames_and_calls( + &[ + (SEND_CLIENT, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS), + (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + (B, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + ], + &[ + (SEND_CLIENT, XI1_PRESS_CALL, FOCUS), + (A, XI1_PRESS_CALL, CHILD), + (B, XI1_PRESS_CALL, CHILD), + ], + ), + &[xi1_implicit(B, CHILD)], + ), + ..P28_PRESS +}; + /// The master pointer's freeze while a sync grab holds the activating press. const FROZEN_BY_PRESS: Grab = Grab::Freeze { device: DEVICEID_MASTER_POINTER, @@ -897,6 +994,41 @@ const ROWS: &[InputRow] = &[ ..NOTHING }, }, + InputRow { + name: "p8_denied_owner_copy_continues_the_natural_walk", + scenario: &Scenario { + setup: setup_p8, + steps: &[press(XTEST_MASTER)], + allow: A_CORE_CHILD, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Core, FOCUS)], + moved: &[moved(A, Kind::Core, FOCUS, CHILD, P_EVENT)], + calls: &[(A, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + grab: None, + }, + }, + InputRow { + name: "p10_denied_foreign_selector_does_not_reject", + scenario: &Scenario { + setup: setup_p10, + steps: &[press(XTEST_MASTER)], + allow: frames_and_calls( + &[(A, Kind::Core, ROOT)], + &[(B, CallKind::Core, CHILD), (A, CallKind::Core, ROOT)], + ), + order: CallOrder::Total, + }, + deny: &[(B, CallKind::Core, CHILD)], + denied: Outcome { + frames: &[(A, Kind::Core, FOCUS)], + moved: &[moved(A, Kind::Core, FOCUS, CHILD, P_EVENT)], + calls: &[(B, CallKind::Core, CHILD), (A, CallKind::Core, FOCUS)], + grab: None, + }, + }, // Mutation: the core fallback takes the memo's result for (A, G, core) // instead of a fresh check (this row then has one call for A, not two). InputRow { @@ -1240,6 +1372,27 @@ const ROWS: &[InputRow] = &[ &[xi1_implicit(A, CHILD)], ), }, + // Replay re-runs the same-window competition: B has the grab class but its + // XI1 copy is denied, so A receives the press and owns the implicit grab. + InputRow { + name: "p28_thawed_xi1_press_picks_the_owner_from_allowed", + scenario: &P28_REPLAY, + deny: &[(B, XI1_PRESS_CALL, CHILD)], + denied: with_grab( + frames_and_calls( + &[ + (SEND_CLIENT, Kind::Xi1(DEVICEID_XTEST_POINTER), FOCUS), + (A, Kind::Xi1(DEVICEID_XTEST_POINTER), CHILD), + ], + &[ + (SEND_CLIENT, XI1_PRESS_CALL, FOCUS), + (A, XI1_PRESS_CALL, CHILD), + (B, XI1_PRESS_CALL, CHILD), + ], + ), + &[xi1_implicit(A, CHILD)], + ), + }, // A and B select the master raw press on the root, the requester the slave's; // A is denied: only A's copy goes, B and the requester keep theirs. // Mutation: the raw copies are written unchecked (every denied-run assertion diff --git a/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs index 5f5ca921a..2d0e564ef 100644 --- a/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs @@ -23,6 +23,7 @@ const XTEST_SLAVE_KEYBOARD: InputOrigin = InputOrigin::XTest(DEVICEID_XTEST_KEYB const CORE_BUTTON_PRESS: u32 = 1 << 2; const CORE_MOTION: u32 = 1 << 6; const XI_BUTTON_PRESS: u32 = 1 << 4; +const XI_KEY_PRESS: u32 = 1 << 2; const XI_RAW_KEY_PRESS: u32 = 1 << 13; const MOTION_TO: (i16, i16) = (125, 125); const FOCUS_EVENT: (i16, i16) = (20, 20); @@ -104,6 +105,7 @@ fn setup_r4_replay_pointer(f: &mut NotifyFixture) { fn setup_r5_replay_keyboard(f: &mut NotifyFixture) { tree(f); select_core(f, B, FOCUS, KEY_PRESS); + select_xi2(f, B, FOCUS, DEVICEID_MASTER_KEYBOARD, XI_KEY_PRESS); grab_key(f, A, ROOT, false, true); } @@ -204,6 +206,128 @@ const R1_PHYSICAL_PASSIVE_GRAB: Grab = Grab::SlavePointer { }, }; +const R1_XTEST_PRESS_STORED: Grab = Grab::Freeze { + device: DEVICEID_XTEST_POINTER, + state: Xi1SyncState::FrozenWithEvent, + other: None, + stored: Some(Held::HostPointer { + kind: PointerEventKind::ButtonPress, + detail: 1, + }), +}; + +const PHYSICAL_POINTER_PRESS_STORED: Grab = Grab::Freeze { + device: PHYSICAL_DEVICE, + state: Xi1SyncState::FrozenWithEvent, + other: None, + stored: Some(Held::HostPointer { + kind: PointerEventKind::ButtonPress, + detail: 1, + }), +}; + +const R1_XTEST_XI1_QUEUED: Grab = Grab::Queued { + device: DEVICEID_XTEST_POINTER, + held: Held::Xi1Routed { + evcode: crate::server::XI_FIRST_EVENT + XI_DEVICE_BUTTON_PRESS_OFFSET, + detail: 1, + }, +}; + +const R1_PHYSICAL_XI1_QUEUED: Grab = Grab::Queued { + device: PHYSICAL_DEVICE, + held: Held::Xi1Routed { + evcode: crate::server::XI_FIRST_EVENT + XI_DEVICE_BUTTON_PRESS_OFFSET, + detail: 1, + }, +}; + +const R1_QUEUE_CHECKPOINT: Outcome = with_grab( + frames_and_calls( + &[ + (A, Kind::Xi2(DEVICEID_XTEST_POINTER), ROOT), + (A, Kind::Xi2(PHYSICAL_DEVICE), ROOT), + ], + &[(A, CallKind::Xi2, ROOT), (A, CallKind::Xi2, ROOT)], + ), + &[ + A_ROOT_KEYBOARD_GRAB, + XTEST_POINTER_DETACHED, + PHYSICAL_POINTER_DETACHED, + R1_XTEST_PASSIVE_GRAB, + R1_PHYSICAL_PASSIVE_GRAB, + Grab::Freeze { + device: DEVICEID_MASTER_KEYBOARD, + state: Xi1SyncState::FrozenNoEvent, + other: None, + stored: None, + }, + R1_XTEST_PRESS_STORED, + PHYSICAL_POINTER_PRESS_STORED, + R1_XTEST_XI1_QUEUED, + R1_PHYSICAL_XI1_QUEUED, + ], +); + +const CORE_POINTER_PRESS_FROZEN: Grab = Grab::Freeze { + device: DEVICEID_MASTER_POINTER, + state: Xi1SyncState::FrozenWithEvent, + other: None, + stored: Some(Held::HostPointer { + kind: PointerEventKind::ButtonPress, + detail: 1, + }), +}; + +const MASTER_POINTER_MOTION_QUEUED: Grab = Grab::Queued { + device: DEVICEID_MASTER_POINTER, + held: Held::HostPointer { + kind: PointerEventKind::MotionNotify, + detail: 0, + }, +}; + +const R6_QUEUE_CHECKPOINT: Outcome = with_grab( + frames_and_calls( + &[(A, Kind::Core, ROOT)], + &[(A, CORE_BUTTON_PRESS_CALL, ROOT)], + ), + &[ + PASSIVE_CORE_POINTER, + CORE_POINTER_PRESS_FROZEN, + MASTER_POINTER_MOTION_QUEUED, + ], +); + +const R7_QUEUE_CHECKPOINT: Outcome = with_grab( + NOTHING, + &[ + A_ROOT_KEYBOARD_GRAB, + Grab::Freeze { + device: DEVICEID_MASTER_KEYBOARD, + state: Xi1SyncState::FrozenNoEvent, + other: None, + stored: None, + }, + Grab::Queued { + device: DEVICEID_MASTER_KEYBOARD, + held: Held::RawKey { + pressed: true, + keycode: KEYCODE, + }, + }, + Grab::Queued { + device: DEVICEID_MASTER_KEYBOARD, + held: Held::HostKeyTransition { + pressed: true, + keycode: KEYCODE, + master: true, + synthetic: false, + }, + }, + ], +); + const R4_REPLAY: Scenario = Scenario { setup: setup_r4_replay_pointer, steps: &[ @@ -240,11 +364,11 @@ const R5_REPLAY: Scenario = Scenario { ], allow: with_grab( frames_and_calls( - &[(A, Kind::Core, ROOT), (B, Kind::Core, FOCUS)], &[ - (A, CORE_KEY_PRESS_CALL, ROOT), - (B, CORE_KEY_PRESS_CALL, FOCUS), + (A, Kind::Core, ROOT), + (B, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), FOCUS), ], + &[(A, CORE_KEY_PRESS_CALL, ROOT), (B, CallKind::Xi2, FOCUS)], ), &[], ), @@ -256,6 +380,7 @@ const R1_XI1_THAW: Scenario = Scenario { steps: &[ button_press(XTEST_SLAVE_POINTER), button_press(PHYSICAL_POINTER), + Step::Checkpoint(R1_QUEUE_CHECKPOINT), Step::Request(allow_core_events::<6>, &[]), ], allow: with_grab( @@ -289,6 +414,7 @@ const R7_THAW: Scenario = Scenario { steps: &[ raw_key_press(XTEST_SLAVE_KEYBOARD), key_press(XTEST_SLAVE_KEYBOARD), + Step::Checkpoint(R7_QUEUE_CHECKPOINT), Step::Request( allow_core_events::<3>, &[ @@ -318,6 +444,7 @@ const R6_THAW: Scenario = Scenario { steps: &[ button_press(XTEST_MASTER_POINTER), motion(XTEST_MASTER_POINTER), + Step::Checkpoint(R6_QUEUE_CHECKPOINT), Step::Request(allow_core_events::<0>, &[]), ], allow: with_grab( @@ -437,11 +564,8 @@ const ROWS: &[InputRow] = &[ deny: &[(A, CORE_KEY_PRESS_CALL, ROOT)], denied: with_grab( frames_and_calls( - &[(B, Kind::Core, FOCUS)], - &[ - (A, CORE_KEY_PRESS_CALL, ROOT), - (B, CORE_KEY_PRESS_CALL, FOCUS), - ], + &[(B, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), FOCUS)], + &[(A, CORE_KEY_PRESS_CALL, ROOT), (B, CallKind::Xi2, FOCUS)], ), &[], ), @@ -453,11 +577,13 @@ const ROWS: &[InputRow] = &[ scenario: &R5_REPLAY, deny: &[ (A, CORE_KEY_PRESS_CALL, ROOT), + (B, CallKind::Xi2, FOCUS), (B, CORE_KEY_PRESS_CALL, FOCUS), ], denied: with_grab( calls_only(&[ (A, CORE_KEY_PRESS_CALL, ROOT), + (B, CallKind::Xi2, FOCUS), (B, CORE_KEY_PRESS_CALL, FOCUS), ]), &[],