forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBf5c97faIvan Molodetskikh2 years ago876 commits

input.rs2453 lines, 86.8 KiBHistoryRawDownload
1use std::any::Any;
2use std::collections::hash_map::Entry;
3use std::collections::HashSet;
4use std::time::Duration;
5
6use calloop::timer::{TimeoutAction, Timer};
7use input::event::gesture::GestureEventCoordinates as _;
8use niri_config::{Action, Bind, Binds, Key, Modifiers, Trigger};
9use niri_ipc::LayoutSwitchTarget;
10use smithay::backend::input::{
11 AbsolutePositionEvent, Axis, AxisSource, ButtonState, Device, DeviceCapability, Event,
12 GestureBeginEvent, GestureEndEvent, GesturePinchUpdateEvent as _, GestureSwipeUpdateEvent as _,
13 InputBackend, InputEvent, KeyState, KeyboardKeyEvent, PointerAxisEvent, PointerButtonEvent,
14 PointerMotionEvent, ProximityState, TabletToolButtonEvent, TabletToolEvent,
15 TabletToolProximityEvent, TabletToolTipEvent, TabletToolTipState, TouchEvent,
16};
17use smithay::backend::libinput::LibinputInputBackend;
18use smithay::input::keyboard::{keysyms, FilterResult, Keysym, ModifiersState};
19use smithay::input::pointer::{
20 AxisFrame, ButtonEvent, CursorImageStatus, GestureHoldBeginEvent, GestureHoldEndEvent,
21 GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent, GestureSwipeBeginEvent,
22 GestureSwipeEndEvent, GestureSwipeUpdateEvent, MotionEvent, RelativeMotionEvent,
23};
24use smithay::input::touch::{DownEvent, MotionEvent as TouchMotionEvent, UpEvent};
25use smithay::utils::{Logical, Point, SERIAL_COUNTER};
26use smithay::wayland::pointer_constraints::{with_pointer_constraint, PointerConstraint};
27use smithay::wayland::tablet_manager::{TabletDescriptor, TabletSeatTrait};
28
29use crate::niri::State;
30use crate::ui::screenshot_ui::ScreenshotUi;
31use crate::utils::spawning::spawn;
32use crate::utils::{center, get_monotonic_time};
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum CompositorMod {
36 Super,
37 Alt,
38}
39
40#[derive(Debug, Clone, Copy, PartialEq)]
41pub struct TabletData {
42 pub aspect_ratio: f64,
43}
44
45impl State {
46 pub fn process_input_event<I: InputBackend + 'static>(&mut self, event: InputEvent<I>)
47 where
48 I::Device: 'static, // Needed for downcasting.
49 {
50 let _span = tracy_client::span!("process_input_event");
51
52 // A bit of a hack, but animation end runs some logic (i.e. workspace clean-up) and it
53 // doesn't always trigger due to damage, etc. So run it here right before it might prove
54 // important. Besides, animations affect the input, so it's best to have up-to-date values
55 // here.
56 self.niri.layout.advance_animations(get_monotonic_time());
57
58 if self.niri.monitors_active {
59 // Notify the idle-notifier of activity.
60 if should_notify_activity(&event) {
61 self.niri
62 .idle_notifier_state
63 .notify_activity(&self.niri.seat);
64 }
65 } else {
66 // Power on monitors if they were off.
67 if should_activate_monitors(&event) {
68 self.niri.activate_monitors(&mut self.backend);
69
70 // Notify the idle-notifier of activity only if we're also powering on the
71 // monitors.
72 self.niri
73 .idle_notifier_state
74 .notify_activity(&self.niri.seat);
75 }
76 }
77
78 let hide_hotkey_overlay =
79 self.niri.hotkey_overlay.is_open() && should_hide_hotkey_overlay(&event);
80
81 let hide_exit_confirm_dialog = self
82 .niri
83 .exit_confirm_dialog
84 .as_ref()
85 .map_or(false, |d| d.is_open())
86 && should_hide_exit_confirm_dialog(&event);
87
88 use InputEvent::*;
89 match event {
90 DeviceAdded { device } => self.on_device_added(device),
91 DeviceRemoved { device } => self.on_device_removed(device),
92 Keyboard { event } => self.on_keyboard::<I>(event),
93 PointerMotion { event } => self.on_pointer_motion::<I>(event),
94 PointerMotionAbsolute { event } => self.on_pointer_motion_absolute::<I>(event),
95 PointerButton { event } => self.on_pointer_button::<I>(event),
96 PointerAxis { event } => self.on_pointer_axis::<I>(event),
97 TabletToolAxis { event } => self.on_tablet_tool_axis::<I>(event),
98 TabletToolTip { event } => self.on_tablet_tool_tip::<I>(event),
99 TabletToolProximity { event } => self.on_tablet_tool_proximity::<I>(event),
100 TabletToolButton { event } => self.on_tablet_tool_button::<I>(event),
101 GestureSwipeBegin { event } => self.on_gesture_swipe_begin::<I>(event),
102 GestureSwipeUpdate { event } => self.on_gesture_swipe_update::<I>(event),
103 GestureSwipeEnd { event } => self.on_gesture_swipe_end::<I>(event),
104 GesturePinchBegin { event } => self.on_gesture_pinch_begin::<I>(event),
105 GesturePinchUpdate { event } => self.on_gesture_pinch_update::<I>(event),
106 GesturePinchEnd { event } => self.on_gesture_pinch_end::<I>(event),
107 GestureHoldBegin { event } => self.on_gesture_hold_begin::<I>(event),
108 GestureHoldEnd { event } => self.on_gesture_hold_end::<I>(event),
109 TouchDown { event } => self.on_touch_down::<I>(event),
110 TouchMotion { event } => self.on_touch_motion::<I>(event),
111 TouchUp { event } => self.on_touch_up::<I>(event),
112 TouchCancel { event } => self.on_touch_cancel::<I>(event),
113 TouchFrame { event } => self.on_touch_frame::<I>(event),
114 SwitchToggle { .. } => (),
115 Special(_) => (),
116 }
117
118 // Do this last so that screenshot still gets it.
119 // FIXME: do this in a less cursed fashion somehow.
120 if hide_hotkey_overlay && self.niri.hotkey_overlay.hide() {
121 self.niri.queue_redraw_all();
122 }
123
124 if let Some(dialog) = &mut self.niri.exit_confirm_dialog {
125 if hide_exit_confirm_dialog && dialog.hide() {
126 self.niri.queue_redraw_all();
127 }
128 }
129 }
130
131 pub fn process_libinput_event(&mut self, event: &mut InputEvent<LibinputInputBackend>) {
132 let _span = tracy_client::span!("process_libinput_event");
133
134 match event {
135 InputEvent::DeviceAdded { device } => {
136 self.niri.devices.insert(device.clone());
137
138 if device.has_capability(input::DeviceCapability::TabletTool) {
139 match device.size() {
140 Some((w, h)) => {
141 let aspect_ratio = w / h;
142 let data = TabletData { aspect_ratio };
143 self.niri.tablets.insert(device.clone(), data);
144 }
145 None => {
146 warn!("tablet tool device has no size");
147 }
148 }
149 }
150
151 if device.has_capability(input::DeviceCapability::Keyboard) {
152 if let Some(led_state) = self
153 .niri
154 .seat
155 .get_keyboard()
156 .map(|keyboard| keyboard.led_state())
157 {
158 device.led_update(led_state.into());
159 }
160 }
161
162 if device.has_capability(input::DeviceCapability::Touch) {
163 self.niri.touch.insert(device.clone());
164 }
165
166 apply_libinput_settings(&self.niri.config.borrow().input, device);
167 }
168 InputEvent::DeviceRemoved { device } => {
169 self.niri.touch.remove(device);
170 self.niri.tablets.remove(device);
171 self.niri.devices.remove(device);
172 }
173 _ => (),
174 }
175 }
176
177 fn on_device_added(&mut self, device: impl Device) {
178 if device.has_capability(DeviceCapability::TabletTool) {
179 let tablet_seat = self.niri.seat.tablet_seat();
180
181 let desc = TabletDescriptor::from(&device);
182 tablet_seat.add_tablet::<Self>(&self.niri.display_handle, &desc);
183 }
184 if device.has_capability(DeviceCapability::Touch) && self.niri.seat.get_touch().is_none() {
185 self.niri.seat.add_touch();
186 }
187 }
188
189 fn on_device_removed(&mut self, device: impl Device) {
190 if device.has_capability(DeviceCapability::TabletTool) {
191 let tablet_seat = self.niri.seat.tablet_seat();
192
193 let desc = TabletDescriptor::from(&device);
194 tablet_seat.remove_tablet(&desc);
195
196 // If there are no tablets in seat we can remove all tools
197 if tablet_seat.count_tablets() == 0 {
198 tablet_seat.clear_tools();
199 }
200 }
201 if device.has_capability(DeviceCapability::Touch) && self.niri.touch.is_empty() {
202 self.niri.seat.remove_touch();
203 }
204 }
205
206 /// Computes the cursor position for the tablet event.
207 ///
208 /// This function handles the tablet output mapping, as well as coordinate clamping and aspect
209 /// ratio correction.
210 fn compute_tablet_position<I: InputBackend>(
211 &self,
212 event: &(impl Event<I> + TabletToolEvent<I>),
213 ) -> Option<Point<f64, Logical>>
214 where
215 I::Device: 'static,
216 {
217 let output = self.niri.output_for_tablet()?;
218 let output_geo = self.niri.global_space.output_geometry(output).unwrap();
219
220 let mut pos = event.position_transformed(output_geo.size);
221 pos.x /= output_geo.size.w as f64;
222 pos.y /= output_geo.size.h as f64;
223
224 let device = event.device();
225 if let Some(device) = (&device as &dyn Any).downcast_ref::<input::Device>() {
226 if let Some(data) = self.niri.tablets.get(device) {
227 // This code does the same thing as mutter with "keep aspect ratio" enabled.
228 let output_aspect_ratio = output_geo.size.w as f64 / output_geo.size.h as f64;
229 let ratio = data.aspect_ratio / output_aspect_ratio;
230
231 if ratio > 1. {
232 pos.x *= ratio;
233 } else {
234 pos.y /= ratio;
235 }
236 }
237 };
238
239 pos.x *= output_geo.size.w as f64;
240 pos.y *= output_geo.size.h as f64;
241 pos.x = pos.x.clamp(0.0, output_geo.size.w as f64 - 1.);
242 pos.y = pos.y.clamp(0.0, output_geo.size.h as f64 - 1.);
243 Some(pos + output_geo.loc.to_f64())
244 }
245
246 fn on_keyboard<I: InputBackend>(&mut self, event: I::KeyboardKeyEvent) {
247 let comp_mod = self.backend.mod_key();
248
249 let serial = SERIAL_COUNTER.next_serial();
250 let time = Event::time_msec(&event);
251 let pressed = event.state() == KeyState::Pressed;
252
253 let Some(Some(bind)) = self.niri.seat.get_keyboard().unwrap().input(
254 self,
255 event.key_code(),
256 event.state(),
257 serial,
258 time,
259 |this, mods, keysym| {
260 let bindings = &this.niri.config.borrow().binds;
261 let key_code = event.key_code();
262 let modified = keysym.modified_sym();
263 let raw = keysym.raw_latin_sym_or_raw_current_sym();
264
265 if let Some(dialog) = &this.niri.exit_confirm_dialog {
266 if dialog.is_open() && pressed && raw == Some(Keysym::Return) {
267 info!("quitting after confirming exit dialog");
268 this.niri.stop_signal.stop();
269 }
270 }
271
272 should_intercept_key(
273 &mut this.niri.suppressed_keys,
274 bindings,
275 comp_mod,
276 key_code,
277 modified,
278 raw,
279 pressed,
280 *mods,
281 &this.niri.screenshot_ui,
282 this.niri.config.borrow().input.disable_power_key_handling,
283 )
284 },
285 ) else {
286 return;
287 };
288
289 // Filter actions when the key is released or the session is locked.
290 if !pressed {
291 return;
292 }
293
294 self.handle_bind(bind);
295 }
296
297 pub fn handle_bind(&mut self, bind: Bind) {
298 let Some(cooldown) = bind.cooldown else {
299 self.do_action(bind.action);
300 return;
301 };
302
303 // Check this first so that it doesn't trigger the cooldown.
304 if self.niri.is_locked() && !allowed_when_locked(&bind.action) {
305 return;
306 }
307
308 match self.niri.bind_cooldown_timers.entry(bind.key) {
309 // The bind is on cooldown.
310 Entry::Occupied(_) => (),
311 Entry::Vacant(entry) => {
312 let timer = Timer::from_duration(cooldown);
313 let token = self
314 .niri
315 .event_loop
316 .insert_source(timer, move |_, _, state| {
317 if state.niri.bind_cooldown_timers.remove(&bind.key).is_none() {
318 error!("bind cooldown timer entry disappeared");
319 }
320 TimeoutAction::Drop
321 })
322 .unwrap();
323 entry.insert(token);
324
325 self.do_action(bind.action);
326 }
327 }
328 }
329
330 pub fn do_action(&mut self, action: Action) {
331 if self.niri.is_locked() && !allowed_when_locked(&action) {
332 return;
333 }
334
335 if let Some(touch) = self.niri.seat.get_touch() {
336 touch.cancel(self);
337 }
338
339 match action {
340 Action::Quit(skip_confirmation) => {
341 if !skip_confirmation {
342 if let Some(dialog) = &mut self.niri.exit_confirm_dialog {
343 if dialog.show() {
344 self.niri.queue_redraw_all();
345 }
346 return;
347 }
348 }
349
350 info!("quitting as requested");
351 self.niri.stop_signal.stop()
352 }
353 Action::ChangeVt(vt) => {
354 self.backend.change_vt(vt);
355 // Changing VT may not deliver the key releases, so clear the state.
356 self.niri.suppressed_keys.clear();
357 }
358 Action::Suspend => {
359 self.backend.suspend();
360 // Suspend may not deliver the key releases, so clear the state.
361 self.niri.suppressed_keys.clear();
362 }
363 Action::PowerOffMonitors => {
364 self.niri.deactivate_monitors(&mut self.backend);
365 }
366 Action::ToggleDebugTint => {
367 self.backend.toggle_debug_tint();
368 self.niri.queue_redraw_all();
369 }
370 Action::Spawn(command) => {
371 spawn(command);
372 }
373 Action::ScreenshotScreen => {
374 let active = self.niri.layout.active_output().cloned();
375 if let Some(active) = active {
376 self.backend.with_primary_renderer(|renderer| {
377 if let Err(err) = self.niri.screenshot(renderer, &active) {
378 warn!("error taking screenshot: {err:?}");
379 }
380 });
381 }
382 }
383 Action::ConfirmScreenshot => {
384 self.backend.with_primary_renderer(|renderer| {
385 match self.niri.screenshot_ui.capture(renderer) {
386 Ok((size, pixels)) => {
387 if let Err(err) = self.niri.save_screenshot(size, pixels) {
388 warn!("error saving screenshot: {err:?}");
389 }
390 }
391 Err(err) => {
392 warn!("error capturing screenshot: {err:?}");
393 }
394 }
395 });
396
397 self.niri.screenshot_ui.close();
398 self.niri
399 .cursor_manager
400 .set_cursor_image(CursorImageStatus::default_named());
401 self.niri.queue_redraw_all();
402 }
403 Action::CancelScreenshot => {
404 self.niri.screenshot_ui.close();
405 self.niri
406 .cursor_manager
407 .set_cursor_image(CursorImageStatus::default_named());
408 self.niri.queue_redraw_all();
409 }
410 Action::Screenshot => {
411 self.backend.with_primary_renderer(|renderer| {
412 self.niri.open_screenshot_ui(renderer);
413 });
414 }
415 Action::ScreenshotWindow => {
416 let active = self.niri.layout.active_window();
417 if let Some((mapped, output)) = active {
418 self.backend.with_primary_renderer(|renderer| {
419 if let Err(err) = self.niri.screenshot_window(renderer, output, mapped) {
420 warn!("error taking screenshot: {err:?}");
421 }
422 });
423 }
424 }
425 Action::CloseWindow => {
426 if let Some(mapped) = self.niri.layout.focus() {
427 mapped.toplevel().send_close();
428 }
429 }
430 Action::FullscreenWindow => {
431 let focus = self.niri.layout.focus().map(|m| m.window.clone());
432 if let Some(window) = focus {
433 self.niri.layout.toggle_fullscreen(&window);
434 // FIXME: granular
435 self.niri.queue_redraw_all();
436 }
437 }
438 Action::SwitchLayout(action) => {
439 self.niri.seat.get_keyboard().unwrap().with_xkb_state(
440 self,
441 |mut state| match action {
442 LayoutSwitchTarget::Next => state.cycle_next_layout(),
443 LayoutSwitchTarget::Prev => state.cycle_prev_layout(),
444 },
445 );
446 }
447 Action::MoveColumnLeft => {
448 self.niri.layout.move_left();
449 self.maybe_warp_cursor_to_focus();
450 // FIXME: granular
451 self.niri.queue_redraw_all();
452 }
453 Action::MoveColumnRight => {
454 self.niri.layout.move_right();
455 self.maybe_warp_cursor_to_focus();
456 // FIXME: granular
457 self.niri.queue_redraw_all();
458 }
459 Action::MoveColumnToFirst => {
460 self.niri.layout.move_column_to_first();
461 self.maybe_warp_cursor_to_focus();
462 // FIXME: granular
463 self.niri.queue_redraw_all();
464 }
465 Action::MoveColumnToLast => {
466 self.niri.layout.move_column_to_last();
467 self.maybe_warp_cursor_to_focus();
468 // FIXME: granular
469 self.niri.queue_redraw_all();
470 }
471 Action::MoveWindowDown => {
472 self.niri.layout.move_down();
473 self.maybe_warp_cursor_to_focus();
474 // FIXME: granular
475 self.niri.queue_redraw_all();
476 }
477 Action::MoveWindowUp => {
478 self.niri.layout.move_up();
479 self.maybe_warp_cursor_to_focus();
480 // FIXME: granular
481 self.niri.queue_redraw_all();
482 }
483 Action::MoveWindowDownOrToWorkspaceDown => {
484 self.niri.layout.move_down_or_to_workspace_down();
485 self.maybe_warp_cursor_to_focus();
486 // FIXME: granular
487 self.niri.queue_redraw_all();
488 }
489 Action::MoveWindowUpOrToWorkspaceUp => {
490 self.niri.layout.move_up_or_to_workspace_up();
491 self.maybe_warp_cursor_to_focus();
492 // FIXME: granular
493 self.niri.queue_redraw_all();
494 }
495 Action::ConsumeOrExpelWindowLeft => {
496 self.niri.layout.consume_or_expel_window_left();
497 self.maybe_warp_cursor_to_focus();
498 // FIXME: granular
499 self.niri.queue_redraw_all();
500 }
501 Action::ConsumeOrExpelWindowRight => {
502 self.niri.layout.consume_or_expel_window_right();
503 self.maybe_warp_cursor_to_focus();
504 // FIXME: granular
505 self.niri.queue_redraw_all();
506 }
507 Action::FocusColumnLeft => {
508 self.niri.layout.focus_left();
509 self.maybe_warp_cursor_to_focus();
510 // FIXME: granular
511 self.niri.queue_redraw_all();
512 }
513 Action::FocusColumnRight => {
514 self.niri.layout.focus_right();
515 self.maybe_warp_cursor_to_focus();
516 // FIXME: granular
517 self.niri.queue_redraw_all();
518 }
519 Action::FocusColumnFirst => {
520 self.niri.layout.focus_column_first();
521 self.maybe_warp_cursor_to_focus();
522 // FIXME: granular
523 self.niri.queue_redraw_all();
524 }
525 Action::FocusColumnLast => {
526 self.niri.layout.focus_column_last();
527 self.maybe_warp_cursor_to_focus();
528 // FIXME: granular
529 self.niri.queue_redraw_all();
530 }
531 Action::FocusWindowDown => {
532 self.niri.layout.focus_down();
533 self.maybe_warp_cursor_to_focus();
534 // FIXME: granular
535 self.niri.queue_redraw_all();
536 }
537 Action::FocusWindowUp => {
538 self.niri.layout.focus_up();
539 self.maybe_warp_cursor_to_focus();
540 // FIXME: granular
541 self.niri.queue_redraw_all();
542 }
543 Action::FocusWindowOrWorkspaceDown => {
544 self.niri.layout.focus_window_or_workspace_down();
545 self.maybe_warp_cursor_to_focus();
546 // FIXME: granular
547 self.niri.queue_redraw_all();
548 }
549 Action::FocusWindowOrWorkspaceUp => {
550 self.niri.layout.focus_window_or_workspace_up();
551 self.maybe_warp_cursor_to_focus();
552 // FIXME: granular
553 self.niri.queue_redraw_all();
554 }
555 Action::MoveWindowToWorkspaceDown => {
556 self.niri.layout.move_to_workspace_down();
557 self.maybe_warp_cursor_to_focus();
558 // FIXME: granular
559 self.niri.queue_redraw_all();
560 }
561 Action::MoveWindowToWorkspaceUp => {
562 self.niri.layout.move_to_workspace_up();
563 self.maybe_warp_cursor_to_focus();
564 // FIXME: granular
565 self.niri.queue_redraw_all();
566 }
567 Action::MoveWindowToWorkspace(idx) => {
568 let idx = idx.saturating_sub(1) as usize;
569 self.niri.layout.move_to_workspace(idx);
570 self.maybe_warp_cursor_to_focus();
571 // FIXME: granular
572 self.niri.queue_redraw_all();
573 }
574 Action::MoveColumnToWorkspaceDown => {
575 self.niri.layout.move_column_to_workspace_down();
576 self.maybe_warp_cursor_to_focus();
577 // FIXME: granular
578 self.niri.queue_redraw_all();
579 }
580 Action::MoveColumnToWorkspaceUp => {
581 self.niri.layout.move_column_to_workspace_up();
582 self.maybe_warp_cursor_to_focus();
583 // FIXME: granular
584 self.niri.queue_redraw_all();
585 }
586 Action::MoveColumnToWorkspace(idx) => {
587 let idx = idx.saturating_sub(1) as usize;
588 self.niri.layout.move_column_to_workspace(idx);
589 self.maybe_warp_cursor_to_focus();
590 // FIXME: granular
591 self.niri.queue_redraw_all();
592 }
593 Action::FocusWorkspaceDown => {
594 self.niri.layout.switch_workspace_down();
595 self.maybe_warp_cursor_to_focus();
596 // FIXME: granular
597 self.niri.queue_redraw_all();
598 }
599 Action::FocusWorkspaceUp => {
600 self.niri.layout.switch_workspace_up();
601 self.maybe_warp_cursor_to_focus();
602 // FIXME: granular
603 self.niri.queue_redraw_all();
604 }
605 Action::FocusWorkspace(idx) => {
606 let idx = idx.saturating_sub(1) as usize;
607
608 let config = &self.niri.config;
609 if config.borrow().input.workspace_auto_back_and_forth {
610 self.niri.layout.switch_workspace_auto_back_and_forth(idx);
611 } else {
612 self.niri.layout.switch_workspace(idx);
613 }
614
615 self.maybe_warp_cursor_to_focus();
616 // FIXME: granular
617 self.niri.queue_redraw_all();
618 }
619 Action::FocusWorkspacePrevious => {
620 self.niri.layout.switch_workspace_previous();
621 // FIXME: granular
622 self.niri.queue_redraw_all();
623 }
624 Action::MoveWorkspaceDown => {
625 self.niri.layout.move_workspace_down();
626 // FIXME: granular
627 self.niri.queue_redraw_all();
628 }
629 Action::MoveWorkspaceUp => {
630 self.niri.layout.move_workspace_up();
631 // FIXME: granular
632 self.niri.queue_redraw_all();
633 }
634 Action::ConsumeWindowIntoColumn => {
635 self.niri.layout.consume_into_column();
636 // This does not cause immediate focus or window size change, so warping mouse to
637 // focus won't do anything here.
638 // FIXME: granular
639 self.niri.queue_redraw_all();
640 }
641 Action::ExpelWindowFromColumn => {
642 self.niri.layout.expel_from_column();
643 self.maybe_warp_cursor_to_focus();
644 // FIXME: granular
645 self.niri.queue_redraw_all();
646 }
647 Action::SwitchPresetColumnWidth => {
648 self.niri.layout.toggle_width();
649 }
650 Action::CenterColumn => {
651 self.niri.layout.center_column();
652 // FIXME: granular
653 self.niri.queue_redraw_all();
654 }
655 Action::MaximizeColumn => {
656 self.niri.layout.toggle_full_width();
657 }
658 Action::FocusMonitorLeft => {
659 if let Some(output) = self.niri.output_left() {
660 self.niri.layout.focus_output(&output);
661 if !self.maybe_warp_cursor_to_focus_centered() {
662 self.move_cursor_to_output(&output);
663 }
664 }
665 }
666 Action::FocusMonitorRight => {
667 if let Some(output) = self.niri.output_right() {
668 self.niri.layout.focus_output(&output);
669 if !self.maybe_warp_cursor_to_focus_centered() {
670 self.move_cursor_to_output(&output);
671 }
672 }
673 }
674 Action::FocusMonitorDown => {
675 if let Some(output) = self.niri.output_down() {
676 self.niri.layout.focus_output(&output);
677 if !self.maybe_warp_cursor_to_focus_centered() {
678 self.move_cursor_to_output(&output);
679 }
680 }
681 }
682 Action::FocusMonitorUp => {
683 if let Some(output) = self.niri.output_up() {
684 self.niri.layout.focus_output(&output);
685 if !self.maybe_warp_cursor_to_focus_centered() {
686 self.move_cursor_to_output(&output);
687 }
688 }
689 }
690 Action::MoveWindowToMonitorLeft => {
691 if let Some(output) = self.niri.output_left() {
692 self.niri.layout.move_to_output(&output);
693 self.niri.layout.focus_output(&output);
694 if !self.maybe_warp_cursor_to_focus_centered() {
695 self.move_cursor_to_output(&output);
696 }
697 }
698 }
699 Action::MoveWindowToMonitorRight => {
700 if let Some(output) = self.niri.output_right() {
701 self.niri.layout.move_to_output(&output);
702 self.niri.layout.focus_output(&output);
703 if !self.maybe_warp_cursor_to_focus_centered() {
704 self.move_cursor_to_output(&output);
705 }
706 }
707 }
708 Action::MoveWindowToMonitorDown => {
709 if let Some(output) = self.niri.output_down() {
710 self.niri.layout.move_to_output(&output);
711 self.niri.layout.focus_output(&output);
712 if !self.maybe_warp_cursor_to_focus_centered() {
713 self.move_cursor_to_output(&output);
714 }
715 }
716 }
717 Action::MoveWindowToMonitorUp => {
718 if let Some(output) = self.niri.output_up() {
719 self.niri.layout.move_to_output(&output);
720 self.niri.layout.focus_output(&output);
721 if !self.maybe_warp_cursor_to_focus_centered() {
722 self.move_cursor_to_output(&output);
723 }
724 }
725 }
726 Action::MoveColumnToMonitorLeft => {
727 if let Some(output) = self.niri.output_left() {
728 self.niri.layout.move_column_to_output(&output);
729 self.niri.layout.focus_output(&output);
730 if !self.maybe_warp_cursor_to_focus_centered() {
731 self.move_cursor_to_output(&output);
732 }
733 }
734 }
735 Action::MoveColumnToMonitorRight => {
736 if let Some(output) = self.niri.output_right() {
737 self.niri.layout.move_column_to_output(&output);
738 self.niri.layout.focus_output(&output);
739 if !self.maybe_warp_cursor_to_focus_centered() {
740 self.move_cursor_to_output(&output);
741 }
742 }
743 }
744 Action::MoveColumnToMonitorDown => {
745 if let Some(output) = self.niri.output_down() {
746 self.niri.layout.move_column_to_output(&output);
747 self.niri.layout.focus_output(&output);
748 if !self.maybe_warp_cursor_to_focus_centered() {
749 self.move_cursor_to_output(&output);
750 }
751 }
752 }
753 Action::MoveColumnToMonitorUp => {
754 if let Some(output) = self.niri.output_up() {
755 self.niri.layout.move_column_to_output(&output);
756 self.niri.layout.focus_output(&output);
757 if !self.maybe_warp_cursor_to_focus_centered() {
758 self.move_cursor_to_output(&output);
759 }
760 }
761 }
762 Action::SetColumnWidth(change) => {
763 self.niri.layout.set_column_width(change);
764 }
765 Action::SetWindowHeight(change) => {
766 self.niri.layout.set_window_height(change);
767 }
768 Action::ShowHotkeyOverlay => {
769 if self.niri.hotkey_overlay.show() {
770 self.niri.queue_redraw_all();
771 }
772 }
773 Action::MoveWorkspaceToMonitorLeft => {
774 if let Some(output) = self.niri.output_left() {
775 self.niri.layout.move_workspace_to_output(&output);
776 if !self.maybe_warp_cursor_to_focus_centered() {
777 self.move_cursor_to_output(&output);
778 }
779 }
780 }
781 Action::MoveWorkspaceToMonitorRight => {
782 if let Some(output) = self.niri.output_right() {
783 self.niri.layout.move_workspace_to_output(&output);
784 if !self.maybe_warp_cursor_to_focus_centered() {
785 self.move_cursor_to_output(&output);
786 }
787 }
788 }
789 Action::MoveWorkspaceToMonitorDown => {
790 if let Some(output) = self.niri.output_down() {
791 self.niri.layout.move_workspace_to_output(&output);
792 if !self.maybe_warp_cursor_to_focus_centered() {
793 self.move_cursor_to_output(&output);
794 }
795 }
796 }
797 Action::MoveWorkspaceToMonitorUp => {
798 if let Some(output) = self.niri.output_up() {
799 self.niri.layout.move_workspace_to_output(&output);
800 if !self.maybe_warp_cursor_to_focus_centered() {
801 self.move_cursor_to_output(&output);
802 }
803 }
804 }
805 }
806 }
807
808 fn on_pointer_motion<I: InputBackend>(&mut self, event: I::PointerMotionEvent) {
809 // We need an output to be able to move the pointer.
810 if self.niri.global_space.outputs().next().is_none() {
811 return;
812 }
813
814 let serial = SERIAL_COUNTER.next_serial();
815
816 let pointer = self.niri.seat.get_pointer().unwrap();
817
818 let pos = pointer.current_location();
819
820 // We have an output, so we can compute the new location and focus.
821 let mut new_pos = pos + event.delta();
822
823 // We received an event for the regular pointer, so show it now.
824 self.niri.tablet_cursor_location = None;
825
826 // Check if we have an active pointer constraint.
827 let mut pointer_confined = None;
828 if let Some(focus) = &self.niri.pointer_focus.surface {
829 let pos_within_surface = pos.to_i32_round() - focus.1;
830
831 let mut pointer_locked = false;
832 with_pointer_constraint(&focus.0, &pointer, |constraint| {
833 let Some(constraint) = constraint else { return };
834 if !constraint.is_active() {
835 return;
836 }
837
838 // Constraint does not apply if not within region.
839 if let Some(region) = constraint.region() {
840 if !region.contains(pos_within_surface) {
841 return;
842 }
843 }
844
845 match &*constraint {
846 PointerConstraint::Locked(_locked) => {
847 pointer_locked = true;
848 }
849 PointerConstraint::Confined(confine) => {
850 pointer_confined = Some((focus.clone(), confine.region().cloned()));
851 }
852 }
853 });
854
855 // If the pointer is locked, only send relative motion.
856 if pointer_locked {
857 pointer.relative_motion(
858 self,
859 Some(focus.clone()),
860 &RelativeMotionEvent {
861 delta: event.delta(),
862 delta_unaccel: event.delta_unaccel(),
863 utime: event.time(),
864 },
865 );
866
867 pointer.frame(self);
868
869 // I guess a redraw to hide the tablet cursor could be nice? Doesn't matter too
870 // much here I think.
871 return;
872 }
873 }
874
875 if self
876 .niri
877 .global_space
878 .output_under(new_pos)
879 .next()
880 .is_none()
881 {
882 // We ended up outside the outputs and need to clip the movement.
883 if let Some(output) = self.niri.global_space.output_under(pos).next() {
884 // The pointer was previously on some output. Clip the movement against its
885 // boundaries.
886 let geom = self.niri.global_space.output_geometry(output).unwrap();
887 new_pos.x = new_pos
888 .x
889 .clamp(geom.loc.x as f64, (geom.loc.x + geom.size.w - 1) as f64);
890 new_pos.y = new_pos
891 .y
892 .clamp(geom.loc.y as f64, (geom.loc.y + geom.size.h - 1) as f64);
893 } else {
894 // The pointer was not on any output in the first place. Find one for it.
895 // Let's do the simple thing and just put it on the first output.
896 let output = self.niri.global_space.outputs().next().unwrap();
897 let geom = self.niri.global_space.output_geometry(output).unwrap();
898 new_pos = center(geom).to_f64();
899 }
900 }
901
902 if let Some(output) = self.niri.screenshot_ui.selection_output() {
903 let geom = self.niri.global_space.output_geometry(output).unwrap();
904 let mut point = new_pos;
905 point.x = point
906 .x
907 .clamp(geom.loc.x as f64, (geom.loc.x + geom.size.w - 1) as f64);
908 point.y = point
909 .y
910 .clamp(geom.loc.y as f64, (geom.loc.y + geom.size.h - 1) as f64);
911 let point = (point - geom.loc.to_f64())
912 .to_physical(output.current_scale().fractional_scale())
913 .to_i32_round();
914 self.niri.screenshot_ui.pointer_motion(point);
915 }
916
917 let under = self.niri.surface_under_and_global_space(new_pos);
918
919 // Handle confined pointer.
920 if let Some((focus_surface, region)) = pointer_confined {
921 let mut prevent = false;
922
923 // Prevent the pointer from leaving the focused surface.
924 if Some(&focus_surface.0) != under.surface.as_ref().map(|(s, _)| s) {
925 prevent = true;
926 }
927
928 // Prevent the pointer from leaving the confine region, if any.
929 if let Some(region) = region {
930 let new_pos_within_surface = new_pos.to_i32_round() - focus_surface.1;
931 if !region.contains(new_pos_within_surface) {
932 prevent = true;
933 }
934 }
935
936 if prevent {
937 pointer.relative_motion(
938 self,
939 Some(focus_surface),
940 &RelativeMotionEvent {
941 delta: event.delta(),
942 delta_unaccel: event.delta_unaccel(),
943 utime: event.time(),
944 },
945 );
946
947 pointer.frame(self);
948
949 return;
950 }
951 }
952
953 self.niri.handle_focus_follows_mouse(&under);
954
955 // Activate a new confinement if necessary.
956 self.niri.maybe_activate_pointer_constraint(new_pos, &under);
957
958 self.niri.pointer_focus.clone_from(&under);
959
960 pointer.motion(
961 self,
962 under.surface.clone(),
963 &MotionEvent {
964 location: new_pos,
965 serial,
966 time: event.time_msec(),
967 },
968 );
969
970 pointer.relative_motion(
971 self,
972 under.surface,
973 &RelativeMotionEvent {
974 delta: event.delta(),
975 delta_unaccel: event.delta_unaccel(),
976 utime: event.time(),
977 },
978 );
979
980 pointer.frame(self);
981
982 // Redraw to update the cursor position.
983 // FIXME: redraw only outputs overlapping the cursor.
984 self.niri.queue_redraw_all();
985 }
986
987 fn on_pointer_motion_absolute<I: InputBackend>(
988 &mut self,
989 event: I::PointerMotionAbsoluteEvent,
990 ) {
991 let Some(output) = self.niri.global_space.outputs().next() else {
992 return;
993 };
994
995 let output_geo = self.niri.global_space.output_geometry(output).unwrap();
996
997 let pos = event.position_transformed(output_geo.size) + output_geo.loc.to_f64();
998
999 let serial = SERIAL_COUNTER.next_serial();
1000
1001 let pointer = self.niri.seat.get_pointer().unwrap();
1002
1003 if let Some(output) = self.niri.screenshot_ui.selection_output() {
1004 let geom = self.niri.global_space.output_geometry(output).unwrap();
1005 let mut point = pos;
1006 point.x = point
1007 .x
1008 .clamp(geom.loc.x as f64, (geom.loc.x + geom.size.w - 1) as f64);
1009 point.y = point
1010 .y
1011 .clamp(geom.loc.y as f64, (geom.loc.y + geom.size.h - 1) as f64);
1012 let point = (point - geom.loc.to_f64())
1013 .to_physical(output.current_scale().fractional_scale())
1014 .to_i32_round();
1015 self.niri.screenshot_ui.pointer_motion(point);
1016 }
1017
1018 let under = self.niri.surface_under_and_global_space(pos);
1019
1020 self.niri.handle_focus_follows_mouse(&under);
1021
1022 self.niri.maybe_activate_pointer_constraint(pos, &under);
1023 self.niri.pointer_focus.clone_from(&under);
1024
1025 pointer.motion(
1026 self,
1027 under.surface,
1028 &MotionEvent {
1029 location: pos,
1030 serial,
1031 time: event.time_msec(),
1032 },
1033 );
1034
1035 pointer.frame(self);
1036
1037 // We moved the regular pointer, so show it now.
1038 self.niri.tablet_cursor_location = None;
1039
1040 // Redraw to update the cursor position.
1041 // FIXME: redraw only outputs overlapping the cursor.
1042 self.niri.queue_redraw_all();
1043 }
1044
1045 fn on_pointer_button<I: InputBackend>(&mut self, event: I::PointerButtonEvent) {
1046 let pointer = self.niri.seat.get_pointer().unwrap();
1047
1048 let serial = SERIAL_COUNTER.next_serial();
1049
1050 let button = event.button_code();
1051
1052 let button_state = event.state();
1053
1054 if ButtonState::Pressed == button_state {
1055 if let Some(mapped) = self.niri.window_under_cursor() {
1056 let window = mapped.window.clone();
1057 self.niri.layout.activate_window(&window);
1058
1059 // FIXME: granular.
1060 self.niri.queue_redraw_all();
1061 } else if let Some(output) = self.niri.output_under_cursor() {
1062 self.niri.layout.activate_output(&output);
1063
1064 // FIXME: granular.
1065 self.niri.queue_redraw_all();
1066 }
1067 };
1068
1069 self.update_pointer_focus();
1070
1071 if let Some(button) = event.button() {
1072 let pos = pointer.current_location();
1073 if let Some((output, _)) = self.niri.output_under(pos) {
1074 let output = output.clone();
1075 let geom = self.niri.global_space.output_geometry(&output).unwrap();
1076 let mut point = pos;
1077 // Re-clamp as pointer can be within 0.5 from the limit which will round up
1078 // to a wrong value.
1079 point.x = point
1080 .x
1081 .clamp(geom.loc.x as f64, (geom.loc.x + geom.size.w - 1) as f64);
1082 point.y = point
1083 .y
1084 .clamp(geom.loc.y as f64, (geom.loc.y + geom.size.h - 1) as f64);
1085 let point = (point - geom.loc.to_f64())
1086 .to_physical(output.current_scale().fractional_scale())
1087 .to_i32_round();
1088 if self
1089 .niri
1090 .screenshot_ui
1091 .pointer_button(output, point, button, button_state)
1092 {
1093 self.niri.queue_redraw_all();
1094 }
1095 }
1096 }
1097
1098 pointer.button(
1099 self,
1100 &ButtonEvent {
1101 button,
1102 state: button_state,
1103 serial,
1104 time: event.time_msec(),
1105 },
1106 );
1107 pointer.frame(self);
1108 }
1109
1110 fn on_pointer_axis<I: InputBackend>(&mut self, event: I::PointerAxisEvent) {
1111 let source = event.source();
1112
1113 let horizontal_amount_v120 = event.amount_v120(Axis::Horizontal);
1114 let vertical_amount_v120 = event.amount_v120(Axis::Vertical);
1115
1116 // Handle wheel scroll bindings.
1117 if source == AxisSource::Wheel {
1118 // If we have a scroll bind with current modifiers, then accumulate and don't pass to
1119 // Wayland. If there's no bind, reset the accumulator.
1120 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
1121 let modifiers = modifiers_from_state(mods);
1122 if self.niri.mods_with_wheel_binds.contains(&modifiers) {
1123 let comp_mod = self.backend.mod_key();
1124
1125 let horizontal = horizontal_amount_v120.unwrap_or(0.);
1126 let ticks = self.niri.horizontal_wheel_tracker.accumulate(horizontal);
1127 if ticks != 0 {
1128 let config = self.niri.config.borrow();
1129 let bindings = &config.binds;
1130 let bind_left =
1131 find_configured_bind(bindings, comp_mod, Trigger::WheelScrollLeft, mods);
1132 let bind_right =
1133 find_configured_bind(bindings, comp_mod, Trigger::WheelScrollRight, mods);
1134 drop(config);
1135
1136 if let Some(right) = bind_right {
1137 for _ in 0..ticks {
1138 self.handle_bind(right.clone());
1139 }
1140 }
1141 if let Some(left) = bind_left {
1142 for _ in ticks..0 {
1143 self.handle_bind(left.clone());
1144 }
1145 }
1146 }
1147
1148 let vertical = vertical_amount_v120.unwrap_or(0.);
1149 let ticks = self.niri.vertical_wheel_tracker.accumulate(vertical);
1150 if ticks != 0 {
1151 let config = self.niri.config.borrow();
1152 let bindings = &config.binds;
1153 let bind_up =
1154 find_configured_bind(bindings, comp_mod, Trigger::WheelScrollUp, mods);
1155 let bind_down =
1156 find_configured_bind(bindings, comp_mod, Trigger::WheelScrollDown, mods);
1157 drop(config);
1158
1159 if let Some(down) = bind_down {
1160 for _ in 0..ticks {
1161 self.handle_bind(down.clone());
1162 }
1163 }
1164 if let Some(up) = bind_up {
1165 for _ in ticks..0 {
1166 self.handle_bind(up.clone());
1167 }
1168 }
1169 }
1170
1171 return;
1172 } else {
1173 self.niri.horizontal_wheel_tracker.reset();
1174 self.niri.vertical_wheel_tracker.reset();
1175 }
1176 }
1177
1178 let horizontal_amount = event.amount(Axis::Horizontal);
1179 let vertical_amount = event.amount(Axis::Vertical);
1180
1181 // Handle touchpad scroll bindings.
1182 if source == AxisSource::Finger {
1183 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
1184 let modifiers = modifiers_from_state(mods);
1185 if self.niri.mods_with_finger_scroll_binds.contains(&modifiers) {
1186 let comp_mod = self.backend.mod_key();
1187
1188 let horizontal = horizontal_amount.unwrap_or(0.);
1189 let ticks = self
1190 .niri
1191 .horizontal_finger_scroll_tracker
1192 .accumulate(horizontal);
1193 if ticks != 0 {
1194 let config = self.niri.config.borrow();
1195 let bindings = &config.binds;
1196 let bind_left =
1197 find_configured_bind(bindings, comp_mod, Trigger::TouchpadScrollLeft, mods);
1198 let bind_right = find_configured_bind(
1199 bindings,
1200 comp_mod,
1201 Trigger::TouchpadScrollRight,
1202 mods,
1203 );
1204 drop(config);
1205
1206 if let Some(right) = bind_right {
1207 for _ in 0..ticks {
1208 self.handle_bind(right.clone());
1209 }
1210 }
1211 if let Some(left) = bind_left {
1212 for _ in ticks..0 {
1213 self.handle_bind(left.clone());
1214 }
1215 }
1216 }
1217
1218 let vertical = vertical_amount.unwrap_or(0.);
1219 let ticks = self
1220 .niri
1221 .vertical_finger_scroll_tracker
1222 .accumulate(vertical);
1223 if ticks != 0 {
1224 let config = self.niri.config.borrow();
1225 let bindings = &config.binds;
1226 let bind_up =
1227 find_configured_bind(bindings, comp_mod, Trigger::TouchpadScrollUp, mods);
1228 let bind_down =
1229 find_configured_bind(bindings, comp_mod, Trigger::TouchpadScrollDown, mods);
1230 drop(config);
1231
1232 if let Some(down) = bind_down {
1233 for _ in 0..ticks {
1234 self.handle_bind(down.clone());
1235 }
1236 }
1237 if let Some(up) = bind_up {
1238 for _ in ticks..0 {
1239 self.handle_bind(up.clone());
1240 }
1241 }
1242 }
1243
1244 return;
1245 } else {
1246 self.niri.horizontal_finger_scroll_tracker.reset();
1247 self.niri.vertical_finger_scroll_tracker.reset();
1248 }
1249 }
1250
1251 let horizontal_amount = horizontal_amount.unwrap_or_else(|| {
1252 // Winit backend, discrete scrolling.
1253 horizontal_amount_v120.unwrap_or(0.0) / 120. * 15.
1254 });
1255 let vertical_amount = vertical_amount.unwrap_or_else(|| {
1256 // Winit backend, discrete scrolling.
1257 vertical_amount_v120.unwrap_or(0.0) / 120. * 15.
1258 });
1259
1260 let mut frame = AxisFrame::new(event.time_msec()).source(source);
1261 if horizontal_amount != 0.0 {
1262 frame = frame
1263 .relative_direction(Axis::Horizontal, event.relative_direction(Axis::Horizontal));
1264 frame = frame.value(Axis::Horizontal, horizontal_amount);
1265 if let Some(v120) = horizontal_amount_v120 {
1266 frame = frame.v120(Axis::Horizontal, v120 as i32);
1267 }
1268 }
1269 if vertical_amount != 0.0 {
1270 frame =
1271 frame.relative_direction(Axis::Vertical, event.relative_direction(Axis::Vertical));
1272 frame = frame.value(Axis::Vertical, vertical_amount);
1273 if let Some(v120) = vertical_amount_v120 {
1274 frame = frame.v120(Axis::Vertical, v120 as i32);
1275 }
1276 }
1277
1278 if source == AxisSource::Finger {
1279 if event.amount(Axis::Horizontal) == Some(0.0) {
1280 frame = frame.stop(Axis::Horizontal);
1281 }
1282 if event.amount(Axis::Vertical) == Some(0.0) {
1283 frame = frame.stop(Axis::Vertical);
1284 }
1285 }
1286
1287 self.update_pointer_focus();
1288
1289 let pointer = &self.niri.seat.get_pointer().unwrap();
1290 pointer.axis(self, frame);
1291 pointer.frame(self);
1292 }
1293
1294 fn on_tablet_tool_axis<I: InputBackend>(&mut self, event: I::TabletToolAxisEvent)
1295 where
1296 I::Device: 'static, // Needed for downcasting.
1297 {
1298 let Some(pos) = self.compute_tablet_position(&event) else {
1299 return;
1300 };
1301
1302 let under = self.niri.surface_under_and_global_space(pos);
1303
1304 let tablet_seat = self.niri.seat.tablet_seat();
1305 let tablet = tablet_seat.get_tablet(&TabletDescriptor::from(&event.device()));
1306 let tool = tablet_seat.get_tool(&event.tool());
1307 if let (Some(tablet), Some(tool)) = (tablet, tool) {
1308 if event.pressure_has_changed() {
1309 tool.pressure(event.pressure());
1310 }
1311 if event.distance_has_changed() {
1312 tool.distance(event.distance());
1313 }
1314 if event.tilt_has_changed() {
1315 tool.tilt(event.tilt());
1316 }
1317 if event.slider_has_changed() {
1318 tool.slider_position(event.slider_position());
1319 }
1320 if event.rotation_has_changed() {
1321 tool.rotation(event.rotation());
1322 }
1323 if event.wheel_has_changed() {
1324 tool.wheel(event.wheel_delta(), event.wheel_delta_discrete());
1325 }
1326
1327 tool.motion(
1328 pos,
1329 under.surface,
1330 &tablet,
1331 SERIAL_COUNTER.next_serial(),
1332 event.time_msec(),
1333 );
1334
1335 self.niri.tablet_cursor_location = Some(pos);
1336 }
1337
1338 // Redraw to update the cursor position.
1339 // FIXME: redraw only outputs overlapping the cursor.
1340 self.niri.queue_redraw_all();
1341 }
1342
1343 fn on_tablet_tool_tip<I: InputBackend>(&mut self, event: I::TabletToolTipEvent) {
1344 let tool = self.niri.seat.tablet_seat().get_tool(&event.tool());
1345
1346 if let Some(tool) = tool {
1347 match event.tip_state() {
1348 TabletToolTipState::Down => {
1349 let serial = SERIAL_COUNTER.next_serial();
1350 tool.tip_down(serial, event.time_msec());
1351
1352 if let Some(pos) = self.niri.tablet_cursor_location {
1353 if let Some(mapped) = self.niri.window_under(pos) {
1354 let window = mapped.window.clone();
1355 self.niri.layout.activate_window(&window);
1356
1357 // FIXME: granular.
1358 self.niri.queue_redraw_all();
1359 } else if let Some((output, _)) = self.niri.output_under(pos) {
1360 let output = output.clone();
1361 self.niri.layout.activate_output(&output);
1362
1363 // FIXME: granular.
1364 self.niri.queue_redraw_all();
1365 }
1366 }
1367 }
1368 TabletToolTipState::Up => {
1369 tool.tip_up(event.time_msec());
1370 }
1371 }
1372 }
1373 }
1374
1375 fn on_tablet_tool_proximity<I: InputBackend>(&mut self, event: I::TabletToolProximityEvent)
1376 where
1377 I::Device: 'static, // Needed for downcasting.
1378 {
1379 let Some(pos) = self.compute_tablet_position(&event) else {
1380 return;
1381 };
1382
1383 let under = self.niri.surface_under_and_global_space(pos);
1384
1385 let tablet_seat = self.niri.seat.tablet_seat();
1386 let tool = tablet_seat.add_tool::<Self>(&self.niri.display_handle, &event.tool());
1387 let tablet = tablet_seat.get_tablet(&TabletDescriptor::from(&event.device()));
1388 if let Some(tablet) = tablet {
1389 match event.state() {
1390 ProximityState::In => {
1391 if let Some(under) = under.surface {
1392 tool.proximity_in(
1393 pos,
1394 under,
1395 &tablet,
1396 SERIAL_COUNTER.next_serial(),
1397 event.time_msec(),
1398 );
1399 }
1400 self.niri.tablet_cursor_location = Some(pos);
1401 }
1402 ProximityState::Out => {
1403 tool.proximity_out(event.time_msec());
1404
1405 // Move the mouse pointer here to avoid discontinuity.
1406 //
1407 // Plus, Wayland SDL2 currently warps the pointer into some weird
1408 // location on proximity out, so this shuold help it a little.
1409 if let Some(pos) = self.niri.tablet_cursor_location {
1410 self.move_cursor(pos);
1411 }
1412
1413 self.niri.tablet_cursor_location = None;
1414 }
1415 }
1416
1417 // FIXME: granular.
1418 self.niri.queue_redraw_all();
1419 }
1420 }
1421
1422 fn on_tablet_tool_button<I: InputBackend>(&mut self, event: I::TabletToolButtonEvent) {
1423 let tool = self.niri.seat.tablet_seat().get_tool(&event.tool());
1424
1425 if let Some(tool) = tool {
1426 tool.button(
1427 event.button(),
1428 event.button_state(),
1429 SERIAL_COUNTER.next_serial(),
1430 event.time_msec(),
1431 );
1432 }
1433 }
1434
1435 fn on_gesture_swipe_begin<I: InputBackend>(&mut self, event: I::GestureSwipeBeginEvent) {
1436 if event.fingers() == 3 {
1437 self.niri.gesture_swipe_3f_cumulative = Some((0., 0.));
1438
1439 // We handled this event.
1440 return;
1441 }
1442
1443 let serial = SERIAL_COUNTER.next_serial();
1444 let pointer = self.niri.seat.get_pointer().unwrap();
1445
1446 if self.update_pointer_focus() {
1447 pointer.frame(self);
1448 }
1449
1450 pointer.gesture_swipe_begin(
1451 self,
1452 &GestureSwipeBeginEvent {
1453 serial,
1454 time: event.time_msec(),
1455 fingers: event.fingers(),
1456 },
1457 );
1458 }
1459
1460 fn on_gesture_swipe_update<I: InputBackend + 'static>(
1461 &mut self,
1462 event: I::GestureSwipeUpdateEvent,
1463 ) where
1464 I::Device: 'static,
1465 {
1466 let mut delta_x = event.delta_x();
1467 let mut delta_y = event.delta_y();
1468
1469 if let Some(libinput_event) =
1470 (&event as &dyn Any).downcast_ref::<input::event::gesture::GestureSwipeUpdateEvent>()
1471 {
1472 delta_x = libinput_event.dx_unaccelerated();
1473 delta_y = libinput_event.dy_unaccelerated();
1474 }
1475
1476 let device = event.device();
1477 if let Some(device) = (&device as &dyn Any).downcast_ref::<input::Device>() {
1478 if device.config_scroll_natural_scroll_enabled() {
1479 delta_x = -delta_x;
1480 delta_y = -delta_y;
1481 }
1482 }
1483
1484 if let Some((cx, cy)) = &mut self.niri.gesture_swipe_3f_cumulative {
1485 *cx += delta_x;
1486 *cy += delta_y;
1487
1488 // Check if the gesture moved far enough to decide. Threshold copied from GNOME Shell.
1489 let (cx, cy) = (*cx, *cy);
1490 if cx * cx + cy * cy >= 16. * 16. {
1491 self.niri.gesture_swipe_3f_cumulative = None;
1492
1493 if let Some(output) = self.niri.output_under_cursor() {
1494 if cx.abs() > cy.abs() {
1495 self.niri.layout.view_offset_gesture_begin(&output);
1496 } else {
1497 self.niri.layout.workspace_switch_gesture_begin(&output);
1498 }
1499 }
1500 }
1501 }
1502
1503 let timestamp = Duration::from_micros(event.time());
1504
1505 let mut handled = false;
1506 let res = self
1507 .niri
1508 .layout
1509 .workspace_switch_gesture_update(delta_y, timestamp);
1510 if let Some(output) = res {
1511 if let Some(output) = output {
1512 self.niri.queue_redraw(&output);
1513 }
1514 handled = true;
1515 }
1516
1517 let res = self
1518 .niri
1519 .layout
1520 .view_offset_gesture_update(delta_x, timestamp);
1521 if let Some(output) = res {
1522 if let Some(output) = output {
1523 self.niri.queue_redraw(&output);
1524 }
1525 handled = true;
1526 }
1527
1528 if handled {
1529 // We handled this event.
1530 return;
1531 }
1532
1533 let pointer = self.niri.seat.get_pointer().unwrap();
1534
1535 if self.update_pointer_focus() {
1536 pointer.frame(self);
1537 }
1538
1539 pointer.gesture_swipe_update(
1540 self,
1541 &GestureSwipeUpdateEvent {
1542 time: event.time_msec(),
1543 delta: event.delta(),
1544 },
1545 );
1546 }
1547
1548 fn on_gesture_swipe_end<I: InputBackend>(&mut self, event: I::GestureSwipeEndEvent) {
1549 self.niri.gesture_swipe_3f_cumulative = None;
1550
1551 let mut handled = false;
1552 let res = self
1553 .niri
1554 .layout
1555 .workspace_switch_gesture_end(event.cancelled());
1556 if let Some(output) = res {
1557 self.niri.queue_redraw(&output);
1558 handled = true;
1559 }
1560
1561 let res = self.niri.layout.view_offset_gesture_end(event.cancelled());
1562 if let Some(output) = res {
1563 self.niri.queue_redraw(&output);
1564 handled = true;
1565 }
1566
1567 if handled {
1568 // We handled this event.
1569 return;
1570 }
1571
1572 let serial = SERIAL_COUNTER.next_serial();
1573 let pointer = self.niri.seat.get_pointer().unwrap();
1574
1575 if self.update_pointer_focus() {
1576 pointer.frame(self);
1577 }
1578
1579 pointer.gesture_swipe_end(
1580 self,
1581 &GestureSwipeEndEvent {
1582 serial,
1583 time: event.time_msec(),
1584 cancelled: event.cancelled(),
1585 },
1586 );
1587 }
1588
1589 fn on_gesture_pinch_begin<I: InputBackend>(&mut self, event: I::GesturePinchBeginEvent) {
1590 let serial = SERIAL_COUNTER.next_serial();
1591 let pointer = self.niri.seat.get_pointer().unwrap();
1592
1593 if self.update_pointer_focus() {
1594 pointer.frame(self);
1595 }
1596
1597 pointer.gesture_pinch_begin(
1598 self,
1599 &GesturePinchBeginEvent {
1600 serial,
1601 time: event.time_msec(),
1602 fingers: event.fingers(),
1603 },
1604 );
1605 }
1606
1607 fn on_gesture_pinch_update<I: InputBackend>(&mut self, event: I::GesturePinchUpdateEvent) {
1608 let pointer = self.niri.seat.get_pointer().unwrap();
1609
1610 if self.update_pointer_focus() {
1611 pointer.frame(self);
1612 }
1613
1614 pointer.gesture_pinch_update(
1615 self,
1616 &GesturePinchUpdateEvent {
1617 time: event.time_msec(),
1618 delta: event.delta(),
1619 scale: event.scale(),
1620 rotation: event.rotation(),
1621 },
1622 );
1623 }
1624
1625 fn on_gesture_pinch_end<I: InputBackend>(&mut self, event: I::GesturePinchEndEvent) {
1626 let serial = SERIAL_COUNTER.next_serial();
1627 let pointer = self.niri.seat.get_pointer().unwrap();
1628
1629 if self.update_pointer_focus() {
1630 pointer.frame(self);
1631 }
1632
1633 pointer.gesture_pinch_end(
1634 self,
1635 &GesturePinchEndEvent {
1636 serial,
1637 time: event.time_msec(),
1638 cancelled: event.cancelled(),
1639 },
1640 );
1641 }
1642
1643 fn on_gesture_hold_begin<I: InputBackend>(&mut self, event: I::GestureHoldBeginEvent) {
1644 let serial = SERIAL_COUNTER.next_serial();
1645 let pointer = self.niri.seat.get_pointer().unwrap();
1646
1647 if self.update_pointer_focus() {
1648 pointer.frame(self);
1649 }
1650
1651 pointer.gesture_hold_begin(
1652 self,
1653 &GestureHoldBeginEvent {
1654 serial,
1655 time: event.time_msec(),
1656 fingers: event.fingers(),
1657 },
1658 );
1659 }
1660
1661 fn on_gesture_hold_end<I: InputBackend>(&mut self, event: I::GestureHoldEndEvent) {
1662 let serial = SERIAL_COUNTER.next_serial();
1663 let pointer = self.niri.seat.get_pointer().unwrap();
1664
1665 if self.update_pointer_focus() {
1666 pointer.frame(self);
1667 }
1668
1669 pointer.gesture_hold_end(
1670 self,
1671 &GestureHoldEndEvent {
1672 serial,
1673 time: event.time_msec(),
1674 cancelled: event.cancelled(),
1675 },
1676 );
1677 }
1678
1679 /// Computes the cursor position for the touch event.
1680 ///
1681 /// This function handles the touch output mapping, as well as coordinate transform
1682 fn compute_touch_location<I: InputBackend, E: AbsolutePositionEvent<I>>(
1683 &self,
1684 evt: &E,
1685 ) -> Option<Point<f64, Logical>> {
1686 let output = self.niri.output_for_touch()?;
1687 let output_geo = self.niri.global_space.output_geometry(output).unwrap();
1688 let transform = output.current_transform();
1689 let size = transform.invert().transform_size(output_geo.size);
1690 Some(
1691 transform.transform_point_in(evt.position_transformed(size), &size.to_f64())
1692 + output_geo.loc.to_f64(),
1693 )
1694 }
1695
1696 fn on_touch_down<I: InputBackend>(&mut self, evt: I::TouchDownEvent) {
1697 let Some(handle) = self.niri.seat.get_touch() else {
1698 return;
1699 };
1700 let Some(touch_location) = self.compute_touch_location(&evt) else {
1701 return;
1702 };
1703
1704 if !handle.is_grabbed() {
1705 let output_under_touch = self
1706 .niri
1707 .global_space
1708 .output_under(touch_location)
1709 .next()
1710 .cloned();
1711 if let Some(mapped) = self.niri.window_under(touch_location) {
1712 let window = mapped.window.clone();
1713 self.niri.layout.activate_window(&window);
1714
1715 // FIXME: granular.
1716 self.niri.queue_redraw_all();
1717 } else if let Some(output) = output_under_touch {
1718 self.niri.layout.activate_output(&output);
1719
1720 // FIXME: granular.
1721 self.niri.queue_redraw_all();
1722 };
1723 };
1724
1725 let serial = SERIAL_COUNTER.next_serial();
1726 let under = self.niri.surface_under_and_global_space(touch_location);
1727 handle.down(
1728 self,
1729 under.surface,
1730 &DownEvent {
1731 slot: evt.slot(),
1732 location: touch_location,
1733 serial,
1734 time: evt.time_msec(),
1735 },
1736 );
1737 }
1738 fn on_touch_up<I: InputBackend>(&mut self, evt: I::TouchUpEvent) {
1739 let Some(handle) = self.niri.seat.get_touch() else {
1740 return;
1741 };
1742 let serial = SERIAL_COUNTER.next_serial();
1743 handle.up(
1744 self,
1745 &UpEvent {
1746 slot: evt.slot(),
1747 serial,
1748 time: evt.time_msec(),
1749 },
1750 )
1751 }
1752 fn on_touch_motion<I: InputBackend>(&mut self, evt: I::TouchMotionEvent) {
1753 let Some(handle) = self.niri.seat.get_touch() else {
1754 return;
1755 };
1756 let Some(touch_location) = self.compute_touch_location(&evt) else {
1757 return;
1758 };
1759 let under = self.niri.surface_under_and_global_space(touch_location);
1760 handle.motion(
1761 self,
1762 under.surface,
1763 &TouchMotionEvent {
1764 slot: evt.slot(),
1765 location: touch_location,
1766 time: evt.time_msec(),
1767 },
1768 );
1769 }
1770 fn on_touch_frame<I: InputBackend>(&mut self, _evt: I::TouchFrameEvent) {
1771 let Some(handle) = self.niri.seat.get_touch() else {
1772 return;
1773 };
1774 handle.frame(self);
1775 }
1776 fn on_touch_cancel<I: InputBackend>(&mut self, _evt: I::TouchCancelEvent) {
1777 let Some(handle) = self.niri.seat.get_touch() else {
1778 return;
1779 };
1780 handle.cancel(self);
1781 }
1782}
1783
1784/// Check whether the key should be intercepted and mark intercepted
1785/// pressed keys as `suppressed`, thus preventing `releases` corresponding
1786/// to them from being delivered.
1787#[allow(clippy::too_many_arguments)]
1788fn should_intercept_key(
1789 suppressed_keys: &mut HashSet<u32>,
1790 bindings: &Binds,
1791 comp_mod: CompositorMod,
1792 key_code: u32,
1793 modified: Keysym,
1794 raw: Option<Keysym>,
1795 pressed: bool,
1796 mods: ModifiersState,
1797 screenshot_ui: &ScreenshotUi,
1798 disable_power_key_handling: bool,
1799) -> FilterResult<Option<Bind>> {
1800 // Actions are only triggered on presses, release of the key
1801 // shouldn't try to intercept anything unless we have marked
1802 // the key to suppress.
1803 if !pressed && !suppressed_keys.contains(&key_code) {
1804 return FilterResult::Forward;
1805 }
1806
1807 let mut final_bind = find_bind(
1808 bindings,
1809 comp_mod,
1810 modified,
1811 raw,
1812 mods,
1813 disable_power_key_handling,
1814 );
1815
1816 // Allow only a subset of compositor actions while the screenshot UI is open, since the user
1817 // cannot see the screen.
1818 if screenshot_ui.is_open() {
1819 let mut use_screenshot_ui_action = true;
1820
1821 if let Some(bind) = &final_bind {
1822 if allowed_during_screenshot(&bind.action) {
1823 use_screenshot_ui_action = false;
1824 }
1825 }
1826
1827 if use_screenshot_ui_action {
1828 if let Some(raw) = raw {
1829 final_bind = screenshot_ui.action(raw, mods).map(|action| Bind {
1830 key: Key {
1831 trigger: Trigger::Keysym(raw),
1832 // Not entirely correct but it doesn't matter in how we currently use it.
1833 modifiers: Modifiers::empty(),
1834 },
1835 action,
1836 cooldown: None,
1837 });
1838 }
1839 }
1840 }
1841
1842 match (final_bind, pressed) {
1843 (Some(bind), true) => {
1844 suppressed_keys.insert(key_code);
1845 FilterResult::Intercept(Some(bind))
1846 }
1847 (_, false) => {
1848 suppressed_keys.remove(&key_code);
1849 FilterResult::Intercept(None)
1850 }
1851 (None, true) => FilterResult::Forward,
1852 }
1853}
1854
1855fn find_bind(
1856 bindings: &Binds,
1857 comp_mod: CompositorMod,
1858 modified: Keysym,
1859 raw: Option<Keysym>,
1860 mods: ModifiersState,
1861 disable_power_key_handling: bool,
1862) -> Option<Bind> {
1863 use keysyms::*;
1864
1865 // Handle hardcoded binds.
1866 #[allow(non_upper_case_globals)] // wat
1867 let hardcoded_action = match modified.raw() {
1868 modified @ KEY_XF86Switch_VT_1..=KEY_XF86Switch_VT_12 => {
1869 let vt = (modified - KEY_XF86Switch_VT_1 + 1) as i32;
1870 Some(Action::ChangeVt(vt))
1871 }
1872 KEY_XF86PowerOff if !disable_power_key_handling => Some(Action::Suspend),
1873 _ => None,
1874 };
1875
1876 if let Some(action) = hardcoded_action {
1877 return Some(Bind {
1878 key: Key {
1879 // Not entirely correct but it doesn't matter in how we currently use it.
1880 trigger: Trigger::Keysym(modified),
1881 modifiers: Modifiers::empty(),
1882 },
1883 action,
1884 cooldown: None,
1885 });
1886 }
1887
1888 let trigger = Trigger::Keysym(raw?);
1889 find_configured_bind(bindings, comp_mod, trigger, mods)
1890}
1891
1892fn find_configured_bind(
1893 bindings: &Binds,
1894 comp_mod: CompositorMod,
1895 trigger: Trigger,
1896 mods: ModifiersState,
1897) -> Option<Bind> {
1898 // Handle configured binds.
1899 let mut modifiers = modifiers_from_state(mods);
1900
1901 let (mod_down, comp_mod) = match comp_mod {
1902 CompositorMod::Super => (mods.logo, Modifiers::SUPER),
1903 CompositorMod::Alt => (mods.alt, Modifiers::ALT),
1904 };
1905 if mod_down {
1906 modifiers |= Modifiers::COMPOSITOR;
1907 }
1908
1909 for bind in &bindings.0 {
1910 if bind.key.trigger != trigger {
1911 continue;
1912 }
1913
1914 let mut bind_modifiers = bind.key.modifiers;
1915 if bind_modifiers.contains(Modifiers::COMPOSITOR) {
1916 bind_modifiers |= comp_mod;
1917 } else if bind_modifiers.contains(comp_mod) {
1918 bind_modifiers |= Modifiers::COMPOSITOR;
1919 }
1920
1921 if bind_modifiers == modifiers {
1922 return Some(bind.clone());
1923 }
1924 }
1925
1926 None
1927}
1928
1929fn modifiers_from_state(mods: ModifiersState) -> Modifiers {
1930 let mut modifiers = Modifiers::empty();
1931 if mods.ctrl {
1932 modifiers |= Modifiers::CTRL;
1933 }
1934 if mods.shift {
1935 modifiers |= Modifiers::SHIFT;
1936 }
1937 if mods.alt {
1938 modifiers |= Modifiers::ALT;
1939 }
1940 if mods.logo {
1941 modifiers |= Modifiers::SUPER;
1942 }
1943 if mods.iso_level3_shift {
1944 modifiers |= Modifiers::ISO_LEVEL3_SHIFT;
1945 }
1946 modifiers
1947}
1948
1949fn should_activate_monitors<I: InputBackend>(event: &InputEvent<I>) -> bool {
1950 match event {
1951 InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true,
1952 InputEvent::PointerButton { event } if event.state() == ButtonState::Pressed => true,
1953 InputEvent::PointerMotion { .. }
1954 | InputEvent::PointerMotionAbsolute { .. }
1955 | InputEvent::PointerAxis { .. }
1956 | InputEvent::GestureSwipeBegin { .. }
1957 | InputEvent::GesturePinchBegin { .. }
1958 | InputEvent::GestureHoldBegin { .. }
1959 | InputEvent::TouchDown { .. }
1960 | InputEvent::TouchMotion { .. }
1961 | InputEvent::TabletToolAxis { .. }
1962 | InputEvent::TabletToolProximity { .. }
1963 | InputEvent::TabletToolTip { .. }
1964 | InputEvent::TabletToolButton { .. } => true,
1965 // Ignore events like device additions and removals, key releases, gesture ends.
1966 _ => false,
1967 }
1968}
1969
1970fn should_hide_hotkey_overlay<I: InputBackend>(event: &InputEvent<I>) -> bool {
1971 match event {
1972 InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true,
1973 InputEvent::PointerButton { event } if event.state() == ButtonState::Pressed => true,
1974 InputEvent::PointerAxis { .. }
1975 | InputEvent::GestureSwipeBegin { .. }
1976 | InputEvent::GesturePinchBegin { .. }
1977 | InputEvent::TouchDown { .. }
1978 | InputEvent::TouchMotion { .. }
1979 | InputEvent::TabletToolTip { .. }
1980 | InputEvent::TabletToolButton { .. } => true,
1981 _ => false,
1982 }
1983}
1984
1985fn should_hide_exit_confirm_dialog<I: InputBackend>(event: &InputEvent<I>) -> bool {
1986 match event {
1987 InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true,
1988 InputEvent::PointerButton { event } if event.state() == ButtonState::Pressed => true,
1989 InputEvent::PointerAxis { .. }
1990 | InputEvent::GestureSwipeBegin { .. }
1991 | InputEvent::GesturePinchBegin { .. }
1992 | InputEvent::TouchDown { .. }
1993 | InputEvent::TouchMotion { .. }
1994 | InputEvent::TabletToolTip { .. }
1995 | InputEvent::TabletToolButton { .. } => true,
1996 _ => false,
1997 }
1998}
1999
2000fn should_notify_activity<I: InputBackend>(event: &InputEvent<I>) -> bool {
2001 !matches!(
2002 event,
2003 InputEvent::DeviceAdded { .. } | InputEvent::DeviceRemoved { .. }
2004 )
2005}
2006
2007fn allowed_when_locked(action: &Action) -> bool {
2008 matches!(
2009 action,
2010 Action::Quit(_)
2011 | Action::ChangeVt(_)
2012 | Action::Suspend
2013 | Action::PowerOffMonitors
2014 | Action::SwitchLayout(_)
2015 )
2016}
2017
2018fn allowed_during_screenshot(action: &Action) -> bool {
2019 matches!(
2020 action,
2021 Action::Quit(_) | Action::ChangeVt(_) | Action::Suspend | Action::PowerOffMonitors
2022 )
2023}
2024
2025pub fn apply_libinput_settings(config: &niri_config::Input, device: &mut input::Device) {
2026 // According to Mutter code, this setting is specific to touchpads.
2027 let is_touchpad = device.config_tap_finger_count() > 0;
2028 if is_touchpad {
2029 let c = &config.touchpad;
2030 let _ = device.config_tap_set_enabled(c.tap);
2031 let _ = device.config_dwt_set_enabled(c.dwt);
2032 let _ = device.config_dwtp_set_enabled(c.dwtp);
2033 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
2034 let _ = device.config_accel_set_speed(c.accel_speed);
2035
2036 if let Some(accel_profile) = c.accel_profile {
2037 let _ = device.config_accel_set_profile(accel_profile.into());
2038 } else if let Some(default) = device.config_accel_default_profile() {
2039 let _ = device.config_accel_set_profile(default);
2040 }
2041
2042 if let Some(tap_button_map) = c.tap_button_map {
2043 let _ = device.config_tap_set_button_map(tap_button_map.into());
2044 } else if let Some(default) = device.config_tap_default_button_map() {
2045 let _ = device.config_tap_set_button_map(default);
2046 }
2047
2048 if let Some(method) = c.click_method {
2049 let _ = device.config_click_set_method(method.into());
2050 } else if let Some(default) = device.config_click_default_method() {
2051 let _ = device.config_click_set_method(default);
2052 }
2053 }
2054
2055 // This is how Mutter tells apart mice.
2056 let mut is_trackball = false;
2057 let mut is_trackpoint = false;
2058 if let Some(udev_device) = unsafe { device.udev_device() } {
2059 if udev_device.property_value("ID_INPUT_TRACKBALL").is_some() {
2060 is_trackball = true;
2061 }
2062 if udev_device
2063 .property_value("ID_INPUT_POINTINGSTICK")
2064 .is_some()
2065 {
2066 is_trackpoint = true;
2067 }
2068 }
2069
2070 let is_mouse = device.has_capability(input::DeviceCapability::Pointer)
2071 && !is_touchpad
2072 && !is_trackball
2073 && !is_trackpoint;
2074 if is_mouse {
2075 let c = &config.mouse;
2076 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
2077 let _ = device.config_accel_set_speed(c.accel_speed);
2078
2079 if let Some(accel_profile) = c.accel_profile {
2080 let _ = device.config_accel_set_profile(accel_profile.into());
2081 } else if let Some(default) = device.config_accel_default_profile() {
2082 let _ = device.config_accel_set_profile(default);
2083 }
2084 }
2085
2086 if is_trackpoint {
2087 let c = &config.trackpoint;
2088 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
2089 let _ = device.config_accel_set_speed(c.accel_speed);
2090
2091 if let Some(accel_profile) = c.accel_profile {
2092 let _ = device.config_accel_set_profile(accel_profile.into());
2093 } else if let Some(default) = device.config_accel_default_profile() {
2094 let _ = device.config_accel_set_profile(default);
2095 }
2096 }
2097}
2098
2099pub fn mods_with_binds(
2100 comp_mod: CompositorMod,
2101 binds: &Binds,
2102 triggers: &[Trigger],
2103) -> HashSet<Modifiers> {
2104 let comp_mod = match comp_mod {
2105 CompositorMod::Super => Modifiers::SUPER,
2106 CompositorMod::Alt => Modifiers::ALT,
2107 };
2108
2109 let mut rv = HashSet::new();
2110 for bind in &binds.0 {
2111 if !triggers.iter().any(|trigger| bind.key.trigger == *trigger) {
2112 continue;
2113 }
2114
2115 let mut mods = bind.key.modifiers;
2116 if mods.contains(Modifiers::COMPOSITOR) {
2117 mods.remove(Modifiers::COMPOSITOR);
2118 mods.insert(comp_mod);
2119 }
2120
2121 rv.insert(mods);
2122 }
2123
2124 rv
2125}
2126
2127pub fn mods_with_wheel_binds(comp_mod: CompositorMod, binds: &Binds) -> HashSet<Modifiers> {
2128 mods_with_binds(
2129 comp_mod,
2130 binds,
2131 &[
2132 Trigger::WheelScrollUp,
2133 Trigger::WheelScrollDown,
2134 Trigger::WheelScrollLeft,
2135 Trigger::WheelScrollRight,
2136 ],
2137 )
2138}
2139
2140pub fn mods_with_finger_scroll_binds(comp_mod: CompositorMod, binds: &Binds) -> HashSet<Modifiers> {
2141 mods_with_binds(
2142 comp_mod,
2143 binds,
2144 &[
2145 Trigger::TouchpadScrollUp,
2146 Trigger::TouchpadScrollDown,
2147 Trigger::TouchpadScrollLeft,
2148 Trigger::TouchpadScrollRight,
2149 ],
2150 )
2151}
2152
2153#[cfg(test)]
2154mod tests {
2155 use super::*;
2156
2157 #[test]
2158 fn bindings_suppress_keys() {
2159 let close_keysym = Keysym::q;
2160 let bindings = Binds(vec![Bind {
2161 key: Key {
2162 trigger: Trigger::Keysym(close_keysym),
2163 modifiers: Modifiers::COMPOSITOR | Modifiers::CTRL,
2164 },
2165 action: Action::CloseWindow,
2166 cooldown: None,
2167 }]);
2168
2169 let comp_mod = CompositorMod::Super;
2170 let mut suppressed_keys = HashSet::new();
2171
2172 let screenshot_ui = ScreenshotUi::new();
2173 let disable_power_key_handling = false;
2174
2175 // The key_code we pick is arbitrary, the only thing
2176 // that matters is that they are different between cases.
2177
2178 let close_key_code = close_keysym.into();
2179 let close_key_event = |suppr: &mut HashSet<u32>, mods: ModifiersState, pressed| {
2180 should_intercept_key(
2181 suppr,
2182 &bindings,
2183 comp_mod,
2184 close_key_code,
2185 close_keysym,
2186 Some(close_keysym),
2187 pressed,
2188 mods,
2189 &screenshot_ui,
2190 disable_power_key_handling,
2191 )
2192 };
2193
2194 // Key event with the code which can't trigger any action.
2195 let none_key_event = |suppr: &mut HashSet<u32>, mods: ModifiersState, pressed| {
2196 should_intercept_key(
2197 suppr,
2198 &bindings,
2199 comp_mod,
2200 Keysym::l.into(),
2201 Keysym::l,
2202 Some(Keysym::l),
2203 pressed,
2204 mods,
2205 &screenshot_ui,
2206 disable_power_key_handling,
2207 )
2208 };
2209
2210 let mut mods = ModifiersState {
2211 logo: true,
2212 ctrl: true,
2213 ..Default::default()
2214 };
2215
2216 // Action press/release.
2217
2218 let filter = close_key_event(&mut suppressed_keys, mods, true);
2219 assert!(matches!(
2220 filter,
2221 FilterResult::Intercept(Some(Bind {
2222 action: Action::CloseWindow,
2223 ..
2224 }))
2225 ));
2226 assert!(suppressed_keys.contains(&close_key_code));
2227
2228 let filter = close_key_event(&mut suppressed_keys, mods, false);
2229 assert!(matches!(filter, FilterResult::Intercept(None)));
2230 assert!(suppressed_keys.is_empty());
2231
2232 // Remove mod to make it for a binding.
2233
2234 mods.shift = true;
2235 let filter = close_key_event(&mut suppressed_keys, mods, true);
2236 assert!(matches!(filter, FilterResult::Forward));
2237
2238 mods.shift = false;
2239 let filter = close_key_event(&mut suppressed_keys, mods, false);
2240 assert!(matches!(filter, FilterResult::Forward));
2241
2242 // Just none press/release.
2243
2244 let filter = none_key_event(&mut suppressed_keys, mods, true);
2245 assert!(matches!(filter, FilterResult::Forward));
2246
2247 let filter = none_key_event(&mut suppressed_keys, mods, false);
2248 assert!(matches!(filter, FilterResult::Forward));
2249
2250 // Press action, press arbitrary, release action, release arbitrary.
2251
2252 let filter = close_key_event(&mut suppressed_keys, mods, true);
2253 assert!(matches!(
2254 filter,
2255 FilterResult::Intercept(Some(Bind {
2256 action: Action::CloseWindow,
2257 ..
2258 }))
2259 ));
2260
2261 let filter = none_key_event(&mut suppressed_keys, mods, true);
2262 assert!(matches!(filter, FilterResult::Forward));
2263
2264 let filter = close_key_event(&mut suppressed_keys, mods, false);
2265 assert!(matches!(filter, FilterResult::Intercept(None)));
2266
2267 let filter = none_key_event(&mut suppressed_keys, mods, false);
2268 assert!(matches!(filter, FilterResult::Forward));
2269
2270 // Trigger and remove all mods.
2271
2272 let filter = close_key_event(&mut suppressed_keys, mods, true);
2273 assert!(matches!(
2274 filter,
2275 FilterResult::Intercept(Some(Bind {
2276 action: Action::CloseWindow,
2277 ..
2278 }))
2279 ));
2280
2281 mods = Default::default();
2282 let filter = close_key_event(&mut suppressed_keys, mods, false);
2283 assert!(matches!(filter, FilterResult::Intercept(None)));
2284
2285 // Ensure that no keys are being suppressed.
2286 assert!(suppressed_keys.is_empty());
2287 }
2288
2289 #[test]
2290 fn comp_mod_handling() {
2291 let bindings = Binds(vec![
2292 Bind {
2293 key: Key {
2294 trigger: Trigger::Keysym(Keysym::q),
2295 modifiers: Modifiers::COMPOSITOR,
2296 },
2297 action: Action::CloseWindow,
2298 cooldown: None,
2299 },
2300 Bind {
2301 key: Key {
2302 trigger: Trigger::Keysym(Keysym::h),
2303 modifiers: Modifiers::SUPER,
2304 },
2305 action: Action::FocusColumnLeft,
2306 cooldown: None,
2307 },
2308 Bind {
2309 key: Key {
2310 trigger: Trigger::Keysym(Keysym::j),
2311 modifiers: Modifiers::empty(),
2312 },
2313 action: Action::FocusWindowDown,
2314 cooldown: None,
2315 },
2316 Bind {
2317 key: Key {
2318 trigger: Trigger::Keysym(Keysym::k),
2319 modifiers: Modifiers::COMPOSITOR | Modifiers::SUPER,
2320 },
2321 action: Action::FocusWindowUp,
2322 cooldown: None,
2323 },
2324 Bind {
2325 key: Key {
2326 trigger: Trigger::Keysym(Keysym::l),
2327 modifiers: Modifiers::SUPER | Modifiers::ALT,
2328 },
2329 action: Action::FocusColumnRight,
2330 cooldown: None,
2331 },
2332 ]);
2333
2334 assert_eq!(
2335 find_configured_bind(
2336 &bindings,
2337 CompositorMod::Super,
2338 Trigger::Keysym(Keysym::q),
2339 ModifiersState {
2340 logo: true,
2341 ..Default::default()
2342 }
2343 )
2344 .as_ref(),
2345 Some(&bindings.0[0])
2346 );
2347 assert_eq!(
2348 find_configured_bind(
2349 &bindings,
2350 CompositorMod::Super,
2351 Trigger::Keysym(Keysym::q),
2352 ModifiersState::default(),
2353 ),
2354 None,
2355 );
2356
2357 assert_eq!(
2358 find_configured_bind(
2359 &bindings,
2360 CompositorMod::Super,
2361 Trigger::Keysym(Keysym::h),
2362 ModifiersState {
2363 logo: true,
2364 ..Default::default()
2365 }
2366 )
2367 .as_ref(),
2368 Some(&bindings.0[1])
2369 );
2370 assert_eq!(
2371 find_configured_bind(
2372 &bindings,
2373 CompositorMod::Super,
2374 Trigger::Keysym(Keysym::h),
2375 ModifiersState::default(),
2376 ),
2377 None,
2378 );
2379
2380 assert_eq!(
2381 find_configured_bind(
2382 &bindings,
2383 CompositorMod::Super,
2384 Trigger::Keysym(Keysym::j),
2385 ModifiersState {
2386 logo: true,
2387 ..Default::default()
2388 }
2389 ),
2390 None,
2391 );
2392 assert_eq!(
2393 find_configured_bind(
2394 &bindings,
2395 CompositorMod::Super,
2396 Trigger::Keysym(Keysym::j),
2397 ModifiersState::default(),
2398 )
2399 .as_ref(),
2400 Some(&bindings.0[2])
2401 );
2402
2403 assert_eq!(
2404 find_configured_bind(
2405 &bindings,
2406 CompositorMod::Super,
2407 Trigger::Keysym(Keysym::k),
2408 ModifiersState {
2409 logo: true,
2410 ..Default::default()
2411 }
2412 )
2413 .as_ref(),
2414 Some(&bindings.0[3])
2415 );
2416 assert_eq!(
2417 find_configured_bind(
2418 &bindings,
2419 CompositorMod::Super,
2420 Trigger::Keysym(Keysym::k),
2421 ModifiersState::default(),
2422 ),
2423 None,
2424 );
2425
2426 assert_eq!(
2427 find_configured_bind(
2428 &bindings,
2429 CompositorMod::Super,
2430 Trigger::Keysym(Keysym::l),
2431 ModifiersState {
2432 logo: true,
2433 alt: true,
2434 ..Default::default()
2435 }
2436 )
2437 .as_ref(),
2438 Some(&bindings.0[4])
2439 );
2440 assert_eq!(
2441 find_configured_bind(
2442 &bindings,
2443 CompositorMod::Super,
2444 Trigger::Keysym(Keysym::l),
2445 ModifiersState {
2446 logo: true,
2447 ..Default::default()
2448 },
2449 ),
2450 None,
2451 );
2452 }
2453}