forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBe0ec6e5Ivan Molodetskikh2 years ago752 commits

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