forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBf2ce84bYuya Nishihara2 years ago1130 commits

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