forge
Explore
Log in

Don't you dare go Hollow

implement `keyboard-shortcuts-inhibit` and `wlr-virtual-pointer` (#630)

Browse files at this commit

0584dd2f1e82417bdabcc0d8cb20fddc2e8cc5e7Unverifiedsodiboo and Ivan MolodetskikhParent: bd559a2
* stub keyboard-shortcuts-inhibit and virtual-pointer impls

* implement keyboard-shortcuts-inhibit

* implement virtual-pointer

* deal with supressed key release edge-case; add allow-inhibiting property

* add toggle-keyboard-shortcuts-inhibit bind

* add InputBackend extensions; use Device::output() for absolute pos events

* add a `State` parameter to the backend exts and better document future intent

* Add some tests for is_inhibiting_shortcuts

---------
niri-config/src/lib.rsmodified+48 -1
@@ -1191,6 +1191,7 @@ pub struct Bind {
1191 pub repeat: bool,1191 pub repeat: bool,
1192 pub cooldown: Option<Duration>,1192 pub cooldown: Option<Duration>,
1193 pub allow_when_locked: bool,1193 pub allow_when_locked: bool,
1194+ pub allow_inhibiting: bool,
1194 }1195 }
1195 1196
1196 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]1197 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
@@ -1278,6 +1279,7 @@ pub enum Action {
1278 id: u64,1279 id: u64,
1279 write_to_disk: bool,1280 write_to_disk: bool,
1280 },1281 },
1282+ ToggleKeyboardShortcutsInhibit,
1281 CloseWindow,1283 CloseWindow,
1282 #[knuffel(skip)]1284 #[knuffel(skip)]
1283 CloseWindowById(u64),1285 CloseWindowById(u64),
@@ -3015,6 +3017,7 @@ where
3015 let mut cooldown = None;3017 let mut cooldown = None;
3016 let mut allow_when_locked = false;3018 let mut allow_when_locked = false;
3017 let mut allow_when_locked_node = None;3019 let mut allow_when_locked_node = None;
3020+ let mut allow_inhibiting = true;
3018 for (name, val) in &node.properties {3021 for (name, val) in &node.properties {
3019 match &***name {3022 match &***name {
3020 "repeat" => {3023 "repeat" => {
@@ -3029,6 +3032,9 @@ where
3029 allow_when_locked = knuffel::traits::DecodeScalar::decode(val, ctx)?;3032 allow_when_locked = knuffel::traits::DecodeScalar::decode(val, ctx)?;
3030 allow_when_locked_node = Some(name);3033 allow_when_locked_node = Some(name);
3031 }3034 }
3035+ "allow-inhibiting" => {
3036+ allow_inhibiting = knuffel::traits::DecodeScalar::decode(val, ctx)?;
3037+ }
3032 name_str => {3038 name_str => {
3033 ctx.emit_error(DecodeError::unexpected(3039 ctx.emit_error(DecodeError::unexpected(
3034 name,3040 name,
@@ -3050,6 +3056,7 @@ where
3050 repeat: true,3056 repeat: true,
3051 cooldown: None,3057 cooldown: None,
3052 allow_when_locked: false,3058 allow_when_locked: false,
3059+ allow_inhibiting: true,
3053 };3060 };
3054 3061
3055 if let Some(child) = children.next() {3062 if let Some(child) = children.next() {
@@ -3072,12 +3079,19 @@ where
3072 }3079 }
3073 }3080 }
3074 3081
3082+ // The toggle-inhibit action must always be uninhibitable.
3083+ // Otherwise, it would be impossible to trigger it.
3084+ if matches!(action, Action::ToggleKeyboardShortcutsInhibit) {
3085+ allow_inhibiting = false;
3086+ }
3087+
3075 Ok(Self {3088 Ok(Self {
3076 key,3089 key,
3077 action,3090 action,
3078 repeat,3091 repeat,
3079 cooldown,3092 cooldown,
3080 allow_when_locked,3093 allow_when_locked,
3094+ allow_inhibiting,
3081 })3095 })
3082 }3096 }
3083 Err(e) => {3097 Err(e) => {
@@ -3463,6 +3477,8 @@ mod tests {
3463 }3477 }
3464 3478
3465 binds {3479 binds {
3480+ Mod+Escape { toggle-keyboard-shortcuts-inhibit; }
3481+ Mod+Shift+Escape allow-inhibiting=true { toggle-keyboard-shortcuts-inhibit; }
3466 Mod+T allow-when-locked=true { spawn "alacritty"; }3482 Mod+T allow-when-locked=true { spawn "alacritty"; }
3467 Mod+Q { close-window; }3483 Mod+Q { close-window; }
3468 Mod+Shift+H { focus-monitor-left; }3484 Mod+Shift+H { focus-monitor-left; }
@@ -3470,7 +3486,7 @@ mod tests {
3470 Mod+Comma { consume-window-into-column; }3486 Mod+Comma { consume-window-into-column; }
3471 Mod+1 { focus-workspace 1; }3487 Mod+1 { focus-workspace 1; }
3472 Mod+Shift+1 { focus-workspace "workspace-1"; }3488 Mod+Shift+1 { focus-workspace "workspace-1"; }
3473- Mod+Shift+E { quit skip-confirmation=true; }3489+ Mod+Shift+E allow-inhibiting=false { quit skip-confirmation=true; }
3474 Mod+WheelScrollDown cooldown-ms=150 { focus-workspace-down; }3490 Mod+WheelScrollDown cooldown-ms=150 { focus-workspace-down; }
3475 }3491 }
3476 3492
@@ -3779,6 +3795,28 @@ mod tests {
3779 },3795 },
3780 ],3796 ],
3781 binds: Binds(vec![3797 binds: Binds(vec![
3798+ Bind {
3799+ key: Key {
3800+ trigger: Trigger::Keysym(Keysym::Escape),
3801+ modifiers: Modifiers::COMPOSITOR,
3802+ },
3803+ action: Action::ToggleKeyboardShortcutsInhibit,
3804+ repeat: true,
3805+ cooldown: None,
3806+ allow_when_locked: false,
3807+ allow_inhibiting: false,
3808+ },
3809+ Bind {
3810+ key: Key {
3811+ trigger: Trigger::Keysym(Keysym::Escape),
3812+ modifiers: Modifiers::COMPOSITOR | Modifiers::SHIFT,
3813+ },
3814+ action: Action::ToggleKeyboardShortcutsInhibit,
3815+ repeat: true,
3816+ cooldown: None,
3817+ allow_when_locked: false,
3818+ allow_inhibiting: false,
3819+ },
3782 Bind {3820 Bind {
3783 key: Key {3821 key: Key {
3784 trigger: Trigger::Keysym(Keysym::t),3822 trigger: Trigger::Keysym(Keysym::t),
@@ -3788,6 +3826,7 @@ mod tests {
3788 repeat: true,3826 repeat: true,
3789 cooldown: None,3827 cooldown: None,
3790 allow_when_locked: true,3828 allow_when_locked: true,
3829+ allow_inhibiting: true,
3791 },3830 },
3792 Bind {3831 Bind {
3793 key: Key {3832 key: Key {
@@ -3798,6 +3837,7 @@ mod tests {
3798 repeat: true,3837 repeat: true,
3799 cooldown: None,3838 cooldown: None,
3800 allow_when_locked: false,3839 allow_when_locked: false,
3840+ allow_inhibiting: true,
3801 },3841 },
3802 Bind {3842 Bind {
3803 key: Key {3843 key: Key {
@@ -3808,6 +3848,7 @@ mod tests {
3808 repeat: true,3848 repeat: true,
3809 cooldown: None,3849 cooldown: None,
3810 allow_when_locked: false,3850 allow_when_locked: false,
3851+ allow_inhibiting: true,
3811 },3852 },
3812 Bind {3853 Bind {
3813 key: Key {3854 key: Key {
@@ -3818,6 +3859,7 @@ mod tests {
3818 repeat: true,3859 repeat: true,
3819 cooldown: None,3860 cooldown: None,
3820 allow_when_locked: false,3861 allow_when_locked: false,
3862+ allow_inhibiting: true,
3821 },3863 },
3822 Bind {3864 Bind {
3823 key: Key {3865 key: Key {
@@ -3828,6 +3870,7 @@ mod tests {
3828 repeat: true,3870 repeat: true,
3829 cooldown: None,3871 cooldown: None,
3830 allow_when_locked: false,3872 allow_when_locked: false,
3873+ allow_inhibiting: true,
3831 },3874 },
3832 Bind {3875 Bind {
3833 key: Key {3876 key: Key {
@@ -3838,6 +3881,7 @@ mod tests {
3838 repeat: true,3881 repeat: true,
3839 cooldown: None,3882 cooldown: None,
3840 allow_when_locked: false,3883 allow_when_locked: false,
3884+ allow_inhibiting: true,
3841 },3885 },
3842 Bind {3886 Bind {
3843 key: Key {3887 key: Key {
@@ -3850,6 +3894,7 @@ mod tests {
3850 repeat: true,3894 repeat: true,
3851 cooldown: None,3895 cooldown: None,
3852 allow_when_locked: false,3896 allow_when_locked: false,
3897+ allow_inhibiting: true,
3853 },3898 },
3854 Bind {3899 Bind {
3855 key: Key {3900 key: Key {
@@ -3860,6 +3905,7 @@ mod tests {
3860 repeat: true,3905 repeat: true,
3861 cooldown: None,3906 cooldown: None,
3862 allow_when_locked: false,3907 allow_when_locked: false,
3908+ allow_inhibiting: false,
3863 },3909 },
3864 Bind {3910 Bind {
3865 key: Key {3911 key: Key {
@@ -3870,6 +3916,7 @@ mod tests {
3870 repeat: true,3916 repeat: true,
3871 cooldown: Some(Duration::from_millis(150)),3917 cooldown: Some(Duration::from_millis(150)),
3872 allow_when_locked: false,3918 allow_when_locked: false,
3919+ allow_inhibiting: true,
3873 },3920 },
3874 ]),3921 ]),
3875 switch_events: SwitchBinds {3922 switch_events: SwitchBinds {
resources/default-config.kdlmodified+10 -0
@@ -536,6 +536,16 @@ binds {
536 Ctrl+Print { screenshot-screen; }536 Ctrl+Print { screenshot-screen; }
537 Alt+Print { screenshot-window; }537 Alt+Print { screenshot-window; }
538 538
539+ // Applications such as remote-desktop clients and software KVM switches may
540+ // request that niri stops processing the keyboard shortcuts defined here
541+ // so they may, for example, forward the key presses as-is to a remote machine.
542+ // It's a good idea to bind an escape hatch to toggle the inhibitor,
543+ // so a buggy application can't hold your session hostage.
544+ //
545+ // The allow-inhibiting=false property can be applied to other binds as well,
546+ // which ensures niri always processes them, even when an inhibitor is active.
547+ Mod+Escape allow-inhibiting=false { toggle-keyboard-shortcuts-inhibit; }
548+
539 // The quit action will show a confirmation dialog to avoid accidental exits.549 // The quit action will show a confirmation dialog to avoid accidental exits.
540 Mod+Shift+E { quit; }550 Mod+Shift+E { quit; }
541 Ctrl+Alt+Delete { quit; }551 Ctrl+Alt+Delete { quit; }
src/handlers/mod.rsmodified+62 -7
@@ -11,7 +11,7 @@ use std::time::Duration;
11 11
12 use smithay::backend::allocator::dmabuf::Dmabuf;12 use smithay::backend::allocator::dmabuf::Dmabuf;
13 use smithay::backend::drm::DrmNode;13 use smithay::backend::drm::DrmNode;
14-use smithay::backend::input::TabletToolDescriptor;14+use smithay::backend::input::{InputEvent, TabletToolDescriptor};
15 use smithay::desktop::{PopupKind, PopupManager};15 use smithay::desktop::{PopupKind, PopupManager};
16 use smithay::input::pointer::{16 use smithay::input::pointer::{
17 CursorIcon, CursorImageStatus, CursorImageSurfaceData, PointerHandle,17 CursorIcon, CursorImageStatus, CursorImageSurfaceData, PointerHandle,
@@ -35,6 +35,9 @@ use smithay::wayland::fractional_scale::FractionalScaleHandler;
35 use smithay::wayland::idle_inhibit::IdleInhibitHandler;35 use smithay::wayland::idle_inhibit::IdleInhibitHandler;
36 use smithay::wayland::idle_notify::{IdleNotifierHandler, IdleNotifierState};36 use smithay::wayland::idle_notify::{IdleNotifierHandler, IdleNotifierState};
37 use smithay::wayland::input_method::{InputMethodHandler, PopupSurface};37 use smithay::wayland::input_method::{InputMethodHandler, PopupSurface};
38+use smithay::wayland::keyboard_shortcuts_inhibit::{
39+ KeyboardShortcutsInhibitHandler, KeyboardShortcutsInhibitState, KeyboardShortcutsInhibitor,
40+};
38 use smithay::wayland::output::OutputHandler;41 use smithay::wayland::output::OutputHandler;
39 use smithay::wayland::pointer_constraints::{with_pointer_constraint, PointerConstraintsHandler};42 use smithay::wayland::pointer_constraints::{with_pointer_constraint, PointerConstraintsHandler};
40 use smithay::wayland::security_context::{43 use smithay::wayland::security_context::{
@@ -59,11 +62,12 @@ use smithay::wayland::xdg_activation::{
59 use smithay::{62 use smithay::{
60 delegate_cursor_shape, delegate_data_control, delegate_data_device, delegate_dmabuf,63 delegate_cursor_shape, delegate_data_control, delegate_data_device, delegate_dmabuf,
61 delegate_drm_lease, delegate_fractional_scale, delegate_idle_inhibit, delegate_idle_notify,64 delegate_drm_lease, delegate_fractional_scale, delegate_idle_inhibit, delegate_idle_notify,
62- delegate_input_method_manager, delegate_output, delegate_pointer_constraints,65+ delegate_input_method_manager, delegate_keyboard_shortcuts_inhibit, delegate_output,
63- delegate_pointer_gestures, delegate_presentation, delegate_primary_selection,66+ delegate_pointer_constraints, delegate_pointer_gestures, delegate_presentation,
64- delegate_relative_pointer, delegate_seat, delegate_security_context, delegate_session_lock,67+ delegate_primary_selection, delegate_relative_pointer, delegate_seat,
65- delegate_single_pixel_buffer, delegate_tablet_manager, delegate_text_input_manager,68+ delegate_security_context, delegate_session_lock, delegate_single_pixel_buffer,
66- delegate_viewporter, delegate_virtual_keyboard_manager, delegate_xdg_activation,69+ delegate_tablet_manager, delegate_text_input_manager, delegate_viewporter,
70+ delegate_virtual_keyboard_manager, delegate_xdg_activation,
67 };71 };
68 72
69 pub use crate::handlers::xdg_shell::KdeDecorationsModeState;73 pub use crate::handlers::xdg_shell::KdeDecorationsModeState;
@@ -75,10 +79,15 @@ use crate::protocols::gamma_control::{GammaControlHandler, GammaControlManagerSt
75 use crate::protocols::mutter_x11_interop::MutterX11InteropHandler;79 use crate::protocols::mutter_x11_interop::MutterX11InteropHandler;
76 use crate::protocols::output_management::{OutputManagementHandler, OutputManagementManagerState};80 use crate::protocols::output_management::{OutputManagementHandler, OutputManagementManagerState};
77 use crate::protocols::screencopy::{Screencopy, ScreencopyHandler, ScreencopyManagerState};81 use crate::protocols::screencopy::{Screencopy, ScreencopyHandler, ScreencopyManagerState};
82+use crate::protocols::virtual_pointer::{
83+ VirtualPointerAxisEvent, VirtualPointerButtonEvent, VirtualPointerHandler,
84+ VirtualPointerInputBackend, VirtualPointerManagerState, VirtualPointerMotionAbsoluteEvent,
85+ VirtualPointerMotionEvent,
86+};
78 use crate::utils::{output_size, send_scale_transform, with_toplevel_role};87 use crate::utils::{output_size, send_scale_transform, with_toplevel_role};
79 use crate::{88 use crate::{
80 delegate_foreign_toplevel, delegate_gamma_control, delegate_mutter_x11_interop,89 delegate_foreign_toplevel, delegate_gamma_control, delegate_mutter_x11_interop,
81- delegate_output_management, delegate_screencopy,90+ delegate_output_management, delegate_screencopy, delegate_virtual_pointer,
82 };91 };
83 92
84 pub const XDG_ACTIVATION_TOKEN_TIMEOUT: Duration = Duration::from_secs(10);93 pub const XDG_ACTIVATION_TOKEN_TIMEOUT: Duration = Duration::from_secs(10);
@@ -243,7 +252,28 @@ impl InputMethodHandler for State {
243 }252 }
244 }253 }
245 254
255+impl KeyboardShortcutsInhibitHandler for State {
256+ fn keyboard_shortcuts_inhibit_state(&mut self) -> &mut KeyboardShortcutsInhibitState {
257+ &mut self.niri.keyboard_shortcuts_inhibit_state
258+ }
259+
260+ fn new_inhibitor(&mut self, inhibitor: KeyboardShortcutsInhibitor) {
261+ // FIXME: show a confirmation dialog with a "remember for this application" kind of toggle.
262+ inhibitor.activate();
263+ self.niri
264+ .keyboard_shortcuts_inhibiting_surfaces
265+ .insert(inhibitor.wl_surface().clone(), inhibitor);
266+ }
267+
268+ fn inhibitor_destroyed(&mut self, inhibitor: KeyboardShortcutsInhibitor) {
269+ self.niri
270+ .keyboard_shortcuts_inhibiting_surfaces
271+ .remove(&inhibitor.wl_surface().clone());
272+ }
273+}
274+
246 delegate_input_method_manager!(State);275 delegate_input_method_manager!(State);
276+delegate_keyboard_shortcuts_inhibit!(State);
247 delegate_virtual_keyboard_manager!(State);277 delegate_virtual_keyboard_manager!(State);
248 278
249 impl SelectionHandler for State {279 impl SelectionHandler for State {
@@ -562,6 +592,31 @@ impl ScreencopyHandler for State {
562 }592 }
563 delegate_screencopy!(State);593 delegate_screencopy!(State);
564 594
595+impl VirtualPointerHandler for State {
596+ fn virtual_pointer_manager_state(&mut self) -> &mut VirtualPointerManagerState {
597+ &mut self.niri.virtual_pointer_state
598+ }
599+
600+ fn on_virtual_pointer_motion(&mut self, event: VirtualPointerMotionEvent) {
601+ self.process_input_event(InputEvent::<VirtualPointerInputBackend>::PointerMotion { event });
602+ }
603+
604+ fn on_virtual_pointer_motion_absolute(&mut self, event: VirtualPointerMotionAbsoluteEvent) {
605+ self.process_input_event(
606+ InputEvent::<VirtualPointerInputBackend>::PointerMotionAbsolute { event },
607+ );
608+ }
609+
610+ fn on_virtual_pointer_button(&mut self, event: VirtualPointerButtonEvent) {
611+ self.process_input_event(InputEvent::<VirtualPointerInputBackend>::PointerButton { event });
612+ }
613+
614+ fn on_virtual_pointer_axis(&mut self, event: VirtualPointerAxisEvent) {
615+ self.process_input_event(InputEvent::<VirtualPointerInputBackend>::PointerAxis { event });
616+ }
617+}
618+delegate_virtual_pointer!(State);
619+
565 impl DrmLeaseHandler for State {620 impl DrmLeaseHandler for State {
566 fn drm_lease_state(&mut self, node: DrmNode) -> &mut DrmLeaseState {621 fn drm_lease_state(&mut self, node: DrmNode) -> &mut DrmLeaseState {
567 self.backend622 self.backend
src/input/backend_ext.rsadded+51 -0
@@ -0,0 +1,51 @@
1+use ::input as libinput;
2+use smithay::backend::input;
3+use smithay::backend::winit::WinitVirtualDevice;
4+use smithay::output::Output;
5+
6+use crate::niri::State;
7+use crate::protocols::virtual_pointer::VirtualPointer;
8+
9+pub trait NiriInputBackend: input::InputBackend<Device = Self::NiriDevice> {
10+ type NiriDevice: NiriInputDevice;
11+}
12+impl<T: input::InputBackend> NiriInputBackend for T
13+where
14+ Self::Device: NiriInputDevice,
15+{
16+ type NiriDevice = Self::Device;
17+}
18+
19+pub trait NiriInputDevice: input::Device {
20+ // FIXME: this should maybe be per-event, not per-device,
21+ // but it's not clear that this matters in practice?
22+ // it might be more obvious once we implement it for libinput
23+ fn output(&self, state: &State) -> Option<Output>;
24+}
25+
26+impl NiriInputDevice for libinput::Device {
27+ fn output(&self, _state: &State) -> Option<Output> {
28+ // FIXME: Allow specifying the output per-device?
29+ None
30+ }
31+}
32+
33+impl NiriInputDevice for WinitVirtualDevice {
34+ fn output(&self, _state: &State) -> Option<Output> {
35+ // FIXME: we should be returning the single output that the winit backend creates,
36+ // but for now, that will cause issues because the output is normally upside down,
37+ // so we apply Transform::Flipped180 to it and that would also cause
38+ // the cursor position to be flipped, which is not what we want.
39+ //
40+ // instead, we just return None and rely on the fact that it has only one output.
41+ // doing so causes the cursor to be placed in *global* output coordinates,
42+ // which are not flipped, and happen to be what we want.
43+ None
44+ }
45+}
46+
47+impl NiriInputDevice for VirtualPointer {
48+ fn output(&self, _: &State) -> Option<Output> {
49+ self.output().cloned()
50+ }
51+}
src/input/mod.rsmodified+138 -13
@@ -11,7 +11,7 @@ use niri_ipc::LayoutSwitchTarget;
11 use smithay::backend::input::{11 use smithay::backend::input::{
12 AbsolutePositionEvent, Axis, AxisSource, ButtonState, Device, DeviceCapability, Event,12 AbsolutePositionEvent, Axis, AxisSource, ButtonState, Device, DeviceCapability, Event,
13 GestureBeginEvent, GestureEndEvent, GesturePinchUpdateEvent as _, GestureSwipeUpdateEvent as _,13 GestureBeginEvent, GestureEndEvent, GesturePinchUpdateEvent as _, GestureSwipeUpdateEvent as _,
14- InputBackend, InputEvent, KeyState, KeyboardKeyEvent, Keycode, MouseButton, PointerAxisEvent,14+ InputEvent, KeyState, KeyboardKeyEvent, Keycode, MouseButton, PointerAxisEvent,
15 PointerButtonEvent, PointerMotionEvent, ProximityState, Switch, SwitchState, SwitchToggleEvent,15 PointerButtonEvent, PointerMotionEvent, ProximityState, Switch, SwitchState, SwitchToggleEvent,
16 TabletToolButtonEvent, TabletToolEvent, TabletToolProximityEvent, TabletToolTipEvent,16 TabletToolButtonEvent, TabletToolEvent, TabletToolProximityEvent, TabletToolTipEvent,
17 TabletToolTipState, TouchEvent,17 TabletToolTipState, TouchEvent,
@@ -28,7 +28,9 @@ use smithay::input::touch::{
28 DownEvent, GrabStartData as TouchGrabStartData, MotionEvent as TouchMotionEvent, UpEvent,28 DownEvent, GrabStartData as TouchGrabStartData, MotionEvent as TouchMotionEvent, UpEvent,
29 };29 };
30 use smithay::input::SeatHandler;30 use smithay::input::SeatHandler;
31+use smithay::output::Output;
31 use smithay::utils::{Logical, Point, Rectangle, Transform, SERIAL_COUNTER};32 use smithay::utils::{Logical, Point, Rectangle, Transform, SERIAL_COUNTER};
33+use smithay::wayland::keyboard_shortcuts_inhibit::KeyboardShortcutsInhibitor;
32 use smithay::wayland::pointer_constraints::{with_pointer_constraint, PointerConstraint};34 use smithay::wayland::pointer_constraints::{with_pointer_constraint, PointerConstraint};
33 use smithay::wayland::tablet_manager::{TabletDescriptor, TabletSeatTrait};35 use smithay::wayland::tablet_manager::{TabletDescriptor, TabletSeatTrait};
34 use touch_move_grab::TouchMoveGrab;36 use touch_move_grab::TouchMoveGrab;
@@ -42,6 +44,7 @@ use crate::ui::screenshot_ui::ScreenshotUi;
42 use crate::utils::spawning::spawn;44 use crate::utils::spawning::spawn;
43 use crate::utils::{center, get_monotonic_time, ResizeEdge};45 use crate::utils::{center, get_monotonic_time, ResizeEdge};
44 46
47+pub mod backend_ext;
45 pub mod move_grab;48 pub mod move_grab;
46 pub mod resize_grab;49 pub mod resize_grab;
47 pub mod scroll_tracker;50 pub mod scroll_tracker;
@@ -50,6 +53,8 @@ pub mod swipe_tracker;
50 pub mod touch_move_grab;53 pub mod touch_move_grab;
51 pub mod touch_resize_grab;54 pub mod touch_resize_grab;
52 55
56+use backend_ext::{NiriInputBackend as InputBackend, NiriInputDevice as _};
57+
53 pub const DOUBLE_CLICK_TIME: Duration = Duration::from_millis(400);58 pub const DOUBLE_CLICK_TIME: Duration = Duration::from_millis(400);
54 59
55 #[derive(Debug, Clone, Copy, PartialEq, Eq)]60 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -264,8 +269,10 @@ impl State {
264 where269 where
265 I::Device: 'static,270 I::Device: 'static,
266 {271 {
272+ let device_output = event.device().output(self);
273+ let device_output = device_output.as_ref();
267 let (target_geo, keep_ratio, px, transform) =274 let (target_geo, keep_ratio, px, transform) =
268- if let Some(output) = self.niri.output_for_tablet() {275+ if let Some(output) = device_output.or_else(|| self.niri.output_for_tablet()) {
269 (276 (
270 self.niri.global_space.output_geometry(output).unwrap(),277 self.niri.global_space.output_geometry(output).unwrap(),
271 true,278 true,
@@ -318,6 +325,18 @@ impl State {
318 Some(pos + target_geo.loc.to_f64())325 Some(pos + target_geo.loc.to_f64())
319 }326 }
320 327
328+ fn is_inhibiting_shortcuts(&self) -> bool {
329+ self.niri
330+ .keyboard_focus
331+ .surface()
332+ .and_then(|surface| {
333+ self.niri
334+ .keyboard_shortcuts_inhibiting_surfaces
335+ .get(surface)
336+ })
337+ .is_some_and(KeyboardShortcutsInhibitor::is_active)
338+ }
339+
321 fn on_keyboard<I: InputBackend>(&mut self, event: I::KeyboardKeyEvent) {340 fn on_keyboard<I: InputBackend>(&mut self, event: I::KeyboardKeyEvent) {
322 let comp_mod = self.backend.mod_key();341 let comp_mod = self.backend.mod_key();
323 342
@@ -342,6 +361,8 @@ impl State {
342 self.hide_cursor_if_needed();361 self.hide_cursor_if_needed();
343 }362 }
344 363
364+ let is_inhibiting_shortcuts = self.is_inhibiting_shortcuts();
365+
345 let Some(Some(bind)) = self.niri.seat.get_keyboard().unwrap().input(366 let Some(Some(bind)) = self.niri.seat.get_keyboard().unwrap().input(
346 self,367 self,
347 event.key_code(),368 event.key_code(),
@@ -372,6 +393,7 @@ impl State {
372 *mods,393 *mods,
373 &this.niri.screenshot_ui,394 &this.niri.screenshot_ui,
374 this.niri.config.borrow().input.disable_power_key_handling,395 this.niri.config.borrow().input.disable_power_key_handling,
396+ is_inhibiting_shortcuts,
375 )397 )
376 },398 },
377 ) else {399 ) else {
@@ -610,6 +632,19 @@ impl State {
610 });632 });
611 }633 }
612 }634 }
635+ Action::ToggleKeyboardShortcutsInhibit => {
636+ if let Some(inhibitor) = self.niri.keyboard_focus.surface().and_then(|surface| {
637+ self.niri
638+ .keyboard_shortcuts_inhibiting_surfaces
639+ .get(surface)
640+ }) {
641+ if inhibitor.is_active() {
642+ inhibitor.inactivate();
643+ } else {
644+ inhibitor.activate();
645+ }
646+ }
647+ }
613 Action::CloseWindow => {648 Action::CloseWindow => {
614 if let Some(mapped) = self.niri.layout.focus() {649 if let Some(mapped) = self.niri.layout.focus() {
615 mapped.toplevel().send_close();650 mapped.toplevel().send_close();
@@ -1731,12 +1766,14 @@ impl State {
1731 &mut self,1766 &mut self,
1732 event: I::PointerMotionAbsoluteEvent,1767 event: I::PointerMotionAbsoluteEvent,
1733 ) {1768 ) {
1734- let Some(output_geo) = self.global_bounding_rectangle() else {1769+ let Some(pos) = self.compute_absolute_location(&event, None).or_else(|| {
1770+ self.global_bounding_rectangle().map(|output_geo| {
1771+ event.position_transformed(output_geo.size) + output_geo.loc.to_f64()
1772+ })
1773+ }) else {
1735 return;1774 return;
1736 };1775 };
1737 1776
1738- let pos = event.position_transformed(output_geo.size) + output_geo.loc.to_f64();
1739-
1740 let serial = SERIAL_COUNTER.next_serial();1777 let serial = SERIAL_COUNTER.next_serial();
1741 1778
1742 let pointer = self.niri.seat.get_pointer().unwrap();1779 let pointer = self.niri.seat.get_pointer().unwrap();
@@ -2613,14 +2650,13 @@ impl State {
2613 );2650 );
2614 }2651 }
2615 2652
2616- /// Computes the cursor position for the touch event.2653+ fn compute_absolute_location<I: InputBackend>(
2617- ///
2618- /// This function handles the touch output mapping, as well as coordinate transform
2619- fn compute_touch_location<I: InputBackend, E: AbsolutePositionEvent<I>>(
2620 &self,2654 &self,
2621- evt: &E,2655+ evt: &impl AbsolutePositionEvent<I>,
2656+ fallback_output: Option<&Output>,
2622 ) -> Option<Point<f64, Logical>> {2657 ) -> Option<Point<f64, Logical>> {
2623- let output = self.niri.output_for_touch()?;2658+ let output = evt.device().output(self);
2659+ let output = output.as_ref().or(fallback_output)?;
2624 let output_geo = self.niri.global_space.output_geometry(output).unwrap();2660 let output_geo = self.niri.global_space.output_geometry(output).unwrap();
2625 let transform = output.current_transform();2661 let transform = output.current_transform();
2626 let size = transform.invert().transform_size(output_geo.size);2662 let size = transform.invert().transform_size(output_geo.size);
@@ -2630,6 +2666,16 @@ impl State {
2630 )2666 )
2631 }2667 }
2632 2668
2669+ /// Computes the cursor position for the touch event.
2670+ ///
2671+ /// This function handles the touch output mapping, as well as coordinate transform
2672+ fn compute_touch_location<I: InputBackend>(
2673+ &self,
2674+ evt: &impl AbsolutePositionEvent<I>,
2675+ ) -> Option<Point<f64, Logical>> {
2676+ self.compute_absolute_location(evt, self.niri.output_for_touch())
2677+ }
2678+
2633 fn on_touch_down<I: InputBackend>(&mut self, evt: I::TouchDownEvent) {2679 fn on_touch_down<I: InputBackend>(&mut self, evt: I::TouchDownEvent) {
2634 let Some(handle) = self.niri.seat.get_touch() else {2680 let Some(handle) = self.niri.seat.get_touch() else {
2635 return;2681 return;
@@ -2780,6 +2826,7 @@ fn should_intercept_key(
2780 mods: ModifiersState,2826 mods: ModifiersState,
2781 screenshot_ui: &ScreenshotUi,2827 screenshot_ui: &ScreenshotUi,
2782 disable_power_key_handling: bool,2828 disable_power_key_handling: bool,
2829+ is_inhibiting_shortcuts: bool,
2783 ) -> FilterResult<Option<Bind>> {2830 ) -> FilterResult<Option<Bind>> {
2784 // Actions are only triggered on presses, release of the key2831 // Actions are only triggered on presses, release of the key
2785 // shouldn't try to intercept anything unless we have marked2832 // shouldn't try to intercept anything unless we have marked
@@ -2820,6 +2867,10 @@ fn should_intercept_key(
2820 repeat: true,2867 repeat: true,
2821 cooldown: None,2868 cooldown: None,
2822 allow_when_locked: false,2869 allow_when_locked: false,
2870+ // The screenshot UI owns the focus anyway, so this doesn't really matter.
2871+ // But logically, nothing can inhibit its actions. Only opening it can be
2872+ // inhibited.
2873+ allow_inhibiting: false,
2823 });2874 });
2824 }2875 }
2825 }2876 }
@@ -2827,10 +2878,19 @@ fn should_intercept_key(
2827 2878
2828 match (final_bind, pressed) {2879 match (final_bind, pressed) {
2829 (Some(bind), true) => {2880 (Some(bind), true) => {
2830- suppressed_keys.insert(key_code);2881+ if is_inhibiting_shortcuts && bind.allow_inhibiting {
2831- FilterResult::Intercept(Some(bind))2882+ FilterResult::Forward
2883+ } else {
2884+ suppressed_keys.insert(key_code);
2885+ FilterResult::Intercept(Some(bind))
2886+ }
2832 }2887 }
2833 (_, false) => {2888 (_, false) => {
2889+ // By this point, we know that the key was supressed on press. Even if we're inhibiting
2890+ // shortcuts, we should still suppress the release.
2891+ // But we don't need to check for shortcuts inhibition here, because
2892+ // if it was inhibited on press (forwarded to the client), it wouldn't be suppressed,
2893+ // so the release would already have been forwarded at the start of this function.
2834 suppressed_keys.remove(&key_code);2894 suppressed_keys.remove(&key_code);
2835 FilterResult::Intercept(None)2895 FilterResult::Intercept(None)
2836 }2896 }
@@ -2870,6 +2930,12 @@ fn find_bind(
2870 repeat: true,2930 repeat: true,
2871 cooldown: None,2931 cooldown: None,
2872 allow_when_locked: false,2932 allow_when_locked: false,
2933+ // In a worst-case scenario, the user has no way to unlock the compositor and a
2934+ // misbehaving client has a keyboard shortcuts inhibitor, "jailing" the user.
2935+ // The user must always be able to change VTs to recover from such a situation.
2936+ // It also makes no sense to inhibit the default power key handling.
2937+ // Hardcoded binds must never be inhibited.
2938+ allow_inhibiting: false,
2873 });2939 });
2874 }2940 }
2875 2941
@@ -3035,6 +3101,7 @@ fn allowed_when_locked(action: &Action) -> bool {
3035 | Action::PowerOffMonitors3101 | Action::PowerOffMonitors
3036 | Action::PowerOnMonitors3102 | Action::PowerOnMonitors
3037 | Action::SwitchLayout(_)3103 | Action::SwitchLayout(_)
3104+ | Action::ToggleKeyboardShortcutsInhibit
3038 )3105 )
3039 }3106 }
3040 3107
@@ -3317,6 +3384,8 @@ pub fn mods_with_finger_scroll_binds(comp_mod: CompositorMod, binds: &Binds) ->
3317 3384
3318 #[cfg(test)]3385 #[cfg(test)]
3319 mod tests {3386 mod tests {
3387+ use std::cell::Cell;
3388+
3320 use super::*;3389 use super::*;
3321 use crate::animation::Clock;3390 use crate::animation::Clock;
3322 3391
@@ -3332,6 +3401,7 @@ mod tests {
3332 repeat: true,3401 repeat: true,
3333 cooldown: None,3402 cooldown: None,
3334 allow_when_locked: false,3403 allow_when_locked: false,
3404+ allow_inhibiting: true,
3335 }]);3405 }]);
3336 3406
3337 let comp_mod = CompositorMod::Super;3407 let comp_mod = CompositorMod::Super;
@@ -3339,6 +3409,7 @@ mod tests {
3339 3409
3340 let screenshot_ui = ScreenshotUi::new(Clock::default(), Default::default());3410 let screenshot_ui = ScreenshotUi::new(Clock::default(), Default::default());
3341 let disable_power_key_handling = false;3411 let disable_power_key_handling = false;
3412+ let is_inhibiting_shortcuts = Cell::new(false);
3342 3413
3343 // The key_code we pick is arbitrary, the only thing3414 // The key_code we pick is arbitrary, the only thing
3344 // that matters is that they are different between cases.3415 // that matters is that they are different between cases.
@@ -3356,6 +3427,7 @@ mod tests {
3356 mods,3427 mods,
3357 &screenshot_ui,3428 &screenshot_ui,
3358 disable_power_key_handling,3429 disable_power_key_handling,
3430+ is_inhibiting_shortcuts.get(),
3359 )3431 )
3360 };3432 };
3361 3433
@@ -3372,6 +3444,7 @@ mod tests {
3372 mods,3444 mods,
3373 &screenshot_ui,3445 &screenshot_ui,
3374 disable_power_key_handling,3446 disable_power_key_handling,
3447+ is_inhibiting_shortcuts.get(),
3375 )3448 )
3376 };3449 };
3377 3450
@@ -3452,6 +3525,53 @@ mod tests {
3452 3525
3453 // Ensure that no keys are being suppressed.3526 // Ensure that no keys are being suppressed.
3454 assert!(suppressed_keys.is_empty());3527 assert!(suppressed_keys.is_empty());
3528+
3529+ // Now test shortcut inhibiting.
3530+
3531+ // With inhibited shortcuts, we don't intercept our shortcut.
3532+ is_inhibiting_shortcuts.set(true);
3533+
3534+ mods = ModifiersState {
3535+ logo: true,
3536+ ctrl: true,
3537+ ..Default::default()
3538+ };
3539+
3540+ let filter = close_key_event(&mut suppressed_keys, mods, true);
3541+ assert!(matches!(filter, FilterResult::Forward));
3542+ assert!(suppressed_keys.is_empty());
3543+
3544+ let filter = close_key_event(&mut suppressed_keys, mods, false);
3545+ assert!(matches!(filter, FilterResult::Forward));
3546+ assert!(suppressed_keys.is_empty());
3547+
3548+ // Toggle it off after pressing the shortcut.
3549+ let filter = close_key_event(&mut suppressed_keys, mods, true);
3550+ assert!(matches!(filter, FilterResult::Forward));
3551+ assert!(suppressed_keys.is_empty());
3552+
3553+ is_inhibiting_shortcuts.set(false);
3554+
3555+ let filter = close_key_event(&mut suppressed_keys, mods, false);
3556+ assert!(matches!(filter, FilterResult::Forward));
3557+ assert!(suppressed_keys.is_empty());
3558+
3559+ // Toggle it on after pressing the shortcut.
3560+ let filter = close_key_event(&mut suppressed_keys, mods, true);
3561+ assert!(matches!(
3562+ filter,
3563+ FilterResult::Intercept(Some(Bind {
3564+ action: Action::CloseWindow,
3565+ ..
3566+ }))
3567+ ));
3568+ assert!(suppressed_keys.contains(&close_key_code));
3569+
3570+ is_inhibiting_shortcuts.set(true);
3571+
3572+ let filter = close_key_event(&mut suppressed_keys, mods, false);
3573+ assert!(matches!(filter, FilterResult::Intercept(None)));
3574+ assert!(suppressed_keys.is_empty());
3455 }3575 }
3456 3576
3457 #[test]3577 #[test]
@@ -3466,6 +3586,7 @@ mod tests {
3466 repeat: true,3586 repeat: true,
3467 cooldown: None,3587 cooldown: None,
3468 allow_when_locked: false,3588 allow_when_locked: false,
3589+ allow_inhibiting: true,
3469 },3590 },
3470 Bind {3591 Bind {
3471 key: Key {3592 key: Key {
@@ -3476,6 +3597,7 @@ mod tests {
3476 repeat: true,3597 repeat: true,
3477 cooldown: None,3598 cooldown: None,
3478 allow_when_locked: false,3599 allow_when_locked: false,
3600+ allow_inhibiting: true,
3479 },3601 },
3480 Bind {3602 Bind {
3481 key: Key {3603 key: Key {
@@ -3486,6 +3608,7 @@ mod tests {
3486 repeat: true,3608 repeat: true,
3487 cooldown: None,3609 cooldown: None,
3488 allow_when_locked: false,3610 allow_when_locked: false,
3611+ allow_inhibiting: true,
3489 },3612 },
3490 Bind {3613 Bind {
3491 key: Key {3614 key: Key {
@@ -3496,6 +3619,7 @@ mod tests {
3496 repeat: true,3619 repeat: true,
3497 cooldown: None,3620 cooldown: None,
3498 allow_when_locked: false,3621 allow_when_locked: false,
3622+ allow_inhibiting: true,
3499 },3623 },
3500 Bind {3624 Bind {
3501 key: Key {3625 key: Key {
@@ -3506,6 +3630,7 @@ mod tests {
3506 repeat: true,3630 repeat: true,
3507 cooldown: None,3631 cooldown: None,
3508 allow_when_locked: false,3632 allow_when_locked: false,
3633+ allow_inhibiting: true,
3509 },3634 },
3510 ]);3635 ]);
3511 3636
src/niri.rsmodified+16 -1
@@ -77,6 +77,9 @@ use smithay::wayland::fractional_scale::FractionalScaleManagerState;
77 use smithay::wayland::idle_inhibit::IdleInhibitManagerState;77 use smithay::wayland::idle_inhibit::IdleInhibitManagerState;
78 use smithay::wayland::idle_notify::IdleNotifierState;78 use smithay::wayland::idle_notify::IdleNotifierState;
79 use smithay::wayland::input_method::{InputMethodManagerState, InputMethodSeat};79 use smithay::wayland::input_method::{InputMethodManagerState, InputMethodSeat};
80+use smithay::wayland::keyboard_shortcuts_inhibit::{
81+ KeyboardShortcutsInhibitState, KeyboardShortcutsInhibitor,
82+};
80 use smithay::wayland::output::OutputManagerState;83 use smithay::wayland::output::OutputManagerState;
81 use smithay::wayland::pointer_constraints::{with_pointer_constraint, PointerConstraintsState};84 use smithay::wayland::pointer_constraints::{with_pointer_constraint, PointerConstraintsState};
82 use smithay::wayland::pointer_gestures::PointerGesturesState;85 use smithay::wayland::pointer_gestures::PointerGesturesState;
@@ -131,6 +134,7 @@ use crate::protocols::gamma_control::GammaControlManagerState;
131 use crate::protocols::mutter_x11_interop::MutterX11InteropManagerState;134 use crate::protocols::mutter_x11_interop::MutterX11InteropManagerState;
132 use crate::protocols::output_management::OutputManagementManagerState;135 use crate::protocols::output_management::OutputManagementManagerState;
133 use crate::protocols::screencopy::{Screencopy, ScreencopyBuffer, ScreencopyManagerState};136 use crate::protocols::screencopy::{Screencopy, ScreencopyBuffer, ScreencopyManagerState};
137+use crate::protocols::virtual_pointer::VirtualPointerManagerState;
134 use crate::pw_utils::{Cast, PipeWire};138 use crate::pw_utils::{Cast, PipeWire};
135 #[cfg(feature = "xdp-gnome-screencast")]139 #[cfg(feature = "xdp-gnome-screencast")]
136 use crate::pw_utils::{CastSizeChange, CastTarget, PwToNiri};140 use crate::pw_utils::{CastSizeChange, CastTarget, PwToNiri};
@@ -252,7 +256,9 @@ pub struct Niri {
252 pub tablet_state: TabletManagerState,256 pub tablet_state: TabletManagerState,
253 pub text_input_state: TextInputManagerState,257 pub text_input_state: TextInputManagerState,
254 pub input_method_state: InputMethodManagerState,258 pub input_method_state: InputMethodManagerState,
259+ pub keyboard_shortcuts_inhibit_state: KeyboardShortcutsInhibitState,
255 pub virtual_keyboard_state: VirtualKeyboardManagerState,260 pub virtual_keyboard_state: VirtualKeyboardManagerState,
261+ pub virtual_pointer_state: VirtualPointerManagerState,
256 pub pointer_gestures_state: PointerGesturesState,262 pub pointer_gestures_state: PointerGesturesState,
257 pub relative_pointer_state: RelativePointerManagerState,263 pub relative_pointer_state: RelativePointerManagerState,
258 pub pointer_constraints_state: PointerConstraintsState,264 pub pointer_constraints_state: PointerConstraintsState,
@@ -290,6 +296,7 @@ pub struct Niri {
290 pub previously_focused_window: Option<Window>,296 pub previously_focused_window: Option<Window>,
291 pub idle_inhibiting_surfaces: HashSet<WlSurface>,297 pub idle_inhibiting_surfaces: HashSet<WlSurface>,
292 pub is_fdo_idle_inhibited: Arc<AtomicBool>,298 pub is_fdo_idle_inhibited: Arc<AtomicBool>,
299+ pub keyboard_shortcuts_inhibiting_surfaces: HashMap<WlSurface, KeyboardShortcutsInhibitor>,
293 300
294 pub cursor_manager: CursorManager,301 pub cursor_manager: CursorManager,
295 pub cursor_texture_cache: CursorTextureCache,302 pub cursor_texture_cache: CursorTextureCache,
@@ -1818,11 +1825,16 @@ impl Niri {
1818 InputMethodManagerState::new::<State, _>(&display_handle, |client| {1825 InputMethodManagerState::new::<State, _>(&display_handle, |client| {
1819 !client.get_data::<ClientState>().unwrap().restricted1826 !client.get_data::<ClientState>().unwrap().restricted
1820 });1827 });
1828+ let keyboard_shortcuts_inhibit_state =
1829+ KeyboardShortcutsInhibitState::new::<State>(&display_handle);
1821 let virtual_keyboard_state =1830 let virtual_keyboard_state =
1822 VirtualKeyboardManagerState::new::<State, _>(&display_handle, |client| {1831 VirtualKeyboardManagerState::new::<State, _>(&display_handle, |client| {
1823 !client.get_data::<ClientState>().unwrap().restricted1832 !client.get_data::<ClientState>().unwrap().restricted
1824 });1833 });
1825-1834+ let virtual_pointer_state =
1835+ VirtualPointerManagerState::new::<State, _>(&display_handle, |client| {
1836+ !client.get_data::<ClientState>().unwrap().restricted
1837+ });
1826 let foreign_toplevel_state =1838 let foreign_toplevel_state =
1827 ForeignToplevelManagerState::new::<State, _>(&display_handle, |client| {1839 ForeignToplevelManagerState::new::<State, _>(&display_handle, |client| {
1828 !client.get_data::<ClientState>().unwrap().restricted1840 !client.get_data::<ClientState>().unwrap().restricted
@@ -2014,7 +2026,9 @@ impl Niri {
2014 xdg_foreign_state,2026 xdg_foreign_state,
2015 text_input_state,2027 text_input_state,
2016 input_method_state,2028 input_method_state,
2029+ keyboard_shortcuts_inhibit_state,
2017 virtual_keyboard_state,2030 virtual_keyboard_state,
2031+ virtual_pointer_state,
2018 shm_state,2032 shm_state,
2019 output_manager_state,2033 output_manager_state,
2020 dmabuf_state,2034 dmabuf_state,
@@ -2049,6 +2063,7 @@ impl Niri {
2049 previously_focused_window: None,2063 previously_focused_window: None,
2050 idle_inhibiting_surfaces: HashSet::new(),2064 idle_inhibiting_surfaces: HashSet::new(),
2051 is_fdo_idle_inhibited: Arc::new(AtomicBool::new(false)),2065 is_fdo_idle_inhibited: Arc::new(AtomicBool::new(false)),
2066+ keyboard_shortcuts_inhibiting_surfaces: HashMap::new(),
2052 cursor_manager,2067 cursor_manager,
2053 cursor_texture_cache: Default::default(),2068 cursor_texture_cache: Default::default(),
2054 cursor_shape_manager_state,2069 cursor_shape_manager_state,
src/protocols/mod.rsmodified+1 -0
@@ -3,5 +3,6 @@ pub mod gamma_control;
3 pub mod mutter_x11_interop;3 pub mod mutter_x11_interop;
4 pub mod output_management;4 pub mod output_management;
5 pub mod screencopy;5 pub mod screencopy;
6+pub mod virtual_pointer;
6 7
7 pub mod raw;8 pub mod raw;
src/protocols/virtual_pointer.rsadded+563 -0
@@ -0,0 +1,563 @@
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, 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 wayland_backend::protocol::WEnum;
18+use wayland_protocols_wlr::virtual_pointer::v1::server::{
19+ zwlr_virtual_pointer_manager_v1, zwlr_virtual_pointer_v1,
20+};
21+use zwlr_virtual_pointer_manager_v1::ZwlrVirtualPointerManagerV1;
22+use zwlr_virtual_pointer_v1::ZwlrVirtualPointerV1;
23+
24+const VERSION: u32 = 2;
25+
26+pub struct VirtualPointerManagerState {
27+ virtual_pointers: HashSet<ZwlrVirtualPointerV1>,
28+}
29+
30+pub struct VirtualPointerManagerGlobalData {
31+ filter: Box<dyn for<'c> Fn(&'c Client) -> bool + Send + Sync>,
32+}
33+
34+pub struct VirtualPointerInputBackend;
35+
36+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
37+pub struct VirtualPointer {
38+ pointer: ZwlrVirtualPointerV1,
39+}
40+
41+#[derive(Debug)]
42+pub struct VirtualPointerUserData {
43+ seat: Option<WlSeat>,
44+ output: Option<Output>,
45+
46+ axis_frame: Mutex<Option<AxisFrame>>,
47+}
48+
49+impl VirtualPointer {
50+ fn data(&self) -> &VirtualPointerUserData {
51+ self.pointer.data().unwrap()
52+ }
53+
54+ pub fn seat(&self) -> Option<&WlSeat> {
55+ self.data().seat.as_ref()
56+ }
57+
58+ pub fn output(&self) -> Option<&Output> {
59+ self.data().output.as_ref()
60+ }
61+
62+ fn finish_axis_frame(&self) -> Option<AxisFrame> {
63+ self.data().axis_frame.lock().unwrap().take()
64+ }
65+
66+ fn mutate_axis_frame(&self, time: Option<u32>, f: impl FnOnce(AxisFrame) -> AxisFrame) {
67+ let mut frame = self.data().axis_frame.lock().unwrap();
68+
69+ *frame = frame.or(time.map(AxisFrame::new)).map(f);
70+ }
71+}
72+
73+impl Device for VirtualPointer {
74+ fn id(&self) -> String {
75+ format!("wlr virtual pointer {}", self.pointer.id())
76+ }
77+
78+ fn name(&self) -> String {
79+ String::from("virtual pointer")
80+ }
81+
82+ fn has_capability(&self, capability: DeviceCapability) -> bool {
83+ matches!(capability, DeviceCapability::Pointer)
84+ }
85+
86+ fn usb_id(&self) -> Option<(u32, u32)> {
87+ None
88+ }
89+
90+ fn syspath(&self) -> Option<std::path::PathBuf> {
91+ None
92+ }
93+}
94+
95+pub struct VirtualPointerMotionEvent {
96+ pointer: VirtualPointer,
97+ time: u32,
98+ dx: f64,
99+ dy: f64,
100+}
101+
102+impl Event<VirtualPointerInputBackend> for VirtualPointerMotionEvent {
103+ fn time(&self) -> u64 {
104+ self.time as u64 * 1000 // millis to micros
105+ }
106+
107+ fn device(&self) -> VirtualPointer {
108+ self.pointer.clone()
109+ }
110+}
111+
112+impl PointerMotionEvent<VirtualPointerInputBackend> for VirtualPointerMotionEvent {
113+ fn delta_x(&self) -> f64 {
114+ self.dx
115+ }
116+
117+ fn delta_y(&self) -> f64 {
118+ self.dy
119+ }
120+
121+ fn delta_x_unaccel(&self) -> f64 {
122+ self.dx
123+ }
124+
125+ fn delta_y_unaccel(&self) -> f64 {
126+ self.dy
127+ }
128+}
129+
130+pub struct VirtualPointerMotionAbsoluteEvent {
131+ pointer: VirtualPointer,
132+ time: u32,
133+ x: u32,
134+ y: u32,
135+ x_extent: u32,
136+ y_extent: u32,
137+}
138+
139+impl Event<VirtualPointerInputBackend> for VirtualPointerMotionAbsoluteEvent {
140+ fn time(&self) -> u64 {
141+ self.time as u64 * 1000 // millis to micros
142+ }
143+
144+ fn device(&self) -> VirtualPointer {
145+ self.pointer.clone()
146+ }
147+}
148+
149+impl AbsolutePositionEvent<VirtualPointerInputBackend> for VirtualPointerMotionAbsoluteEvent {
150+ fn x(&self) -> f64 {
151+ self.x as f64 / self.x_extent as f64
152+ }
153+
154+ fn y(&self) -> f64 {
155+ self.y as f64 / self.y_extent as f64
156+ }
157+
158+ fn x_transformed(&self, width: i32) -> f64 {
159+ (self.x as i64 * width as i64) as f64 / self.x_extent as f64
160+ }
161+
162+ fn y_transformed(&self, height: i32) -> f64 {
163+ (self.y as i64 * height as i64) as f64 / self.y_extent as f64
164+ }
165+}
166+
167+pub struct VirtualPointerButtonEvent {
168+ pointer: VirtualPointer,
169+ time: u32,
170+ button: u32,
171+ state: ButtonState,
172+}
173+
174+impl Event<VirtualPointerInputBackend> for VirtualPointerButtonEvent {
175+ fn time(&self) -> u64 {
176+ self.time as u64 * 1000 // millis to micros
177+ }
178+
179+ fn device(&self) -> VirtualPointer {
180+ self.pointer.clone()
181+ }
182+}
183+
184+impl PointerButtonEvent<VirtualPointerInputBackend> for VirtualPointerButtonEvent {
185+ fn button_code(&self) -> u32 {
186+ self.button
187+ }
188+
189+ fn state(&self) -> ButtonState {
190+ self.state
191+ }
192+}
193+
194+pub struct VirtualPointerAxisEvent {
195+ pointer: VirtualPointer,
196+ frame: AxisFrame,
197+}
198+
199+impl Event<VirtualPointerInputBackend> for VirtualPointerAxisEvent {
200+ fn time(&self) -> u64 {
201+ self.frame.time as u64 * 1000 // millis to micros
202+ }
203+
204+ fn device(&self) -> VirtualPointer {
205+ self.pointer.clone()
206+ }
207+}
208+
209+fn tuple_axis<T>(tuple: (T, T), axis: Axis) -> T {
210+ match axis {
211+ Axis::Horizontal => tuple.0,
212+ Axis::Vertical => tuple.1,
213+ }
214+}
215+
216+impl PointerAxisEvent<VirtualPointerInputBackend> for VirtualPointerAxisEvent {
217+ fn amount(&self, axis: Axis) -> Option<f64> {
218+ Some(tuple_axis(self.frame.axis, axis))
219+ }
220+
221+ fn amount_v120(&self, axis: Axis) -> Option<f64> {
222+ self.frame.v120.map(|v120| tuple_axis(v120, axis) as f64)
223+ }
224+
225+ fn source(&self) -> AxisSource {
226+ self.frame.source.unwrap_or_else(|| {
227+ warn!("AxisSource: no source set, giving bogus value");
228+ AxisSource::Continuous
229+ })
230+ }
231+
232+ fn relative_direction(&self, axis: Axis) -> AxisRelativeDirection {
233+ tuple_axis(self.frame.relative_direction, axis)
234+ }
235+}
236+
237+impl PointerMotionAbsoluteEvent<VirtualPointerInputBackend> for VirtualPointerMotionAbsoluteEvent {}
238+
239+impl InputBackend for VirtualPointerInputBackend {
240+ type Device = VirtualPointer;
241+
242+ type KeyboardKeyEvent = UnusedEvent;
243+ type PointerAxisEvent = VirtualPointerAxisEvent;
244+ type PointerButtonEvent = VirtualPointerButtonEvent;
245+ type PointerMotionEvent = VirtualPointerMotionEvent;
246+ type PointerMotionAbsoluteEvent = VirtualPointerMotionAbsoluteEvent;
247+
248+ type GestureSwipeBeginEvent = UnusedEvent;
249+ type GestureSwipeUpdateEvent = UnusedEvent;
250+ type GestureSwipeEndEvent = UnusedEvent;
251+ type GesturePinchBeginEvent = UnusedEvent;
252+ type GesturePinchUpdateEvent = UnusedEvent;
253+ type GesturePinchEndEvent = UnusedEvent;
254+ type GestureHoldBeginEvent = UnusedEvent;
255+ type GestureHoldEndEvent = UnusedEvent;
256+
257+ type TouchDownEvent = UnusedEvent;
258+ type TouchUpEvent = UnusedEvent;
259+ type TouchMotionEvent = UnusedEvent;
260+ type TouchCancelEvent = UnusedEvent;
261+ type TouchFrameEvent = UnusedEvent;
262+ type TabletToolAxisEvent = UnusedEvent;
263+ type TabletToolProximityEvent = UnusedEvent;
264+ type TabletToolTipEvent = UnusedEvent;
265+ type TabletToolButtonEvent = UnusedEvent;
266+
267+ type SwitchToggleEvent = UnusedEvent;
268+
269+ type SpecialEvent = UnusedEvent;
270+}
271+
272+pub trait VirtualPointerHandler {
273+ fn virtual_pointer_manager_state(&mut self) -> &mut VirtualPointerManagerState;
274+
275+ fn create_virtual_pointer(&mut self, pointer: VirtualPointer) {
276+ let _ = pointer;
277+ }
278+ fn destroy_virtual_pointer(&mut self, pointer: VirtualPointer) {
279+ let _ = pointer;
280+ }
281+
282+ fn on_virtual_pointer_motion(&mut self, event: VirtualPointerMotionEvent);
283+ fn on_virtual_pointer_motion_absolute(&mut self, event: VirtualPointerMotionAbsoluteEvent);
284+ fn on_virtual_pointer_button(&mut self, event: VirtualPointerButtonEvent);
285+ fn on_virtual_pointer_axis(&mut self, event: VirtualPointerAxisEvent);
286+}
287+
288+impl VirtualPointerManagerState {
289+ pub fn new<D, F>(display: &DisplayHandle, filter: F) -> Self
290+ where
291+ D: GlobalDispatch<ZwlrVirtualPointerManagerV1, VirtualPointerManagerGlobalData>,
292+ D: Dispatch<ZwlrVirtualPointerManagerV1, ()>,
293+ D: Dispatch<ZwlrVirtualPointerV1, VirtualPointerUserData>,
294+ D: VirtualPointerHandler,
295+ D: 'static,
296+ F: for<'c> Fn(&'c Client) -> bool + Send + Sync + 'static,
297+ {
298+ let global_data = VirtualPointerManagerGlobalData {
299+ filter: Box::new(filter),
300+ };
301+ display.create_global::<D, ZwlrVirtualPointerManagerV1, _>(VERSION, global_data);
302+
303+ Self {
304+ virtual_pointers: HashSet::new(),
305+ }
306+ }
307+}
308+
309+impl<D> GlobalDispatch<ZwlrVirtualPointerManagerV1, VirtualPointerManagerGlobalData, D>
310+ for VirtualPointerManagerState
311+where
312+ D: GlobalDispatch<ZwlrVirtualPointerManagerV1, VirtualPointerManagerGlobalData>,
313+ D: Dispatch<ZwlrVirtualPointerManagerV1, ()>,
314+ D: Dispatch<ZwlrVirtualPointerV1, VirtualPointerUserData>,
315+ D: VirtualPointerHandler,
316+ D: 'static,
317+{
318+ fn bind(
319+ _state: &mut D,
320+ _handle: &DisplayHandle,
321+ _client: &Client,
322+ manager: New<ZwlrVirtualPointerManagerV1>,
323+ _manager_state: &VirtualPointerManagerGlobalData,
324+ data_init: &mut DataInit<'_, D>,
325+ ) {
326+ data_init.init(manager, ());
327+ }
328+
329+ fn can_view(client: Client, global_data: &VirtualPointerManagerGlobalData) -> bool {
330+ (global_data.filter)(&client)
331+ }
332+}
333+
334+impl<D> Dispatch<ZwlrVirtualPointerManagerV1, (), D> for VirtualPointerManagerState
335+where
336+ D: Dispatch<ZwlrVirtualPointerManagerV1, ()>,
337+ D: Dispatch<ZwlrVirtualPointerV1, VirtualPointerUserData>,
338+ D: VirtualPointerHandler,
339+ D: 'static,
340+{
341+ fn request(
342+ state: &mut D,
343+ _client: &Client,
344+ _resource: &ZwlrVirtualPointerManagerV1,
345+ request: <ZwlrVirtualPointerManagerV1 as Resource>::Request,
346+ _data: &(),
347+ _dhandle: &DisplayHandle,
348+ data_init: &mut DataInit<'_, D>,
349+ ) {
350+ let (id, seat, output) = match request {
351+ zwlr_virtual_pointer_manager_v1::Request::CreateVirtualPointer { seat, id } => {
352+ (id, seat, None)
353+ }
354+ zwlr_virtual_pointer_manager_v1::Request::CreateVirtualPointerWithOutput {
355+ seat,
356+ output,
357+ id,
358+ } => (id, seat, output.as_ref().and_then(Output::from_resource)),
359+ zwlr_virtual_pointer_manager_v1::Request::Destroy => return,
360+ _ => unreachable!(),
361+ };
362+
363+ let pointer = data_init.init(
364+ id,
365+ VirtualPointerUserData {
366+ seat,
367+ output,
368+ axis_frame: Mutex::new(None),
369+ },
370+ );
371+ state
372+ .virtual_pointer_manager_state()
373+ .virtual_pointers
374+ .insert(pointer.clone());
375+
376+ state.create_virtual_pointer(VirtualPointer { pointer });
377+ }
378+}
379+
380+impl<D> Dispatch<ZwlrVirtualPointerV1, VirtualPointerUserData, D> for VirtualPointerManagerState
381+where
382+ D: Dispatch<ZwlrVirtualPointerV1, VirtualPointerUserData>,
383+ D: VirtualPointerHandler,
384+ D: 'static,
385+{
386+ fn request(
387+ handler: &mut D,
388+ _client: &Client,
389+ resource: &ZwlrVirtualPointerV1,
390+ request: <ZwlrVirtualPointerV1 as Resource>::Request,
391+ _data: &VirtualPointerUserData,
392+ _dhandle: &DisplayHandle,
393+ _data_init: &mut DataInit<'_, D>,
394+ ) {
395+ let pointer = VirtualPointer {
396+ pointer: resource.clone(),
397+ };
398+ match request {
399+ zwlr_virtual_pointer_v1::Request::Motion { time, dx, dy } => {
400+ let event = VirtualPointerMotionEvent {
401+ pointer,
402+ time,
403+ dx,
404+ dy,
405+ };
406+ handler.on_virtual_pointer_motion(event);
407+ }
408+ zwlr_virtual_pointer_v1::Request::MotionAbsolute {
409+ time,
410+ x,
411+ y,
412+ x_extent,
413+ y_extent,
414+ } => {
415+ let event = VirtualPointerMotionAbsoluteEvent {
416+ pointer,
417+ time,
418+ x,
419+ y,
420+ x_extent,
421+ y_extent,
422+ };
423+ handler.on_virtual_pointer_motion_absolute(event);
424+ }
425+ zwlr_virtual_pointer_v1::Request::Button {
426+ time,
427+ button,
428+ state,
429+ } => {
430+ // state is an enum but wlroots treats it as a C boolean (zero or nonzero)
431+ // so we emulate that behaviour too. ButtonState::Pressed and any invalid value
432+ // counts as pressed.
433+ // https://gitlab.freedesktop.org/wlroots/wlroots/-/blob/3187479c07c34a4de82c06a316a763a36a0499da/types/wlr_virtual_pointer_v1.c#L74
434+ let state = match state {
435+ WEnum::Value(wl_pointer::ButtonState::Released) => ButtonState::Released,
436+ _ => ButtonState::Pressed,
437+ };
438+ let event = VirtualPointerButtonEvent {
439+ pointer,
440+ time,
441+ button,
442+ state,
443+ };
444+ handler.on_virtual_pointer_button(event);
445+ }
446+ zwlr_virtual_pointer_v1::Request::Axis { time, axis, value } => {
447+ let axis = match axis {
448+ WEnum::Value(wl_pointer::Axis::VerticalScroll) => Axis::Vertical,
449+ WEnum::Value(wl_pointer::Axis::HorizontalScroll) => Axis::Horizontal,
450+ _ => {
451+ warn!("Axis: invalid axis");
452+ resource.post_error(
453+ zwlr_virtual_pointer_v1::Error::InvalidAxis,
454+ "invalid axis",
455+ );
456+ return;
457+ }
458+ };
459+
460+ pointer.mutate_axis_frame(Some(time), |frame| frame.value(axis, value));
461+ }
462+ zwlr_virtual_pointer_v1::Request::Frame => {
463+ if let Some(frame) = pointer.finish_axis_frame() {
464+ let event = VirtualPointerAxisEvent { pointer, frame };
465+ handler.on_virtual_pointer_axis(event);
466+ }
467+ }
468+ zwlr_virtual_pointer_v1::Request::AxisSource { axis_source } => {
469+ let axis_source = match axis_source {
470+ WEnum::Value(wl_pointer::AxisSource::Wheel) => AxisSource::Wheel,
471+ WEnum::Value(wl_pointer::AxisSource::Finger) => AxisSource::Finger,
472+ WEnum::Value(wl_pointer::AxisSource::Continuous) => AxisSource::Continuous,
473+ WEnum::Value(wl_pointer::AxisSource::WheelTilt) => AxisSource::WheelTilt,
474+
475+ _ => {
476+ warn!("AxisSource: invalid axis source");
477+ resource.post_error(
478+ zwlr_virtual_pointer_v1::Error::InvalidAxisSource,
479+ "invalid axis source",
480+ );
481+ return;
482+ }
483+ };
484+
485+ pointer.mutate_axis_frame(None, |frame| frame.source(axis_source));
486+ }
487+ zwlr_virtual_pointer_v1::Request::AxisStop { time, axis } => {
488+ let axis = match axis {
489+ WEnum::Value(wl_pointer::Axis::VerticalScroll) => Axis::Vertical,
490+ WEnum::Value(wl_pointer::Axis::HorizontalScroll) => Axis::Horizontal,
491+ _ => {
492+ warn!("AxisStop: invalid axis");
493+ resource.post_error(
494+ zwlr_virtual_pointer_v1::Error::InvalidAxis,
495+ "invalid axis",
496+ );
497+ return;
498+ }
499+ };
500+
501+ pointer.mutate_axis_frame(Some(time), |frame| frame.stop(axis));
502+ }
503+ zwlr_virtual_pointer_v1::Request::AxisDiscrete {
504+ time,
505+ axis,
506+ value,
507+ discrete,
508+ } => {
509+ let axis = match axis {
510+ WEnum::Value(wl_pointer::Axis::VerticalScroll) => Axis::Vertical,
511+ WEnum::Value(wl_pointer::Axis::HorizontalScroll) => Axis::Horizontal,
512+ _ => {
513+ warn!("AxisDiscrete: invalid axis");
514+ resource.post_error(
515+ zwlr_virtual_pointer_v1::Error::InvalidAxis,
516+ "invalid axis",
517+ );
518+ return;
519+ }
520+ };
521+ pointer.mutate_axis_frame(Some(time), |frame| {
522+ frame.value(axis, value).v120(axis, discrete)
523+ });
524+ }
525+ zwlr_virtual_pointer_v1::Request::Destroy => {}
526+ _ => unreachable!(),
527+ }
528+ }
529+
530+ fn destroyed(
531+ handler: &mut D,
532+ _client: wayland_backend::server::ClientId,
533+ resource: &ZwlrVirtualPointerV1,
534+ _data: &VirtualPointerUserData,
535+ ) {
536+ let pointer = VirtualPointer {
537+ pointer: resource.clone(),
538+ };
539+
540+ handler.destroy_virtual_pointer(pointer);
541+ handler
542+ .virtual_pointer_manager_state()
543+ .virtual_pointers
544+ .remove(resource);
545+ }
546+}
547+
548+#[macro_export]
549+macro_rules! delegate_virtual_pointer {
550+ ($(@<$( $lt:tt $( : $clt:tt $(+ $dlt:tt )* )? ),+>)? $ty: ty) => {
551+ smithay::reexports::wayland_server::delegate_global_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
552+ smithay::reexports::wayland_protocols_wlr::virtual_pointer::v1::server::zwlr_virtual_pointer_manager_v1::ZwlrVirtualPointerManagerV1: $crate::protocols::virtual_pointer::VirtualPointerManagerGlobalData
553+ ] => $crate::protocols::virtual_pointer::VirtualPointerManagerState);
554+
555+ smithay::reexports::wayland_server::delegate_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
556+ smithay::reexports::wayland_protocols_wlr::virtual_pointer::v1::server::zwlr_virtual_pointer_manager_v1::ZwlrVirtualPointerManagerV1: ()
557+ ] => $crate::protocols::virtual_pointer::VirtualPointerManagerState);
558+
559+ smithay::reexports::wayland_server::delegate_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty: [
560+ smithay::reexports::wayland_protocols_wlr::virtual_pointer::v1::server::zwlr_virtual_pointer_v1::ZwlrVirtualPointerV1: $crate::protocols::virtual_pointer::VirtualPointerUserData
561+ ] => $crate::protocols::virtual_pointer::VirtualPointerManagerState);
562+ };
563+}