forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB8bcd18aIvan Molodetskikh2 years ago417 commits

input.rs1321 lines, 46.4 KiBHistoryRawDownload
1use std::any::Any;
2use std::collections::HashSet;
3
4use smithay::backend::input::{
5 AbsolutePositionEvent, Axis, AxisSource, ButtonState, Device, DeviceCapability, Event,
6 GestureBeginEvent, GestureEndEvent, GesturePinchUpdateEvent as _, GestureSwipeUpdateEvent as _,
7 InputBackend, InputEvent, KeyState, KeyboardKeyEvent, PointerAxisEvent, PointerButtonEvent,
8 PointerMotionEvent, ProximityState, TabletToolButtonEvent, TabletToolEvent,
9 TabletToolProximityEvent, TabletToolTipEvent, TabletToolTipState,
10};
11use smithay::backend::libinput::LibinputInputBackend;
12use smithay::input::keyboard::{keysyms, FilterResult, Keysym, ModifiersState};
13use smithay::input::pointer::{
14 AxisFrame, ButtonEvent, CursorImageStatus, GestureHoldBeginEvent, GestureHoldEndEvent,
15 GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent, GestureSwipeBeginEvent,
16 GestureSwipeEndEvent, GestureSwipeUpdateEvent, MotionEvent, RelativeMotionEvent,
17};
18use smithay::reexports::input;
19use smithay::utils::{Logical, Point, SERIAL_COUNTER};
20use smithay::wayland::tablet_manager::{TabletDescriptor, TabletSeatTrait};
21
22use crate::config::{Action, Binds, LayoutAction, Modifiers};
23use crate::niri::State;
24use crate::screenshot_ui::ScreenshotUi;
25use crate::utils::{center, get_monotonic_time, spawn};
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum CompositorMod {
29 Super,
30 Alt,
31}
32
33#[derive(Debug, Clone, Copy, PartialEq)]
34pub struct TabletData {
35 pub aspect_ratio: f64,
36}
37
38impl State {
39 pub fn process_input_event<I: InputBackend>(&mut self, event: InputEvent<I>)
40 where
41 I::Device: 'static, // Needed for downcasting.
42 {
43 let _span = tracy_client::span!("process_input_event");
44
45 // A bit of a hack, but animation end runs some logic (i.e. workspace clean-up) and it
46 // doesn't always trigger due to damage, etc. So run it here right before it might prove
47 // important. Besides, animations affect the input, so it's best to have up-to-date values
48 // here.
49 self.niri.layout.advance_animations(get_monotonic_time());
50
51 // Power on monitors if they were off.
52 if should_activate_monitors(&event) {
53 self.niri.activate_monitors(&self.backend);
54 }
55
56 use InputEvent::*;
57 match event {
58 DeviceAdded { device } => self.on_device_added(device),
59 DeviceRemoved { device } => self.on_device_removed(device),
60 Keyboard { event } => self.on_keyboard::<I>(event),
61 PointerMotion { event } => self.on_pointer_motion::<I>(event),
62 PointerMotionAbsolute { event } => self.on_pointer_motion_absolute::<I>(event),
63 PointerButton { event } => self.on_pointer_button::<I>(event),
64 PointerAxis { event } => self.on_pointer_axis::<I>(event),
65 TabletToolAxis { event } => self.on_tablet_tool_axis::<I>(event),
66 TabletToolTip { event } => self.on_tablet_tool_tip::<I>(event),
67 TabletToolProximity { event } => self.on_tablet_tool_proximity::<I>(event),
68 TabletToolButton { event } => self.on_tablet_tool_button::<I>(event),
69 GestureSwipeBegin { event } => self.on_gesture_swipe_begin::<I>(event),
70 GestureSwipeUpdate { event } => self.on_gesture_swipe_update::<I>(event),
71 GestureSwipeEnd { event } => self.on_gesture_swipe_end::<I>(event),
72 GesturePinchBegin { event } => self.on_gesture_pinch_begin::<I>(event),
73 GesturePinchUpdate { event } => self.on_gesture_pinch_update::<I>(event),
74 GesturePinchEnd { event } => self.on_gesture_pinch_end::<I>(event),
75 GestureHoldBegin { event } => self.on_gesture_hold_begin::<I>(event),
76 GestureHoldEnd { event } => self.on_gesture_hold_end::<I>(event),
77 TouchDown { .. } => (),
78 TouchMotion { .. } => (),
79 TouchUp { .. } => (),
80 TouchCancel { .. } => (),
81 TouchFrame { .. } => (),
82 Special(_) => (),
83 }
84 }
85
86 pub fn process_libinput_event(&mut self, event: &mut InputEvent<LibinputInputBackend>) {
87 let _span = tracy_client::span!("process_libinput_event");
88
89 match event {
90 InputEvent::DeviceAdded { device } => {
91 // According to Mutter code, this setting is specific to touchpads.
92 let is_touchpad = device.config_tap_finger_count() > 0;
93 if is_touchpad {
94 let c = &self.niri.config.borrow().input.touchpad;
95 let _ = device.config_tap_set_enabled(c.tap);
96 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
97 let _ = device.config_accel_set_speed(c.accel_speed);
98 }
99
100 if device.has_capability(input::DeviceCapability::TabletTool) {
101 match device.size() {
102 Some((w, h)) => {
103 let aspect_ratio = w / h;
104 let data = TabletData { aspect_ratio };
105 self.niri.tablets.insert(device.clone(), data);
106 }
107 None => {
108 warn!("tablet tool device has no size");
109 }
110 }
111 }
112 }
113 InputEvent::DeviceRemoved { device } => {
114 self.niri.tablets.remove(device);
115 }
116 _ => (),
117 }
118 }
119
120 fn on_device_added(&mut self, device: impl Device) {
121 if device.has_capability(DeviceCapability::TabletTool) {
122 let tablet_seat = self.niri.seat.tablet_seat();
123
124 let desc = TabletDescriptor::from(&device);
125 tablet_seat.add_tablet::<Self>(&self.niri.display_handle, &desc);
126 }
127 }
128
129 fn on_device_removed(&mut self, device: impl Device) {
130 if device.has_capability(DeviceCapability::TabletTool) {
131 let tablet_seat = self.niri.seat.tablet_seat();
132
133 let desc = TabletDescriptor::from(&device);
134 tablet_seat.remove_tablet(&desc);
135
136 // If there are no tablets in seat we can remove all tools
137 if tablet_seat.count_tablets() == 0 {
138 tablet_seat.clear_tools();
139 }
140 }
141 }
142
143 /// Computes the cursor position for the tablet event.
144 ///
145 /// This function handles the tablet output mapping, as well as coordinate clamping and aspect
146 /// ratio correction.
147 fn compute_tablet_position<I: InputBackend>(
148 &self,
149 event: &(impl Event<I> + TabletToolEvent<I>),
150 ) -> Option<Point<f64, Logical>>
151 where
152 I::Device: 'static,
153 {
154 let output = self.niri.output_for_tablet()?;
155 let output_geo = self.niri.global_space.output_geometry(output).unwrap();
156
157 let mut pos = event.position_transformed(output_geo.size);
158 pos.x /= output_geo.size.w as f64;
159 pos.y /= output_geo.size.h as f64;
160
161 let device = event.device();
162 if let Some(device) = (&device as &dyn Any).downcast_ref::<input::Device>() {
163 if let Some(data) = self.niri.tablets.get(device) {
164 // This code does the same thing as mutter with "keep aspect ratio" enabled.
165 let output_aspect_ratio = output_geo.size.w as f64 / output_geo.size.h as f64;
166 let ratio = data.aspect_ratio / output_aspect_ratio;
167
168 if ratio > 1. {
169 pos.x *= ratio;
170 } else {
171 pos.y /= ratio;
172 }
173 }
174 };
175
176 pos.x *= output_geo.size.w as f64;
177 pos.y *= output_geo.size.h as f64;
178 pos.x = pos.x.clamp(0.0, output_geo.size.w as f64 - 1.);
179 pos.y = pos.y.clamp(0.0, output_geo.size.h as f64 - 1.);
180 Some(pos + output_geo.loc.to_f64())
181 }
182
183 fn on_keyboard<I: InputBackend>(&mut self, event: I::KeyboardKeyEvent) {
184 let comp_mod = self.backend.mod_key();
185
186 let serial = SERIAL_COUNTER.next_serial();
187 let time = Event::time_msec(&event);
188 let pressed = event.state() == KeyState::Pressed;
189
190 let Some(Some(action)) = self.niri.seat.get_keyboard().unwrap().input(
191 self,
192 event.key_code(),
193 event.state(),
194 serial,
195 time,
196 |this, mods, keysym| {
197 let bindings = &this.niri.config.borrow().binds;
198 let key_code = event.key_code();
199 let modified = keysym.modified_sym();
200 let raw = keysym.raw_latin_sym_or_raw_current_sym();
201 should_intercept_key(
202 &mut this.niri.suppressed_keys,
203 bindings,
204 comp_mod,
205 key_code,
206 modified,
207 raw,
208 pressed,
209 *mods,
210 &this.niri.screenshot_ui,
211 )
212 },
213 ) else {
214 return;
215 };
216
217 // Filter actions when the key is released or the session is locked.
218 if !pressed {
219 return;
220 }
221
222 if self.niri.is_locked() && !allowed_when_locked(&action) {
223 return;
224 }
225
226 match action {
227 Action::Quit => {
228 info!("quitting because quit bind was pressed");
229 self.niri.stop_signal.stop()
230 }
231 Action::ChangeVt(vt) => {
232 self.backend.change_vt(vt);
233 // Changing `VT` may not deliver the key releases, so clear the state.
234 self.niri.suppressed_keys.clear();
235 }
236 Action::Suspend => {
237 self.backend.suspend();
238 // Suspend may not deliver the key releases, so clear the state.
239 self.niri.suppressed_keys.clear();
240 }
241 Action::PowerOffMonitors => {
242 self.niri.deactivate_monitors(&self.backend);
243 }
244 Action::ToggleDebugTint => {
245 self.backend.toggle_debug_tint();
246 }
247 Action::Spawn(command) => {
248 spawn(command);
249 }
250 Action::ScreenshotScreen => {
251 let active = self.niri.layout.active_output().cloned();
252 if let Some(active) = active {
253 if let Some(renderer) = self.backend.renderer() {
254 if let Err(err) = self.niri.screenshot(renderer, &active) {
255 warn!("error taking screenshot: {err:?}");
256 }
257 }
258 }
259 }
260 Action::ConfirmScreenshot => {
261 if let Some(renderer) = self.backend.renderer() {
262 match self.niri.screenshot_ui.capture(renderer) {
263 Ok((size, pixels)) => {
264 if let Err(err) = self.niri.save_screenshot(size, pixels) {
265 warn!("error saving screenshot: {err:?}");
266 }
267 }
268 Err(err) => {
269 warn!("error capturing screenshot: {err:?}");
270 }
271 }
272 }
273
274 self.niri.screenshot_ui.close();
275 self.niri
276 .cursor_manager
277 .set_cursor_image(CursorImageStatus::default_named());
278 self.niri.queue_redraw_all();
279 }
280 Action::CancelScreenshot => {
281 self.niri.screenshot_ui.close();
282 self.niri
283 .cursor_manager
284 .set_cursor_image(CursorImageStatus::default_named());
285 self.niri.queue_redraw_all();
286 }
287 Action::Screenshot => {
288 if let Some(renderer) = self.backend.renderer() {
289 self.niri.open_screenshot_ui(renderer);
290 }
291 }
292 Action::ScreenshotWindow => {
293 let active = self.niri.layout.active_window();
294 if let Some((window, output)) = active {
295 if let Some(renderer) = self.backend.renderer() {
296 if let Err(err) = self.niri.screenshot_window(renderer, &output, &window) {
297 warn!("error taking screenshot: {err:?}");
298 }
299 }
300 }
301 }
302 Action::CloseWindow => {
303 if let Some(window) = self.niri.layout.focus() {
304 window.toplevel().send_close();
305 }
306 }
307 Action::FullscreenWindow => {
308 let focus = self.niri.layout.focus().cloned();
309 if let Some(window) = focus {
310 self.niri.layout.toggle_fullscreen(&window);
311 }
312 }
313 Action::SwitchLayout(action) => {
314 self.niri.seat.get_keyboard().unwrap().with_xkb_state(
315 self,
316 |mut state| match action {
317 LayoutAction::Next => state.cycle_next_layout(),
318 LayoutAction::Prev => state.cycle_prev_layout(),
319 },
320 );
321 }
322 Action::MoveColumnLeft => {
323 self.niri.layout.move_left();
324 // FIXME: granular
325 self.niri.queue_redraw_all();
326 }
327 Action::MoveColumnRight => {
328 self.niri.layout.move_right();
329 // FIXME: granular
330 self.niri.queue_redraw_all();
331 }
332 Action::MoveWindowDown => {
333 self.niri.layout.move_down();
334 // FIXME: granular
335 self.niri.queue_redraw_all();
336 }
337 Action::MoveWindowUp => {
338 self.niri.layout.move_up();
339 // FIXME: granular
340 self.niri.queue_redraw_all();
341 }
342 Action::FocusColumnLeft => {
343 self.niri.layout.focus_left();
344 }
345 Action::FocusColumnRight => {
346 self.niri.layout.focus_right();
347 }
348 Action::FocusWindowDown => {
349 self.niri.layout.focus_down();
350 }
351 Action::FocusWindowUp => {
352 self.niri.layout.focus_up();
353 }
354 Action::MoveWindowToWorkspaceDown => {
355 self.niri.layout.move_to_workspace_down();
356 // FIXME: granular
357 self.niri.queue_redraw_all();
358 }
359 Action::MoveWindowToWorkspaceUp => {
360 self.niri.layout.move_to_workspace_up();
361 // FIXME: granular
362 self.niri.queue_redraw_all();
363 }
364 Action::MoveWindowToWorkspace(idx) => {
365 let idx = idx.saturating_sub(1) as usize;
366 self.niri.layout.move_to_workspace(idx);
367 // FIXME: granular
368 self.niri.queue_redraw_all();
369 }
370 Action::FocusWorkspaceDown => {
371 self.niri.layout.switch_workspace_down();
372 // FIXME: granular
373 self.niri.queue_redraw_all();
374 }
375 Action::FocusWorkspaceUp => {
376 self.niri.layout.switch_workspace_up();
377 // FIXME: granular
378 self.niri.queue_redraw_all();
379 }
380 Action::FocusWorkspace(idx) => {
381 let idx = idx.saturating_sub(1) as usize;
382 self.niri.layout.switch_workspace(idx);
383 // FIXME: granular
384 self.niri.queue_redraw_all();
385 }
386 Action::MoveWorkspaceDown => {
387 self.niri.layout.move_workspace_down();
388 // FIXME: granular
389 self.niri.queue_redraw_all();
390 }
391 Action::MoveWorkspaceUp => {
392 self.niri.layout.move_workspace_up();
393 // FIXME: granular
394 self.niri.queue_redraw_all();
395 }
396 Action::ConsumeWindowIntoColumn => {
397 self.niri.layout.consume_into_column();
398 // FIXME: granular
399 self.niri.queue_redraw_all();
400 }
401 Action::ExpelWindowFromColumn => {
402 self.niri.layout.expel_from_column();
403 // FIXME: granular
404 self.niri.queue_redraw_all();
405 }
406 Action::SwitchPresetColumnWidth => {
407 self.niri.layout.toggle_width();
408 }
409 Action::CenterColumn => {
410 self.niri.layout.center_column();
411 // FIXME: granular
412 self.niri.queue_redraw_all();
413 }
414 Action::MaximizeColumn => {
415 self.niri.layout.toggle_full_width();
416 }
417 Action::FocusMonitorLeft => {
418 if let Some(output) = self.niri.output_left() {
419 self.niri.layout.focus_output(&output);
420 self.move_cursor_to_output(&output);
421 }
422 }
423 Action::FocusMonitorRight => {
424 if let Some(output) = self.niri.output_right() {
425 self.niri.layout.focus_output(&output);
426 self.move_cursor_to_output(&output);
427 }
428 }
429 Action::FocusMonitorDown => {
430 if let Some(output) = self.niri.output_down() {
431 self.niri.layout.focus_output(&output);
432 self.move_cursor_to_output(&output);
433 }
434 }
435 Action::FocusMonitorUp => {
436 if let Some(output) = self.niri.output_up() {
437 self.niri.layout.focus_output(&output);
438 self.move_cursor_to_output(&output);
439 }
440 }
441 Action::MoveWindowToMonitorLeft => {
442 if let Some(output) = self.niri.output_left() {
443 self.niri.layout.move_to_output(&output);
444 self.move_cursor_to_output(&output);
445 }
446 }
447 Action::MoveWindowToMonitorRight => {
448 if let Some(output) = self.niri.output_right() {
449 self.niri.layout.move_to_output(&output);
450 self.move_cursor_to_output(&output);
451 }
452 }
453 Action::MoveWindowToMonitorDown => {
454 if let Some(output) = self.niri.output_down() {
455 self.niri.layout.move_to_output(&output);
456 self.move_cursor_to_output(&output);
457 }
458 }
459 Action::MoveWindowToMonitorUp => {
460 if let Some(output) = self.niri.output_up() {
461 self.niri.layout.move_to_output(&output);
462 self.move_cursor_to_output(&output);
463 }
464 }
465 Action::SetColumnWidth(change) => {
466 self.niri.layout.set_column_width(change);
467 }
468 Action::SetWindowHeight(change) => {
469 self.niri.layout.set_window_height(change);
470 }
471 }
472 }
473
474 fn on_pointer_motion<I: InputBackend>(&mut self, event: I::PointerMotionEvent) {
475 // We need an output to be able to move the pointer.
476 if self.niri.global_space.outputs().next().is_none() {
477 return;
478 }
479
480 let serial = SERIAL_COUNTER.next_serial();
481
482 let pointer = self.niri.seat.get_pointer().unwrap();
483
484 let pos = pointer.current_location();
485
486 // We have an output, so we can compute the new location and focus.
487 let mut new_pos = pos + event.delta();
488
489 if self
490 .niri
491 .global_space
492 .output_under(new_pos)
493 .next()
494 .is_none()
495 {
496 // We ended up outside the outputs and need to clip the movement.
497 if let Some(output) = self.niri.global_space.output_under(pos).next() {
498 // The pointer was previously on some output. Clip the movement against its
499 // boundaries.
500 let geom = self.niri.global_space.output_geometry(output).unwrap();
501 new_pos.x = new_pos
502 .x
503 .clamp(geom.loc.x as f64, (geom.loc.x + geom.size.w - 1) as f64);
504 new_pos.y = new_pos
505 .y
506 .clamp(geom.loc.y as f64, (geom.loc.y + geom.size.h - 1) as f64);
507 } else {
508 // The pointer was not on any output in the first place. Find one for it.
509 // Let's do the simple thing and just put it on the first output.
510 let output = self.niri.global_space.outputs().next().unwrap();
511 let geom = self.niri.global_space.output_geometry(output).unwrap();
512 new_pos = center(geom).to_f64();
513 }
514 }
515
516 if let Some(output) = self.niri.screenshot_ui.selection_output() {
517 let geom = self.niri.global_space.output_geometry(output).unwrap();
518 let mut point = new_pos;
519 point.x = point
520 .x
521 .clamp(geom.loc.x as f64, (geom.loc.x + geom.size.w - 1) as f64);
522 point.y = point
523 .y
524 .clamp(geom.loc.y as f64, (geom.loc.y + geom.size.h - 1) as f64);
525 let point = (point - geom.loc.to_f64())
526 .to_physical(output.current_scale().fractional_scale())
527 .to_i32_round();
528 self.niri.screenshot_ui.pointer_motion(point);
529 }
530
531 let under = self.niri.surface_under_and_global_space(new_pos);
532 self.niri.pointer_focus = under.clone();
533 let under = under.map(|u| u.surface);
534
535 pointer.motion(
536 self,
537 under.clone(),
538 &MotionEvent {
539 location: new_pos,
540 serial,
541 time: event.time_msec(),
542 },
543 );
544
545 pointer.relative_motion(
546 self,
547 under,
548 &RelativeMotionEvent {
549 delta: event.delta(),
550 delta_unaccel: event.delta_unaccel(),
551 utime: event.time(),
552 },
553 );
554
555 pointer.frame(self);
556
557 // We moved the regular pointer, so show it now.
558 self.niri.tablet_cursor_location = None;
559
560 // Redraw to update the cursor position.
561 // FIXME: redraw only outputs overlapping the cursor.
562 self.niri.queue_redraw_all();
563 }
564
565 fn on_pointer_motion_absolute<I: InputBackend>(
566 &mut self,
567 event: I::PointerMotionAbsoluteEvent,
568 ) {
569 let Some(output) = self.niri.global_space.outputs().next() else {
570 return;
571 };
572
573 let output_geo = self.niri.global_space.output_geometry(output).unwrap();
574
575 let pos = event.position_transformed(output_geo.size) + output_geo.loc.to_f64();
576
577 let serial = SERIAL_COUNTER.next_serial();
578
579 let pointer = self.niri.seat.get_pointer().unwrap();
580
581 if let Some(output) = self.niri.screenshot_ui.selection_output() {
582 let geom = self.niri.global_space.output_geometry(output).unwrap();
583 let mut point = pos;
584 point.x = point
585 .x
586 .clamp(geom.loc.x as f64, (geom.loc.x + geom.size.w - 1) as f64);
587 point.y = point
588 .y
589 .clamp(geom.loc.y as f64, (geom.loc.y + geom.size.h - 1) as f64);
590 let point = (point - geom.loc.to_f64())
591 .to_physical(output.current_scale().fractional_scale())
592 .to_i32_round();
593 self.niri.screenshot_ui.pointer_motion(point);
594 }
595
596 let under = self.niri.surface_under_and_global_space(pos);
597 self.niri.pointer_focus = under.clone();
598 let under = under.map(|u| u.surface);
599
600 pointer.motion(
601 self,
602 under,
603 &MotionEvent {
604 location: pos,
605 serial,
606 time: event.time_msec(),
607 },
608 );
609
610 pointer.frame(self);
611
612 // We moved the regular pointer, so show it now.
613 self.niri.tablet_cursor_location = None;
614
615 // Redraw to update the cursor position.
616 // FIXME: redraw only outputs overlapping the cursor.
617 self.niri.queue_redraw_all();
618 }
619
620 fn on_pointer_button<I: InputBackend>(&mut self, event: I::PointerButtonEvent) {
621 let pointer = self.niri.seat.get_pointer().unwrap();
622
623 let serial = SERIAL_COUNTER.next_serial();
624
625 let button = event.button_code();
626
627 let button_state = event.state();
628
629 if ButtonState::Pressed == button_state && !pointer.is_grabbed() {
630 if let Some(window) = self.niri.window_under_cursor() {
631 let window = window.clone();
632 self.niri.layout.activate_window(&window);
633 } else if let Some(output) = self.niri.output_under_cursor() {
634 self.niri.layout.activate_output(&output);
635 }
636 };
637
638 self.update_pointer_focus();
639
640 if let Some(button) = event.button() {
641 let pos = pointer.current_location();
642 if let Some((output, _)) = self.niri.output_under(pos) {
643 let output = output.clone();
644 let geom = self.niri.global_space.output_geometry(&output).unwrap();
645 let mut point = pos;
646 // Re-clamp as pointer can be within 0.5 from the limit which will round up
647 // to a wrong value.
648 point.x = point
649 .x
650 .clamp(geom.loc.x as f64, (geom.loc.x + geom.size.w - 1) as f64);
651 point.y = point
652 .y
653 .clamp(geom.loc.y as f64, (geom.loc.y + geom.size.h - 1) as f64);
654 let point = (point - geom.loc.to_f64())
655 .to_physical(output.current_scale().fractional_scale())
656 .to_i32_round();
657 if self
658 .niri
659 .screenshot_ui
660 .pointer_button(output, point, button, button_state)
661 {
662 self.niri.queue_redraw_all();
663 }
664 }
665 }
666
667 pointer.button(
668 self,
669 &ButtonEvent {
670 button,
671 state: button_state,
672 serial,
673 time: event.time_msec(),
674 },
675 );
676 pointer.frame(self);
677 }
678
679 fn on_pointer_axis<I: InputBackend>(&mut self, event: I::PointerAxisEvent) {
680 let source = event.source();
681
682 let horizontal_amount = event
683 .amount(Axis::Horizontal)
684 .unwrap_or_else(|| event.amount_discrete(Axis::Horizontal).unwrap_or(0.0) * 3.0);
685 let vertical_amount = event
686 .amount(Axis::Vertical)
687 .unwrap_or_else(|| event.amount_discrete(Axis::Vertical).unwrap_or(0.0) * 3.0);
688 let horizontal_amount_discrete = event.amount_discrete(Axis::Horizontal);
689 let vertical_amount_discrete = event.amount_discrete(Axis::Vertical);
690
691 let mut frame = AxisFrame::new(event.time_msec()).source(source);
692 if horizontal_amount != 0.0 {
693 frame = frame.value(Axis::Horizontal, horizontal_amount);
694 if let Some(discrete) = horizontal_amount_discrete {
695 frame = frame.discrete(Axis::Horizontal, discrete as i32);
696 }
697 }
698 if vertical_amount != 0.0 {
699 frame = frame.value(Axis::Vertical, vertical_amount);
700 if let Some(discrete) = vertical_amount_discrete {
701 frame = frame.discrete(Axis::Vertical, discrete as i32);
702 }
703 }
704
705 if source == AxisSource::Finger {
706 if event.amount(Axis::Horizontal) == Some(0.0) {
707 frame = frame.stop(Axis::Horizontal);
708 }
709 if event.amount(Axis::Vertical) == Some(0.0) {
710 frame = frame.stop(Axis::Vertical);
711 }
712 }
713
714 self.update_pointer_focus();
715
716 let pointer = &self.niri.seat.get_pointer().unwrap();
717 pointer.axis(self, frame);
718 pointer.frame(self);
719 }
720
721 fn on_tablet_tool_axis<I: InputBackend>(&mut self, event: I::TabletToolAxisEvent)
722 where
723 I::Device: 'static, // Needed for downcasting.
724 {
725 let Some(pos) = self.compute_tablet_position(&event) else {
726 return;
727 };
728
729 let under = self.niri.surface_under_and_global_space(pos);
730 let under = under.map(|u| u.surface);
731
732 let tablet_seat = self.niri.seat.tablet_seat();
733 let tablet = tablet_seat.get_tablet(&TabletDescriptor::from(&event.device()));
734 let tool = tablet_seat.get_tool(&event.tool());
735 if let (Some(tablet), Some(tool)) = (tablet, tool) {
736 if event.pressure_has_changed() {
737 tool.pressure(event.pressure());
738 }
739 if event.distance_has_changed() {
740 tool.distance(event.distance());
741 }
742 if event.tilt_has_changed() {
743 tool.tilt(event.tilt());
744 }
745 if event.slider_has_changed() {
746 tool.slider_position(event.slider_position());
747 }
748 if event.rotation_has_changed() {
749 tool.rotation(event.rotation());
750 }
751 if event.wheel_has_changed() {
752 tool.wheel(event.wheel_delta(), event.wheel_delta_discrete());
753 }
754
755 tool.motion(
756 pos,
757 under,
758 &tablet,
759 SERIAL_COUNTER.next_serial(),
760 event.time_msec(),
761 );
762
763 self.niri.tablet_cursor_location = Some(pos);
764 }
765
766 // Redraw to update the cursor position.
767 // FIXME: redraw only outputs overlapping the cursor.
768 self.niri.queue_redraw_all();
769 }
770
771 fn on_tablet_tool_tip<I: InputBackend>(&mut self, event: I::TabletToolTipEvent) {
772 let tool = self.niri.seat.tablet_seat().get_tool(&event.tool());
773
774 if let Some(tool) = tool {
775 match event.tip_state() {
776 TabletToolTipState::Down => {
777 let serial = SERIAL_COUNTER.next_serial();
778 tool.tip_down(serial, event.time_msec());
779
780 if let Some(pos) = self.niri.tablet_cursor_location {
781 if let Some(window) = self.niri.window_under(pos) {
782 let window = window.clone();
783 self.niri.layout.activate_window(&window);
784
785 // FIXME: granular.
786 self.niri.queue_redraw_all();
787 } else if let Some((output, _)) = self.niri.output_under(pos) {
788 let output = output.clone();
789 self.niri.layout.activate_output(&output);
790
791 // FIXME: granular.
792 self.niri.queue_redraw_all();
793 }
794 }
795 }
796 TabletToolTipState::Up => {
797 tool.tip_up(event.time_msec());
798 }
799 }
800 }
801 }
802
803 fn on_tablet_tool_proximity<I: InputBackend>(&mut self, event: I::TabletToolProximityEvent)
804 where
805 I::Device: 'static, // Needed for downcasting.
806 {
807 let Some(pos) = self.compute_tablet_position(&event) else {
808 return;
809 };
810
811 let under = self.niri.surface_under_and_global_space(pos);
812 let under = under.map(|u| u.surface);
813
814 let tablet_seat = self.niri.seat.tablet_seat();
815 let tool = tablet_seat.add_tool::<Self>(&self.niri.display_handle, &event.tool());
816 let tablet = tablet_seat.get_tablet(&TabletDescriptor::from(&event.device()));
817 if let Some(tablet) = tablet {
818 match event.state() {
819 ProximityState::In => {
820 if let Some(under) = under {
821 tool.proximity_in(
822 pos,
823 under,
824 &tablet,
825 SERIAL_COUNTER.next_serial(),
826 event.time_msec(),
827 );
828 }
829 self.niri.tablet_cursor_location = Some(pos);
830 }
831 ProximityState::Out => {
832 tool.proximity_out(event.time_msec());
833
834 // Move the mouse pointer here to avoid discontinuity.
835 //
836 // Plus, Wayland SDL2 currently warps the pointer into some weird
837 // location on proximity out, so this shuold help it a little.
838 if let Some(pos) = self.niri.tablet_cursor_location {
839 self.move_cursor(pos);
840 }
841
842 self.niri.tablet_cursor_location = None;
843 }
844 }
845
846 // FIXME: granular.
847 self.niri.queue_redraw_all();
848 }
849 }
850
851 fn on_tablet_tool_button<I: InputBackend>(&mut self, event: I::TabletToolButtonEvent) {
852 let tool = self.niri.seat.tablet_seat().get_tool(&event.tool());
853
854 if let Some(tool) = tool {
855 tool.button(
856 event.button(),
857 event.button_state(),
858 SERIAL_COUNTER.next_serial(),
859 event.time_msec(),
860 );
861 }
862 }
863
864 fn on_gesture_swipe_begin<I: InputBackend>(&mut self, event: I::GestureSwipeBeginEvent) {
865 if event.fingers() == 3 {
866 if let Some(output) = self.niri.output_under_cursor() {
867 self.niri.layout.workspace_switch_gesture_begin(&output);
868
869 // FIXME: granular. This one is awkward because this can cancel a gesture on
870 // multiple other outputs in theory.
871 self.niri.queue_redraw_all();
872 }
873
874 // We handled this event.
875 return;
876 }
877
878 let serial = SERIAL_COUNTER.next_serial();
879 let pointer = self.niri.seat.get_pointer().unwrap();
880
881 if self.update_pointer_focus() {
882 pointer.frame(self);
883 }
884
885 pointer.gesture_swipe_begin(
886 self,
887 &GestureSwipeBeginEvent {
888 serial,
889 time: event.time_msec(),
890 fingers: event.fingers(),
891 },
892 );
893 }
894
895 fn on_gesture_swipe_update<I: InputBackend>(&mut self, event: I::GestureSwipeUpdateEvent) {
896 let res = self
897 .niri
898 .layout
899 .workspace_switch_gesture_update(event.delta_y());
900 if let Some(output) = res {
901 if let Some(output) = output {
902 self.niri.queue_redraw(output);
903 }
904
905 // We handled this event.
906 return;
907 }
908
909 let pointer = self.niri.seat.get_pointer().unwrap();
910
911 if self.update_pointer_focus() {
912 pointer.frame(self);
913 }
914
915 pointer.gesture_swipe_update(
916 self,
917 &GestureSwipeUpdateEvent {
918 time: event.time_msec(),
919 delta: event.delta(),
920 },
921 );
922 }
923
924 fn on_gesture_swipe_end<I: InputBackend>(&mut self, event: I::GestureSwipeEndEvent) {
925 let res = self
926 .niri
927 .layout
928 .workspace_switch_gesture_end(event.cancelled());
929 if let Some(output) = res {
930 self.niri.queue_redraw(output);
931
932 // We handled this event.
933 return;
934 }
935
936 let serial = SERIAL_COUNTER.next_serial();
937 let pointer = self.niri.seat.get_pointer().unwrap();
938
939 if self.update_pointer_focus() {
940 pointer.frame(self);
941 }
942
943 pointer.gesture_swipe_end(
944 self,
945 &GestureSwipeEndEvent {
946 serial,
947 time: event.time_msec(),
948 cancelled: event.cancelled(),
949 },
950 );
951 }
952
953 fn on_gesture_pinch_begin<I: InputBackend>(&mut self, event: I::GesturePinchBeginEvent) {
954 let serial = SERIAL_COUNTER.next_serial();
955 let pointer = self.niri.seat.get_pointer().unwrap();
956
957 if self.update_pointer_focus() {
958 pointer.frame(self);
959 }
960
961 pointer.gesture_pinch_begin(
962 self,
963 &GesturePinchBeginEvent {
964 serial,
965 time: event.time_msec(),
966 fingers: event.fingers(),
967 },
968 );
969 }
970
971 fn on_gesture_pinch_update<I: InputBackend>(&mut self, event: I::GesturePinchUpdateEvent) {
972 let pointer = self.niri.seat.get_pointer().unwrap();
973
974 if self.update_pointer_focus() {
975 pointer.frame(self);
976 }
977
978 pointer.gesture_pinch_update(
979 self,
980 &GesturePinchUpdateEvent {
981 time: event.time_msec(),
982 delta: event.delta(),
983 scale: event.scale(),
984 rotation: event.rotation(),
985 },
986 );
987 }
988
989 fn on_gesture_pinch_end<I: InputBackend>(&mut self, event: I::GesturePinchEndEvent) {
990 let serial = SERIAL_COUNTER.next_serial();
991 let pointer = self.niri.seat.get_pointer().unwrap();
992
993 if self.update_pointer_focus() {
994 pointer.frame(self);
995 }
996
997 pointer.gesture_pinch_end(
998 self,
999 &GesturePinchEndEvent {
1000 serial,
1001 time: event.time_msec(),
1002 cancelled: event.cancelled(),
1003 },
1004 );
1005 }
1006
1007 fn on_gesture_hold_begin<I: InputBackend>(&mut self, event: I::GestureHoldBeginEvent) {
1008 let serial = SERIAL_COUNTER.next_serial();
1009 let pointer = self.niri.seat.get_pointer().unwrap();
1010
1011 if self.update_pointer_focus() {
1012 pointer.frame(self);
1013 }
1014
1015 pointer.gesture_hold_begin(
1016 self,
1017 &GestureHoldBeginEvent {
1018 serial,
1019 time: event.time_msec(),
1020 fingers: event.fingers(),
1021 },
1022 );
1023 }
1024
1025 fn on_gesture_hold_end<I: InputBackend>(&mut self, event: I::GestureHoldEndEvent) {
1026 let serial = SERIAL_COUNTER.next_serial();
1027 let pointer = self.niri.seat.get_pointer().unwrap();
1028
1029 if self.update_pointer_focus() {
1030 pointer.frame(self);
1031 }
1032
1033 pointer.gesture_hold_end(
1034 self,
1035 &GestureHoldEndEvent {
1036 serial,
1037 time: event.time_msec(),
1038 cancelled: event.cancelled(),
1039 },
1040 );
1041 }
1042}
1043
1044/// Check whether the key should be intercepted and mark intercepted
1045/// pressed keys as `suppressed`, thus preventing `releases` corresponding
1046/// to them from being delivered.
1047#[allow(clippy::too_many_arguments)]
1048fn should_intercept_key(
1049 suppressed_keys: &mut HashSet<u32>,
1050 bindings: &Binds,
1051 comp_mod: CompositorMod,
1052 key_code: u32,
1053 modified: Keysym,
1054 raw: Option<Keysym>,
1055 pressed: bool,
1056 mods: ModifiersState,
1057 screenshot_ui: &ScreenshotUi,
1058) -> FilterResult<Option<Action>> {
1059 // Actions are only triggered on presses, release of the key
1060 // shouldn't try to intercept anything unless we have marked
1061 // the key to suppress.
1062 if !pressed && !suppressed_keys.contains(&key_code) {
1063 return FilterResult::Forward;
1064 }
1065
1066 let mut final_action = action(bindings, comp_mod, modified, raw, mods);
1067
1068 // Allow only a subset of compositor actions while the screenshot UI is open, since the user
1069 // cannot see the screen.
1070 if screenshot_ui.is_open() {
1071 let mut use_screenshot_ui_action = true;
1072
1073 if let Some(action) = &final_action {
1074 if allowed_during_screenshot(action) {
1075 use_screenshot_ui_action = false;
1076 }
1077 }
1078
1079 if use_screenshot_ui_action {
1080 final_action = screenshot_ui.action(raw, mods);
1081 }
1082 }
1083
1084 match (final_action, pressed) {
1085 (Some(action), true) => {
1086 suppressed_keys.insert(key_code);
1087 FilterResult::Intercept(Some(action))
1088 }
1089 (_, false) => {
1090 suppressed_keys.remove(&key_code);
1091 FilterResult::Intercept(None)
1092 }
1093 (None, true) => FilterResult::Forward,
1094 }
1095}
1096
1097fn action(
1098 bindings: &Binds,
1099 comp_mod: CompositorMod,
1100 modified: Keysym,
1101 raw: Option<Keysym>,
1102 mods: ModifiersState,
1103) -> Option<Action> {
1104 use keysyms::*;
1105
1106 // Handle hardcoded binds.
1107 #[allow(non_upper_case_globals)] // wat
1108 match modified.raw() {
1109 modified @ KEY_XF86Switch_VT_1..=KEY_XF86Switch_VT_12 => {
1110 let vt = (modified - KEY_XF86Switch_VT_1 + 1) as i32;
1111 return Some(Action::ChangeVt(vt));
1112 }
1113 KEY_XF86PowerOff => return Some(Action::Suspend),
1114 _ => (),
1115 }
1116
1117 // Handle configured binds.
1118 let mut modifiers = Modifiers::empty();
1119 if mods.ctrl {
1120 modifiers |= Modifiers::CTRL;
1121 }
1122 if mods.shift {
1123 modifiers |= Modifiers::SHIFT;
1124 }
1125 if mods.alt {
1126 modifiers |= Modifiers::ALT;
1127 }
1128 if mods.logo {
1129 modifiers |= Modifiers::SUPER;
1130 }
1131
1132 let (mod_down, mut comp_mod) = match comp_mod {
1133 CompositorMod::Super => (mods.logo, Modifiers::SUPER),
1134 CompositorMod::Alt => (mods.alt, Modifiers::ALT),
1135 };
1136 if mod_down {
1137 modifiers |= Modifiers::COMPOSITOR;
1138 } else {
1139 comp_mod = Modifiers::empty();
1140 }
1141
1142 let Some(raw) = raw else {
1143 return None;
1144 };
1145
1146 for bind in &bindings.0 {
1147 if bind.key.keysym != raw {
1148 continue;
1149 }
1150
1151 if bind.key.modifiers | comp_mod == modifiers {
1152 return bind.actions.first().cloned();
1153 }
1154 }
1155
1156 None
1157}
1158
1159fn should_activate_monitors<I: InputBackend>(event: &InputEvent<I>) -> bool {
1160 match event {
1161 InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true,
1162 InputEvent::PointerMotion { .. }
1163 | InputEvent::PointerMotionAbsolute { .. }
1164 | InputEvent::PointerButton { .. }
1165 | InputEvent::PointerAxis { .. }
1166 | InputEvent::GestureSwipeBegin { .. }
1167 | InputEvent::GesturePinchBegin { .. }
1168 | InputEvent::GestureHoldBegin { .. }
1169 | InputEvent::TouchDown { .. }
1170 | InputEvent::TouchMotion { .. }
1171 | InputEvent::TabletToolAxis { .. }
1172 | InputEvent::TabletToolProximity { .. }
1173 | InputEvent::TabletToolTip { .. }
1174 | InputEvent::TabletToolButton { .. } => true,
1175 // Ignore events like device additions and removals, key releases, gesture ends.
1176 _ => false,
1177 }
1178}
1179
1180fn allowed_when_locked(action: &Action) -> bool {
1181 matches!(
1182 action,
1183 Action::Quit
1184 | Action::ChangeVt(_)
1185 | Action::Suspend
1186 | Action::PowerOffMonitors
1187 | Action::SwitchLayout(_)
1188 )
1189}
1190
1191fn allowed_during_screenshot(action: &Action) -> bool {
1192 matches!(
1193 action,
1194 Action::Quit | Action::ChangeVt(_) | Action::Suspend | Action::PowerOffMonitors
1195 )
1196}
1197
1198#[cfg(test)]
1199mod tests {
1200 use super::*;
1201 use crate::config::{Action, Bind, Binds, Key, Modifiers};
1202
1203 #[test]
1204 fn bindings_suppress_keys() {
1205 let close_keysym = Keysym::q;
1206 let bindings = Binds(vec![Bind {
1207 key: Key {
1208 keysym: close_keysym,
1209 modifiers: Modifiers::COMPOSITOR | Modifiers::CTRL,
1210 },
1211 actions: vec![Action::CloseWindow],
1212 }]);
1213
1214 let comp_mod = CompositorMod::Super;
1215 let mut suppressed_keys = HashSet::new();
1216
1217 let screenshot_ui = ScreenshotUi::new();
1218
1219 // The key_code we pick is arbitrary, the only thing
1220 // that matters is that they are different between cases.
1221
1222 let close_key_code = close_keysym.into();
1223 let close_key_event = |suppr: &mut HashSet<u32>, mods: ModifiersState, pressed| {
1224 should_intercept_key(
1225 suppr,
1226 &bindings,
1227 comp_mod,
1228 close_key_code,
1229 close_keysym,
1230 Some(close_keysym),
1231 pressed,
1232 mods,
1233 &screenshot_ui,
1234 )
1235 };
1236
1237 // Key event with the code which can't trigger any action.
1238 let none_key_event = |suppr: &mut HashSet<u32>, mods: ModifiersState, pressed| {
1239 should_intercept_key(
1240 suppr,
1241 &bindings,
1242 comp_mod,
1243 Keysym::l.into(),
1244 Keysym::l,
1245 Some(Keysym::l),
1246 pressed,
1247 mods,
1248 &screenshot_ui,
1249 )
1250 };
1251
1252 let mut mods = ModifiersState {
1253 logo: true,
1254 ctrl: true,
1255 ..Default::default()
1256 };
1257
1258 // Action press/release.
1259
1260 let filter = close_key_event(&mut suppressed_keys, mods, true);
1261 assert!(matches!(
1262 filter,
1263 FilterResult::Intercept(Some(Action::CloseWindow))
1264 ));
1265 assert!(suppressed_keys.contains(&close_key_code));
1266
1267 let filter = close_key_event(&mut suppressed_keys, mods, false);
1268 assert!(matches!(filter, FilterResult::Intercept(None)));
1269 assert!(suppressed_keys.is_empty());
1270
1271 // Remove mod to make it for a binding.
1272
1273 mods.shift = true;
1274 let filter = close_key_event(&mut suppressed_keys, mods, true);
1275 assert!(matches!(filter, FilterResult::Forward));
1276
1277 mods.shift = false;
1278 let filter = close_key_event(&mut suppressed_keys, mods, false);
1279 assert!(matches!(filter, FilterResult::Forward));
1280
1281 // Just none press/release.
1282
1283 let filter = none_key_event(&mut suppressed_keys, mods, true);
1284 assert!(matches!(filter, FilterResult::Forward));
1285
1286 let filter = none_key_event(&mut suppressed_keys, mods, false);
1287 assert!(matches!(filter, FilterResult::Forward));
1288
1289 // Press action, press arbitrary, release action, release arbitrary.
1290
1291 let filter = close_key_event(&mut suppressed_keys, mods, true);
1292 assert!(matches!(
1293 filter,
1294 FilterResult::Intercept(Some(Action::CloseWindow))
1295 ));
1296
1297 let filter = none_key_event(&mut suppressed_keys, mods, true);
1298 assert!(matches!(filter, FilterResult::Forward));
1299
1300 let filter = close_key_event(&mut suppressed_keys, mods, false);
1301 assert!(matches!(filter, FilterResult::Intercept(None)));
1302
1303 let filter = none_key_event(&mut suppressed_keys, mods, false);
1304 assert!(matches!(filter, FilterResult::Forward));
1305
1306 // Trigger and remove all mods.
1307
1308 let filter = close_key_event(&mut suppressed_keys, mods, true);
1309 assert!(matches!(
1310 filter,
1311 FilterResult::Intercept(Some(Action::CloseWindow))
1312 ));
1313
1314 mods = Default::default();
1315 let filter = close_key_event(&mut suppressed_keys, mods, false);
1316 assert!(matches!(filter, FilterResult::Intercept(None)));
1317
1318 // Ensure that no keys are being suppressed.
1319 assert!(suppressed_keys.is_empty());
1320 }
1321}