forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9debb5dIvan Molodetskikh2 years ago1485 commits

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