diff --git a/Cargo.lock b/Cargo.lock index 0b1105f0..b0915935 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3396,7 +3396,7 @@ checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100" [[package]] name = "smithay" version = "0.7.0" -source = "git+https://github.com/Smithay/smithay.git?rev=19c16d3e34172fcc8fb3d293bcae563b0a19ea70#19c16d3e34172fcc8fb3d293bcae563b0a19ea70" +source = "git+https://github.com/Smithay/smithay.git?rev=9786228efad25d65af0bb516642c1e8b0c359f37#9786228efad25d65af0bb516642c1e8b0c359f37" dependencies = [ "aliasable", "appendlist", @@ -3473,7 +3473,7 @@ dependencies = [ [[package]] name = "smithay-drm-extras" version = "0.1.0" -source = "git+https://github.com/Smithay/smithay.git?rev=19c16d3e34172fcc8fb3d293bcae563b0a19ea70#19c16d3e34172fcc8fb3d293bcae563b0a19ea70" +source = "git+https://github.com/Smithay/smithay.git?rev=9786228efad25d65af0bb516642c1e8b0c359f37#9786228efad25d65af0bb516642c1e8b0c359f37" dependencies = [ "drm", "libdisplay-info", diff --git a/Cargo.toml b/Cargo.toml index 5c5d0305..8199eb3c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,13 +28,13 @@ tracy-client = { version = "0.18.5", default-features = false } [workspace.dependencies.smithay] # version = "0.4.1" git = "https://github.com/Smithay/smithay.git" -rev = "19c16d3e34172fcc8fb3d293bcae563b0a19ea70" +rev = "9786228efad25d65af0bb516642c1e8b0c359f37" default-features = false [workspace.dependencies.smithay-drm-extras] # version = "0.1.0" git = "https://github.com/Smithay/smithay.git" -rev = "19c16d3e34172fcc8fb3d293bcae563b0a19ea70" +rev = "9786228efad25d65af0bb516642c1e8b0c359f37" # path = "../smithay/smithay-drm-extras" [package] diff --git a/src/handlers/mod.rs b/src/handlers/mod.rs index f55f4d6f..8ad784ed 100644 --- a/src/handlers/mod.rs +++ b/src/handlers/mod.rs @@ -2,6 +2,7 @@ pub mod background_effect; mod compositor; pub mod image_copy_capture; mod layer_shell; +pub mod virtual_keyboard; mod xdg_shell; use std::fs::File; @@ -62,6 +63,7 @@ use smithay::wayland::session_lock::{ LockSurface, SessionLockHandler, SessionLockManagerState, SessionLocker, }; use smithay::wayland::text_input::TextInputActivation; +use smithay::wayland::virtual_pointer::{VirtualPointerBackend, VirtualPointerHandler}; use smithay::wayland::xdg_activation::{ XdgActivationHandler, XdgActivationState, XdgActivationToken, XdgActivationTokenData, }; @@ -79,11 +81,6 @@ use crate::protocols::gamma_control::{GammaControlHandler, GammaControlManagerSt use crate::protocols::mutter_x11_interop::MutterX11InteropHandler; use crate::protocols::output_management::{OutputManagementHandler, OutputManagementManagerState}; use crate::protocols::screencopy::{Screencopy, ScreencopyHandler, ScreencopyManagerState}; -use crate::protocols::virtual_pointer::{ - VirtualPointerAxisEvent, VirtualPointerButtonEvent, VirtualPointerHandler, - VirtualPointerInputBackend, VirtualPointerManagerState, VirtualPointerMotionAbsoluteEvent, - VirtualPointerMotionEvent, -}; use crate::utils::{output_size, send_scale_transform}; pub const XDG_ACTIVATION_TOKEN_TIMEOUT: Duration = Duration::from_secs(10); @@ -660,26 +657,8 @@ impl ScreencopyHandler for State { } impl VirtualPointerHandler for State { - fn virtual_pointer_manager_state(&mut self) -> &mut VirtualPointerManagerState { - &mut self.niri.virtual_pointer_state - } - - fn on_virtual_pointer_motion(&mut self, event: VirtualPointerMotionEvent) { - self.process_input_event(InputEvent::::PointerMotion { event }); - } - - fn on_virtual_pointer_motion_absolute(&mut self, event: VirtualPointerMotionAbsoluteEvent) { - self.process_input_event( - InputEvent::::PointerMotionAbsolute { event }, - ); - } - - fn on_virtual_pointer_button(&mut self, event: VirtualPointerButtonEvent) { - self.process_input_event(InputEvent::::PointerButton { event }); - } - - fn on_virtual_pointer_axis(&mut self, event: VirtualPointerAxisEvent) { - self.process_input_event(InputEvent::::PointerAxis { event }); + fn process_virtual_pointer_event(&mut self, event: InputEvent) { + self.process_input_event(event); } } diff --git a/src/handlers/virtual_keyboard.rs b/src/handlers/virtual_keyboard.rs new file mode 100644 index 00000000..587a426d --- /dev/null +++ b/src/handlers/virtual_keyboard.rs @@ -0,0 +1,253 @@ +//! `zwp_virtual_keyboard_v1` handling. +//! +//! Virtual keyboards are handled like a real keyboard (binds, grabs, etc), but differ in a few +//! ways: +//! +//! - A virtual keyboard's keymap may differ from the seat's one, and if so, will be swapped before +//! events from it are forwarded (restoring the saved layout and a subset of modifiers when +//! swapping back to the original one). +//! - If the virtual keyboard uses `no_keymap` or the same one as the seat, it will use the seat's +//! xkb state directly. +//! - If a client grabs the keyboard, then forwards events through a virtual keyboard (e.g., fcitx), +//! they are then forwarded bypassing the grab to avoid loops (sway special-cases this too). +//! - Modifiers set through the `modifiers` request apply to the shared xkb state (see +//! `DeviceRemoved`). + +use std::sync::Arc; + +use smithay::backend::input::{Event, InputEvent, KeyboardKeyEvent}; +use smithay::utils::SERIAL_COUNTER; +use smithay::wayland::input_method::InputMethodSeat; +use smithay::wayland::virtual_keyboard::{ + VirtualKeyboardBackend, VirtualKeyboardDevice, VirtualKeyboardHandler, VirtualKeyboardKeyEvent, + VirtualKeyboardSpecialEvent, +}; + +use crate::niri::{SavedKeyboardState, State}; + +/// Virtual keyboard keymap (which temporarily replaces the shared seat one). +#[derive(Debug)] +pub struct VirtualKeyboardKeymap { + pub device: VirtualKeyboardDevice, + pub keymap: Arc, + pub saved: SavedKeyboardState, +} + +impl VirtualKeyboardHandler for State { + fn process_virtual_keyboard_event(&mut self, event: InputEvent) { + match event { + InputEvent::Keyboard { event } => { + let device = event.device(); + self.activate_virtual_keyboard_keymap(&device); + if self.is_input_method_virtual_keyboard(&device) { + // Do not forward passed-through events from a grab back to + // the grab. + self.forward_input_method_key(&event); + } else { + self.process_input_event(InputEvent::::Keyboard { + event, + }); + } + } + InputEvent::Special(VirtualKeyboardSpecialEvent::Modifiers { + device, + mods_depressed, + mods_latched, + mods_locked, + group, + }) => { + self.activate_virtual_keyboard_keymap(&device); + + let keyboard = self.niri.seat.get_keyboard().unwrap(); + keyboard.with_xkb_state(self, |mut context| { + context.set_modifier_mask(mods_depressed, mods_latched, mods_locked, group); + }); + } + InputEvent::Special(VirtualKeyboardSpecialEvent::KeymapChanged { .. }) => { + // The new keymap will be activated by the next key or modifiers event. + } + InputEvent::DeviceRemoved { device } => { + // Restore the original keymap if this device is active. This is + // checked based on the device rather than on the keymap, since + // the client may have replaced its keymap after we activated it + // and not sent any key/modifier events afterwards before + // removing the device. + let active = self + .niri + .virtual_keyboard_keymap + .as_ref() + .is_some_and(|active| active.device == device); + if active { + self.restore_configured_keymap(); + } + + // The held keys have already been released by smithay. + // + // We don't reset the modifiers since there's no way to tell which ones were set by + // this keyboard specifically since the masks are absolute. This only affects + // virtual keyboards without a keymap, or with the same keymap as the seat. We could + // track which bits were set by each virtual keyboard, but it's more complex, and we + // still would need to rebuild the modifier state after to avoid potentially leaving + // modifiers without a corresponding key stuck, and it's not really possible to + // rebuild it cleanly for all possible layouts (e.g., `grp:alt_shift_toggle`, + // layouts with multi-level modifier keys) without tracking the exact sequence the + // modifiers were pressed in (see + // https://github.com/niri-wm/niri/pull/4548#discussion_r4237056727). + // + // Not resetting the modifiers means that: + // + // - a locked modifier or layout group set by `modifiers` stays until the user + // toggles it (most layouts have clearLocks on Shift/Ctrl/Alt/Super, so those can + // be reset by pressing the key, but ones without a corresponding key can't be + // cleared without a keymap change or another modifiers request from a virtual + // keyboard) + // - if the virtual keyboard sets the modifiers without taking into account the + // existing state and clears a locked modifier, the locked modifier will remain + // cleared + // - a modifier set only through `modifiers` will stay set until the corresponding + // key is pressed + // + // To handle this properly, we need support for per-device xkb state (and we can + // merge the modifier state across the xkb states to keep shortcuts working across + // keyboards) in smithay like sway and hyprland. + self.process_input_event(InputEvent::::DeviceRemoved { + device, + }); + } + event => self.process_input_event(event), + } + } +} + +impl State { + /// Whether the virtual keyboard belongs to the input method that has grabbed the keyboard. + pub fn is_input_method_virtual_keyboard(&self, device: &VirtualKeyboardDevice) -> bool { + let grab_client = self.niri.seat.input_method().keyboard_grab_client(); + grab_client.is_some() && grab_client == device.client() + } + + /// Forwards a key that the input method is passing through directly to the focused surface. + /// + /// While an input method holds the keyboard grab, keys go through the binds and then to the + /// input method, which sends back unhandled ones through its own virtual keyboard. If we + /// handled these normally, they would get sent back to the grab, looping forever. + /// + /// Note that sway also special-cases this in the same way. + pub fn forward_input_method_key(&mut self, event: &VirtualKeyboardKeyEvent) { + let serial = SERIAL_COUNTER.next_serial(); + + // The modifiers associated with the physical key went to the input method + // rather than to the surface, so always send the current ones. + let keyboard = self.niri.seat.get_keyboard().unwrap(); + keyboard.input_forward_bypassing_grab( + self, + event.key_code(), + event.state(), + serial, + event.time(), + true, + ); + } + + /// Activates the virtual keyboard's keymap on the current seat, unless it already is. + pub fn activate_virtual_keyboard_keymap(&mut self, device: &VirtualKeyboardDevice) { + let Some(keymap) = device.keymap() else { + // The keycodes are relative to the configured keymap, so make sure + // it's the active one. + self.restore_configured_keymap(); + return; + }; + + if let Some(active) = &mut self.niri.virtual_keyboard_keymap { + if active.keymap == keymap { + // Another virtual keyboard may have installed an identical + // keymap. Take ownership of it anyway, so that removing that + // one doesn't take the keymap out from under us. + active.device = device.clone(); + return; + } + } + + // A keymap identical to the configured one (e.g. from an input method + // forwarding keys with the keymap it received from us) doesn't need to + // be swapped in, which would needlessly reset the keyboard state. + if *self.configured_keymap() == *keymap { + self.restore_configured_keymap(); + return; + } + + // Save the state from before the first virtual keyboard keymap, since + // swapping keymaps resets it, and a virtual keyboard should neither + // affect nor be affected by it. + let saved = match &self.niri.virtual_keyboard_keymap { + Some(active) => active.saved, + None => self.current_keyboard_state(), + }; + + let keyboard = self.niri.seat.get_keyboard().unwrap(); + if let Err(err) = keyboard.set_keymap_from_string(self, keymap.to_string()) { + warn!("error setting virtual keyboard keymap: {err:?}"); + return; + } + + self.niri.virtual_keyboard_keymap = Some(VirtualKeyboardKeymap { + device: device.clone(), + keymap, + saved, + }); + self.ipc_keyboard_layouts_changed(); + } + + /// Switches the seat back from a virtual keyboard's keymap to the configured one, if needed. + /// + /// The configured keymap was saved as text before the virtual keyboard's replaced it, so this + /// doesn't re-read the xkb file or recompile the xkb config unnecessarily. + pub fn restore_configured_keymap(&mut self) { + let Some(active) = self.niri.virtual_keyboard_keymap.take() else { + return; + }; + + let keyboard = self.niri.seat.get_keyboard().unwrap(); + let restored = self.niri.configured_keymap.clone().is_some_and(|keymap| { + keyboard + .set_keymap_from_string(self, keymap.to_string()) + .inspect_err(|err| warn!("error restoring configured keymap: {err:?}")) + .is_ok() + }); + + if !restored { + // Shouldn't happen unless there's an xkbcommon bug or configured_keymap somehow ends + // up none while a virtual keymap is active, but fall back to loading it from the + // config. + error!("failed to restore the configured keymap, reloading it from the config"); + self.niri.virtual_keyboard_keymap = Some(active); + self.niri.configured_keymap = None; + self.load_configured_keymap(); + return; + } + + self.restore_keyboard_state(active.saved); + self.ipc_keyboard_layouts_changed(); + } + + /// Returns the configured keymap as XKB_KEYMAP_FORMAT_TEXT_V1. + fn configured_keymap(&mut self) -> Arc { + if let Some(keymap) = &self.niri.configured_keymap { + return keymap.clone(); + } + + // The seat has the configured keymap while no virtual keyboard keymap is active. + if self.niri.virtual_keyboard_keymap.is_some() { + error!("virtual_keyboard_keymap must be None when resetting configured_keymap"); + } + + let keyboard = self.niri.seat.get_keyboard().unwrap(); + let keymap: Arc = keyboard + .with_xkb_state(self, |context| { + context.xkb().lock().unwrap().keymap_as_string() + }) + .into(); + self.niri.configured_keymap = Some(keymap.clone()); + keymap + } +} diff --git a/src/input/backend_ext.rs b/src/input/backend_ext.rs index 99f4a904..862bbbfd 100644 --- a/src/input/backend_ext.rs +++ b/src/input/backend_ext.rs @@ -2,9 +2,10 @@ use ::input as libinput; use smithay::backend::input; use smithay::backend::winit::WinitVirtualDevice; use smithay::output::Output; +use smithay::wayland::virtual_keyboard::VirtualKeyboardDevice; +use smithay::wayland::virtual_pointer::VirtualPointerDevice; use crate::niri::State; -use crate::protocols::virtual_pointer::VirtualPointer; pub trait NiriInputBackend: input::InputBackend { type NiriDevice: NiriInputDevice; @@ -44,8 +45,14 @@ impl NiriInputDevice for WinitVirtualDevice { } } -impl NiriInputDevice for VirtualPointer { +impl NiriInputDevice for VirtualPointerDevice { fn output(&self, _: &State) -> Option { - self.output().cloned() + self.output() + } +} + +impl NiriInputDevice for VirtualKeyboardDevice { + fn output(&self, _: &State) -> Option { + None } } diff --git a/src/input/mod.rs b/src/input/mod.rs index 0ca0bb51..10c1d02c 100644 --- a/src/input/mod.rs +++ b/src/input/mod.rs @@ -19,7 +19,9 @@ use smithay::backend::input::{ }; use smithay::backend::libinput::LibinputInputBackend; use smithay::input::dnd::DnDGrab; -use smithay::input::keyboard::{keysyms, FilterResult, Keysym, Layout, ModifiersState}; +use smithay::input::keyboard::{ + keysyms, FilterResult, KeyboardSource, Keysym, Layout, ModifiersState, +}; use smithay::input::pointer::{ AxisFrame, ButtonEvent, CursorIcon, CursorImageStatus, Focus, GestureHoldBeginEvent, GestureHoldEndEvent, GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent, @@ -38,6 +40,7 @@ use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface; use smithay::utils::{Logical, Point, Rectangle, Transform, SERIAL_COUNTER}; use smithay::wayland::keyboard_shortcuts_inhibit::KeyboardShortcutsInhibitor; use smithay::wayland::pointer_constraints::{with_pointer_constraint, PointerConstraint}; +use smithay::wayland::virtual_keyboard::VirtualKeyboardDevice; use touch_overview_grab::TouchOverviewGrab; use self::move_grab::MoveGrab; @@ -417,7 +420,26 @@ impl State { &mut self, event: I::KeyboardKeyEvent, consumed_by_a11y: &mut bool, - ) { + ) where + I::Device: 'static, + { + let device = event.device(); + let virtual_keyboard = (&device as &dyn Any).downcast_ref::(); + + // Restore the real keymap if required (the virtual keyboard uses its own one). + if virtual_keyboard.is_none() { + self.restore_configured_keymap(); + } + + // Keys from a virtual keyboard are tracked separately from the physical + // ones, otherwise, a virtual keyboard sending a key already held by + // another keyboard (an IME, e.g., fcitx, forwarding keys it got through its + // grab) would release it prematurely. + // + // Note that keyboard shortcuts can still be pressed across multiple + // keyboards even with this, as intended. + let source = virtual_keyboard.map_or(KeyboardSource::MAIN, |device| device.source()); + let mod_key = self.backend.mod_key(&self.niri.config.borrow()); let serial = SERIAL_COUNTER.next_serial(); @@ -468,7 +490,8 @@ impl State { #[cfg(not(feature = "dbus"))] let _ = consumed_by_a11y; - let Some(Some(bind)) = self.niri.seat.get_keyboard().unwrap().input( + let Some(Some(bind)) = self.niri.seat.get_keyboard().unwrap().input_from_source( + source, self, event.key_code(), event.state(), diff --git a/src/niri.rs b/src/niri.rs index 0432a8c4..c2bf92d8 100644 --- a/src/niri.rs +++ b/src/niri.rs @@ -114,6 +114,7 @@ use smithay::wayland::tablet_manager::TabletManagerState; use smithay::wayland::text_input::TextInputManagerState; use smithay::wayland::viewporter::ViewporterState; use smithay::wayland::virtual_keyboard::VirtualKeyboardManagerState; +use smithay::wayland::virtual_pointer::VirtualPointerManagerState; use smithay::wayland::xdg_activation::XdgActivationState; use smithay::wayland::xdg_foreign::XdgForeignState; use wayland_server::protocol::wl_output::WlOutput; @@ -136,6 +137,7 @@ use crate::frame_clock::FrameClock; use crate::handlers::image_copy_capture::{ self as image_copy_capture_impl, CaptureBuffer, ImageCopyCursorSession, ImageCopySession, }; +use crate::handlers::virtual_keyboard::VirtualKeyboardKeymap; use crate::handlers::{configure_lock_surface, XDG_ACTIVATION_TOKEN_TIMEOUT}; use crate::input::pick_color_grab::PickColorGrab; use crate::input::scroll_swipe_gesture::ScrollSwipeGesture; @@ -160,7 +162,6 @@ use crate::protocols::gamma_control::GammaControlManagerState; use crate::protocols::mutter_x11_interop::MutterX11InteropManagerState; use crate::protocols::output_management::OutputManagementManagerState; use crate::protocols::screencopy::{Screencopy, ScreencopyBuffer, ScreencopyManagerState}; -use crate::protocols::virtual_pointer::VirtualPointerManagerState; use crate::render_helpers::blur::BlurOptions; use crate::render_helpers::debug::push_opaque_regions; use crate::render_helpers::primary_gpu_texture::PrimaryGpuTextureRenderElement; @@ -201,6 +202,14 @@ const CLEAR_COLOR_LOCKED: [f32; 4] = [0.3, 0.1, 0.1, 1.]; // should be ~1.995 seconds. const FRAME_CALLBACK_THROTTLE: Option = Some(Duration::from_millis(995)); +/// Parts of the seat keyboard state that get reset when its keymap is replaced. +#[derive(Debug, Clone, Copy, Default)] +pub struct SavedKeyboardState { + pub layout: Option, + pub caps_lock: Option, + pub num_lock: Option, +} + pub struct Niri { pub config: Rc>, @@ -360,6 +369,21 @@ pub struct Niri { /// Most recent XKB settings from org.freedesktop.locale1. pub xkb_from_locale1: Option, + /// Virtual keyboard for which the keymap is currently active on the seat, + /// if any. + /// + /// Note that the keymap may be changed by the client at any time, and it + /// only gets activated on the next key/modifier event from the virtual + /// keyboard. + pub virtual_keyboard_keymap: Option, + /// Configured (non-virtual-keyboard) keymap as XKB_KEYMAP_FORMAT_TEXT_V1. + /// + /// Computed lazily from the seat while no virtual keyboard keymap is + /// active, and cleared whenever the configured keymap changes. Used to + /// compare against virtual keyboard keymaps, and to switch back to it + /// afterwards without going through the config again. + pub configured_keymap: Option>, + pub cursor_manager: CursorManager, pub cursor_texture_cache: CursorTextureCache, pub cursor_shape_manager_state: CursorShapeManagerState, @@ -1512,18 +1536,14 @@ impl State { let keymap = std::fs::read_to_string(xkb_file).context("failed to read xkb_file")?; let keyboard = self.niri.seat.get_keyboard().unwrap(); - let num_lock = keyboard.modifier_state().num_lock; + let restore = self.keyboard_state_to_restore(); keyboard .set_keymap_from_string(self, keymap) .context("failed to set keymap")?; - - // Restore num lock to its previous value. - let mut mods_state = keyboard.modifier_state(); - if mods_state.num_lock != num_lock { - mods_state.num_lock = num_lock; - keyboard.set_modifier_state(mods_state); - } + self.niri.virtual_keyboard_keymap = None; + self.niri.configured_keymap = None; + self.restore_keyboard_state(restore); Ok(()) } @@ -1539,20 +1559,111 @@ impl State { pub fn set_xkb_config(&mut self, xkb: XkbConfig) { let keyboard = self.niri.seat.get_keyboard().unwrap(); - let num_lock = keyboard.modifier_state().num_lock; + let restore = self.keyboard_state_to_restore(); if let Err(err) = keyboard.set_xkb_config(self, xkb) { warn!("error updating xkb config: {err:?}"); return; } + self.niri.virtual_keyboard_keymap = None; + self.niri.configured_keymap = None; + self.restore_keyboard_state(restore); + } - // Restore num lock to its previous value. - let mut mods_state = keyboard.modifier_state(); - if mods_state.num_lock != num_lock { - mods_state.num_lock = num_lock; - keyboard.set_modifier_state(mods_state); + /// Returns the keyboard state to restore after replacing the seat's keymap (which resets it). + /// + /// When switching back from a virtual keyboard's keymap, this is the state from before it was + /// activated. Otherwise, only Num Lock is carried over. + pub fn keyboard_state_to_restore(&self) -> SavedKeyboardState { + match &self.niri.virtual_keyboard_keymap { + Some(active) => active.saved, + None => { + let keyboard = self.niri.seat.get_keyboard().unwrap(); + SavedKeyboardState { + num_lock: Some(keyboard.modifier_state().num_lock), + ..Default::default() + } + } } } + /// Returns the current keyboard state that gets reset by replacing the seat's keymap. + pub fn current_keyboard_state(&mut self) -> SavedKeyboardState { + let keyboard = self.niri.seat.get_keyboard().unwrap(); + let mods = keyboard.modifier_state(); + let layout = keyboard.with_xkb_state(self, |context| { + context.xkb().lock().unwrap().active_layout() + }); + SavedKeyboardState { + layout: Some(layout), + caps_lock: Some(mods.caps_lock), + num_lock: Some(mods.num_lock), + } + } + + pub fn restore_keyboard_state(&mut self, state: SavedKeyboardState) { + let keyboard = self.niri.seat.get_keyboard().unwrap(); + + let mut mods = keyboard.modifier_state(); + let mut mods_changed = false; + if let Some(caps_lock) = state.caps_lock { + if mods.caps_lock != caps_lock { + mods.caps_lock = caps_lock; + mods_changed = true; + } + } + if let Some(num_lock) = state.num_lock { + if mods.num_lock != num_lock { + mods.num_lock = num_lock; + mods_changed = true; + } + } + if mods_changed { + keyboard.set_modifier_state(mods); + // set_modifier_state() doesn't tell the focused client on its own. + keyboard.advertise_modifier_state(self); + } + + // set_modifier_state() can reset the layout, so restore it afterwards. + if let Some(layout) = state.layout { + keyboard.with_xkb_state(self, |mut context| { + let (exists, current) = { + let xkb = context.xkb().lock().unwrap(); + (xkb.layouts().any(|l| l == layout), xkb.active_layout()) + }; + if exists && current != layout { + context.set_layout(layout); + } + }); + } + } + + /// Loads the configured keymap (xkb file, xkb config, or locale1's) onto the seat, replacing a + /// virtual keyboard's if there is one. + pub fn load_configured_keymap(&mut self) { + let mut xkb = self.niri.config.borrow().input.keyboard.xkb.clone(); + let mut set_xkb_config = true; + + if let Some(xkb_file) = xkb.file.take() { + if let Err(err) = self.set_xkb_file(xkb_file) { + warn!("error loading xkb_file: {err:?}"); + } else { + set_xkb_config = false; + } + } + + if set_xkb_config { + // If xkb is unset in the niri config, use settings from locale1. + if xkb == Xkb::default() { + trace!("using xkb from locale1"); + xkb = self.niri.xkb_from_locale1.clone().unwrap_or_default(); + } + + self.set_xkb_config(xkb.to_xkb_config()); + } + + self.ipc_keyboard_layouts_changed(); + } + pub fn reload_config(&mut self, config: Result) { let _span = tracy_client::span!("State::reload_config"); @@ -1600,7 +1711,7 @@ impl State { *CHILD_ENV.write().unwrap() = mem::take(&mut config.environment); - let mut reload_xkb = None; + let mut reload_xkb = false; let mut libinput_config_changed = false; let mut output_config_changed = false; let mut preserved_output_config = None; @@ -1622,7 +1733,7 @@ impl State { // We need &mut self to reload the xkb config, so just store it here. if config.input.keyboard.xkb != old_config.input.keyboard.xkb { - reload_xkb = Some(config.input.keyboard.xkb.clone()); + reload_xkb = true; } // Reload the repeat info. @@ -1755,31 +1866,8 @@ impl State { drop(old_config); // Now with a &mut self we can reload the xkb config. - if let Some(mut xkb) = reload_xkb { - let mut set_xkb_config = true; - - // It's fine to .take() the xkb file, as this is a - // clone and the file field is not used in the XkbConfig. - if let Some(xkb_file) = xkb.file.take() { - if let Err(err) = self.set_xkb_file(xkb_file) { - warn!("error reloading xkb_file: {err:?}"); - } else { - // We successfully set xkb file so we don't need to fallback to XkbConfig. - set_xkb_config = false; - } - } - - if set_xkb_config { - // If xkb is unset in the niri config, use settings from locale1. - if xkb == Xkb::default() { - trace!("using xkb from locale1"); - xkb = self.niri.xkb_from_locale1.clone().unwrap_or_default(); - } - - self.set_xkb_config(xkb.to_xkb_config()); - } - - self.ipc_keyboard_layouts_changed(); + if reload_xkb { + self.load_configured_keymap(); } if libinput_config_changed { @@ -2744,6 +2832,8 @@ impl Niri { is_fdo_idle_inhibited: Arc::new(AtomicBool::new(false)), keyboard_shortcuts_inhibiting_surfaces: HashMap::new(), xkb_from_locale1: None, + virtual_keyboard_keymap: None, + configured_keymap: None, cursor_manager, cursor_texture_cache: Default::default(), cursor_shape_manager_state, diff --git a/src/protocols/mod.rs b/src/protocols/mod.rs index 9a6b25a7..9ec4c760 100644 --- a/src/protocols/mod.rs +++ b/src/protocols/mod.rs @@ -4,7 +4,6 @@ pub mod gamma_control; pub mod mutter_x11_interop; pub mod output_management; pub mod screencopy; -pub mod virtual_pointer; pub mod raw; diff --git a/src/protocols/virtual_pointer.rs b/src/protocols/virtual_pointer.rs deleted file mode 100644 index 233133f8..00000000 --- a/src/protocols/virtual_pointer.rs +++ /dev/null @@ -1,545 +0,0 @@ -use std::collections::HashSet; -use std::sync::Mutex; - -use smithay::backend::input::{ - AbsolutePositionEvent, Axis, AxisRelativeDirection, AxisSource, ButtonState, Device, - DeviceCapability, Event, InputBackend, InputTime, PointerAxisEvent, PointerButtonEvent, - PointerMotionAbsoluteEvent, PointerMotionEvent, UnusedEvent, -}; -use smithay::input::pointer::AxisFrame; -use smithay::output::Output; -use smithay::reexports::wayland_protocols_wlr; -use smithay::reexports::wayland_server::protocol::wl_pointer; -use smithay::reexports::wayland_server::protocol::wl_seat::WlSeat; -use smithay::reexports::wayland_server::{ - Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource, -}; -use smithay::wayland::{Dispatch2, GlobalDispatch2}; -use wayland_backend::protocol::WEnum; -use wayland_protocols_wlr::virtual_pointer::v1::server::{ - zwlr_virtual_pointer_manager_v1, zwlr_virtual_pointer_v1, -}; -use zwlr_virtual_pointer_manager_v1::ZwlrVirtualPointerManagerV1; -use zwlr_virtual_pointer_v1::ZwlrVirtualPointerV1; - -use crate::protocols::EmptyData; - -const VERSION: u32 = 2; - -pub struct VirtualPointerManagerState { - virtual_pointers: HashSet, -} - -pub struct VirtualPointerManagerGlobalData { - filter: Box Fn(&'c Client) -> bool + Send + Sync>, -} - -pub struct VirtualPointerInputBackend; - -#[derive(Clone, Debug, Hash, Eq, PartialEq)] -pub struct VirtualPointer { - pointer: ZwlrVirtualPointerV1, -} - -#[derive(Debug)] -pub struct VirtualPointerUserData { - seat: Option, - output: Option, - - axis_frame: Mutex>, -} - -impl VirtualPointer { - fn data(&self) -> &VirtualPointerUserData { - self.pointer.data().unwrap() - } - - pub fn seat(&self) -> Option<&WlSeat> { - self.data().seat.as_ref() - } - - pub fn output(&self) -> Option<&Output> { - self.data().output.as_ref() - } - - fn finish_axis_frame(&self) -> Option { - self.data().axis_frame.lock().unwrap().take() - } - - fn mutate_axis_frame(&self, time: Option, f: impl FnOnce(AxisFrame) -> AxisFrame) { - let mut frame = self.data().axis_frame.lock().unwrap(); - - *frame = frame - .or(time.map(InputTime::from_millis).map(AxisFrame::new)) - .map(f); - } -} - -impl Device for VirtualPointer { - fn id(&self) -> String { - format!("wlr virtual pointer {}", self.pointer.id()) - } - - fn name(&self) -> String { - String::from("virtual pointer") - } - - fn has_capability(&self, capability: DeviceCapability) -> bool { - matches!(capability, DeviceCapability::Pointer) - } - - fn usb_id(&self) -> Option<(u32, u32)> { - None - } - - fn syspath(&self) -> Option { - None - } -} - -pub struct VirtualPointerMotionEvent { - pointer: VirtualPointer, - time: u32, - dx: f64, - dy: f64, -} - -impl Event for VirtualPointerMotionEvent { - fn time(&self) -> InputTime { - InputTime::from_millis(self.time) - } - - fn device(&self) -> VirtualPointer { - self.pointer.clone() - } -} - -impl PointerMotionEvent for VirtualPointerMotionEvent { - fn delta_x(&self) -> f64 { - self.dx - } - - fn delta_y(&self) -> f64 { - self.dy - } - - fn delta_x_unaccel(&self) -> f64 { - self.dx - } - - fn delta_y_unaccel(&self) -> f64 { - self.dy - } -} - -pub struct VirtualPointerMotionAbsoluteEvent { - pointer: VirtualPointer, - time: u32, - x: u32, - y: u32, - x_extent: u32, - y_extent: u32, -} - -impl Event for VirtualPointerMotionAbsoluteEvent { - fn time(&self) -> InputTime { - InputTime::from_millis(self.time) - } - - fn device(&self) -> VirtualPointer { - self.pointer.clone() - } -} - -impl AbsolutePositionEvent for VirtualPointerMotionAbsoluteEvent { - fn x(&self) -> f64 { - self.x as f64 / self.x_extent as f64 - } - - fn y(&self) -> f64 { - self.y as f64 / self.y_extent as f64 - } - - fn x_transformed(&self, width: i32) -> f64 { - (self.x as i64 * width as i64) as f64 / self.x_extent as f64 - } - - fn y_transformed(&self, height: i32) -> f64 { - (self.y as i64 * height as i64) as f64 / self.y_extent as f64 - } -} - -pub struct VirtualPointerButtonEvent { - pointer: VirtualPointer, - time: u32, - button: u32, - state: ButtonState, -} - -impl Event for VirtualPointerButtonEvent { - fn time(&self) -> InputTime { - InputTime::from_millis(self.time) - } - - fn device(&self) -> VirtualPointer { - self.pointer.clone() - } -} - -impl PointerButtonEvent for VirtualPointerButtonEvent { - fn button_code(&self) -> u32 { - self.button - } - - fn state(&self) -> ButtonState { - self.state - } -} - -pub struct VirtualPointerAxisEvent { - pointer: VirtualPointer, - frame: AxisFrame, -} - -impl Event for VirtualPointerAxisEvent { - fn time(&self) -> InputTime { - self.frame.time - } - - fn device(&self) -> VirtualPointer { - self.pointer.clone() - } -} - -fn tuple_axis(tuple: (T, T), axis: Axis) -> T { - match axis { - Axis::Horizontal => tuple.0, - Axis::Vertical => tuple.1, - } -} - -impl PointerAxisEvent for VirtualPointerAxisEvent { - fn amount(&self, axis: Axis) -> Option { - Some(tuple_axis(self.frame.axis, axis)) - } - - fn amount_v120(&self, axis: Axis) -> Option { - self.frame.v120.map(|v120| tuple_axis(v120, axis) as f64) - } - - fn source(&self) -> AxisSource { - self.frame.source.unwrap_or_else(|| { - warn!("AxisSource: no source set, giving bogus value"); - AxisSource::Continuous - }) - } - - fn relative_direction(&self, axis: Axis) -> AxisRelativeDirection { - tuple_axis(self.frame.relative_direction, axis) - } -} - -impl PointerMotionAbsoluteEvent for VirtualPointerMotionAbsoluteEvent {} - -impl InputBackend for VirtualPointerInputBackend { - type Device = VirtualPointer; - - type KeyboardKeyEvent = UnusedEvent; - type PointerAxisEvent = VirtualPointerAxisEvent; - type PointerButtonEvent = VirtualPointerButtonEvent; - type PointerMotionEvent = VirtualPointerMotionEvent; - type PointerMotionAbsoluteEvent = VirtualPointerMotionAbsoluteEvent; - - 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; -} - -pub trait VirtualPointerHandler { - fn virtual_pointer_manager_state(&mut self) -> &mut VirtualPointerManagerState; - - fn create_virtual_pointer(&mut self, pointer: VirtualPointer) { - let _ = pointer; - } - fn destroy_virtual_pointer(&mut self, pointer: VirtualPointer) { - let _ = pointer; - } - - fn on_virtual_pointer_motion(&mut self, event: VirtualPointerMotionEvent); - fn on_virtual_pointer_motion_absolute(&mut self, event: VirtualPointerMotionAbsoluteEvent); - fn on_virtual_pointer_button(&mut self, event: VirtualPointerButtonEvent); - fn on_virtual_pointer_axis(&mut self, event: VirtualPointerAxisEvent); -} - -impl VirtualPointerManagerState { - pub fn new(display: &DisplayHandle, filter: F) -> Self - where - D: GlobalDispatch, - D: VirtualPointerHandler, - D: 'static, - F: for<'c> Fn(&'c Client) -> bool + Send + Sync + 'static, - { - let global_data = VirtualPointerManagerGlobalData { - filter: Box::new(filter), - }; - display.create_global::(VERSION, global_data); - - Self { - virtual_pointers: HashSet::new(), - } - } -} - -impl GlobalDispatch2 for VirtualPointerManagerGlobalData -where - D: Dispatch, - D: 'static, -{ - fn bind( - &self, - _state: &mut D, - _handle: &DisplayHandle, - _client: &Client, - manager: New, - data_init: &mut DataInit<'_, D>, - ) { - data_init.init(manager, EmptyData); - } - - fn can_view(&self, client: &Client) -> bool { - (self.filter)(client) - } -} - -impl Dispatch2 for EmptyData -where - D: Dispatch, - D: VirtualPointerHandler, - D: 'static, -{ - fn request( - &self, - state: &mut D, - _client: &Client, - _resource: &ZwlrVirtualPointerManagerV1, - request: ::Request, - _dhandle: &DisplayHandle, - data_init: &mut DataInit<'_, D>, - ) { - let (id, seat, output) = match request { - zwlr_virtual_pointer_manager_v1::Request::CreateVirtualPointer { seat, id } => { - (id, seat, None) - } - zwlr_virtual_pointer_manager_v1::Request::CreateVirtualPointerWithOutput { - seat, - output, - id, - } => (id, seat, output.as_ref().and_then(Output::from_resource)), - zwlr_virtual_pointer_manager_v1::Request::Destroy => return, - _ => unreachable!(), - }; - - let pointer = data_init.init( - id, - VirtualPointerUserData { - seat, - output, - axis_frame: Mutex::new(None), - }, - ); - state - .virtual_pointer_manager_state() - .virtual_pointers - .insert(pointer.clone()); - - state.create_virtual_pointer(VirtualPointer { pointer }); - } -} - -impl Dispatch2 for VirtualPointerUserData -where - D: VirtualPointerHandler, - D: 'static, -{ - fn request( - &self, - handler: &mut D, - _client: &Client, - resource: &ZwlrVirtualPointerV1, - request: ::Request, - _dhandle: &DisplayHandle, - _data_init: &mut DataInit<'_, D>, - ) { - let pointer = VirtualPointer { - pointer: resource.clone(), - }; - match request { - zwlr_virtual_pointer_v1::Request::Motion { time, dx, dy } => { - let event = VirtualPointerMotionEvent { - pointer, - time, - dx, - dy, - }; - handler.on_virtual_pointer_motion(event); - } - zwlr_virtual_pointer_v1::Request::MotionAbsolute { - time, - x, - y, - x_extent, - y_extent, - } => { - let event = VirtualPointerMotionAbsoluteEvent { - pointer, - time, - x, - y, - x_extent, - y_extent, - }; - handler.on_virtual_pointer_motion_absolute(event); - } - zwlr_virtual_pointer_v1::Request::Button { - time, - button, - state, - } => { - // state is an enum but wlroots treats it as a C boolean (zero or nonzero) - // so we emulate that behaviour too. ButtonState::Pressed and any invalid value - // counts as pressed. - // https://gitlab.freedesktop.org/wlroots/wlroots/-/blob/3187479c07c34a4de82c06a316a763a36a0499da/types/wlr_virtual_pointer_v1.c#L74 - let state = match state { - WEnum::Value(wl_pointer::ButtonState::Released) => ButtonState::Released, - _ => ButtonState::Pressed, - }; - let event = VirtualPointerButtonEvent { - pointer, - time, - button, - state, - }; - handler.on_virtual_pointer_button(event); - } - zwlr_virtual_pointer_v1::Request::Axis { time, axis, value } => { - let axis = match axis { - WEnum::Value(wl_pointer::Axis::VerticalScroll) => Axis::Vertical, - WEnum::Value(wl_pointer::Axis::HorizontalScroll) => Axis::Horizontal, - _ => { - warn!("Axis: invalid axis"); - resource.post_error( - zwlr_virtual_pointer_v1::Error::InvalidAxis, - "invalid axis", - ); - return; - } - }; - - pointer.mutate_axis_frame(Some(time), |frame| frame.value(axis, value)); - } - zwlr_virtual_pointer_v1::Request::Frame => { - if let Some(frame) = pointer.finish_axis_frame() { - let event = VirtualPointerAxisEvent { pointer, frame }; - handler.on_virtual_pointer_axis(event); - } - } - zwlr_virtual_pointer_v1::Request::AxisSource { axis_source } => { - let axis_source = match axis_source { - WEnum::Value(wl_pointer::AxisSource::Wheel) => AxisSource::Wheel, - WEnum::Value(wl_pointer::AxisSource::Finger) => AxisSource::Finger, - WEnum::Value(wl_pointer::AxisSource::Continuous) => AxisSource::Continuous, - WEnum::Value(wl_pointer::AxisSource::WheelTilt) => AxisSource::WheelTilt, - - _ => { - warn!("AxisSource: invalid axis source"); - resource.post_error( - zwlr_virtual_pointer_v1::Error::InvalidAxisSource, - "invalid axis source", - ); - return; - } - }; - - pointer.mutate_axis_frame(None, |frame| frame.source(axis_source)); - } - zwlr_virtual_pointer_v1::Request::AxisStop { time, axis } => { - let axis = match axis { - WEnum::Value(wl_pointer::Axis::VerticalScroll) => Axis::Vertical, - WEnum::Value(wl_pointer::Axis::HorizontalScroll) => Axis::Horizontal, - _ => { - warn!("AxisStop: invalid axis"); - resource.post_error( - zwlr_virtual_pointer_v1::Error::InvalidAxis, - "invalid axis", - ); - return; - } - }; - - pointer.mutate_axis_frame(Some(time), |frame| frame.stop(axis)); - } - zwlr_virtual_pointer_v1::Request::AxisDiscrete { - time, - axis, - value, - discrete, - } => { - let axis = match axis { - WEnum::Value(wl_pointer::Axis::VerticalScroll) => Axis::Vertical, - WEnum::Value(wl_pointer::Axis::HorizontalScroll) => Axis::Horizontal, - _ => { - warn!("AxisDiscrete: invalid axis"); - resource.post_error( - zwlr_virtual_pointer_v1::Error::InvalidAxis, - "invalid axis", - ); - return; - } - }; - pointer.mutate_axis_frame(Some(time), |frame| { - frame - .value(axis, value) - .v120(axis, discrete.saturating_mul(120)) - }); - } - zwlr_virtual_pointer_v1::Request::Destroy => {} - _ => unreachable!(), - } - } - - fn destroyed( - &self, - handler: &mut D, - _client: wayland_backend::server::ClientId, - resource: &ZwlrVirtualPointerV1, - ) { - let pointer = VirtualPointer { - pointer: resource.clone(), - }; - - handler.destroy_virtual_pointer(pointer); - handler - .virtual_pointer_manager_state() - .virtual_pointers - .remove(resource); - } -}