forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBba4e748Ivan Molodetskikh2 years ago794 commits

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