diff --git a/niri-config/src/binds.rs b/niri-config/src/binds.rs index e1a6a546..d02aa595 100644 --- a/niri-config/src/binds.rs +++ b/niri-config/src/binds.rs @@ -393,6 +393,10 @@ pub enum Action { MruSetScope(MruScope), #[knuffel(skip)] MruCycleScope, + + // Doesn't look like knuffel allows gating on #[cfg(test)]... + #[knuffel(skip)] + TestAction, } impl From for Action { diff --git a/src/input/mod.rs b/src/input/mod.rs index 488e2688..3c0f04c8 100644 --- a/src/input/mod.rs +++ b/src/input/mod.rs @@ -2428,6 +2428,12 @@ impl State { self.niri.queue_redraw_mru_output(); } } + Action::TestAction => { + #[cfg(test)] + { + self.niri.test_action_count += 1; + } + } } } diff --git a/src/niri.rs b/src/niri.rs index 6d4b957c..abebcc2e 100644 --- a/src/niri.rs +++ b/src/niri.rs @@ -435,6 +435,9 @@ pub struct Niri { #[cfg(feature = "xdp-gnome-screencast")] pub casting: Screencasting, + + #[cfg(test)] + pub test_action_count: usize, } smithay::delegate_dispatch2!(State); @@ -2776,6 +2779,9 @@ impl Niri { #[cfg(feature = "xdp-gnome-screencast")] casting: screencasting, + + #[cfg(test)] + test_action_count: 0, }; niri.reset_pointer_inactivity_timer(); diff --git a/src/tests/binds.rs b/src/tests/binds.rs new file mode 100644 index 00000000..f4627e9a --- /dev/null +++ b/src/tests/binds.rs @@ -0,0 +1,284 @@ +use std::fmt::Write as _; + +use insta::assert_snapshot; +use niri_config::{Action, Config}; +use smithay::backend::input::{InputEvent, InputTime, KeyState, Keycode}; +use smithay::input::keyboard::xkb::Keymap; +use wayland_client::protocol::wl_surface::WlSurface; + +use crate::tests::client::ClientId; +use crate::tests::fixture::Fixture; +use crate::tests::test_input_backend::{TestInputBackend, TestKeyboardKeyEvent}; + +enum Op { + Press(Keycode), + Release(Keycode), +} + +fn parse(keymap: &Keymap, input: &str) -> Vec { + let mut ops = Vec::new(); + for part in input.split_ascii_whitespace() { + let name = &part[1..]; + let Some(key) = keymap.key_by_name(name) else { + panic!("unknown key {name}"); + }; + + let c = part.bytes().next().unwrap(); + let op = match c { + b'+' => Op::Press(key), + b'-' => Op::Release(key), + _ => panic!("keys must begin with + or -, got {c}"), + }; + + ops.push(op); + } + ops +} + +fn set_up(config: &str) -> (Fixture, ClientId, WlSurface) { + let mut config = Config::parse_mem(config).unwrap(); + // knuffel doesn't understand #[cfg(test)]... + for bind in &mut config.binds.0 { + bind.action = Action::TestAction; + } + + let mut f = Fixture::with_config(config); + f.add_output(1, (1920, 1080)); + + let id = f.add_client(); + let window = f.client(id).create_window(); + let surface = window.surface.clone(); + window.commit(); + f.roundtrip(id); + + let window = f.client(id).window(&surface); + window.attach_new_buffer(); + window.ack_last_and_commit(); + f.roundtrip(id); + + let _ = f.client(id).state.recent_keyboard_events(&surface); + + (f, id, surface) +} + +fn run_f(f: &mut Fixture, id: ClientId, surface: &WlSurface, input: &str) -> String { + let state = f.niri_state(); + let keyboard = state.niri.seat.get_keyboard().unwrap(); + let ops = keyboard.with_xkb_state(state, |xkb| { + let xkb = xkb.xkb().lock().unwrap(); + let keymap = unsafe { xkb.keymap() }; + parse(keymap, input) + }); + + let mut rv = String::new(); + + for op in ops { + let (code, key_state) = match op { + Op::Press(code) => (code, KeyState::Pressed), + Op::Release(code) => (code, KeyState::Released), + }; + + let state = f.niri_state(); + let keyboard = state.niri.seat.get_keyboard().unwrap(); + keyboard.with_xkb_state(state, |xkb| { + let xkb = xkb.xkb().lock().unwrap(); + let xkb_state = unsafe { xkb.state() }; + let keymap = xkb_state.get_keymap(); + + let c = match key_state { + KeyState::Pressed => "+", + KeyState::Released => "-", + }; + + let name = keymap.key_get_name(code).unwrap_or("None"); + let keysym = xkb_state.key_get_one_sym(code); + + let _ = writeln!(&mut rv, "{c}{name} {:>3} {keysym:?}", code.raw()); + }); + + let prev = state.niri.test_action_count; + + state.process_input_event(InputEvent::::Keyboard { + event: TestKeyboardKeyEvent { + time: InputTime::from_micros(0), + code, + state: key_state, + count: 1, // niri doesn't use this + }, + }); + + let diff = f.niri().test_action_count - prev; + for _ in 0..diff { + let _ = writeln!(&mut rv, " niri test-action"); + } + + f.roundtrip(id); + for event in f.client(id).state.recent_keyboard_events(surface) { + let _ = writeln!(&mut rv, " surface {event}"); + } + } + + rv +} + +fn run(config: &str, input: &str) -> String { + let (mut f, id, surface) = set_up(config); + run_f(&mut f, id, &surface, input) +} + +#[test] +fn combos() { + let c = " + binds { + Mod+Ctrl+Q { close-window; } + } + "; + + // Action press/release. + assert_snapshot!( + run(c, "+LWIN +LCTL +LatQ -LatQ -LCTL -LWIN"), + @" + +LWIN 133 XK_Super_L + surface modifiers: depressed=64, latched=0, locked=0, group=0 + surface key pressed: 125 + +LCTL 37 XK_Control_L + surface modifiers: depressed=68, latched=0, locked=0, group=0 + surface key pressed: 29 + +AD01 24 XK_q + niri test-action + -AD01 24 XK_q + -LCTL 37 XK_Control_L + surface modifiers: depressed=64, latched=0, locked=0, group=0 + surface key released: 29 + -LWIN 133 XK_Super_L + surface modifiers: depressed=0, latched=0, locked=0, group=0 + surface key released: 125 + " + ); + + // Extra Alt = no action. + assert_snapshot!( + run(c, "+LWIN +LCTL +LALT +LatQ -LatQ -LALT -LCTL -LWIN"), + @" + +LWIN 133 XK_Super_L + surface modifiers: depressed=64, latched=0, locked=0, group=0 + surface key pressed: 125 + +LCTL 37 XK_Control_L + surface modifiers: depressed=68, latched=0, locked=0, group=0 + surface key pressed: 29 + +LALT 64 XK_Alt_L + surface modifiers: depressed=76, latched=0, locked=0, group=0 + surface key pressed: 56 + +AD01 24 XK_q + surface key pressed: 16 + -AD01 24 XK_q + surface key released: 16 + -LALT 64 XK_Alt_L + surface modifiers: depressed=68, latched=0, locked=0, group=0 + surface key released: 56 + -LCTL 37 XK_Control_L + surface modifiers: depressed=64, latched=0, locked=0, group=0 + surface key released: 29 + -LWIN 133 XK_Super_L + surface modifiers: depressed=0, latched=0, locked=0, group=0 + surface key released: 125 + " + ); + + // Key that doesn't correspond to any bind. + assert_snapshot!( + run(c, "+LWIN +LCTL +LatA -LatA -LCTL -LWIN"), + @" + +LWIN 133 XK_Super_L + surface modifiers: depressed=64, latched=0, locked=0, group=0 + surface key pressed: 125 + +LCTL 37 XK_Control_L + surface modifiers: depressed=68, latched=0, locked=0, group=0 + surface key pressed: 29 + +AC01 38 XK_a + surface key pressed: 30 + -AC01 38 XK_a + surface key released: 30 + -LCTL 37 XK_Control_L + surface modifiers: depressed=64, latched=0, locked=0, group=0 + surface key released: 29 + -LWIN 133 XK_Super_L + surface modifiers: depressed=0, latched=0, locked=0, group=0 + surface key released: 125 + " + ); + + // Press action, press arbitrary, release action, release arbitrary. + assert_snapshot!( + run(c, "+LWIN +LCTL +LatQ +LatA -LatQ -LatA -LCTL -LWIN"), + @" + +LWIN 133 XK_Super_L + surface modifiers: depressed=64, latched=0, locked=0, group=0 + surface key pressed: 125 + +LCTL 37 XK_Control_L + surface modifiers: depressed=68, latched=0, locked=0, group=0 + surface key pressed: 29 + +AD01 24 XK_q + niri test-action + +AC01 38 XK_a + surface key pressed: 30 + -AD01 24 XK_q + -AC01 38 XK_a + surface key released: 30 + -LCTL 37 XK_Control_L + surface modifiers: depressed=64, latched=0, locked=0, group=0 + surface key released: 29 + -LWIN 133 XK_Super_L + surface modifiers: depressed=0, latched=0, locked=0, group=0 + surface key released: 125 + " + ); + + // Press arbitrary, press action, release arbitrary, release action. + assert_snapshot!( + run(c, "+LWIN +LCTL +LatA +LatQ -LatA -LatQ -LCTL -LWIN"), + @" + +LWIN 133 XK_Super_L + surface modifiers: depressed=64, latched=0, locked=0, group=0 + surface key pressed: 125 + +LCTL 37 XK_Control_L + surface modifiers: depressed=68, latched=0, locked=0, group=0 + surface key pressed: 29 + +AC01 38 XK_a + surface key pressed: 30 + +AD01 24 XK_q + niri test-action + -AC01 38 XK_a + surface key released: 30 + -AD01 24 XK_q + -LCTL 37 XK_Control_L + surface modifiers: depressed=64, latched=0, locked=0, group=0 + surface key released: 29 + -LWIN 133 XK_Super_L + surface modifiers: depressed=0, latched=0, locked=0, group=0 + surface key released: 125 + " + ); + + // Trigger action then release mods. + assert_snapshot!( + run(c, "+LWIN +LCTL +LatQ -LCTL -LWIN -LatQ"), + @" + +LWIN 133 XK_Super_L + surface modifiers: depressed=64, latched=0, locked=0, group=0 + surface key pressed: 125 + +LCTL 37 XK_Control_L + surface modifiers: depressed=68, latched=0, locked=0, group=0 + surface key pressed: 29 + +AD01 24 XK_q + niri test-action + -LCTL 37 XK_Control_L + surface modifiers: depressed=64, latched=0, locked=0, group=0 + surface key released: 29 + -LWIN 133 XK_Super_L + surface modifiers: depressed=0, latched=0, locked=0, group=0 + surface key released: 125 + -AD01 24 XK_q + " + ); +} diff --git a/src/tests/client.rs b/src/tests/client.rs index b8599db6..c2e15a84 100644 --- a/src/tests/client.rs +++ b/src/tests/client.rs @@ -30,8 +30,10 @@ use wayland_client::protocol::wl_buffer::{self, WlBuffer}; use wayland_client::protocol::wl_callback::{self, WlCallback}; use wayland_client::protocol::wl_compositor::WlCompositor; use wayland_client::protocol::wl_display::WlDisplay; +use wayland_client::protocol::wl_keyboard::{self, WlKeyboard}; use wayland_client::protocol::wl_output::{self, WlOutput}; use wayland_client::protocol::wl_registry::{self, WlRegistry}; +use wayland_client::protocol::wl_seat::{self, WlSeat}; use wayland_client::protocol::wl_surface::{self, WlSurface}; use wayland_client::{Connection, Dispatch, Proxy as _, QueueHandle}; @@ -51,6 +53,8 @@ pub struct State { pub globals: Vec, pub outputs: HashMap, + pub surfaces: HashMap, + pub seats: HashMap, pub compositor: Option, pub xdg_wm_base: Option, @@ -91,6 +95,41 @@ pub struct LayerSurface { pub configures_looked_at: usize, } +#[derive(Debug, Default)] +pub struct Seat { + pub keyboard: Option, +} + +#[derive(Debug)] +pub struct Surface { + pub keyboard_events_received: Vec, + pub keyboard_events_looked_at: usize, +} + +#[derive(Debug)] +pub struct Keyboard { + pub proxy: WlKeyboard, + pub surface: Option, +} + +#[derive(Debug)] +pub enum KeyboardEvent { + Enter { + keys: Vec, + }, + Leave, + Key { + key: u32, + state: wl_keyboard::KeyState, + }, + Modifiers { + depressed: u32, + latched: u32, + locked: u32, + group: u32, + }, +} + #[derive(Debug, Clone, Default)] pub struct Configure { pub size: (i32, i32), @@ -138,6 +177,41 @@ impl ClientId { } } +impl fmt::Display for KeyboardEvent { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + KeyboardEvent::Enter { keys } => { + write!(f, "enter: {keys:?}")?; + } + KeyboardEvent::Leave => { + write!(f, "leave")?; + } + KeyboardEvent::Key { key, state } => { + let action = match state { + wl_keyboard::KeyState::Released => "released", + wl_keyboard::KeyState::Pressed => "pressed", + wl_keyboard::KeyState::Repeated => "repeated", + _ => unreachable!(), + }; + write!(f, "key {action}: {key}")?; + } + KeyboardEvent::Modifiers { + depressed, + latched, + locked, + group, + } => { + write!( + f, + "modifiers: depressed={depressed}, latched={latched}, \ + locked={locked}, group={group}" + )?; + } + } + Ok(()) + } +} + impl fmt::Display for Configure { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "size: {} × {}, ", self.size.0, self.size.1)?; @@ -179,6 +253,8 @@ impl Client { qh: qh.clone(), globals: Vec::new(), outputs: HashMap::new(), + surfaces: HashMap::new(), + seats: HashMap::new(), compositor: None, xdg_wm_base: None, layer_shell: None, @@ -249,12 +325,25 @@ impl Client { } impl State { - pub fn create_window(&mut self) -> &mut Window { + pub fn create_surface(&mut self) -> WlSurface { let compositor = self.compositor.as_ref().unwrap(); + let surface = compositor.create_surface(&self.qh, ()); + self.surfaces.insert( + surface.clone(), + Surface { + keyboard_events_received: Vec::new(), + keyboard_events_looked_at: 0, + }, + ); + surface + } + + pub fn create_window(&mut self) -> &mut Window { + let surface = self.create_surface(); + let xdg_wm_base = self.xdg_wm_base.as_ref().unwrap(); let viewporter = self.viewporter.as_ref().unwrap(); - let surface = compositor.create_surface(&self.qh, ()); let xdg_surface = xdg_wm_base.get_xdg_surface(&surface, &self.qh, ()); let xdg_toplevel = xdg_surface.get_toplevel(&self.qh, ()); let viewport = viewporter.get_viewport(&surface, &self.qh, ()); @@ -291,11 +380,11 @@ impl State { layer: zwlr_layer_shell_v1::Layer, namespace: String, ) -> &mut LayerSurface { - let compositor = self.compositor.as_ref().unwrap(); + let surface = self.create_surface(); + let layer_shell = self.layer_shell.as_ref().unwrap(); let viewporter = self.viewporter.as_ref().unwrap(); - let surface = compositor.create_surface(&self.qh, ()); let layer_surface = layer_shell.get_layer_surface(&surface, output, layer, namespace, &self.qh, ()); let viewport = viewporter.get_viewport(&surface, &self.qh, ()); @@ -323,6 +412,14 @@ impl State { .find(|w| w.surface == *surface) .unwrap() } + + pub fn recent_keyboard_events( + &mut self, + surface: &WlSurface, + ) -> impl Iterator + '_ { + let surface = self.surfaces.get_mut(surface).unwrap(); + surface.recent_keyboard_events() + } } impl Window { @@ -476,6 +573,14 @@ impl LayerSurface { } } +impl Surface { + pub fn recent_keyboard_events(&mut self) -> impl Iterator { + let start = self.keyboard_events_looked_at; + self.keyboard_events_looked_at = self.keyboard_events_received.len(); + self.keyboard_events_received[start..].iter() + } +} + impl Dispatch> for State { fn event( _state: &mut Self, @@ -529,6 +634,11 @@ impl Dispatch for State { let version = min(version, WlOutput::interface().version); let output = registry.bind(name, version, qh, ()); state.outputs.insert(output, String::new()); + } else if interface == WlSeat::interface().name { + let version = min(version, WlSeat::interface().version); + state + .seats + .insert(registry.bind(name, version, qh, ()), Seat::default()); } let global = Global { @@ -567,6 +677,107 @@ impl Dispatch for State { } } +impl Dispatch for State { + fn event( + state: &mut Self, + seat: &WlSeat, + event: ::Event, + _data: &(), + _conn: &Connection, + qh: &QueueHandle, + ) { + match event { + wl_seat::Event::Capabilities { capabilities } => { + let capabilities = capabilities.into_result().unwrap(); + let data = state.seats.get_mut(seat).unwrap(); + + if capabilities.contains(wl_seat::Capability::Keyboard) { + if data.keyboard.is_none() { + let keyboard = Keyboard { + proxy: seat.get_keyboard(qh, seat.clone()), + surface: None, + }; + data.keyboard = Some(keyboard); + } + } else { + if let Some(keyboard) = data.keyboard.take() { + keyboard.proxy.release(); + } + } + } + wl_seat::Event::Name { .. } => (), + _ => unreachable!(), + } + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + _keyboard: &WlKeyboard, + event: ::Event, + seat: &WlSeat, + _conn: &Connection, + _qhandle: &QueueHandle, + ) { + let seat = state.seats.get_mut(seat).unwrap(); + let keyboard = seat.keyboard.as_mut().unwrap(); + + match event { + wl_keyboard::Event::Keymap { .. } => (), + wl_keyboard::Event::Enter { surface, keys, .. } => { + keyboard.surface = Some(surface.clone()); + + let event = KeyboardEvent::Enter { keys }; + let surface = state.surfaces.get_mut(&surface).unwrap(); + surface.keyboard_events_received.push(event); + } + wl_keyboard::Event::Leave { .. } => { + let surface = keyboard.surface.take().unwrap(); + + let event = KeyboardEvent::Leave; + let surface = state.surfaces.get_mut(&surface).unwrap(); + surface.keyboard_events_received.push(event); + } + wl_keyboard::Event::Key { + key, + state: key_state, + .. + } => { + let key_state = key_state.into_result().unwrap(); + let surface = keyboard.surface.clone().unwrap(); + + let event = KeyboardEvent::Key { + key, + state: key_state, + }; + let surface = state.surfaces.get_mut(&surface).unwrap(); + surface.keyboard_events_received.push(event); + } + wl_keyboard::Event::Modifiers { + mods_depressed, + mods_latched, + mods_locked, + group, + .. + } => { + let surface = keyboard.surface.clone().unwrap(); + + let event = KeyboardEvent::Modifiers { + depressed: mods_depressed, + latched: mods_latched, + locked: mods_locked, + group, + }; + let surface = state.surfaces.get_mut(&surface).unwrap(); + surface.keyboard_events_received.push(event); + } + wl_keyboard::Event::RepeatInfo { .. } => (), + _ => unreachable!(), + } + } +} + impl Dispatch for State { fn event( _state: &mut Self, diff --git a/src/tests/mod.rs b/src/tests/mod.rs index 314feb06..ad66c822 100644 --- a/src/tests/mod.rs +++ b/src/tests/mod.rs @@ -3,8 +3,10 @@ use fixture::Fixture; mod client; mod fixture; mod server; +mod test_input_backend; mod animations; +mod binds; mod floating; mod fullscreen; mod layer_shell; diff --git a/src/tests/test_input_backend.rs b/src/tests/test_input_backend.rs new file mode 100644 index 00000000..e9355f3e --- /dev/null +++ b/src/tests/test_input_backend.rs @@ -0,0 +1,104 @@ +use smithay::backend::input::{ + Device, DeviceCapability, Event, InputBackend, InputTime, KeyState, KeyboardKeyEvent, Keycode, + UnusedEvent, +}; +use smithay::output::Output; + +use crate::input::backend_ext::NiriInputDevice; + +pub struct TestInputBackend; + +#[derive(PartialEq, Eq, Hash)] +pub struct TestInputDevice; + +pub struct TestKeyboardKeyEvent { + pub time: InputTime, + pub code: Keycode, + pub state: KeyState, + pub count: u32, +} + +impl InputBackend for TestInputBackend { + type Device = TestInputDevice; + + type KeyboardKeyEvent = TestKeyboardKeyEvent; + type PointerAxisEvent = UnusedEvent; + type PointerButtonEvent = UnusedEvent; + type PointerMotionEvent = UnusedEvent; + type PointerMotionAbsoluteEvent = UnusedEvent; + + type GestureSwipeBeginEvent = UnusedEvent; + type GestureSwipeUpdateEvent = UnusedEvent; + type GestureSwipeEndEvent = UnusedEvent; + type GesturePinchBeginEvent = UnusedEvent; + type GesturePinchUpdateEvent = UnusedEvent; + type GesturePinchEndEvent = UnusedEvent; + type GestureHoldBeginEvent = UnusedEvent; + type GestureHoldEndEvent = UnusedEvent; + + type TouchDownEvent = UnusedEvent; + type TouchUpEvent = UnusedEvent; + type TouchMotionEvent = UnusedEvent; + type TouchCancelEvent = UnusedEvent; + type TouchFrameEvent = UnusedEvent; + type TabletToolAxisEvent = UnusedEvent; + type TabletToolProximityEvent = UnusedEvent; + type TabletToolTipEvent = UnusedEvent; + type TabletToolButtonEvent = UnusedEvent; + + type SwitchToggleEvent = UnusedEvent; + + type SpecialEvent = UnusedEvent; +} + +impl Device for TestInputDevice { + fn id(&self) -> String { + String::from("test") + } + + fn name(&self) -> String { + String::from("test input device") + } + + fn has_capability(&self, capability: DeviceCapability) -> bool { + matches!(capability, DeviceCapability::Keyboard) + } + + fn usb_id(&self) -> Option<(u32, u32)> { + None + } + + fn syspath(&self) -> Option { + None + } +} + +impl NiriInputDevice for TestInputDevice { + fn output(&self, _state: &crate::niri::State) -> Option { + None + } +} + +impl Event for TestKeyboardKeyEvent { + fn time(&self) -> InputTime { + self.time + } + + fn device(&self) -> ::Device { + TestInputDevice + } +} + +impl KeyboardKeyEvent for TestKeyboardKeyEvent { + fn key_code(&self) -> Keycode { + self.code + } + + fn state(&self) -> KeyState { + self.state + } + + fn count(&self) -> u32 { + self.count + } +}