diff --git a/crates/yserver-core/src/core_loop/fanout.rs b/crates/yserver-core/src/core_loop/fanout.rs index 5b219ca5a..bce984eeb 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. @@ -130,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 @@ -198,13 +199,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; @@ -218,14 +220,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); + let mut 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; + subs.retain(|sub| { + if walk.shadowed.contains(sub) { + stops = true; + false + } else { + let allowed = + walk.memo + .allows(state, *sub, EventSubject::Window(current), &batch); + stops |= allowed; + allowed + } + }); + if stops { + return Some((current, x, y, subs, child.unwrap_or(ResourceId(0)))); + } } let window = state.resources.window(current)?; if window.parent == current { @@ -293,6 +325,87 @@ 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(_) + ) +} + +/// 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(), + } + } + + /// 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( + &mut self, + state: &ServerState, + client: ClientId, + subject: EventSubject, + events: &EventBatch<'_>, + ) -> bool { + if !state.policies_installed() { + return true; + } + if let Some(allowed) = self.known(client, subject, 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], @@ -431,7 +544,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, @@ -459,100 +575,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, @@ -964,7 +986,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, \ @@ -980,6 +1003,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); @@ -989,7 +1013,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/key_fanout.rs b/crates/yserver-core/src/core_loop/key_fanout.rs index f49c8ad36..dcc1b7816 100644 --- a/crates/yserver-core/src/core_loop/key_fanout.rs +++ b/crates/yserver-core/src/core_loop/key_fanout.rs @@ -12,10 +12,13 @@ //! 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::{ - core_loop::fanout::{fanout_event_to_clients, subscribers_by_id}, + access::{EventBatch, EventDescription, EventSubject}, + 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, @@ -546,6 +549,7 @@ fn deliver_routed_key_with_master_status( grab.via_xi2, device_id, synthetic_repeat, + OwnerWrite::FreshCheck, ); merge_dropped( &mut dropped, @@ -553,12 +557,21 @@ 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 = 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, + &xi2_forms, + false, + false, + synthetic_repeat, + ); + write_key_copies(state, &event, &xi2_forms, target, &copies, synthetic_repeat) }; merge_dropped( &mut dropped, @@ -566,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), @@ -606,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) + key_grabbed_natural_target( + state, + &event, + &xi2_forms, + owner, + via_xi2, + synthetic_repeat, + ) } else { None }; @@ -619,6 +643,7 @@ fn deliver_routed_key_with_master_status( via_xi2, grab_device_id, synthetic_repeat, + OwnerWrite::Decided, ) } else { deliver_key_to_grab_owner( @@ -629,6 +654,7 @@ fn deliver_routed_key_with_master_status( via_xi2, grab_device_id, synthetic_repeat, + OwnerWrite::FreshCheck, ) }; // XI1 leg runs under grabs too — the router handles its @@ -648,15 +674,17 @@ 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, + &xi2_forms, master_transition_accepted, master_transition_accepted, 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), @@ -684,18 +712,21 @@ 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(); } - let mut dropped = deliver_key_to_window( + let copies = key_copies_at( state, &event, + &xi2_forms, focus, master_transition_accepted, master_transition_accepted, 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), @@ -703,109 +734,250 @@ 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, + /// Per-form recipient slots, slave form before master. + xi2: [Vec; 2], + stops: bool, +} + +/// 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 slave-first XI2 forms one key event can carry. Their two fixed slots +/// are shared by every window and client plan for the event. +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 +/// 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. +/// +/// `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, - target_window: ResourceId, + forms: &KeyXi2Forms, + window: ResourceId, + client: ClientId, include_master_form: bool, include_core_form: bool, synthetic_repeat: bool, -) -> Vec { + 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 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() - .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)); - } - } + let evtype = xi2_evtype_for(event); + let xi2_suppressed = synthetic_repeat && !event.pressed; + 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() + .flatten() + .any(|(device_id, _)| !included(*device_id) && selected(*device_id)) + { + stops = true; } - // 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())) - }) - .collect() + // 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() + .flatten() + .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 { - Vec::new() + let allowed = receive(crate::xinput::xi2_event_description(evtype)); + stops |= allowed; + allowed }; - let mut dropped = if core_targets.is_empty() { - 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 { - fanout_event_to_clients(state, &core_targets, |buf, seq, order| { - x11::encode_key_event(buf, order, key_event_wire(event, seq, fields)); - }) + let allowed = receive(EventDescription::core(if event.pressed { 2 } else { 3 })); + stops |= allowed; + allowed }; - // 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; + ClientKeyPlan { + xi2_copy, + core_copy, + stops, } +} - 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(); +/// 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, + forms: &KeyXi2Forms, + 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 = [Vec::new(), 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, + 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 + && let Some(record) = state.clients.get(id) + { + 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); + } + } + } + } + KeyCopies { core, xi2, 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, + forms: &KeyXi2Forms, + 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, &copies.core, |buf, seq, order| { + x11::encode_key_event(buf, order, key_event_wire(event, seq, fields)); + }) + }; + 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, &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 } +/// 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 @@ -836,40 +1008,136 @@ fn deliver_key_to_grab_owner( via_xi2: bool, device_id: u16, synthetic_repeat: 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 description = grab_owner_description(event, via_xi2); if via_xi2 { - if synthetic_repeat && !event.pressed { - 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, + 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 { + 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. 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, + 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(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, + forms: &KeyXi2Forms, + owner: ClientId, + window: ResourceId, + 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) + .map(|client| { + client_key_plan( + state, event, - fields, - device_id, - source_id, + forms, + window, + client, + true, + true, synthetic_repeat, - ); - }) - } else { - if synthetic_repeat - && !event.pressed - && state - .xkb_clients - .get(&owner.0) - .is_some_and(|flags| flags.wants_detectable_auto_repeat()) - { - return Vec::new(); - } - fanout_event_to_clients(state, &[owner], |buf, seq, order| { - x11::encode_key_event(buf, order, key_event_wire(event, seq, fields)); + &|description| { + receive_allows(state, client, subject, &EventBatch::new(&[description])) + }, + ) + .stops }) - } + .fold(false, |rejects, stops| rejects | stops) } fn xi2_evtype_for(event: &HostKeyEvent) -> u16 { @@ -882,18 +1150,16 @@ 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 [None, None]; }; - let mut forms = Vec::with_capacity(2); - if let Some(slave_id) = source.slave_deviceid { - forms.push((slave_id, slave_id)); - } - if let Some(master_id) = source.attached_master { - forms.push((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( @@ -1149,10 +1415,24 @@ 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. + 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 + && 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), + ), ); } } @@ -1193,20 +1473,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, @@ -1220,7 +1494,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) { @@ -1489,20 +1785,24 @@ fn deliver_xi1_focused_key( }, true, None, + &mut crate::core_loop::fanout::ReceiveMemo::new(), ) } -/// 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 (`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( + state: &ServerState, + focus: ResourceId, + event: &HostKeyEvent, + forms: &KeyXi2Forms, + 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,62 +1821,65 @@ 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; - } - } - 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, - 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 - .iter() - .any(|(device_id, _)| key_xi2_form_selected(client, window, *device_id, evtype)) + let copies_at = |window: ResourceId| { + key_copies_at( + state, + event, + forms, + window, + include_master_form, + include_core_form, + synthetic_repeat, + ) + }; + let Some(depth) = chain.iter().position(|w| *w == focus) else { + return (focus, copies_at(focus)); + }; + 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 + }) { - clients.push(ClientId(*id)); + continue; + } + let copies = copies_at(*window); + if copies.stops { + return (*window, copies); } } - clients + (focus, copies_at(focus)) } -/// 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, + forms: &KeyXi2Forms, owner: ClientId, + 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; @@ -1604,9 +1907,41 @@ 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 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 state + .clients + .keys() + .any(|id| ClientId(*id) != owner && selects(ClientId(*id))) + { + return None; + } + } else { + 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.rs b/crates/yserver-core/src/core_loop/pointer_fanout.rs index 2f23d0583..a50149c3e 100644 --- a/crates/yserver-core/src/core_loop/pointer_fanout.rs +++ b/crates/yserver-core/src/core_loop/pointer_fanout.rs @@ -19,21 +19,23 @@ 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::{ 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, }; +pub use xi1::*; 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 +1025,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 +1384,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 +1396,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() { @@ -1416,6 +1423,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). @@ -1432,6 +1443,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 @@ -1459,6 +1471,9 @@ fn pointer_event_fanout_to_state_inner( mask_bit, Some(xi2_evtype(event.kind)), None, + Some(&mut receive), + true, + false, ) }); if let Some(route) = natural_route { @@ -1485,6 +1500,8 @@ fn pointer_event_fanout_to_state_inner( target, top_level_id_opt.unwrap_or(ROOT_WINDOW), is_replay, + // The route asked Receive for this copy: the write reuses it. + false, ); merge_dropped(&mut dropped, extras); handled_core_via_grab = true; @@ -1495,7 +1512,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); @@ -1516,6 +1536,7 @@ fn pointer_event_fanout_to_state_inner( target, top_level_id_opt.unwrap_or(ROOT_WINDOW), is_replay, + false, ); merge_dropped(&mut dropped, extras); } @@ -1527,7 +1548,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); @@ -1546,6 +1570,7 @@ fn pointer_event_fanout_to_state_inner( target, top_level_id_opt.unwrap_or(ROOT_WINDOW), is_replay, + false, ); merge_dropped(&mut dropped, extras); } @@ -1711,6 +1736,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; @@ -1759,6 +1785,26 @@ 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)); + // 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 + && button_transition.source_accepted; if !handled_core_via_grab && button_transition.master_accepted && (top_level_id_opt.is_some() || is_crossing) @@ -1794,14 +1840,66 @@ 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 = 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, + 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 +1908,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 +1956,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 +2025,6 @@ 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 owner_events_slave_route = if xi2_grab_delivery && let Some(grab) = grab_for_form(state, xi_source, Xi2PointerForm::Slave, replay) && grab.passive @@ -2017,6 +2059,9 @@ fn pointer_event_fanout_to_state_inner( pointer_mask_bit(event.kind, event.state), Some(xi2_evtype(event.kind)), xi1_class, + slave_form_emitted.then_some(&mut receive), + false, + false, ) } else { OwnerEventsRoute::Fallback @@ -2047,6 +2092,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 @@ -2081,11 +2132,24 @@ fn pointer_event_fanout_to_state_inner( && !state.xi1_active_grabs.contains_key(&deviceid) && !state.xi2_pointer_grabs.contains_key(&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, + state, + target, + deviceid, + q.evcode, + &mut receive, + slave_form_checked, + 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); } @@ -2129,6 +2193,13 @@ 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 decides its + // XI2 recipients through the same memo, so they are written as they stand. + 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, @@ -2152,9 +2223,18 @@ 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_pass_target == target, + 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 +2242,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() @@ -2195,6 +2280,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 @@ -2243,6 +2333,9 @@ fn pointer_event_fanout_to_state_inner( pointer_mask_bit(event.kind, event.state), Some(xi2_evtype), None, + master_form_emitted.then_some(&mut receive), + core_grab_routed, + false, ) } else { OwnerEventsRoute::Fallback @@ -2257,18 +2350,23 @@ 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); + OwnerEventsRoute::Fallback if via_xi2 => { + // The grab window's attempt: one fresh check before the mask. + 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); + } + 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), + )); } - 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), - )); } _ => {} } @@ -2287,21 +2385,26 @@ 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(( - 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; + // The grab window's attempt: one fresh check before the mask. + 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); + } + 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; + } } _ => {} } @@ -2339,9 +2442,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, @@ -2355,24 +2467,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); } @@ -2423,6 +2542,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, @@ -2515,6 +2635,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 && slave_pass_target == target, + master: master_form_checked, + }), ); let wants_slave_at_target = wants_slave; if slave_pass_target != target { @@ -2526,9 +2651,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 +2813,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 +2824,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 +2925,83 @@ 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 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 + // at one window share one call). + // 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 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) + }; + 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 @@ -2992,9 +3192,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 @@ -3037,933 +3253,88 @@ 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>, -) -> Vec { - use crate::xinput::{ - XI_DEVICE_BUTTON_PRESS_OFFSET, XI_DEVICE_BUTTON_RELEASE_OFFSET, XI_DEVICE_KEY_PRESS_OFFSET, - XI_DEVICE_KEY_RELEASE_OFFSET, +fn translate_host_event( + state: &ServerState, + xid_map: &HostXidMap, + event: HostPointerEvent, +) -> HostPointerEvent { + let Some(top_level_id) = xid_map.get(&event.host_xid).copied() else { + return event; }; - 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 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), - }; - log::debug!( - "xi1_route: evcode={} GRAB owner={} window=0x{:x} detail={}", - q.evcode, - grab.owner.0, - event_window.0, - q.detail, - ); - let deliver = !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 = 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(); - 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, - ); - } - let dropped = xi1_fan_device_event(state, &[g.owner], g.grab_window, &q); - 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; - } + let Some((rx, ry)) = state + .resources + .window(top_level_id) + .map(|w| (w.x + event.event_x, w.y + event.event_y)) + else { + return event; + }; + HostPointerEvent { + origin: event.origin, + root_x: rx, + root_y: ry, + ..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 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, - } +/// Recipients of a core Enter/Leave on `window` — Xorg `CoreEnterLeaveEvent` +/// (`dix/events.c:4748`). A crossing never propagates. Under a pointer grab +/// only the grab client gets it: on the grab window through the grab's mask, +/// and with `owner_events` through its own selection on `window`. +fn core_crossing_targets(state: &ServerState, window: ResourceId, mask_bit: u32) -> Vec { + let Some((grab_window, grab_client, _, _, owner_events, via_xi2, grab_mask)) = + active_grab_target(state) + else { + return crate::core_loop::fanout::subscribers_by_id(state, window, mask_bit); + }; + let mut mask = if window == grab_window && !via_xi2 { + grab_mask } 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)) - }) - } - } + 0 }; - 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; - } + if owner_events { + mask |= state + .clients + .get(&grab_client.0) + .and_then(|c| c.event_masks.get(&window).copied()) + .unwrap_or(0); } - // 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); + if mask & mask_bit == 0 { + Vec::new() + } else { + vec![grab_client] } - dropped } -/// 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). -fn compute_xi1_route_targets( +fn active_grab_target( state: &ServerState, - q: &crate::server::Xi1QueuedEvent, -) -> Option<(Vec, ResourceId)> { - match q.focus_route { - crate::server::Xi1FocusRoute::Walk => { - compute_xi1_targets_bounded(state, q.natural_target, q.evcode, q.deviceid, None) - } - crate::server::Xi1FocusRoute::WalkUpTo(stop) => { - compute_xi1_targets_bounded(state, q.natural_target, q.evcode, q.deviceid, Some(stop)) - } - 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)) - } - } - crate::server::Xi1FocusRoute::Drop => None, - } +) -> Option<( + yserver_protocol::x11::ResourceId, + ClientId, + i32, + i32, + bool, + bool, + u32, +)> { + let grab = state.active_pointer_grab?; + active_pointer_grab_target(state, grab) } -fn resolve_slave_press_delivery( +fn active_grab_for_source( state: &ServerState, - target: ResourceId, - deviceid: u16, - xi1_evcode: u8, -) -> SlavePressDelivery { - 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), - ); - if !xi2_recipients.is_empty() { - return SlavePressDelivery::Xi2 { - window, - recipients: xi2_recipients, - }; - } - - let xi1_recipients = xi1_window_selectors(state, window, xi1_evcode, deviceid); - if !xi1_recipients.is_empty() { - return SlavePressDelivery::Xi1 { - window, - recipients: xi1_recipients, - }; - } - - if window == ROOT_WINDOW { - break; + source: PointerXiSource, +) -> Option { + if let Some(device_id) = source.slave_deviceid { + if let Some(grab) = state.xi2_pointer_grabs.get(&device_id) { + return Some(*grab); } - let Some(parent) = state.resources.parent_of(window) else { - break; - }; - window = parent; + return (source.attached_master == Some(XI2_MASTER_POINTER_DEVICE_ID)) + .then_some(state.active_pointer_grab) + .flatten(); } - 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| { - !state - .xkb_clients - .get(&client.0) - .is_some_and(|flags| flags.wants_detectable_auto_repeat()) - }) - .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); - } - 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() - } - } -} - -/// 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, - event: HostPointerEvent, -) -> HostPointerEvent { - let Some(top_level_id) = xid_map.get(&event.host_xid).copied() else { - return event; - }; - let Some((rx, ry)) = state - .resources - .window(top_level_id) - .map(|w| (w.x + event.event_x, w.y + event.event_y)) - else { - return event; - }; - HostPointerEvent { - origin: event.origin, - root_x: rx, - root_y: ry, - ..event - } -} - -/// Recipients of a core Enter/Leave on `window` — Xorg `CoreEnterLeaveEvent` -/// (`dix/events.c:4748`). A crossing never propagates. Under a pointer grab -/// only the grab client gets it: on the grab window through the grab's mask, -/// and with `owner_events` through its own selection on `window`. -fn core_crossing_targets(state: &ServerState, window: ResourceId, mask_bit: u32) -> Vec { - let Some((grab_window, grab_client, _, _, owner_events, via_xi2, grab_mask)) = - active_grab_target(state) - else { - return crate::core_loop::fanout::subscribers_by_id(state, window, mask_bit); - }; - let mut mask = if window == grab_window && !via_xi2 { - grab_mask - } else { - 0 - }; - if owner_events { - mask |= state - .clients - .get(&grab_client.0) - .and_then(|c| c.event_masks.get(&window).copied()) - .unwrap_or(0); - } - if mask & mask_bit == 0 { - Vec::new() - } else { - vec![grab_client] - } -} - -fn active_grab_target( - state: &ServerState, -) -> Option<( - yserver_protocol::x11::ResourceId, - ClientId, - i32, - i32, - bool, - bool, - u32, -)> { - let grab = state.active_pointer_grab?; - active_pointer_grab_target(state, grab) -} - -fn active_grab_for_source( - state: &ServerState, - source: PointerXiSource, -) -> Option { - if let Some(device_id) = source.slave_deviceid { - if let Some(grab) = state.xi2_pointer_grabs.get(&device_id) { - return Some(*grab); - } - return (source.attached_master == Some(XI2_MASTER_POINTER_DEVICE_ID)) - .then_some(state.active_pointer_grab) - .flatten(); - } - (source.sourceid == XI2_MASTER_POINTER_DEVICE_ID) - .then_some(state.active_pointer_grab) - .flatten() + (source.sourceid == XI2_MASTER_POINTER_DEVICE_ID) + .then_some(state.active_pointer_grab) + .flatten() } fn active_grab_for_device( @@ -4006,6 +3377,87 @@ 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() +} + +/// 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 grab_window_allows( + state: &ServerState, + 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; + } + state.clients.contains_key(&owner.0) + && receive_allows( + state, + owner, + EventSubject::Window(grab_window), + &EventBatch::new(descriptions), + ) +} + +/// `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, @@ -4054,6 +3506,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 +3514,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 +3532,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 +3570,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 +3586,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 +3979,36 @@ 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) if state.policies_installed() => !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) + }), + Some(_) => 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,23 +4019,62 @@ 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)) + let description = crate::xinput::xi2_event_description(evtype); + let batch = EventBatch::new(std::slice::from_ref(&description)); + 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) + }) }) .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 +/// 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 /// only for a device that owns a sprite: `ProcessDeviceEvent` calls /// `CheckMotion` only `if (IsMaster(device) || IsFloating(device))` @@ -4577,7 +4107,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 +4118,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 +4129,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 +4141,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 +4218,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 +4237,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..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 @@ -1,11 +1,39 @@ //! 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, + 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. +#[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( @@ -14,10 +42,30 @@ pub(super) fn xi1_window_selectors( evcode: u8, deviceid: u16, ) -> Vec { - xi1_window_selectors_with_grab_class(state, window, evcode, deviceid) + xi1_window_selector_iter(state, window, evcode, deviceid).collect() +} + +/// 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, +) -> impl Iterator + '_ { + let class = (u32::from(deviceid) << 8) | u32::from(evcode); + state + .xi_input_clients + .get(&window) .into_iter() - .map(|(client, _)| client) - .collect() + .flatten() + .filter(move |entry| { + !entry.server_owned_placeholder && state.clients.contains_key(&entry.client.0) + }) + .filter_map(move |entry| { + let classes = entry.xi1_masks.get(&deviceid)?; + classes.contains(&class).then_some(entry.client) + }) } /// Returns the canonical input-client entries that select an XI1 event and @@ -98,6 +146,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,6 +188,9 @@ pub(super) fn xi2_motion_targets_for_source( 0, Some(XI_MOTION), None, + receive.as_deref_mut(), + false, + false, ) } else { OwnerEventsRoute::Fallback @@ -166,6 +218,18 @@ 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 (`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, + grab.owner, + grab_window, + &crate::xinput::xi2_event_description(XI_MOTION), + )) { let child = xi2_child_toward(state, grab_window, target); targets.push(Xi2MotionTarget { @@ -183,9 +247,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, + receive.as_deref_mut(), + ) else { continue; }; let child = xi2_child_toward(state, window, target); @@ -198,9 +267,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) - { + 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, @@ -219,13 +293,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)>, @@ -257,6 +333,9 @@ pub(super) fn xi1_selection_filter_for_slave_grab( 0, Some(evtype), Some(class), + Some(receive), + false, + true, ) } else { OwnerEventsRoute::Fallback @@ -267,8 +346,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 } @@ -377,10 +457,186 @@ 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) -> EventDescriptions { + let offset = evcode.saturating_sub(crate::server::XI_FIRST_EVENT); + if offset == crate::xinput::XI_DEVICE_MOTION_NOTIFY_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)) + } +} + +/// 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 /// 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. `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, @@ -392,65 +648,76 @@ pub(super) fn owner_events_route( core_mask: u32, xi2_evtype: Option, xi1_mask: Option, + mut receive: Option<&mut ReceiveMemo>, + 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 { - let mut rejected = false; - if let Some(evtype) = xi2_evtype { - let subscribers = - xi2_form_targets_for_source(state, current, form, evtype, slave_deviceid); - 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; - } - } - if form == Xi2PointerForm::Slave - && let (Some(device_id), Some(class)) = (slave_deviceid, xi1_mask) - { - 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; - } + 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: leg.protocol(), + }; } } - 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; - } + 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; 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/pointer_fanout/xi1.rs b/crates/yserver-core/src/core_loop/pointer_fanout/xi1.rs new file mode 100644 index 000000000..333206a70 --- /dev/null +++ b/crates/yserver-core/src/core_loop/pointer_fanout/xi1.rs @@ -0,0 +1,996 @@ +//! 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) 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, +) -> 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), + }; + Xi1RouteWindows { + state, + next, + stop_at, + } +} + +/// 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 !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 +} + +/// 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 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) + }; + 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 { + if xi1_gets_no_copy(state, q, owner) { + return false; + } + if !state.policies_installed() { + return true; + } + let batch = 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 +/// 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 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 && 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| { + 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() + } + } +} 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..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 @@ -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, @@ -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; 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, @@ -1052,23 +1060,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 +1220,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" + ); } } @@ -1406,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) }; @@ -1550,12 +1562,19 @@ 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(); 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 +1605,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, @@ -1599,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) }; @@ -1632,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" ); } @@ -1679,7 +1710,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], @@ -1708,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). 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) @@ -1729,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, @@ -1749,30 +1783,67 @@ 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) - .map(|frame| u16::from_be_bytes([frame[8], frame[9]])) + .map(|frame| dec16(&frame[8..10], ClientByteOrder::BigEndian)) .collect(); 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: 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 +1851,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_input_support.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs new file mode 100644 index 000000000..36c9a984d --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_input_support.rs @@ -0,0 +1,2092 @@ +//! Shared scenario harness for the key and pointer Receive tests (PR 4c +//! 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, split_frames}, + extensions::{ExtensionHook, RecordedExtensionCheck}, + xi2::xi_select_body, +}; +use crate::{ + access::{Decision, EventDescription, EventSubject, RequestOpcodes}, + core_loop::{ + DeviceInfo, InputOrigin, client_io, + key_fanout::{ + RawKeyEvent, key_event_fanout_after_transition, key_event_fanout_to_state, + raw_key_event_to_state, + }, + pointer_fanout::{emit_scroll_stop_to_state, pointer_event_fanout_to_state}, + process_request::RequestOutcome, + }, + host_x11::{HostKeyEvent, HostPointerEvent, HostXidMap, PointerEventKind}, + nested::XI2_MAJOR_OPCODE, + resources::ROOT_WINDOW, + server::{QueuedInputEvent, ServerState, Xi1SyncState}, + 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, ResourceId, SequenceNumber}; + +pub(super) const SEND_CLIENT: u32 = 1; +/// The client that selects on the child window (A). +pub(super) const A: u32 = 2; +/// 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; +pub(super) const POINTER: (i16, i16) = (120, 120); +pub(super) const KEYCODE: u8 = 38; +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; +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; +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. + static SENT_REQUESTS: RefCell> = const { RefCell::new(Vec::new()) }; +} + +fn take_sent_requests() -> Vec<(u32, u8, 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). +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), + /// 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), + /// 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 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), +} + +/// 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 { + /// 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 ordered list of descriptions, each with its own numbering. A batch + /// 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]), +} + +/// 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, PartialOrd, Ord)] +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) +} + +#[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 }, + /// `pointer_event_fanout_to_state` with `handle_grabs` and `!is_replay`. + /// `button` is the detail of a button event and is ignored for motion. + 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), + }, + /// `emit_scroll_stop_to_state`: the two-Motion smooth-scroll stop, probed + /// from root position `at`. + ScrollStop { origin: InputOrigin, at: (i16, i16) }, +} + +impl Drive { + /// 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::ScrollStop { .. } => 6, + 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 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 { + match self { + Drive::Entry { .. } | Drive::After { .. } | Drive::Raw { .. } => u32::from(KEYCODE), + Drive::Pointer { kind, button, .. } => match kind { + PointerEventKind::ButtonPress | PointerEventKind::ButtonRelease => { + u32::from(button) + } + _ => 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. + fn is_wheel_press(self) -> bool { + matches!( + self, + Drive::Pointer { + kind: PointerEventKind::ButtonPress, + button: 4..=7, + .. + } + ) + } +} + +// ---- 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 = 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"); + assert!( + matches!(outcome, RequestOutcome::Handled), + "request handled" + ); + assert!( + 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)) +} + +/// `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); +} + +/// 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 body = super::xi1_select_extension_event_body(window, classes); + 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])]); + 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 = next_sequence(f, client); + 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) { + xi_grab_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 xi_grab_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) { + grab_keyboard_modes(f, owner, window, owner_events, 1, 1); +} + +/// 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, +) { + 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(&[ + 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..]; + 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( + 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::Pointer { + origin, + kind, + button, + to, + delta, + } => 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: to.0, + root_y: to.1, + event_x: to.0, + event_y: to.1, + state: 0, + crossing_mode: 0, + child: 0, + raw_dx: delta.0, + raw_dy: delta.1, + device_axes: None, + tree_change: false, + }, + 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 { + origin, + keycode: KEYCODE, + pressed, + time: TIME, + }, + false, + false, + ), + }; + assert!(dropped.is_empty(), "delivery queued a disconnect"); +} + +/// 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(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(Named::Xi2(extension.event_type)), + 13..=17 => Some(Named::Raw(extension.event_type)), + _ => None, + } + } + Some(extension) if extension.major_opcode == XI2_MAJOR_OPCODE => { + Some(Named::Xi1(extension.event_type)) + } + _ => None, + } +} + +/// 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 the listed (client, batch, window) Receive checks: a call is denied +/// 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; + } + let (Some(EventSubject::Window(window)), Some(events)) = (call.receive, call.events.as_deref()) + else { + return Decision::Allow; + }; + let Some(names) = names_of(events) else { + return Decision::Allow; + }; + let hit = denied.iter().any(|entry| { + 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 } +} + +struct InputFrame { + kind: Kind, + window: u32, + sequence: u16, + event_type: Option, + detail: Option, + placement: (u32, (i16, i16)), +} + +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, + /// Captured bytes, sequence and decoded frames after each scenario step. + steps: Vec, +} + +fn client_frames<'a>( + client: &'a ClientBytes, +) -> impl Iterator + 'a { + client.steps.iter().enumerate().flat_map(|(step, capture)| { + 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)] +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 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. + Xi1 { + device: u16, + owner: u32, + window: u32, + }, + /// 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, + other: Option, + stored: Option, + }, + /// One withheld event in the global `sync_pending` queue, in order. + 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)] +pub(super) enum Held { + 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) => 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::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::RawKey { + 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)] +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, +} + +struct StepRun { + events: Vec, + request: Option<(u32, u8, u8)>, + hooks: Vec, + replies: Vec<(u32, u8)>, + grab: Vec, +} + +struct Run { + clients: Vec, + /// Each step carries its request, ordered hooks and reply/error frames. + steps: Vec, + state: String, + grab: Vec, +} + +/// 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. +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 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 { + 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, + }); + } + 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, + other: freeze.other.map(|client| client.0), + stored: freeze.stored.as_ref().map(held), + }); + } + for pending in &state.sync_pending { + facts.push(Grab::Queued { + device: pending.device, + held: held(&pending.event), + }); + } + facts +} + +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 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 the `(detail, wheel press)` of one of the events the +/// step runs under. +fn delivered(name: &str, run: &Run, steps: &[Vec<(u16, u32)>]) -> Vec { + let mut frames = Vec::new(); + for client in &run.clients { + 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 +} + +// ---- 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), + /// A request, and the event steps whose events it writes (a thaw or replay + /// 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 +/// client (`state.clients` is a HashMap, so the order across clients is not a +/// contract). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum CallOrder { + Total, + PerClient, +} + +/// 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), +} + +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. +#[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, +}; + +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 { + 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 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(..) | Step::Checkpoint(..) => None, + }; + let mut current = scenario.steps.iter().find_map(event); + scenario + .steps + .iter() + .map(|step| match step { + Step::Event(drive) => { + current = Some(*drive); + vec![*drive] + } + Step::Checkpoint(..) => Vec::new(), + Step::Request(_, []) => { + vec![current.expect("a scenario drives at least one event")] + } + Step::Request(_, replays) => replays.iter().filter_map(event).collect(), + }) + .collect() +} + +/// 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, 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; + for client in [SEND_CLIENT, A, B] { + f.drain(ClientId(client)); + } + take_sent_requests(); + let step_drives = step_events(scenario); + let step_evs: Vec> = step_drives + .iter() + .map(|drives| drives.iter().map(|drive| drive.ev()).collect()) + .collect(); + let recorder = policy.map(|denied| { + let evs: Vec = step_evs.concat(); + 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, + steps: Vec::new(), + }) + .collect(); + 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), + Step::Checkpoint(_) => {} + } + let sent = take_sent_requests(); + assert_eq!( + sent.len(), + usize::from(matches!(step, Step::Request(..))), + "{name}: step {index} sent the expected number of requests" + ); + 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); + 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, + 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(), + "{name}: delivery queued a disconnect" + ); + Run { + clients, + steps: step_runs, + 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)), + } +} + +/// 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 +/// 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<_> = client_frames(allowed) + .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 (_, 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 + .iter() + .filter(|(k, w, _)| (*k, *w) == (kind, window)) + .nth(nth); + if let Some((.., same)) = same { + assert_eq!( + frame_bytes(capture, frame), + *same, + "{name}: client {} {kind:?} @{window:#x} bytes under denial", + got.client + ); + } else if !matches!(kind, Kind::Xi1Valuator(_)) { + let client = got.client; + moved.push(( + client, + Move { + client, + kind, + window, + child: input.placement.0, + event: input.placement.1, + }, + )); + } + } + } + moved +} + +/// 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. +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 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) +} + +/// A row's expected call in the same form: a shorthand is the zeroed name. +fn canonical_call(call: &Call) -> Seen { + expected_call(call, 0) +} + +fn receive_calls(name: &str, steps: &[StepRun]) -> Vec<((usize, usize), Seen, Vec)> { + steps + .iter() + .enumerate() + .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 step_run = &run.steps[step_index]; + let actual: Vec<_> = step_run + .hooks + .iter() + .filter(|hook| hook.hook != ExtensionHook::Receive) + .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") + }); + (major >= 128).then_some((client, RequestOpcodes { major, minor: data })) + } + }; + 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, + Some(opcode), + "{name} [{mode}]: step {step_index} dispatch opcode pair" + ); + } + } +} + +/// 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 = receive_calls(name, &run.steps) + .iter() + .map(|(_, call, evs)| canonical_seen(call, evs)) + .collect(); + let calls: Vec = want.calls.iter().map(canonical_call).collect(); + let calls_match = match scenario.order { + CallOrder::Total => got == calls, + CallOrder::PerClient => { + grouped(got.iter().map(|(c, n, w)| (*c, (n.clone(), *w)))) + == grouped(calls.iter().map(|(c, n, w)| (*c, (n.clone(), *w)))) + } + }; + assert!( + calls_match, + "{name} [{mode}]: Receive calls ({:?}) differ\n got: {got:?}\n want: {calls:?}", + scenario.order + ); + 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> = run + .steps + .iter() + .map(|step| { + let drives = &step.events; + drives + .iter() + .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(); + assert_eq!( + grouped( + delivered(name, run, &steps) + .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" + ); +} + +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( + name: &str, + scenario: &Scenario, + client: u32, + window: u32, + request_events: &[u16], + first_event: u16, + second_event: u16, +) { + let run = play(name, "allow-all", scenario, Some(&[])); + check_outcome(name, "allow-all", scenario, &run, &scenario.allow); + let calls = receive_calls(name, &run.steps); + let call_position = |event| { + calls + .iter() + .find(|(_, call, evs)| { + call.0 == client + && call.1.as_slice() == [Named::Xi2(event)] + && call.2 == window + && evs.as_slice() == request_events + }) + .map(|(position, _, _)| *position) + .unwrap_or_else(|| panic!("{name}: request recorded the XI2 event {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; + 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); + })); + 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!( + message.contains("Receive calls"), + "{name}: swapped calls fail at the Receive trace comparison, got {message:?}" + ); +} + +/// 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, "no-policy", scenario, None); + let allow = play(name, "allow-all", scenario, Some(&[])); + let bytes = |run: &Run| { + run.clients + .iter() + .map(|c| { + ( + c.client, + c.order, + c.steps + .iter() + .flat_map(|step| step.bytes.iter().copied()) + .collect::>(), + ) + }) + .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" + ); + 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"); + } + + 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 + .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") + ); +} + +mod batch_naming { + use super::*; + + fn no_setup(_: &mut NotifyFixture) {} + + 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::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(), + grab: 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. + #[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)); + } + + /// 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_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)]; + + let scenario = Scenario { + setup: no_setup, + steps: REQUEST_STEP, + allow: Outcome { + calls: SHORTHAND, + ..NOTHING + }, + order: CallOrder::Total, + }; + let run = Run { + clients: 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(), + grab: 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] + fn xi1_releases_decode_and_unknown_xi1_frames_fail() { + let order = ClientByteOrder::LittleEndian; + 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 new file mode 100644 index 000000000..75f11cf34 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_key_input.rs @@ -0,0 +1,715 @@ +//! Receive decisions in the focused key walk and XI2-over-core shadowing +//! (PR 4c part 2, keyboard). +//! +//! 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, + server::Xi1SyncState, + xinput::{DEVICEID_MASTER_KEYBOARD, DEVICEID_XTEST_KEYBOARD}, +}; + +// ---- setups -------------------------------------------------------------- + +/// 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); +} + +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); +} + +/// 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); + for device in [DEVICEID_MASTER_KEYBOARD, DEVICEID_XTEST_KEYBOARD] { + select_xi2(f, A, CHILD, device, XI_KEY_PRESS_AND_RELEASE); + } +} + +/// 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) { + 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); +} + +/// 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); +} + +/// 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); +} + +/// 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 +/// first and B is not asked (k9, same window). +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); +} + +/// 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. +fn setup_k9b(f: &mut NotifyFixture) { + tree(f); + grab_keyboard(f, A, ROOT, true); + for client in [A, B, SEND_CLIENT] { + select_core(f, client, CHILD, KEY_PRESS); + } +} + +/// 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); +} + +/// 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) { + tree(f); + grab_key(f, A, ROOT, false, true); + select_core(f, B, FOCUS, KEY_PRESS); +} + +/// 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) { + 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); +} + +/// 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. +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); + xi_grab_device(f, A, DEVICEID_MASTER_KEYBOARD, CHILD, true, mask); + select_xi2(f, A, ROOT, DEVICEID_MASTER_KEYBOARD, XI_RAW_KEY_PRESS); +} + +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); + 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); +} + +// ---- 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 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] = &[A_ROOT_KEYBOARD_GRAB]; + +const K1_SCENARIO: Scenario = Scenario { + setup: setup_k1, + steps: &[PRESS], + allow: A_CORE_CHILD, + order: CallOrder::Total, +}; + +const K4_SCENARIO: Scenario = Scenario { + setup: setup_k4, + steps: &[XTEST_PRESS], + allow: frames_and_calls( + &[ + (A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD), + (A, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), CHILD), + ], + &[(A, CallKind::Xi2, CHILD)], + ), + 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], + allow: frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_XTEST_KEYBOARD), CHILD)], + &[(A, CallKind::Xi2, CHILD)], + ), + order: CallOrder::Total, +}; + +const K5B_MASTER_SCENARIO: Scenario = Scenario { + setup: setup_k5b_master, + steps: &[SLAVE_PRESS], + allow: NOTHING, + order: CallOrder::Total, +}; + +const K8_SCENARIO: Scenario = Scenario { + setup: setup_k8, + steps: &[PRESS], + allow: Outcome { + grab: Some(A_GRABS_ROOT), + ..A_CORE_CHILD + }, + 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], + 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 = 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] = &[ + A_ROOT_KEYBOARD_GRAB, + Grab::Freeze { + device: DEVICEID_MASTER_KEYBOARD, + state: Xi1SyncState::FrozenWithEvent, + other: None, + stored: Some(Held::HostKeyTransition { + pressed: true, + keycode: KEYCODE, + master: true, + synthetic: false, + }), + }, +]; + +/// 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 = 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 ---------------------------------------------------------------- + +const ROWS: &[InputRow] = &[ + InputRow { + name: "k1_denied_pointer_window_selector_advances_the_focus_walk", + scenario: &K1_SCENARIO, + deny: &[(A, CallKind::Core, CHILD)], + 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: 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: frames_and_calls( + &[(B, Kind::Core, CHILD)], + &[(A, CallKind::Core, CHILD), (B, CallKind::Core, CHILD)], + ), + }, + // 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: 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", + 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, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: calls_only(&[(A, CallKind::Xi2, CHILD)]), + }, + InputRow { + name: "k5b_excluded_master_form_still_stops", + scenario: &K5B_MASTER_SCENARIO, + 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 { + name: "k9_owner_on_the_same_window_qualifies_first", + scenario: &K8_SCENARIO, + 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 { + setup: setup_k9b, + steps: &[PRESS], + allow: Outcome { + grab: Some(A_GRABS_ROOT), + ..A_CORE_CHILD + }, + order: CallOrder::PerClient, + }, + deny: &[(A, CallKind::Core, CHILD)], + 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", + scenario: &K10_SCENARIO, + deny: &[], + denied: K10_SCENARIO.allow, + }, + // 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: 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. + 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: Outcome { + grab: Some(A_GRABS_SLAVE), + ..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, + }, + // 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: frames_and_calls( + &[(A, Kind::Raw(DEVICEID_MASTER_KEYBOARD), ROOT)], + &[ + (A, CallKind::Raw, ROOT), + (A, CallKind::Raw, CHILD), + (A, CallKind::Raw, ROOT), + ], + ), + }, + 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). + 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, + }, +]; + +#[test] +fn key_rows() { + check_rows(ROWS); +} 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..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 @@ -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,13 +301,22 @@ pub(super) struct Row { pub(super) effects: fn(&NotifyFixture) -> String, } -/// 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`. +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 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), @@ -344,6 +356,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], @@ -358,6 +388,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 + ), } } @@ -384,7 +420,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) @@ -477,17 +517,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"); } } @@ -515,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 new file mode 100644 index 000000000..193e61936 --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_pointer_input.rs @@ -0,0 +1,1685 @@ +//! 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 +//! 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. +//! 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, +}; +use crate::{ + core_loop::InputOrigin, + host_x11::PointerEventKind, + server::Xi1SyncState, + xinput::{DEVICEID_MASTER_POINTER, DEVICEID_XTEST_POINTER}, +}; +use yserver_protocol::x11::{ClientId, ResourceId}; + +/// Core ButtonPressMask, ButtonReleaseMask 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), 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, and the device id the registry gives it. +const XTEST_MASTER: InputOrigin = InputOrigin::XTest(DEVICEID_MASTER_POINTER); +const XTEST_SLAVE: InputOrigin = InputOrigin::XTest(DEVICEID_XTEST_POINTER); + +const fn button(origin: InputOrigin, kind: PointerEventKind, to: (i16, i16)) -> Step { + Step::Event(Drive::Pointer { + origin, + kind, + button: 1, + to, + delta: (0, 0), + }) +} + +const fn press(origin: InputOrigin) -> Step { + button(origin, PointerEventKind::ButtonPress, 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) -> 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_POINTER, + 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_POINTER, + 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); + +/// 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); + +// ---- setup helpers ------------------------------------------------------- + +/// 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)) { + drive( + f, + Drive::Pointer { + origin: XTEST_MASTER, + kind: PointerEventKind::MotionNotify, + button: 0, + to: at, + delta: (0, 0), + }, + ); +} + +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; + +/// `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); +} + +/// `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(&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, owner, XI_MAJOR, XI_PASSIVE_GRAB_DEVICE, &body); +} + +/// 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) { + 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 +/// 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. +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(&[MODE, 0]); + 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) { + 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 +// window G is the root unless a row says otherwise: it is on no selection. + +/// 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_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); + select_core(f, A, CHILD, CORE_BUTTON_PRESS); +} + +/// 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); + select_core(f, A, CHILD, CORE_BUTTON_PRESS); +} + +/// 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); + register_physical_pointer(f); + drive( + f, + Drive::Pointer { + origin: PHYSICAL_POINTER, + kind: PointerEventKind::ButtonPress, + button: 1, + to: POINTER, + delta: (0, 0), + }, + ); + 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) { + 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); +} + +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); +} + +/// 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. +fn setup_p12(f: &mut NotifyFixture) { + tree(f); + select_core(f, B, CHILD, CORE_BUTTON_PRESS); + 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) { + tree(f); + 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) { + setup_p14_xi2_master_from_slave(f); + select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); +} + +/// 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); +} + +/// An async `GrabButton` with owner_events on G: the activation dispatch writes +/// 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 +/// 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); + select_xi2(f, A, FOCUS, DEVICEID_MASTER_POINTER, XI_BUTTON_PRESS); + grab_button(f, A, ROOT, true, false); +} + +/// 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 +} + +/// 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 XI1 class of the slave's `DeviceMotionNotify`. +fn xi1_slave_motion() -> u32 { + xi1_class( + DEVICEID_XTEST_POINTER, + crate::xinput::XI_DEVICE_MOTION_NOTIFY_OFFSET, + ) +} + +fn setup_p16(f: &mut NotifyFixture) { + tree(f); + select_core(f, A, CHILD, CORE_BUTTON_PRESS); +} + +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); +} + +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()]); +} + +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); + select_xi1(f, A, CHILD, &[xi1_slave_press()]); + select_xi1( + f, + B, + CHILD, + &[xi1_slave_press(), xi1_grab_class(DEVICEID_XTEST_POINTER)], + ); +} + +/// 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); + 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, + ); +} + +/// 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(f); + select_xi2(f, A, CHILD, DEVICEID_MASTER_POINTER, XI_MOTION); + select_xi2(f, B, FOCUS, DEVICEID_MASTER_POINTER, XI_MOTION); +} + +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) { + tree(f); + park_pointer(f); + select_xi1(f, A, CHILD, &[xi1_slave_motion()]); +} + +fn setup_p24(f: &mut NotifyFixture) { + setup_p25(f); + select_xi1(f, B, FOCUS, &[xi1_slave_motion()]); +} + +/// 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, OWNER_EVENTS); +} + +/// A also selects the press on P. +fn setup_p26_foreign_rejects(f: &mut NotifyFixture) { + setup_p26::(f); + 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_later_window(f: &mut NotifyFixture) { + tree(f); + select_xi1(f, B, CHILD, &[xi1_slave_press()]); + select_xi1(f, A, FOCUS, &[xi1_slave_press()]); + 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); +} + +// ---- 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), +]); + +/// 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. +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, + }) +} + +/// 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, + }) +} + +const fn xi1_implicit(owner: u32, window: u32) -> Grab { + Grab::Xi1 { + device: DEVICEID_XTEST_POINTER, + owner, + window, + } +} + +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, + state: Xi1SyncState::FrozenWithEvent, + other: None, + stored: Some(Held::HostPointer { + kind: PointerEventKind::ButtonPress, + detail: 1, + }), +}; + +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, + }, +}; + +const SLAVE_PASSIVE_GRAB: Grab = Grab::SlavePointer { + device: DEVICEID_XTEST_POINTER, + grab: PointerGrab { + owner: A, + window: ROOT, + implicit: false, + passive: true, + via_xi2: true, + }, +}; + +const P26_OWNER_EVENTS: Scenario = Scenario { + setup: setup_p26::, + 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, ROOT)], + ), + 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 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)], +); +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( + &[ + (A, Kind::Xi1Motion(DEVICEID_XTEST_POINTER), CHILD), + (A, Kind::Xi1Valuator(DEVICEID_XTEST_POINTER), 0), + ], + &[(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)]); + +const P14_FROM_SLAVE: Scenario = Scenario { + setup: setup_p14_xi2_master_from_slave, + steps: &[press(XTEST_SLAVE)], + 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: 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: 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 P27_THAWED_XI1_FILTER: Scenario = Scenario { + setup: setup_p27_thawed_xi1_filter, + steps: &[ + press(XTEST_SLAVE), + Step::Request(allow_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, + ], + ), + order: CallOrder::Total, +}; + +// ---- 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 + // 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, + }, + // 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)], + ), + }, + // 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], + ), + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, CHILD)], + 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 + // 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: frames_and_calls( + &[ + (A, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS), + (B, Kind::Xi2(DEVICEID_MASTER_POINTER), FOCUS), + ], + &[(A, CallKind::Xi2, FOCUS), (B, CallKind::Xi2, FOCUS)], + ), + 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, + }, + }, + // 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 + }, + }, + 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 { + 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: A_CORE_CHILD, + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, CHILD)], + denied: calls_only(&[ + (A, CallKind::Core, CHILD), + (B, CallKind::Xi2, CHILD), + (A, CallKind::Core, CHILD), + ]), + }, + // 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). + InputRow { + name: "p11_owner_qualifies_in_a_later_protocol", + scenario: &Scenario { + setup: setup_p11, + steps: &[press(XTEST_MASTER)], + allow: A_CORE_CHILD, + 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: 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", + scenario: &Scenario { + setup: setup_p12::, + steps: &[press(XTEST_MASTER)], + allow: calls_only(&[(A, CallKind::Core, ROOT)]), + order: CallOrder::Total, + }, + 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 { + steps: &[ + press(XTEST_SLAVE), + motion(XTEST_SLAVE), + Step::Request(allow_master::, &[]), + ], + 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: 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 + // 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 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; 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 { + steps: &[ + press(XTEST_MASTER), + motion(XTEST_MASTER), + Step::Request( + allow_master::, + &[press(XTEST_MASTER), motion(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, XI2_PRESS_CALL, CHILD), + (A, MOTION_CALL, CHILD), + ], + grab: Some(&[implicit(A, CHILD, true)]), + ..P14_FROM_MASTER.allow + }, + ..P14_FROM_MASTER + }, + deny: &[(A, CallKind::Xi2, CHILD)], + denied: with_grab( + calls_only(&[(A, CallKind::Xi2, CHILD), (A, XI2_PRESS_CALL, CHILD)]), + &[], + ), + }, + // 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 { + steps: &[press(XTEST_SLAVE), motion(XTEST_SLAVE)], + allow: Outcome { + grab: Some(&[passive(ROOT, true), FROZEN_BY_PRESS, MASTER_PART_QUEUED]), + ..P14_OWNER_EVENTS.allow + }, + ..P14_OWNER_EVENTS + }, + deny: &[(A, CallKind::Xi2, ROOT)], + 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. + // 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: frames_and_calls(&[(A, Kind::Core, ROOT)], &[(A, CallKind::Core, ROOT)]), + order: CallOrder::Total, + }, + deny: &[(A, CallKind::Core, CHILD)], + denied: frames_and_calls(&[(A, Kind::Core, ROOT)], &[(A, CallKind::Core, ROOT)]), + }, + // 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: 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: 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 + // denied copy still enters the owner preference is not caught by any probe.) + InputRow { + name: "p17_xi2_owner_preference_among_allowed", + scenario: &Scenario { + setup: setup_p17, + steps: &[press(XTEST_MASTER)], + 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: 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 + // 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: 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: 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)], + ), + }, + 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). + // 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: 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: 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)], + ), + }, + // 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 + // 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: 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), + ], + &[ + (SEND_CLIENT, RAW_BUTTON_PRESS_CALL, ROOT), + (A, RAW_BUTTON_PRESS_CALL, ROOT), + (B, RAW_BUTTON_PRESS_CALL, ROOT), + ], + ), + 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: frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_MASTER_POINTER), CHILD)], + &[(A, SCROLL_MOTION_CALL, CHILD)], + ), + 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, + }, + }, + // 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", + scenario: &Scenario { + setup: setup_scroll_stop_two_forms, + steps: &[SCROLL_STOP], + 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), + ], + &[(A, STOP_BATCH, CHILD)], + ), + order: CallOrder::Total, + }, + deny: &[(A, STOP_BATCH, CHILD)], + denied: calls_only(&[(A, STOP_BATCH, CHILD)]), + }, + // 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: A_XI1_MOTION_AT_CHILD, + 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: A_XI1_MOTION_AT_CHILD, + order: CallOrder::Total, + }, + deny: &[(A, XI1_MOTION_CALL, CHILD)], + denied: calls_only(&[(A, XI1_MOTION_CALL, CHILD)]), + }, + // 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::, + steps: &[press(XTEST_SLAVE)], + 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: 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. + 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, + }, + // 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: 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: 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)], + ), + }, + // 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: 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)], + 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, + }, + }, + InputRow { + name: "p27_thawed_xi1_press_filter_asks_no_xi2_copy", + scenario: &P27_THAWED_XI1_FILTER, + deny: &[(A, XI2_PRESS_CALL, CHILD)], + 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, + ], + ), + }, + // 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: frames_and_calls( + &[(A, Kind::Xi2(DEVICEID_XTEST_POINTER), CHILD)], + &[(A, CallKind::Xi2, CHILD)], + ), + order: CallOrder::Total, + }, + deny: &[(A, XI2_PRESS_CALL, CHILD)], + 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, + )], + ), + }, +]; + +#[test] +fn pointer_rows() { + check_rows(ROWS); +} + +#[test] +fn multi_event_request_runner_rejects_swapped_press_and_motion_calls() { + let row = ROWS + .iter() + .find(|row| { + row.name == "p14_denied_xi2_activating_press_from_a_master_origin_still_freezes@replay" + }) + .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/access_replay_input.rs b/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs new file mode 100644 index 000000000..2d0e564ef --- /dev/null +++ b/crates/yserver-core/src/core_loop/process_request/tests/access_replay_input.rs @@ -0,0 +1,702 @@ +//! 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_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); + +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 { + xi1_pointer_class_for(DEVICEID_XTEST_POINTER, offset) +} + +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) { + 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); + select_xi2(f, B, FOCUS, DEVICEID_MASTER_KEYBOARD, XI_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); + 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); + 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 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 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 { + 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_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: &[ + button_press(XTEST_MASTER_POINTER), + Step::Request( + allow_core_events::<2>, + &[button_press(XTEST_MASTER_POINTER)], + ), + ], + 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, + })], + ), + 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: with_grab( + frames_and_calls( + &[ + (A, Kind::Core, ROOT), + (B, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), FOCUS), + ], + &[(A, CORE_KEY_PRESS_CALL, ROOT), (B, CallKind::Xi2, FOCUS)], + ), + &[], + ), + 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::Checkpoint(R1_QUEUE_CHECKPOINT), + Step::Request(allow_core_events::<6>, &[]), + ], + 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, + ], + ), + 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::Checkpoint(R7_QUEUE_CHECKPOINT), + Step::Request( + allow_core_events::<3>, + &[ + raw_key_press(XTEST_SLAVE_KEYBOARD), + key_press(XTEST_SLAVE_KEYBOARD), + ], + ), + ], + 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, +}; + +const R6_THAW: Scenario = Scenario { + setup: setup_r6_queued_motion, + steps: &[ + button_press(XTEST_MASTER_POINTER), + motion(XTEST_MASTER_POINTER), + Step::Checkpoint(R6_QUEUE_CHECKPOINT), + 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: &[ + button_press(XTEST_SLAVE_POINTER), + Step::Request( + allow_xi1_pointer_events::<2>, + &[button_press(XTEST_SLAVE_POINTER)], + ), + ], + 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: 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, +}; + +const ROWS: &[InputRow] = &[ + InputRow { + name: "r1_equal_key_xi1_routed_entries_share_freeze_pass", + scenario: &R1_XI1_THAW, + deny: &[], + 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, + ], + ), + }, + 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: 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, + })], + ), + }, + // 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: with_grab( + frames_and_calls( + &[(B, Kind::Xi2(DEVICEID_MASTER_KEYBOARD), FOCUS)], + &[(A, CORE_KEY_PRESS_CALL, ROOT), (B, CallKind::Xi2, 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 { + name: "r5_replay_keyboard_rechecks_the_focus", + 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), + ]), + &[], + ), + }, + 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`. + 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: 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], + ), + }, + 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, + deny: &[ + (A, XI1_BUTTON_PRESS_CALL, ROOT), + (B, XI1_BUTTON_PRESS_CALL, CHILD), + ], + 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, + }], + ), + }, + // 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: with_grab( + calls_only(&[(A, XI1_BUTTON_PRESS_CALL, ROOT)]), + &[A_ROOT_XI1_POINTER_GRAB, XI1_POINTER_PRESS_STORED], + ), + }, +]; + +#[test] +fn replay_rows() { + check_rows(ROWS) +} 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..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 @@ -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. @@ -14,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::{ @@ -222,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) } @@ -313,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, @@ -324,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, @@ -980,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); @@ -997,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; } @@ -1106,84 +1097,9 @@ 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"); } } } - -/// 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/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<'_>, 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..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 @@ -7,6 +7,8 @@ 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; mod access_notify_lifecycle; @@ -14,11 +16,13 @@ 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; mod access_record; mod access_render; +mod access_replay_input; mod access_resources; mod access_saver; mod access_send; 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..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()); @@ -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/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(); 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). 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 diff --git a/docs/status.md b/docs/status.md index ee96d7246..626c1f34d 100644 --- a/docs/status.md +++ b/docs/status.md @@ -39,6 +39,9 @@ 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. - **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`). 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..5b28688cb --- /dev/null +++ b/docs/superpowers/plans/2026-12-01-access-control-pr4c-keyboard.md @@ -0,0 +1,147 @@ +# 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` (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 + +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. 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 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` 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. + - `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. + - `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, 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`. + +### 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`, 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); + - 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. 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, and the trace has no call for F (the owner qualified first). + - `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 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`. + +### 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. 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 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. +- [ ] **Step 5: commit** `feat(access): Receive checks raw key copies and the grab leg`. 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..fdab4a3a3 --- /dev/null +++ b/docs/superpowers/plans/2026-12-01-access-control-pr4c-pointer.md @@ -0,0 +1,194 @@ +# 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`. 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`) 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 (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:`. +- 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. 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, 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, `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, 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`: + ```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(&mut self, state: &ServerState, client: ClientId, + subject: EventSubject, events: &EventBatch<'_>) -> bool; + } + ``` + 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; + - 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: +- **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. `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`. 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): + - `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, 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 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). +- [ ] **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) +- 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`, `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 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 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): + - `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): 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. +- [ ] **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) +- 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, else the parent. Its XI1 recipients are decided: the router writes them unchecked and picks the XI1 implicit owner among them. + +- [ ] **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. + - `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`. + +### 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` :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))` 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:** + - `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 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. +- [ ] **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_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`, `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: +- 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) 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`: 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` 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). +- [ ] **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`. 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..afd1157d2 --- /dev/null +++ b/docs/superpowers/plans/2026-12-02-access-control-pr4c-input-tests.md @@ -0,0 +1,73 @@ +# 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. 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; 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. + +**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. `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, 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. +- 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. +- 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 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: probe baseline, the runner, and the key table + +**Files:** +- 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) + 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, 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 } +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, 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`. 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..47111b2ac --- /dev/null +++ b/docs/superpowers/plans/2026-12-02-access-control-pr4c-replay.md @@ -0,0 +1,86 @@ +# 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 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` 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 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 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 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 (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 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) `sdd-p3/probes.py`, `sdd-p3/replay.py` as in Global Constraints. + +**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 (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 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`. + +### Task 2: the XI1 thaw filter asks no XI2 copy + +**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` 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).** + - `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) }`), registered in `process_request/tests/mod.rs` next to `access_key_input`; input-only helpers go in `access_input_support.rs`. + +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 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`. + +### Task 4: PR readiness + +**Files:** Modify `docs/status.md`. + +- [ ] **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`. 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..b66173480 --- /dev/null +++ b/docs/superpowers/plans/2026-12-03-access-control-pr4c-review.md @@ -0,0 +1,213 @@ +# 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. +- 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:** 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. +- 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 + +**"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. + +**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 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. + +**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; +- 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 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 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. + - 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 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 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 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 + +**Files:** +- `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 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.** + - 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) 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). +- `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. + - 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.** + - 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 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`, 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. + +- [ ] **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. + + Keep every comparison listed in the Global Constraints. +- [ ] **Step 3: Tables.** + - 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.** + - 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`.