use crate::error::EmulationError; use super::{Emulation, error::WlrootsEmulationCreationError}; use async_trait::async_trait; use bitflags::bitflags; use std::collections::HashMap; use std::io; use std::os::fd::{AsFd, OwnedFd}; use std::sync::{Arc, Mutex}; use std::time::{SystemTime, UNIX_EPOCH}; use wayland_client::WEnum; use wayland_client::backend::WaylandError; use wayland_client::protocol::wl_keyboard::{self, WlKeyboard}; use wayland_client::protocol::wl_output::WlOutput; use wayland_client::protocol::wl_pointer::{Axis, AxisSource, ButtonState}; use wayland_client::protocol::wl_seat::WlSeat; use wayland_protocols::xdg::xdg_output::zv1::client::{ zxdg_output_manager_v1::ZxdgOutputManagerV1, zxdg_output_v1::{self, ZxdgOutputV1}, }; use wayland_protocols_wlr::virtual_pointer::v1::client::{ zwlr_virtual_pointer_manager_v1::ZwlrVirtualPointerManagerV1 as VpManager, zwlr_virtual_pointer_v1::ZwlrVirtualPointerV1 as Vp, }; use wayland_protocols_misc::zwp_virtual_keyboard_v1::client::{ zwp_virtual_keyboard_manager_v1::ZwpVirtualKeyboardManagerV1 as VkManager, zwp_virtual_keyboard_v1::ZwpVirtualKeyboardV1 as Vk, }; use wayland_client::{ Connection, Dispatch, EventQueue, QueueHandle, delegate_noop, globals::{GlobalListContents, registry_queue_init}, protocol::{wl_registry, wl_seat}, }; use input_event::{Event, KeyboardEvent, PointerEvent, scancode}; use super::error::WaylandBindError; use super::{Edge, EmulationHandle}; /// logical output geometry, used to place the cursor on entry #[derive(Default)] struct OutputGeometry { global_name: u32, xdg_output: Option, pos: (i32, i32), size: (i32, i32), } struct State { keymap: Option<(u32, OwnedFd, u32)>, /// compositor sent a new keymap (layout change) not yet applied keymap_changed: bool, outputs: Vec, xdg_output_manager: Option, /// shared by all clients, so the keymap fd is sent once instead of once per client keyboard: Option, input_for_client: HashMap, seat: wl_seat::WlSeat, qh: QueueHandle, vpm: VpManager, vkm: VkManager, } // App State, implements Dispatch event handlers pub(crate) struct WlrootsEmulation { last_flush_failed: bool, /// events consumed since compositor events were last read since_dispatch: u32, state: State, queue: EventQueue, } impl WlrootsEmulation { pub(crate) fn new() -> Result { let conn = Connection::connect_to_env()?; let (globals, queue) = registry_queue_init::(&conn)?; let qh = queue.handle(); let seat: wl_seat::WlSeat = globals .bind(&qh, 7..=8, ()) .map_err(|e| WaylandBindError::new(e, "wl_seat 7..=8"))?; let vpm: VpManager = globals .bind(&qh, 1..=1, ()) .map_err(|e| WaylandBindError::new(e, "wlr-virtual-pointer-unstable-v1"))?; let vkm: VkManager = globals .bind(&qh, 1..=1, ()) .map_err(|e| WaylandBindError::new(e, "virtual-keyboard-unstable-v1"))?; let input_for_client: HashMap = HashMap::new(); // optional: only needed to place the cursor where it entered let xdg_output_manager: Option = globals.bind(&qh, 1..=3, ()).ok(); let output_globals: Vec = globals.contents().with_list(|list| { list.iter() .filter(|g| g.interface == "wl_output") .map(|g| g.name) .collect() }); let mut emulate = WlrootsEmulation { last_flush_failed: false, since_dispatch: 0, state: State { keymap: None, keymap_changed: false, outputs: Vec::new(), xdg_output_manager, keyboard: None, input_for_client, seat, vpm, vkm, qh, }, queue, }; for name in output_globals { emulate.state.add_output(globals.registry(), name); } while emulate.state.keymap.is_none() { emulate.queue.blocking_dispatch(&mut emulate.state)?; } // collect initial output geometry emulate.queue.roundtrip(&mut emulate.state)?; emulate.state.keymap_changed = false; // let fd = unsafe { &File::from_raw_fd(emulate.state.keymap.unwrap().1.as_raw_fd()) }; // let mmap = unsafe { MmapOptions::new().map_copy(fd).unwrap() }; // log::debug!("{:?}", &mmap[..100]); Ok(emulate) } } impl State { fn add_output(&mut self, registry: &wl_registry::WlRegistry, name: u32) { let Some(manager) = self.xdg_output_manager.as_ref() else { return; }; let wl_output: WlOutput = registry.bind(name, 1, &self.qh, ()); let xdg_output = manager.get_xdg_output(&wl_output, &self.qh, name); self.outputs.push(OutputGeometry { global_name: name, xdg_output: Some(xdg_output), ..Default::default() }); } fn remove_output(&mut self, name: u32) { self.outputs.retain(|o| { if o.global_name != name { return true; } // wl_output is bound at v1, which has no release request if let Some(x) = &o.xdg_output { x.destroy(); } false }); } fn edge_point(&self, edge: Edge, offset: f64) -> Option<(u32, u32, u32, u32)> { edge_point(self.outputs.iter().map(|o| (o.pos, o.size)), edge, offset) } fn add_client(&mut self, client: EmulationHandle) { let pointer: Vp = self.vpm.create_virtual_pointer(None, &self.qh, ()); let keyboard = match self.keyboard.as_ref() { Some(keyboard) => keyboard.clone(), None => { let keyboard: Vk = self.vkm.create_virtual_keyboard(&self.seat, &self.qh, ()); // TODO: use server side keymap let Some((format, fd, size)) = self.keymap.as_ref() else { panic!("no keymap"); }; keyboard.keymap(*format, fd.as_fd(), *size); self.keyboard = Some(keyboard.clone()); keyboard } }; let vinput = VirtualInput { pointer, keyboard, modifiers: Arc::new(Mutex::new(XMods::empty())), }; self.input_for_client.insert(client, vinput); } fn destroy_client(&mut self, handle: EmulationHandle) { // the shared keyboard outlives every client; keys are released by InputEmulation::destroy if let Some(input) = self.input_for_client.remove(&handle) { input.pointer.destroy(); } } } impl WlrootsEmulation { /// read and handle pending compositor events without blocking fn dispatch(&mut self) -> Result<(), WaylandError> { self.since_dispatch = 0; if let Some(guard) = self.queue.prepare_read() { match guard.read() { Ok(_) => {} Err(WaylandError::Io(e)) if e.kind() == io::ErrorKind::WouldBlock => {} Err(e) => return Err(e), } } if let Err(e) = self.queue.dispatch_pending(&mut self.state) { log::warn!("wayland dispatch failed: {e}"); } if std::mem::take(&mut self.state.keymap_changed) { if let (Some(keyboard), Some((format, fd, size))) = (self.state.keyboard.as_ref(), self.state.keymap.as_ref()) { log::info!("compositor keymap changed, updating virtual keyboard"); keyboard.keymap(*format, fd.as_fd(), *size); } } Ok(()) } } fn now_ms() -> u32 { SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default() .as_millis() as u32 } /// Point on `edge` of the output layout at `offset` (fraction) along it, as /// `(x, y, width, height)` relative to the layout's bounding box. /// `outputs` are `(position, size)` in logical coordinates. fn edge_point( outputs: impl Iterator, edge: Edge, offset: f64, ) -> Option<(u32, u32, u32, u32)> { // stay this many logical pixels inside the edge, so the cursor does not // land on our own 1px capture surface there and bounce straight back const INSET: i32 = 2; let outputs: Vec<_> = outputs.filter(|(_, s)| s.0 > 0 && s.1 > 0).collect(); let min_x = outputs.iter().map(|(p, _)| p.0).min()?; let min_y = outputs.iter().map(|(p, _)| p.1).min()?; let max_x = outputs.iter().map(|(p, s)| p.0 + s.0).max()?; let max_y = outputs.iter().map(|(p, s)| p.1 + s.1).max()?; // span (start, end) along the edge of every output touching it let spans = outputs.iter().filter_map(|&(p, s)| match edge { Edge::Left => (p.0 == min_x).then_some((p.1, p.1 + s.1)), Edge::Right => (p.0 + s.0 == max_x).then_some((p.1, p.1 + s.1)), Edge::Top => (p.1 == min_y).then_some((p.0, p.0 + s.0)), Edge::Bottom => (p.1 + s.1 == max_y).then_some((p.0, p.0 + s.0)), }); let (lo, hi) = spans.fold((i32::MAX, i32::MIN), |(lo, hi), (a, b)| { (lo.min(a), hi.max(b)) }); if hi <= lo { return None; } let along = (lo as f64 + offset.clamp(0.0, 1.0) * (hi - lo) as f64) .clamp(lo as f64, (hi - 1) as f64) as i32; let (x, y) = match edge { Edge::Left => (min_x + INSET, along), Edge::Right => (max_x - 1 - INSET, along), Edge::Top => (along, min_y + INSET), Edge::Bottom => (along, max_y - 1 - INSET), }; let (w, h) = (max_x - min_x, max_y - min_y); Some(( (x - min_x).clamp(0, w - 1) as u32, (y - min_y).clamp(0, h - 1) as u32, w as u32, h as u32, )) } #[async_trait] impl Emulation for WlrootsEmulation { async fn consume( &mut self, event: Event, handle: EmulationHandle, ) -> Result<(), EmulationError> { // read compositor events now and then; nothing else drains the // socket, and keymap updates (layout switches) arrive there self.since_dispatch += 1; if self.since_dispatch >= 64 { self.dispatch()?; } if let Some(virtual_input) = self.state.input_for_client.get(&handle) { if self.last_flush_failed { match self.queue.flush() { Err(WaylandError::Io(e)) if e.kind() == io::ErrorKind::WouldBlock => { /* * outgoing buffer is full - sending more events * will overwhelm the output buffer and leave the * wayland connection in a broken state */ log::warn!("can't keep up, discarding event: ({handle}) - {event:?}"); return Ok(()); } _ => {} } } virtual_input .consume_event(event) .unwrap_or_else(|_| panic!("failed to convert event: {event:?}")); match self.queue.flush() { Err(WaylandError::Io(e)) if e.kind() == io::ErrorKind::WouldBlock => { self.last_flush_failed = true; log::warn!("can't keep up, discarding event: ({handle}) - {event:?}"); } Err(WaylandError::Protocol(e)) => panic!("wayland protocol violation: {e}"), Ok(()) => self.last_flush_failed = false, Err(e) => Err(e)?, } } Ok(()) } async fn warp(&mut self, handle: EmulationHandle, edge: Edge, offset: Option) { // without an offset (old peer) keep the cursor where it is let Some(offset) = offset else { return }; if let Err(e) = self.dispatch() { log::warn!("{e}"); } let Some(input) = self.state.input_for_client.get(&handle) else { return; }; let Some((x, y, w, h)) = self.state.edge_point(edge, offset) else { log::debug!("no output geometry, not placing cursor"); return; }; log::debug!("placing cursor at {edge:?} edge ({x}, {y}) of {w}x{h}"); input.pointer.motion_absolute(now_ms(), x, y, w, h); input.pointer.frame(); if let Err(e) = self.queue.flush() { log::warn!("{e}"); } } async fn create(&mut self, handle: EmulationHandle) { if let Err(e) = self.dispatch() { log::warn!("{e}"); } self.state.add_client(handle); if let Err(e) = self.queue.flush() { log::error!("{e}"); } } async fn destroy(&mut self, handle: EmulationHandle) { self.state.destroy_client(handle); if let Err(e) = self.queue.flush() { log::error!("{e}"); } } async fn terminate(&mut self) { /* nothing to do */ } } struct VirtualInput { pointer: Vp, keyboard: Vk, modifiers: Arc>, } impl VirtualInput { fn consume_event(&self, event: Event) -> Result<(), ()> { // the peer's timestamps use its own clock and unit (libei sends microseconds, // windows and macos send 0); clients compare them to detect double clicks let now = now_ms(); match event { Event::Pointer(e) => { match e { PointerEvent::Motion { dx, dy, .. } => self.pointer.motion(now, dx, dy), PointerEvent::Button { button, state, .. } => { let state: ButtonState = state.try_into()?; self.pointer.button(now, button, state); } // axis_source belongs before the axis events of a frame; // the single frame below closes it PointerEvent::Axis { axis, value, .. } => { let axis: Axis = (axis as u32).try_into()?; self.pointer.axis_source(AxisSource::Continuous); self.pointer.axis(now, axis, value); } PointerEvent::AxisDiscrete120 { axis, value } => { let axis: Axis = (axis as u32).try_into()?; self.pointer.axis_source(AxisSource::Wheel); self.pointer .axis_discrete(now, axis, value as f64 / 8., value / 120); } } self.pointer.frame(); } Event::Keyboard(e) => match e { KeyboardEvent::Key { key, state, .. } => { self.keyboard.key(now, key, state as u32); if let Ok(mut mods) = self.modifiers.lock() { if mods.update_by_key_event(key, state) { log::trace!("Key triggers modifier change: {mods:?}"); self.keyboard.modifiers( mods.mask_pressed().bits(), 0, mods.mask_locks().bits(), 0, ); } } } KeyboardEvent::Modifiers { depressed: mods_depressed, latched: mods_latched, locked: mods_locked, group, } => { // Synchronize internal modifier state, assuming server is authoritative if let Ok(mut mods) = self.modifiers.lock() { mods.update_by_mods_event(e); } self.keyboard .modifiers(mods_depressed, mods_latched, mods_locked, group); } }, } Ok(()) } } delegate_noop!(State: Vp); delegate_noop!(State: Vk); delegate_noop!(State: VpManager); delegate_noop!(State: VkManager); impl Dispatch for State { fn event( state: &mut State, registry: &wl_registry::WlRegistry, event: wl_registry::Event, _: &GlobalListContents, _: &Connection, _: &QueueHandle, ) { match event { wl_registry::Event::Global { name, interface, .. } if interface == "wl_output" => state.add_output(registry, name), wl_registry::Event::GlobalRemove { name } => state.remove_output(name), _ => {} } } } impl Dispatch for State { fn event( state: &mut Self, _: &ZxdgOutputV1, event: zxdg_output_v1::Event, name: &u32, _: &Connection, _: &QueueHandle, ) { let Some(output) = state.outputs.iter_mut().find(|o| o.global_name == *name) else { return; }; match event { zxdg_output_v1::Event::LogicalPosition { x, y } => output.pos = (x, y), zxdg_output_v1::Event::LogicalSize { width, height } => output.size = (width, height), _ => {} } } } delegate_noop!(State: ignore WlOutput); delegate_noop!(State: ZxdgOutputManagerV1); impl Dispatch for State { fn event( state: &mut Self, _: &WlKeyboard, event: ::Event, _: &(), _: &Connection, _: &QueueHandle, ) { if let wl_keyboard::Event::Keymap { format, fd, size } = event { state.keymap = Some((u32::from(format), fd, size)); state.keymap_changed = true; } } } impl Dispatch for State { fn event( _: &mut Self, seat: &WlSeat, event: ::Event, _: &(), _: &Connection, qhandle: &QueueHandle, ) { if let wl_seat::Event::Capabilities { capabilities: WEnum::Value(capabilities), } = event { if capabilities.contains(wl_seat::Capability::Keyboard) { seat.get_keyboard(qhandle, ()); } } } } // From X11/X.h bitflags! { #[repr(C)] #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] struct XMods: u32 { const ShiftMask = (1<<0); const LockMask = (1<<1); const ControlMask = (1<<2); const Mod1Mask = (1<<3); const Mod2Mask = (1<<4); const Mod3Mask = (1<<5); const Mod4Mask = (1<<6); const Mod5Mask = (1<<7); } } impl XMods { fn update_by_mods_event(&mut self, evt: KeyboardEvent) { if let KeyboardEvent::Modifiers { depressed, locked, .. } = evt { *self = XMods::from_bits_truncate(depressed) | XMods::from_bits_truncate(locked); } } fn update_by_key_event(&mut self, key: u32, state: u8) -> bool { if let Ok(key) = scancode::Linux::try_from(key) { log::trace!("Attempting to process modifier from: {key:#?}"); let pressed_mask = match key { scancode::Linux::KeyLeftShift | scancode::Linux::KeyRightShift => XMods::ShiftMask, scancode::Linux::KeyLeftCtrl | scancode::Linux::KeyRightCtrl => XMods::ControlMask, scancode::Linux::KeyLeftAlt | scancode::Linux::KeyRightalt => XMods::Mod1Mask, scancode::Linux::KeyLeftMeta | scancode::Linux::KeyRightmeta => XMods::Mod4Mask, _ => XMods::empty(), }; let locked_mask = match key { scancode::Linux::KeyCapsLock => XMods::LockMask, scancode::Linux::KeyNumlock => XMods::Mod2Mask, scancode::Linux::KeyScrollLock => XMods::Mod3Mask, _ => XMods::empty(), }; // unchanged if pressed_mask.is_empty() && locked_mask.is_empty() { log::trace!("{key:#?} is not a modifier key"); return false; } match state { 1 => self.insert(pressed_mask), _ => { self.remove(pressed_mask); self.toggle(locked_mask); } } true } else { false } } fn mask_locks(&self) -> XMods { *self & (XMods::LockMask | XMods::Mod2Mask | XMods::Mod3Mask) } fn mask_pressed(&self) -> XMods { *self & (XMods::ShiftMask | XMods::ControlMask | XMods::Mod1Mask | XMods::Mod4Mask) } } #[cfg(test)] mod tests { use super::*; // como: eDP-1 1920x1080 at (0,0), DP-1 1920x1080 at (1920,0) const TWO: [((i32, i32), (i32, i32)); 2] = [((0, 0), (1920, 1080)), ((1920, 0), (1920, 1080))]; #[test] fn right_edge_uses_rightmost_output() { let p = edge_point(TWO.into_iter(), Edge::Right, 0.5).unwrap(); assert_eq!(p, (3840 - 3, 540, 3840, 1080)); } #[test] fn left_edge_extremes_stay_on_screen() { assert_eq!( edge_point(TWO.into_iter(), Edge::Left, 0.0).unwrap(), (2, 0, 3840, 1080) ); assert_eq!( edge_point(TWO.into_iter(), Edge::Left, 1.0).unwrap(), (2, 1079, 3840, 1080) ); } #[test] fn top_edge_spans_both_outputs() { assert_eq!( edge_point(TWO.into_iter(), Edge::Top, 0.75).unwrap(), (2880, 2, 3840, 1080) ); } #[test] fn offset_outputs_and_no_outputs() { // second output lower and to the right: right edge is only DP let o = [((0, 0), (1920, 1080)), ((1920, 300), (1280, 1024))]; assert_eq!( edge_point(o.into_iter(), Edge::Right, 0.0).unwrap(), (3197, 300, 3200, 1324) ); assert!(edge_point(std::iter::empty(), Edge::Right, 0.5).is_none()); } }