forge
Explore
Log in

Don't you dare go Hollow

Use the new virtual keyboard/pointer implementations from smithay

Browse files at this commit

7da6ae44032ec92f4ff28a42ca23f11c092f487fPatrick GaskinParent: ee146f8
  • feat
    • use the new virtual keyboard/pointer implementations from smithay
Show full message
feat: use the new virtual keyboard/pointer implementations from smithay

Fixes a bunch of virtual input bugs, most notably keybind handling and
virtual keyboard keymaps.
Cargo.lockmodified+2 -2
@@ -3396,7 +3396,7 @@ checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100"
3396 [[package]]3396 [[package]]
3397 name = "smithay"3397 name = "smithay"
3398 version = "0.7.0"3398 version = "0.7.0"
3399-source = "git+https://github.com/Smithay/smithay.git?rev=19c16d3e34172fcc8fb3d293bcae563b0a19ea70#19c16d3e34172fcc8fb3d293bcae563b0a19ea70"3399+source = "git+https://github.com/Smithay/smithay.git?rev=9786228efad25d65af0bb516642c1e8b0c359f37#9786228efad25d65af0bb516642c1e8b0c359f37"
3400 dependencies = [3400 dependencies = [
3401 "aliasable",3401 "aliasable",
3402 "appendlist",3402 "appendlist",
@@ -3473,7 +3473,7 @@ dependencies = [
3473 [[package]]3473 [[package]]
3474 name = "smithay-drm-extras"3474 name = "smithay-drm-extras"
3475 version = "0.1.0"3475 version = "0.1.0"
3476-source = "git+https://github.com/Smithay/smithay.git?rev=19c16d3e34172fcc8fb3d293bcae563b0a19ea70#19c16d3e34172fcc8fb3d293bcae563b0a19ea70"3476+source = "git+https://github.com/Smithay/smithay.git?rev=9786228efad25d65af0bb516642c1e8b0c359f37#9786228efad25d65af0bb516642c1e8b0c359f37"
3477 dependencies = [3477 dependencies = [
3478 "drm",3478 "drm",
3479 "libdisplay-info",3479 "libdisplay-info",
Cargo.tomlmodified+2 -2
@@ -28,13 +28,13 @@ tracy-client = { version = "0.18.5", default-features = false }
28 [workspace.dependencies.smithay]28 [workspace.dependencies.smithay]
29 # version = "0.4.1"29 # version = "0.4.1"
30 git = "https://github.com/Smithay/smithay.git"30 git = "https://github.com/Smithay/smithay.git"
31-rev = "19c16d3e34172fcc8fb3d293bcae563b0a19ea70"31+rev = "9786228efad25d65af0bb516642c1e8b0c359f37"
32 default-features = false32 default-features = false
33 33
34 [workspace.dependencies.smithay-drm-extras]34 [workspace.dependencies.smithay-drm-extras]
35 # version = "0.1.0"35 # version = "0.1.0"
36 git = "https://github.com/Smithay/smithay.git"36 git = "https://github.com/Smithay/smithay.git"
37-rev = "19c16d3e34172fcc8fb3d293bcae563b0a19ea70"37+rev = "9786228efad25d65af0bb516642c1e8b0c359f37"
38 # path = "../smithay/smithay-drm-extras"38 # path = "../smithay/smithay-drm-extras"
39 39
40 [package]40 [package]
src/handlers/mod.rsmodified+4 -25
@@ -2,6 +2,7 @@ pub mod background_effect;
2 mod compositor;2 mod compositor;
3 pub mod image_copy_capture;3 pub mod image_copy_capture;
4 mod layer_shell;4 mod layer_shell;
5+pub mod virtual_keyboard;
5 mod xdg_shell;6 mod xdg_shell;
6 7
7 use std::fs::File;8 use std::fs::File;
@@ -62,6 +63,7 @@ use smithay::wayland::session_lock::{
62 LockSurface, SessionLockHandler, SessionLockManagerState, SessionLocker,63 LockSurface, SessionLockHandler, SessionLockManagerState, SessionLocker,
63 };64 };
64 use smithay::wayland::text_input::TextInputActivation;65 use smithay::wayland::text_input::TextInputActivation;
66+use smithay::wayland::virtual_pointer::{VirtualPointerBackend, VirtualPointerHandler};
65 use smithay::wayland::xdg_activation::{67 use smithay::wayland::xdg_activation::{
66 XdgActivationHandler, XdgActivationState, XdgActivationToken, XdgActivationTokenData,68 XdgActivationHandler, XdgActivationState, XdgActivationToken, XdgActivationTokenData,
67 };69 };
@@ -79,11 +81,6 @@ use crate::protocols::gamma_control::{GammaControlHandler, GammaControlManagerSt
79 use crate::protocols::mutter_x11_interop::MutterX11InteropHandler;81 use crate::protocols::mutter_x11_interop::MutterX11InteropHandler;
80 use crate::protocols::output_management::{OutputManagementHandler, OutputManagementManagerState};82 use crate::protocols::output_management::{OutputManagementHandler, OutputManagementManagerState};
81 use crate::protocols::screencopy::{Screencopy, ScreencopyHandler, ScreencopyManagerState};83 use crate::protocols::screencopy::{Screencopy, ScreencopyHandler, ScreencopyManagerState};
82-use crate::protocols::virtual_pointer::{
83- VirtualPointerAxisEvent, VirtualPointerButtonEvent, VirtualPointerHandler,
84- VirtualPointerInputBackend, VirtualPointerManagerState, VirtualPointerMotionAbsoluteEvent,
85- VirtualPointerMotionEvent,
86-};
87 use crate::utils::{output_size, send_scale_transform};84 use crate::utils::{output_size, send_scale_transform};
88 85
89 pub const XDG_ACTIVATION_TOKEN_TIMEOUT: Duration = Duration::from_secs(10);86 pub const XDG_ACTIVATION_TOKEN_TIMEOUT: Duration = Duration::from_secs(10);
@@ -660,26 +657,8 @@ impl ScreencopyHandler for State {
660 }657 }
661 658
662 impl VirtualPointerHandler for State {659 impl VirtualPointerHandler for State {
663- fn virtual_pointer_manager_state(&mut self) -> &mut VirtualPointerManagerState {660+ fn process_virtual_pointer_event(&mut self, event: InputEvent<VirtualPointerBackend>) {
664- &mut self.niri.virtual_pointer_state661+ self.process_input_event(event);
665- }
666-
667- fn on_virtual_pointer_motion(&mut self, event: VirtualPointerMotionEvent) {
668- self.process_input_event(InputEvent::<VirtualPointerInputBackend>::PointerMotion { event });
669- }
670-
671- fn on_virtual_pointer_motion_absolute(&mut self, event: VirtualPointerMotionAbsoluteEvent) {
672- self.process_input_event(
673- InputEvent::<VirtualPointerInputBackend>::PointerMotionAbsolute { event },
674- );
675- }
676-
677- fn on_virtual_pointer_button(&mut self, event: VirtualPointerButtonEvent) {
678- self.process_input_event(InputEvent::<VirtualPointerInputBackend>::PointerButton { event });
679- }
680-
681- fn on_virtual_pointer_axis(&mut self, event: VirtualPointerAxisEvent) {
682- self.process_input_event(InputEvent::<VirtualPointerInputBackend>::PointerAxis { event });
683 }662 }
684 }663 }
685 664
src/handlers/virtual_keyboard.rsadded+253 -0
@@ -0,0 +1,253 @@
1+//! `zwp_virtual_keyboard_v1` handling.
2+//!
3+//! Virtual keyboards are handled like a real keyboard (binds, grabs, etc), but differ in a few
4+//! ways:
5+//!
6+//! - A virtual keyboard's keymap may differ from the seat's one, and if so, will be swapped before
7+//! events from it are forwarded (restoring the saved layout and a subset of modifiers when
8+//! swapping back to the original one).
9+//! - If the virtual keyboard uses `no_keymap` or the same one as the seat, it will use the seat's
10+//! xkb state directly.
11+//! - If a client grabs the keyboard, then forwards events through a virtual keyboard (e.g., fcitx),
12+//! they are then forwarded bypassing the grab to avoid loops (sway special-cases this too).
13+//! - Modifiers set through the `modifiers` request apply to the shared xkb state (see
14+//! `DeviceRemoved`).
15+
16+use std::sync::Arc;
17+
18+use smithay::backend::input::{Event, InputEvent, KeyboardKeyEvent};
19+use smithay::utils::SERIAL_COUNTER;
20+use smithay::wayland::input_method::InputMethodSeat;
21+use smithay::wayland::virtual_keyboard::{
22+ VirtualKeyboardBackend, VirtualKeyboardDevice, VirtualKeyboardHandler, VirtualKeyboardKeyEvent,
23+ VirtualKeyboardSpecialEvent,
24+};
25+
26+use crate::niri::{SavedKeyboardState, State};
27+
28+/// Virtual keyboard keymap (which temporarily replaces the shared seat one).
29+#[derive(Debug)]
30+pub struct VirtualKeyboardKeymap {
31+ pub device: VirtualKeyboardDevice,
32+ pub keymap: Arc<str>,
33+ pub saved: SavedKeyboardState,
34+}
35+
36+impl VirtualKeyboardHandler for State {
37+ fn process_virtual_keyboard_event(&mut self, event: InputEvent<VirtualKeyboardBackend>) {
38+ match event {
39+ InputEvent::Keyboard { event } => {
40+ let device = event.device();
41+ self.activate_virtual_keyboard_keymap(&device);
42+ if self.is_input_method_virtual_keyboard(&device) {
43+ // Do not forward passed-through events from a grab back to
44+ // the grab.
45+ self.forward_input_method_key(&event);
46+ } else {
47+ self.process_input_event(InputEvent::<VirtualKeyboardBackend>::Keyboard {
48+ event,
49+ });
50+ }
51+ }
52+ InputEvent::Special(VirtualKeyboardSpecialEvent::Modifiers {
53+ device,
54+ mods_depressed,
55+ mods_latched,
56+ mods_locked,
57+ group,
58+ }) => {
59+ self.activate_virtual_keyboard_keymap(&device);
60+
61+ let keyboard = self.niri.seat.get_keyboard().unwrap();
62+ keyboard.with_xkb_state(self, |mut context| {
63+ context.set_modifier_mask(mods_depressed, mods_latched, mods_locked, group);
64+ });
65+ }
66+ InputEvent::Special(VirtualKeyboardSpecialEvent::KeymapChanged { .. }) => {
67+ // The new keymap will be activated by the next key or modifiers event.
68+ }
69+ InputEvent::DeviceRemoved { device } => {
70+ // Restore the original keymap if this device is active. This is
71+ // checked based on the device rather than on the keymap, since
72+ // the client may have replaced its keymap after we activated it
73+ // and not sent any key/modifier events afterwards before
74+ // removing the device.
75+ let active = self
76+ .niri
77+ .virtual_keyboard_keymap
78+ .as_ref()
79+ .is_some_and(|active| active.device == device);
80+ if active {
81+ self.restore_configured_keymap();
82+ }
83+
84+ // The held keys have already been released by smithay.
85+ //
86+ // We don't reset the modifiers since there's no way to tell which ones were set by
87+ // this keyboard specifically since the masks are absolute. This only affects
88+ // virtual keyboards without a keymap, or with the same keymap as the seat. We could
89+ // track which bits were set by each virtual keyboard, but it's more complex, and we
90+ // still would need to rebuild the modifier state after to avoid potentially leaving
91+ // modifiers without a corresponding key stuck, and it's not really possible to
92+ // rebuild it cleanly for all possible layouts (e.g., `grp:alt_shift_toggle`,
93+ // layouts with multi-level modifier keys) without tracking the exact sequence the
94+ // modifiers were pressed in (see
95+ // https://github.com/niri-wm/niri/pull/4548#discussion_r4237056727).
96+ //
97+ // Not resetting the modifiers means that:
98+ //
99+ // - a locked modifier or layout group set by `modifiers` stays until the user
100+ // toggles it (most layouts have clearLocks on Shift/Ctrl/Alt/Super, so those can
101+ // be reset by pressing the key, but ones without a corresponding key can't be
102+ // cleared without a keymap change or another modifiers request from a virtual
103+ // keyboard)
104+ // - if the virtual keyboard sets the modifiers without taking into account the
105+ // existing state and clears a locked modifier, the locked modifier will remain
106+ // cleared
107+ // - a modifier set only through `modifiers` will stay set until the corresponding
108+ // key is pressed
109+ //
110+ // To handle this properly, we need support for per-device xkb state (and we can
111+ // merge the modifier state across the xkb states to keep shortcuts working across
112+ // keyboards) in smithay like sway and hyprland.
113+ self.process_input_event(InputEvent::<VirtualKeyboardBackend>::DeviceRemoved {
114+ device,
115+ });
116+ }
117+ event => self.process_input_event(event),
118+ }
119+ }
120+}
121+
122+impl State {
123+ /// Whether the virtual keyboard belongs to the input method that has grabbed the keyboard.
124+ pub fn is_input_method_virtual_keyboard(&self, device: &VirtualKeyboardDevice) -> bool {
125+ let grab_client = self.niri.seat.input_method().keyboard_grab_client();
126+ grab_client.is_some() && grab_client == device.client()
127+ }
128+
129+ /// Forwards a key that the input method is passing through directly to the focused surface.
130+ ///
131+ /// While an input method holds the keyboard grab, keys go through the binds and then to the
132+ /// input method, which sends back unhandled ones through its own virtual keyboard. If we
133+ /// handled these normally, they would get sent back to the grab, looping forever.
134+ ///
135+ /// Note that sway also special-cases this in the same way.
136+ pub fn forward_input_method_key(&mut self, event: &VirtualKeyboardKeyEvent) {
137+ let serial = SERIAL_COUNTER.next_serial();
138+
139+ // The modifiers associated with the physical key went to the input method
140+ // rather than to the surface, so always send the current ones.
141+ let keyboard = self.niri.seat.get_keyboard().unwrap();
142+ keyboard.input_forward_bypassing_grab(
143+ self,
144+ event.key_code(),
145+ event.state(),
146+ serial,
147+ event.time(),
148+ true,
149+ );
150+ }
151+
152+ /// Activates the virtual keyboard's keymap on the current seat, unless it already is.
153+ pub fn activate_virtual_keyboard_keymap(&mut self, device: &VirtualKeyboardDevice) {
154+ let Some(keymap) = device.keymap() else {
155+ // The keycodes are relative to the configured keymap, so make sure
156+ // it's the active one.
157+ self.restore_configured_keymap();
158+ return;
159+ };
160+
161+ if let Some(active) = &mut self.niri.virtual_keyboard_keymap {
162+ if active.keymap == keymap {
163+ // Another virtual keyboard may have installed an identical
164+ // keymap. Take ownership of it anyway, so that removing that
165+ // one doesn't take the keymap out from under us.
166+ active.device = device.clone();
167+ return;
168+ }
169+ }
170+
171+ // A keymap identical to the configured one (e.g. from an input method
172+ // forwarding keys with the keymap it received from us) doesn't need to
173+ // be swapped in, which would needlessly reset the keyboard state.
174+ if *self.configured_keymap() == *keymap {
175+ self.restore_configured_keymap();
176+ return;
177+ }
178+
179+ // Save the state from before the first virtual keyboard keymap, since
180+ // swapping keymaps resets it, and a virtual keyboard should neither
181+ // affect nor be affected by it.
182+ let saved = match &self.niri.virtual_keyboard_keymap {
183+ Some(active) => active.saved,
184+ None => self.current_keyboard_state(),
185+ };
186+
187+ let keyboard = self.niri.seat.get_keyboard().unwrap();
188+ if let Err(err) = keyboard.set_keymap_from_string(self, keymap.to_string()) {
189+ warn!("error setting virtual keyboard keymap: {err:?}");
190+ return;
191+ }
192+
193+ self.niri.virtual_keyboard_keymap = Some(VirtualKeyboardKeymap {
194+ device: device.clone(),
195+ keymap,
196+ saved,
197+ });
198+ self.ipc_keyboard_layouts_changed();
199+ }
200+
201+ /// Switches the seat back from a virtual keyboard's keymap to the configured one, if needed.
202+ ///
203+ /// The configured keymap was saved as text before the virtual keyboard's replaced it, so this
204+ /// doesn't re-read the xkb file or recompile the xkb config unnecessarily.
205+ pub fn restore_configured_keymap(&mut self) {
206+ let Some(active) = self.niri.virtual_keyboard_keymap.take() else {
207+ return;
208+ };
209+
210+ let keyboard = self.niri.seat.get_keyboard().unwrap();
211+ let restored = self.niri.configured_keymap.clone().is_some_and(|keymap| {
212+ keyboard
213+ .set_keymap_from_string(self, keymap.to_string())
214+ .inspect_err(|err| warn!("error restoring configured keymap: {err:?}"))
215+ .is_ok()
216+ });
217+
218+ if !restored {
219+ // Shouldn't happen unless there's an xkbcommon bug or configured_keymap somehow ends
220+ // up none while a virtual keymap is active, but fall back to loading it from the
221+ // config.
222+ error!("failed to restore the configured keymap, reloading it from the config");
223+ self.niri.virtual_keyboard_keymap = Some(active);
224+ self.niri.configured_keymap = None;
225+ self.load_configured_keymap();
226+ return;
227+ }
228+
229+ self.restore_keyboard_state(active.saved);
230+ self.ipc_keyboard_layouts_changed();
231+ }
232+
233+ /// Returns the configured keymap as XKB_KEYMAP_FORMAT_TEXT_V1.
234+ fn configured_keymap(&mut self) -> Arc<str> {
235+ if let Some(keymap) = &self.niri.configured_keymap {
236+ return keymap.clone();
237+ }
238+
239+ // The seat has the configured keymap while no virtual keyboard keymap is active.
240+ if self.niri.virtual_keyboard_keymap.is_some() {
241+ error!("virtual_keyboard_keymap must be None when resetting configured_keymap");
242+ }
243+
244+ let keyboard = self.niri.seat.get_keyboard().unwrap();
245+ let keymap: Arc<str> = keyboard
246+ .with_xkb_state(self, |context| {
247+ context.xkb().lock().unwrap().keymap_as_string()
248+ })
249+ .into();
250+ self.niri.configured_keymap = Some(keymap.clone());
251+ keymap
252+ }
253+}
src/input/backend_ext.rsmodified+10 -3
@@ -2,9 +2,10 @@ use ::input as libinput;
2 use smithay::backend::input;2 use smithay::backend::input;
3 use smithay::backend::winit::WinitVirtualDevice;3 use smithay::backend::winit::WinitVirtualDevice;
4 use smithay::output::Output;4 use smithay::output::Output;
5+use smithay::wayland::virtual_keyboard::VirtualKeyboardDevice;
6+use smithay::wayland::virtual_pointer::VirtualPointerDevice;
5 7
6 use crate::niri::State;8 use crate::niri::State;
7-use crate::protocols::virtual_pointer::VirtualPointer;
8 9
9 pub trait NiriInputBackend: input::InputBackend<Device = Self::NiriDevice> {10 pub trait NiriInputBackend: input::InputBackend<Device = Self::NiriDevice> {
10 type NiriDevice: NiriInputDevice;11 type NiriDevice: NiriInputDevice;
@@ -44,8 +45,14 @@ impl NiriInputDevice for WinitVirtualDevice {
44 }45 }
45 }46 }
46 47
47-impl NiriInputDevice for VirtualPointer {48+impl NiriInputDevice for VirtualPointerDevice {
48 fn output(&self, _: &State) -> Option<Output> {49 fn output(&self, _: &State) -> Option<Output> {
49- self.output().cloned()50+ self.output()
51+ }
52+}
53+
54+impl NiriInputDevice for VirtualKeyboardDevice {
55+ fn output(&self, _: &State) -> Option<Output> {
56+ None
50 }57 }
51 }58 }
src/input/mod.rsmodified+26 -3
@@ -19,7 +19,9 @@ use smithay::backend::input::{
19 };19 };
20 use smithay::backend::libinput::LibinputInputBackend;20 use smithay::backend::libinput::LibinputInputBackend;
21 use smithay::input::dnd::DnDGrab;21 use smithay::input::dnd::DnDGrab;
22-use smithay::input::keyboard::{keysyms, FilterResult, Keysym, Layout, ModifiersState};22+use smithay::input::keyboard::{
23+ keysyms, FilterResult, KeyboardSource, Keysym, Layout, ModifiersState,
24+};
23 use smithay::input::pointer::{25 use smithay::input::pointer::{
24 AxisFrame, ButtonEvent, CursorIcon, CursorImageStatus, Focus, GestureHoldBeginEvent,26 AxisFrame, ButtonEvent, CursorIcon, CursorImageStatus, Focus, GestureHoldBeginEvent,
25 GestureHoldEndEvent, GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent,27 GestureHoldEndEvent, GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent,
@@ -38,6 +40,7 @@ use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
38 use smithay::utils::{Logical, Point, Rectangle, Transform, SERIAL_COUNTER};40 use smithay::utils::{Logical, Point, Rectangle, Transform, SERIAL_COUNTER};
39 use smithay::wayland::keyboard_shortcuts_inhibit::KeyboardShortcutsInhibitor;41 use smithay::wayland::keyboard_shortcuts_inhibit::KeyboardShortcutsInhibitor;
40 use smithay::wayland::pointer_constraints::{with_pointer_constraint, PointerConstraint};42 use smithay::wayland::pointer_constraints::{with_pointer_constraint, PointerConstraint};
43+use smithay::wayland::virtual_keyboard::VirtualKeyboardDevice;
41 use touch_overview_grab::TouchOverviewGrab;44 use touch_overview_grab::TouchOverviewGrab;
42 45
43 use self::move_grab::MoveGrab;46 use self::move_grab::MoveGrab;
@@ -417,7 +420,26 @@ impl State {
417 &mut self,420 &mut self,
418 event: I::KeyboardKeyEvent,421 event: I::KeyboardKeyEvent,
419 consumed_by_a11y: &mut bool,422 consumed_by_a11y: &mut bool,
420- ) {423+ ) where
424+ I::Device: 'static,
425+ {
426+ let device = event.device();
427+ let virtual_keyboard = (&device as &dyn Any).downcast_ref::<VirtualKeyboardDevice>();
428+
429+ // Restore the real keymap if required (the virtual keyboard uses its own one).
430+ if virtual_keyboard.is_none() {
431+ self.restore_configured_keymap();
432+ }
433+
434+ // Keys from a virtual keyboard are tracked separately from the physical
435+ // ones, otherwise, a virtual keyboard sending a key already held by
436+ // another keyboard (an IME, e.g., fcitx, forwarding keys it got through its
437+ // grab) would release it prematurely.
438+ //
439+ // Note that keyboard shortcuts can still be pressed across multiple
440+ // keyboards even with this, as intended.
441+ let source = virtual_keyboard.map_or(KeyboardSource::MAIN, |device| device.source());
442+
421 let mod_key = self.backend.mod_key(&self.niri.config.borrow());443 let mod_key = self.backend.mod_key(&self.niri.config.borrow());
422 444
423 let serial = SERIAL_COUNTER.next_serial();445 let serial = SERIAL_COUNTER.next_serial();
@@ -468,7 +490,8 @@ impl State {
468 #[cfg(not(feature = "dbus"))]490 #[cfg(not(feature = "dbus"))]
469 let _ = consumed_by_a11y;491 let _ = consumed_by_a11y;
470 492
471- let Some(Some(bind)) = self.niri.seat.get_keyboard().unwrap().input(493+ let Some(Some(bind)) = self.niri.seat.get_keyboard().unwrap().input_from_source(
494+ source,
472 self,495 self,
473 event.key_code(),496 event.key_code(),
474 event.state(),497 event.state(),
src/niri.rsmodified+132 -42
@@ -114,6 +114,7 @@ use smithay::wayland::tablet_manager::TabletManagerState;
114 use smithay::wayland::text_input::TextInputManagerState;114 use smithay::wayland::text_input::TextInputManagerState;
115 use smithay::wayland::viewporter::ViewporterState;115 use smithay::wayland::viewporter::ViewporterState;
116 use smithay::wayland::virtual_keyboard::VirtualKeyboardManagerState;116 use smithay::wayland::virtual_keyboard::VirtualKeyboardManagerState;
117+use smithay::wayland::virtual_pointer::VirtualPointerManagerState;
117 use smithay::wayland::xdg_activation::XdgActivationState;118 use smithay::wayland::xdg_activation::XdgActivationState;
118 use smithay::wayland::xdg_foreign::XdgForeignState;119 use smithay::wayland::xdg_foreign::XdgForeignState;
119 use wayland_server::protocol::wl_output::WlOutput;120 use wayland_server::protocol::wl_output::WlOutput;
@@ -136,6 +137,7 @@ use crate::frame_clock::FrameClock;
136 use crate::handlers::image_copy_capture::{137 use crate::handlers::image_copy_capture::{
137 self as image_copy_capture_impl, CaptureBuffer, ImageCopyCursorSession, ImageCopySession,138 self as image_copy_capture_impl, CaptureBuffer, ImageCopyCursorSession, ImageCopySession,
138 };139 };
140+use crate::handlers::virtual_keyboard::VirtualKeyboardKeymap;
139 use crate::handlers::{configure_lock_surface, XDG_ACTIVATION_TOKEN_TIMEOUT};141 use crate::handlers::{configure_lock_surface, XDG_ACTIVATION_TOKEN_TIMEOUT};
140 use crate::input::pick_color_grab::PickColorGrab;142 use crate::input::pick_color_grab::PickColorGrab;
141 use crate::input::scroll_swipe_gesture::ScrollSwipeGesture;143 use crate::input::scroll_swipe_gesture::ScrollSwipeGesture;
@@ -160,7 +162,6 @@ use crate::protocols::gamma_control::GammaControlManagerState;
160 use crate::protocols::mutter_x11_interop::MutterX11InteropManagerState;162 use crate::protocols::mutter_x11_interop::MutterX11InteropManagerState;
161 use crate::protocols::output_management::OutputManagementManagerState;163 use crate::protocols::output_management::OutputManagementManagerState;
162 use crate::protocols::screencopy::{Screencopy, ScreencopyBuffer, ScreencopyManagerState};164 use crate::protocols::screencopy::{Screencopy, ScreencopyBuffer, ScreencopyManagerState};
163-use crate::protocols::virtual_pointer::VirtualPointerManagerState;
164 use crate::render_helpers::blur::BlurOptions;165 use crate::render_helpers::blur::BlurOptions;
165 use crate::render_helpers::debug::push_opaque_regions;166 use crate::render_helpers::debug::push_opaque_regions;
166 use crate::render_helpers::primary_gpu_texture::PrimaryGpuTextureRenderElement;167 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.];
201 // should be ~1.995 seconds.202 // should be ~1.995 seconds.
202 const FRAME_CALLBACK_THROTTLE: Option<Duration> = Some(Duration::from_millis(995));203 const FRAME_CALLBACK_THROTTLE: Option<Duration> = Some(Duration::from_millis(995));
203 204
205+/// Parts of the seat keyboard state that get reset when its keymap is replaced.
206+#[derive(Debug, Clone, Copy, Default)]
207+pub struct SavedKeyboardState {
208+ pub layout: Option<KeyboardLayout>,
209+ pub caps_lock: Option<bool>,
210+ pub num_lock: Option<bool>,
211+}
212+
204 pub struct Niri {213 pub struct Niri {
205 pub config: Rc<RefCell<Config>>,214 pub config: Rc<RefCell<Config>>,
206 215
@@ -360,6 +369,21 @@ pub struct Niri {
360 /// Most recent XKB settings from org.freedesktop.locale1.369 /// Most recent XKB settings from org.freedesktop.locale1.
361 pub xkb_from_locale1: Option<Xkb>,370 pub xkb_from_locale1: Option<Xkb>,
362 371
372+ /// Virtual keyboard for which the keymap is currently active on the seat,
373+ /// if any.
374+ ///
375+ /// Note that the keymap may be changed by the client at any time, and it
376+ /// only gets activated on the next key/modifier event from the virtual
377+ /// keyboard.
378+ pub virtual_keyboard_keymap: Option<VirtualKeyboardKeymap>,
379+ /// Configured (non-virtual-keyboard) keymap as XKB_KEYMAP_FORMAT_TEXT_V1.
380+ ///
381+ /// Computed lazily from the seat while no virtual keyboard keymap is
382+ /// active, and cleared whenever the configured keymap changes. Used to
383+ /// compare against virtual keyboard keymaps, and to switch back to it
384+ /// afterwards without going through the config again.
385+ pub configured_keymap: Option<Arc<str>>,
386+
363 pub cursor_manager: CursorManager,387 pub cursor_manager: CursorManager,
364 pub cursor_texture_cache: CursorTextureCache,388 pub cursor_texture_cache: CursorTextureCache,
365 pub cursor_shape_manager_state: CursorShapeManagerState,389 pub cursor_shape_manager_state: CursorShapeManagerState,
@@ -1512,18 +1536,14 @@ impl State {
1512 let keymap = std::fs::read_to_string(xkb_file).context("failed to read xkb_file")?;1536 let keymap = std::fs::read_to_string(xkb_file).context("failed to read xkb_file")?;
1513 1537
1514 let keyboard = self.niri.seat.get_keyboard().unwrap();1538 let keyboard = self.niri.seat.get_keyboard().unwrap();
1515- let num_lock = keyboard.modifier_state().num_lock;1539+ let restore = self.keyboard_state_to_restore();
1516 1540
1517 keyboard1541 keyboard
1518 .set_keymap_from_string(self, keymap)1542 .set_keymap_from_string(self, keymap)
1519 .context("failed to set keymap")?;1543 .context("failed to set keymap")?;
1520-1544+ self.niri.virtual_keyboard_keymap = None;
1521- // Restore num lock to its previous value.1545+ self.niri.configured_keymap = None;
1522- let mut mods_state = keyboard.modifier_state();1546+ self.restore_keyboard_state(restore);
1523- if mods_state.num_lock != num_lock {
1524- mods_state.num_lock = num_lock;
1525- keyboard.set_modifier_state(mods_state);
1526- }
1527 1547
1528 Ok(())1548 Ok(())
1529 }1549 }
@@ -1539,20 +1559,111 @@ impl State {
1539 1559
1540 pub fn set_xkb_config(&mut self, xkb: XkbConfig) {1560 pub fn set_xkb_config(&mut self, xkb: XkbConfig) {
1541 let keyboard = self.niri.seat.get_keyboard().unwrap();1561 let keyboard = self.niri.seat.get_keyboard().unwrap();
1542- let num_lock = keyboard.modifier_state().num_lock;1562+ let restore = self.keyboard_state_to_restore();
1543 if let Err(err) = keyboard.set_xkb_config(self, xkb) {1563 if let Err(err) = keyboard.set_xkb_config(self, xkb) {
1544 warn!("error updating xkb config: {err:?}");1564 warn!("error updating xkb config: {err:?}");
1545 return;1565 return;
1546 }1566 }
1567+ self.niri.virtual_keyboard_keymap = None;
1568+ self.niri.configured_keymap = None;
1569+ self.restore_keyboard_state(restore);
1570+ }
1547 1571
1548- // Restore num lock to its previous value.1572+ /// Returns the keyboard state to restore after replacing the seat's keymap (which resets it).
1549- let mut mods_state = keyboard.modifier_state();1573+ ///
1550- if mods_state.num_lock != num_lock {1574+ /// When switching back from a virtual keyboard's keymap, this is the state from before it was
1551- mods_state.num_lock = num_lock;1575+ /// activated. Otherwise, only Num Lock is carried over.
1552- keyboard.set_modifier_state(mods_state);1576+ pub fn keyboard_state_to_restore(&self) -> SavedKeyboardState {
1577+ match &self.niri.virtual_keyboard_keymap {
1578+ Some(active) => active.saved,
1579+ None => {
1580+ let keyboard = self.niri.seat.get_keyboard().unwrap();
1581+ SavedKeyboardState {
1582+ num_lock: Some(keyboard.modifier_state().num_lock),
1583+ ..Default::default()
1584+ }
1585+ }
1553 }1586 }
1554 }1587 }
1555 1588
1589+ /// Returns the current keyboard state that gets reset by replacing the seat's keymap.
1590+ pub fn current_keyboard_state(&mut self) -> SavedKeyboardState {
1591+ let keyboard = self.niri.seat.get_keyboard().unwrap();
1592+ let mods = keyboard.modifier_state();
1593+ let layout = keyboard.with_xkb_state(self, |context| {
1594+ context.xkb().lock().unwrap().active_layout()
1595+ });
1596+ SavedKeyboardState {
1597+ layout: Some(layout),
1598+ caps_lock: Some(mods.caps_lock),
1599+ num_lock: Some(mods.num_lock),
1600+ }
1601+ }
1602+
1603+ pub fn restore_keyboard_state(&mut self, state: SavedKeyboardState) {
1604+ let keyboard = self.niri.seat.get_keyboard().unwrap();
1605+
1606+ let mut mods = keyboard.modifier_state();
1607+ let mut mods_changed = false;
1608+ if let Some(caps_lock) = state.caps_lock {
1609+ if mods.caps_lock != caps_lock {
1610+ mods.caps_lock = caps_lock;
1611+ mods_changed = true;
1612+ }
1613+ }
1614+ if let Some(num_lock) = state.num_lock {
1615+ if mods.num_lock != num_lock {
1616+ mods.num_lock = num_lock;
1617+ mods_changed = true;
1618+ }
1619+ }
1620+ if mods_changed {
1621+ keyboard.set_modifier_state(mods);
1622+ // set_modifier_state() doesn't tell the focused client on its own.
1623+ keyboard.advertise_modifier_state(self);
1624+ }
1625+
1626+ // set_modifier_state() can reset the layout, so restore it afterwards.
1627+ if let Some(layout) = state.layout {
1628+ keyboard.with_xkb_state(self, |mut context| {
1629+ let (exists, current) = {
1630+ let xkb = context.xkb().lock().unwrap();
1631+ (xkb.layouts().any(|l| l == layout), xkb.active_layout())
1632+ };
1633+ if exists && current != layout {
1634+ context.set_layout(layout);
1635+ }
1636+ });
1637+ }
1638+ }
1639+
1640+ /// Loads the configured keymap (xkb file, xkb config, or locale1's) onto the seat, replacing a
1641+ /// virtual keyboard's if there is one.
1642+ pub fn load_configured_keymap(&mut self) {
1643+ let mut xkb = self.niri.config.borrow().input.keyboard.xkb.clone();
1644+ let mut set_xkb_config = true;
1645+
1646+ if let Some(xkb_file) = xkb.file.take() {
1647+ if let Err(err) = self.set_xkb_file(xkb_file) {
1648+ warn!("error loading xkb_file: {err:?}");
1649+ } else {
1650+ set_xkb_config = false;
1651+ }
1652+ }
1653+
1654+ if set_xkb_config {
1655+ // If xkb is unset in the niri config, use settings from locale1.
1656+ if xkb == Xkb::default() {
1657+ trace!("using xkb from locale1");
1658+ xkb = self.niri.xkb_from_locale1.clone().unwrap_or_default();
1659+ }
1660+
1661+ self.set_xkb_config(xkb.to_xkb_config());
1662+ }
1663+
1664+ self.ipc_keyboard_layouts_changed();
1665+ }
1666+
1556 pub fn reload_config(&mut self, config: Result<Config, ()>) {1667 pub fn reload_config(&mut self, config: Result<Config, ()>) {
1557 let _span = tracy_client::span!("State::reload_config");1668 let _span = tracy_client::span!("State::reload_config");
1558 1669
@@ -1600,7 +1711,7 @@ impl State {
1600 1711
1601 *CHILD_ENV.write().unwrap() = mem::take(&mut config.environment);1712 *CHILD_ENV.write().unwrap() = mem::take(&mut config.environment);
1602 1713
1603- let mut reload_xkb = None;1714+ let mut reload_xkb = false;
1604 let mut libinput_config_changed = false;1715 let mut libinput_config_changed = false;
1605 let mut output_config_changed = false;1716 let mut output_config_changed = false;
1606 let mut preserved_output_config = None;1717 let mut preserved_output_config = None;
@@ -1622,7 +1733,7 @@ impl State {
1622 1733
1623 // We need &mut self to reload the xkb config, so just store it here.1734 // We need &mut self to reload the xkb config, so just store it here.
1624 if config.input.keyboard.xkb != old_config.input.keyboard.xkb {1735 if config.input.keyboard.xkb != old_config.input.keyboard.xkb {
1625- reload_xkb = Some(config.input.keyboard.xkb.clone());1736+ reload_xkb = true;
1626 }1737 }
1627 1738
1628 // Reload the repeat info.1739 // Reload the repeat info.
@@ -1755,31 +1866,8 @@ impl State {
1755 drop(old_config);1866 drop(old_config);
1756 1867
1757 // Now with a &mut self we can reload the xkb config.1868 // Now with a &mut self we can reload the xkb config.
1758- if let Some(mut xkb) = reload_xkb {1869+ if reload_xkb {
1759- let mut set_xkb_config = true;1870+ self.load_configured_keymap();
1760-
1761- // It's fine to .take() the xkb file, as this is a
1762- // clone and the file field is not used in the XkbConfig.
1763- if let Some(xkb_file) = xkb.file.take() {
1764- if let Err(err) = self.set_xkb_file(xkb_file) {
1765- warn!("error reloading xkb_file: {err:?}");
1766- } else {
1767- // We successfully set xkb file so we don't need to fallback to XkbConfig.
1768- set_xkb_config = false;
1769- }
1770- }
1771-
1772- if set_xkb_config {
1773- // If xkb is unset in the niri config, use settings from locale1.
1774- if xkb == Xkb::default() {
1775- trace!("using xkb from locale1");
1776- xkb = self.niri.xkb_from_locale1.clone().unwrap_or_default();
1777- }
1778-
1779- self.set_xkb_config(xkb.to_xkb_config());
1780- }
1781-
1782- self.ipc_keyboard_layouts_changed();
1783 }1871 }
1784 1872
1785 if libinput_config_changed {1873 if libinput_config_changed {
@@ -2744,6 +2832,8 @@ impl Niri {
2744 is_fdo_idle_inhibited: Arc::new(AtomicBool::new(false)),2832 is_fdo_idle_inhibited: Arc::new(AtomicBool::new(false)),
2745 keyboard_shortcuts_inhibiting_surfaces: HashMap::new(),2833 keyboard_shortcuts_inhibiting_surfaces: HashMap::new(),
2746 xkb_from_locale1: None,2834 xkb_from_locale1: None,
2835+ virtual_keyboard_keymap: None,
2836+ configured_keymap: None,
2747 cursor_manager,2837 cursor_manager,
2748 cursor_texture_cache: Default::default(),2838 cursor_texture_cache: Default::default(),
2749 cursor_shape_manager_state,2839 cursor_shape_manager_state,
src/protocols/mod.rsmodified+0 -1
@@ -4,7 +4,6 @@ pub mod gamma_control;
4 pub mod mutter_x11_interop;4 pub mod mutter_x11_interop;
5 pub mod output_management;5 pub mod output_management;
6 pub mod screencopy;6 pub mod screencopy;
7-pub mod virtual_pointer;
8 7
9 pub mod raw;8 pub mod raw;
10 9
src/protocols/virtual_pointer.rsdeleted+0 -545
@@ -1,545 +0,0 @@
1-use std::collections::HashSet;
2-use std::sync::Mutex;
3-
4-use smithay::backend::input::{
5- AbsolutePositionEvent, Axis, AxisRelativeDirection, AxisSource, ButtonState, Device,
6- DeviceCapability, Event, InputBackend, InputTime, PointerAxisEvent, PointerButtonEvent,
7- PointerMotionAbsoluteEvent, PointerMotionEvent, UnusedEvent,
8-};
9-use smithay::input::pointer::AxisFrame;
10-use smithay::output::Output;
11-use smithay::reexports::wayland_protocols_wlr;
12-use smithay::reexports::wayland_server::protocol::wl_pointer;
13-use smithay::reexports::wayland_server::protocol::wl_seat::WlSeat;
14-use smithay::reexports::wayland_server::{
15- Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource,
16-};
17-use smithay::wayland::{Dispatch2, GlobalDispatch2};
18-use wayland_backend::protocol::WEnum;
19-use wayland_protocols_wlr::virtual_pointer::v1::server::{
20- zwlr_virtual_pointer_manager_v1, zwlr_virtual_pointer_v1,
21-};
22-use zwlr_virtual_pointer_manager_v1::ZwlrVirtualPointerManagerV1;
23-use zwlr_virtual_pointer_v1::ZwlrVirtualPointerV1;
24-
25-use crate::protocols::EmptyData;
26-
27-const VERSION: u32 = 2;
28-
29-pub struct VirtualPointerManagerState {
30- virtual_pointers: HashSet<ZwlrVirtualPointerV1>,
31-}
32-
33-pub struct VirtualPointerManagerGlobalData {
34- filter: Box<dyn for<'c> Fn(&'c Client) -> bool + Send + Sync>,
35-}
36-
37-pub struct VirtualPointerInputBackend;
38-
39-#[derive(Clone, Debug, Hash, Eq, PartialEq)]
40-pub struct VirtualPointer {
41- pointer: ZwlrVirtualPointerV1,
42-}
43-
44-#[derive(Debug)]
45-pub struct VirtualPointerUserData {
46- seat: Option<WlSeat>,
47- output: Option<Output>,
48-
49- axis_frame: Mutex<Option<AxisFrame>>,
50-}
51-
52-impl VirtualPointer {
53- fn data(&self) -> &VirtualPointerUserData {
54- self.pointer.data().unwrap()
55- }
56-
57- pub fn seat(&self) -> Option<&WlSeat> {
58- self.data().seat.as_ref()
59- }
60-
61- pub fn output(&self) -> Option<&Output> {
62- self.data().output.as_ref()
63- }
64-
65- fn finish_axis_frame(&self) -> Option<AxisFrame> {
66- self.data().axis_frame.lock().unwrap().take()
67- }
68-
69- fn mutate_axis_frame(&self, time: Option<u32>, f: impl FnOnce(AxisFrame) -> AxisFrame) {
70- let mut frame = self.data().axis_frame.lock().unwrap();
71-
72- *frame = frame
73- .or(time.map(InputTime::from_millis).map(AxisFrame::new))
74- .map(f);
75- }
76-}
77-
78-impl Device for VirtualPointer {
79- fn id(&self) -> String {
80- format!("wlr virtual pointer {}", self.pointer.id())
81- }
82-
83- fn name(&self) -> String {
84- String::from("virtual pointer")
85- }
86-
87- fn has_capability(&self, capability: DeviceCapability) -> bool {
88- matches!(capability, DeviceCapability::Pointer)
89- }
90-
91- fn usb_id(&self) -> Option<(u32, u32)> {
92- None
93- }
94-
95- fn syspath(&self) -> Option<std::path::PathBuf> {
96- None
97- }
98-}
99-
100-pub struct VirtualPointerMotionEvent {
101- pointer: VirtualPointer,
102- time: u32,
103- dx: f64,
104- dy: f64,
105-}
106-
107-impl Event<VirtualPointerInputBackend> for VirtualPointerMotionEvent {
108- fn time(&self) -> InputTime {
109- InputTime::from_millis(self.time)
110- }
111-
112- fn device(&self) -> VirtualPointer {
113- self.pointer.clone()
114- }
115-}
116-
117-impl PointerMotionEvent<VirtualPointerInputBackend> for VirtualPointerMotionEvent {
118- fn delta_x(&self) -> f64 {
119- self.dx
120- }
121-
122- fn delta_y(&self) -> f64 {
123- self.dy
124- }
125-
126- fn delta_x_unaccel(&self) -> f64 {
127- self.dx
128- }
129-
130- fn delta_y_unaccel(&self) -> f64 {
131- self.dy
132- }
133-}
134-
135-pub struct VirtualPointerMotionAbsoluteEvent {
136- pointer: VirtualPointer,
137- time: u32,
138- x: u32,
139- y: u32,
140- x_extent: u32,
141- y_extent: u32,
142-}
143-
144-impl Event<VirtualPointerInputBackend> for VirtualPointerMotionAbsoluteEvent {
145- fn time(&self) -> InputTime {
146- InputTime::from_millis(self.time)
147- }
148-
149- fn device(&self) -> VirtualPointer {
150- self.pointer.clone()
151- }
152-}
153-
154-impl AbsolutePositionEvent<VirtualPointerInputBackend> for VirtualPointerMotionAbsoluteEvent {
155- fn x(&self) -> f64 {
156- self.x as f64 / self.x_extent as f64
157- }
158-
159- fn y(&self) -> f64 {
160- self.y as f64 / self.y_extent as f64
161- }
162-
163- fn x_transformed(&self, width: i32) -> f64 {
164- (self.x as i64 * width as i64) as f64 / self.x_extent as f64
165- }
166-
167- fn y_transformed(&self, height: i32) -> f64 {
168- (self.y as i64 * height as i64) as f64 / self.y_extent as f64
169- }
170-}
171-
172-pub struct VirtualPointerButtonEvent {
173- pointer: VirtualPointer,
174- time: u32,
175- button: u32,
176- state: ButtonState,
177-}
178-
179-impl Event<VirtualPointerInputBackend> for VirtualPointerButtonEvent {
180- fn time(&self) -> InputTime {
181- InputTime::from_millis(self.time)
182- }
183-
184- fn device(&self) -> VirtualPointer {
185- self.pointer.clone()
186- }
187-}
188-
189-impl PointerButtonEvent<VirtualPointerInputBackend> for VirtualPointerButtonEvent {
190- fn button_code(&self) -> u32 {
191- self.button
192- }
193-
194- fn state(&self) -> ButtonState {
195- self.state
196- }
197-}
198-
199-pub struct VirtualPointerAxisEvent {
200- pointer: VirtualPointer,
201- frame: AxisFrame,
202-}
203-
204-impl Event<VirtualPointerInputBackend> for VirtualPointerAxisEvent {
205- fn time(&self) -> InputTime {
206- self.frame.time
207- }
208-
209- fn device(&self) -> VirtualPointer {
210- self.pointer.clone()
211- }
212-}
213-
214-fn tuple_axis<T>(tuple: (T, T), axis: Axis) -> T {
215- match axis {
216- Axis::Horizontal => tuple.0,
217- Axis::Vertical => tuple.1,
218- }
219-}
220-
221-impl PointerAxisEvent<VirtualPointerInputBackend> for VirtualPointerAxisEvent {
222- fn amount(&self, axis: Axis) -> Option<f64> {
223- Some(tuple_axis(self.frame.axis, axis))
224- }
225-
226- fn amount_v120(&self, axis: Axis) -> Option<f64> {
227- self.frame.v120.map(|v120| tuple_axis(v120, axis) as f64)
228- }
229-
230- fn source(&self) -> AxisSource {
231- self.frame.source.unwrap_or_else(|| {
232- warn!("AxisSource: no source set, giving bogus value");
233- AxisSource::Continuous
234- })
235- }
236-
237- fn relative_direction(&self, axis: Axis) -> AxisRelativeDirection {
238- tuple_axis(self.frame.relative_direction, axis)
239- }
240-}
241-
242-impl PointerMotionAbsoluteEvent<VirtualPointerInputBackend> for VirtualPointerMotionAbsoluteEvent {}
243-
244-impl InputBackend for VirtualPointerInputBackend {
245- type Device = VirtualPointer;
246-
247- type KeyboardKeyEvent = UnusedEvent;
248- type PointerAxisEvent = VirtualPointerAxisEvent;
249- type PointerButtonEvent = VirtualPointerButtonEvent;
250- type PointerMotionEvent = VirtualPointerMotionEvent;
251- type PointerMotionAbsoluteEvent = VirtualPointerMotionAbsoluteEvent;
252-
253- type GestureSwipeBeginEvent = UnusedEvent;
254- type GestureSwipeUpdateEvent = UnusedEvent;
255- type GestureSwipeEndEvent = UnusedEvent;
256- type GesturePinchBeginEvent = UnusedEvent;
257- type GesturePinchUpdateEvent = UnusedEvent;
258- type GesturePinchEndEvent = UnusedEvent;
259- type GestureHoldBeginEvent = UnusedEvent;
260- type GestureHoldEndEvent = UnusedEvent;
261-
262- type TouchDownEvent = UnusedEvent;
263- type TouchUpEvent = UnusedEvent;
264- type TouchMotionEvent = UnusedEvent;
265- type TouchCancelEvent = UnusedEvent;
266- type TouchFrameEvent = UnusedEvent;
267- type TabletToolAxisEvent = UnusedEvent;
268- type TabletToolProximityEvent = UnusedEvent;
269- type TabletToolTipEvent = UnusedEvent;
270- type TabletToolButtonEvent = UnusedEvent;
271-
272- type SwitchToggleEvent = UnusedEvent;
273-
274- type SpecialEvent = UnusedEvent;
275-}
276-
277-pub trait VirtualPointerHandler {
278- fn virtual_pointer_manager_state(&mut self) -> &mut VirtualPointerManagerState;
279-
280- fn create_virtual_pointer(&mut self, pointer: VirtualPointer) {
281- let _ = pointer;
282- }
283- fn destroy_virtual_pointer(&mut self, pointer: VirtualPointer) {
284- let _ = pointer;
285- }
286-
287- fn on_virtual_pointer_motion(&mut self, event: VirtualPointerMotionEvent);
288- fn on_virtual_pointer_motion_absolute(&mut self, event: VirtualPointerMotionAbsoluteEvent);
289- fn on_virtual_pointer_button(&mut self, event: VirtualPointerButtonEvent);
290- fn on_virtual_pointer_axis(&mut self, event: VirtualPointerAxisEvent);
291-}
292-
293-impl VirtualPointerManagerState {
294- pub fn new<D, F>(display: &DisplayHandle, filter: F) -> Self
295- where
296- D: GlobalDispatch<ZwlrVirtualPointerManagerV1, VirtualPointerManagerGlobalData>,
297- D: VirtualPointerHandler,
298- D: 'static,
299- F: for<'c> Fn(&'c Client) -> bool + Send + Sync + 'static,
300- {
301- let global_data = VirtualPointerManagerGlobalData {
302- filter: Box::new(filter),
303- };
304- display.create_global::<D, ZwlrVirtualPointerManagerV1, _>(VERSION, global_data);
305-
306- Self {
307- virtual_pointers: HashSet::new(),
308- }
309- }
310-}
311-
312-impl<D> GlobalDispatch2<ZwlrVirtualPointerManagerV1, D> for VirtualPointerManagerGlobalData
313-where
314- D: Dispatch<ZwlrVirtualPointerManagerV1, EmptyData>,
315- D: 'static,
316-{
317- fn bind(
318- &self,
319- _state: &mut D,
320- _handle: &DisplayHandle,
321- _client: &Client,
322- manager: New<ZwlrVirtualPointerManagerV1>,
323- data_init: &mut DataInit<'_, D>,
324- ) {
325- data_init.init(manager, EmptyData);
326- }
327-
328- fn can_view(&self, client: &Client) -> bool {
329- (self.filter)(client)
330- }
331-}
332-
333-impl<D> Dispatch2<ZwlrVirtualPointerManagerV1, D> for EmptyData
334-where
335- D: Dispatch<ZwlrVirtualPointerV1, VirtualPointerUserData>,
336- D: VirtualPointerHandler,
337- D: 'static,
338-{
339- fn request(
340- &self,
341- state: &mut D,
342- _client: &Client,
343- _resource: &ZwlrVirtualPointerManagerV1,
344- request: <ZwlrVirtualPointerManagerV1 as Resource>::Request,
345- _dhandle: &DisplayHandle,
346- data_init: &mut DataInit<'_, D>,
347- ) {
348- let (id, seat, output) = match request {
349- zwlr_virtual_pointer_manager_v1::Request::CreateVirtualPointer { seat, id } => {
350- (id, seat, None)
351- }
352- zwlr_virtual_pointer_manager_v1::Request::CreateVirtualPointerWithOutput {
353- seat,
354- output,
355- id,
356- } => (id, seat, output.as_ref().and_then(Output::from_resource)),
357- zwlr_virtual_pointer_manager_v1::Request::Destroy => return,
358- _ => unreachable!(),
359- };
360-
361- let pointer = data_init.init(
362- id,
363- VirtualPointerUserData {
364- seat,
365- output,
366- axis_frame: Mutex::new(None),
367- },
368- );
369- state
370- .virtual_pointer_manager_state()
371- .virtual_pointers
372- .insert(pointer.clone());
373-
374- state.create_virtual_pointer(VirtualPointer { pointer });
375- }
376-}
377-
378-impl<D> Dispatch2<ZwlrVirtualPointerV1, D> for VirtualPointerUserData
379-where
380- D: VirtualPointerHandler,
381- D: 'static,
382-{
383- fn request(
384- &self,
385- handler: &mut D,
386- _client: &Client,
387- resource: &ZwlrVirtualPointerV1,
388- request: <ZwlrVirtualPointerV1 as Resource>::Request,
389- _dhandle: &DisplayHandle,
390- _data_init: &mut DataInit<'_, D>,
391- ) {
392- let pointer = VirtualPointer {
393- pointer: resource.clone(),
394- };
395- match request {
396- zwlr_virtual_pointer_v1::Request::Motion { time, dx, dy } => {
397- let event = VirtualPointerMotionEvent {
398- pointer,
399- time,
400- dx,
401- dy,
402- };
403- handler.on_virtual_pointer_motion(event);
404- }
405- zwlr_virtual_pointer_v1::Request::MotionAbsolute {
406- time,
407- x,
408- y,
409- x_extent,
410- y_extent,
411- } => {
412- let event = VirtualPointerMotionAbsoluteEvent {
413- pointer,
414- time,
415- x,
416- y,
417- x_extent,
418- y_extent,
419- };
420- handler.on_virtual_pointer_motion_absolute(event);
421- }
422- zwlr_virtual_pointer_v1::Request::Button {
423- time,
424- button,
425- state,
426- } => {
427- // state is an enum but wlroots treats it as a C boolean (zero or nonzero)
428- // so we emulate that behaviour too. ButtonState::Pressed and any invalid value
429- // counts as pressed.
430- // https://gitlab.freedesktop.org/wlroots/wlroots/-/blob/3187479c07c34a4de82c06a316a763a36a0499da/types/wlr_virtual_pointer_v1.c#L74
431- let state = match state {
432- WEnum::Value(wl_pointer::ButtonState::Released) => ButtonState::Released,
433- _ => ButtonState::Pressed,
434- };
435- let event = VirtualPointerButtonEvent {
436- pointer,
437- time,
438- button,
439- state,
440- };
441- handler.on_virtual_pointer_button(event);
442- }
443- zwlr_virtual_pointer_v1::Request::Axis { time, axis, value } => {
444- let axis = match axis {
445- WEnum::Value(wl_pointer::Axis::VerticalScroll) => Axis::Vertical,
446- WEnum::Value(wl_pointer::Axis::HorizontalScroll) => Axis::Horizontal,
447- _ => {
448- warn!("Axis: invalid axis");
449- resource.post_error(
450- zwlr_virtual_pointer_v1::Error::InvalidAxis,
451- "invalid axis",
452- );
453- return;
454- }
455- };
456-
457- pointer.mutate_axis_frame(Some(time), |frame| frame.value(axis, value));
458- }
459- zwlr_virtual_pointer_v1::Request::Frame => {
460- if let Some(frame) = pointer.finish_axis_frame() {
461- let event = VirtualPointerAxisEvent { pointer, frame };
462- handler.on_virtual_pointer_axis(event);
463- }
464- }
465- zwlr_virtual_pointer_v1::Request::AxisSource { axis_source } => {
466- let axis_source = match axis_source {
467- WEnum::Value(wl_pointer::AxisSource::Wheel) => AxisSource::Wheel,
468- WEnum::Value(wl_pointer::AxisSource::Finger) => AxisSource::Finger,
469- WEnum::Value(wl_pointer::AxisSource::Continuous) => AxisSource::Continuous,
470- WEnum::Value(wl_pointer::AxisSource::WheelTilt) => AxisSource::WheelTilt,
471-
472- _ => {
473- warn!("AxisSource: invalid axis source");
474- resource.post_error(
475- zwlr_virtual_pointer_v1::Error::InvalidAxisSource,
476- "invalid axis source",
477- );
478- return;
479- }
480- };
481-
482- pointer.mutate_axis_frame(None, |frame| frame.source(axis_source));
483- }
484- zwlr_virtual_pointer_v1::Request::AxisStop { time, axis } => {
485- let axis = match axis {
486- WEnum::Value(wl_pointer::Axis::VerticalScroll) => Axis::Vertical,
487- WEnum::Value(wl_pointer::Axis::HorizontalScroll) => Axis::Horizontal,
488- _ => {
489- warn!("AxisStop: invalid axis");
490- resource.post_error(
491- zwlr_virtual_pointer_v1::Error::InvalidAxis,
492- "invalid axis",
493- );
494- return;
495- }
496- };
497-
498- pointer.mutate_axis_frame(Some(time), |frame| frame.stop(axis));
499- }
500- zwlr_virtual_pointer_v1::Request::AxisDiscrete {
501- time,
502- axis,
503- value,
504- discrete,
505- } => {
506- let axis = match axis {
507- WEnum::Value(wl_pointer::Axis::VerticalScroll) => Axis::Vertical,
508- WEnum::Value(wl_pointer::Axis::HorizontalScroll) => Axis::Horizontal,
509- _ => {
510- warn!("AxisDiscrete: invalid axis");
511- resource.post_error(
512- zwlr_virtual_pointer_v1::Error::InvalidAxis,
513- "invalid axis",
514- );
515- return;
516- }
517- };
518- pointer.mutate_axis_frame(Some(time), |frame| {
519- frame
520- .value(axis, value)
521- .v120(axis, discrete.saturating_mul(120))
522- });
523- }
524- zwlr_virtual_pointer_v1::Request::Destroy => {}
525- _ => unreachable!(),
526- }
527- }
528-
529- fn destroyed(
530- &self,
531- handler: &mut D,
532- _client: wayland_backend::server::ClientId,
533- resource: &ZwlrVirtualPointerV1,
534- ) {
535- let pointer = VirtualPointer {
536- pointer: resource.clone(),
537- };
538-
539- handler.destroy_virtual_pointer(pointer);
540- handler
541- .virtual_pointer_manager_state()
542- .virtual_pointers
543- .remove(resource);
544- }
545-}