forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBaf6485cIvan Molodetskikh2 years ago725 commits

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