forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBb0eb8adIvan Molodetskikh3 months ago2857 commits

mod.rs5649 lines, 223.7 KiBHistoryRawDownload
1use std::any::Any;
2use std::collections::hash_map::Entry;
3use std::collections::HashSet;
4use std::time::Duration;
5
6use calloop::timer::{TimeoutAction, Timer};
7use input::event::gesture::GestureEventCoordinates as _;
8use niri_config::{
9 Action, Bind, Binds, Config, Key, ModKey, Modifiers, MruDirection, SwitchBinds, Trigger,
10};
11use niri_ipc::LayoutSwitchTarget;
12use smithay::backend::input::{
13 AbsolutePositionEvent, Axis, AxisSource, ButtonState, Device, DeviceCapability, Event,
14 GestureBeginEvent, GestureEndEvent, GesturePinchUpdateEvent as _, GestureSwipeUpdateEvent as _,
15 InputEvent, KeyState, KeyboardKeyEvent, Keycode, MouseButton, PointerAxisEvent,
16 PointerButtonEvent, PointerMotionEvent, ProximityState, Switch, SwitchState, SwitchToggleEvent,
17 TabletToolButtonEvent, TabletToolEvent, TabletToolProximityEvent, TabletToolTipEvent,
18 TabletToolTipState, TouchEvent,
19};
20use smithay::backend::libinput::LibinputInputBackend;
21use smithay::input::dnd::DnDGrab;
22use smithay::input::keyboard::{keysyms, FilterResult, Keysym, Layout, ModifiersState};
23use smithay::input::pointer::{
24 AxisFrame, ButtonEvent, CursorIcon, CursorImageStatus, Focus, GestureHoldBeginEvent,
25 GestureHoldEndEvent, GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent,
26 GestureSwipeBeginEvent, GestureSwipeEndEvent, GestureSwipeUpdateEvent,
27 GrabStartData as PointerGrabStartData, MotionEvent, PointerGrab, RelativeMotionEvent,
28};
29use smithay::input::tablet::tool::GrabStartData as TabletToolGrabStartData;
30use smithay::input::tablet::{TabletDescriptor, TabletSeatHandler, TabletSeatTrait};
31use smithay::input::touch::{
32 DownEvent, GrabStartData as TouchGrabStartData, MotionEvent as TouchMotionEvent, UpEvent,
33};
34use smithay::input::{tablet, SeatHandler};
35use smithay::output::Output;
36use smithay::reexports::wayland_server::protocol::wl_data_source::WlDataSource;
37use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
38use smithay::utils::{Logical, Point, Rectangle, Transform, SERIAL_COUNTER};
39use smithay::wayland::keyboard_shortcuts_inhibit::KeyboardShortcutsInhibitor;
40use smithay::wayland::pointer_constraints::{with_pointer_constraint, PointerConstraint};
41use touch_overview_grab::TouchOverviewGrab;
42
43use self::move_grab::MoveGrab;
44use self::pick_color_grab::PickColorGrab;
45use self::pick_window_grab::PickWindowGrab;
46use self::resize_grab::ResizeGrab;
47use self::spatial_movement_grab::SpatialMovementGrab;
48#[cfg(feature = "dbus")]
49use crate::dbus::freedesktop_a11y::KbMonBlock;
50use crate::layout::scrolling::ScrollDirection;
51use crate::layout::{ActivateWindow, LayoutElement as _};
52use crate::niri::{CastTarget, PointerVisibility, State};
53use crate::ui::mru::{WindowMru, WindowMruUi};
54use crate::ui::screenshot_ui::ScreenshotUi;
55use crate::utils::spawning::{spawn, spawn_sh};
56use crate::utils::{center, get_monotonic_time, CastSessionId, ResizeEdge};
57
58pub mod backend_ext;
59pub mod click_grab;
60pub mod move_grab;
61pub mod pick_color_grab;
62pub mod pick_window_grab;
63pub mod resize_grab;
64pub mod scroll_swipe_gesture;
65pub mod scroll_tracker;
66pub mod spatial_movement_grab;
67pub mod swipe_tracker;
68pub mod touch_overview_grab;
69
70use backend_ext::{NiriInputBackend as InputBackend, NiriInputDevice as _};
71
72pub const DOUBLE_CLICK_TIME: Duration = Duration::from_millis(400);
73
74#[derive(Debug, Clone, Copy, PartialEq)]
75pub struct TabletData {
76 pub aspect_ratio: f64,
77}
78
79pub enum AnyStartData<D: SeatHandler + TabletSeatHandler> {
80 Pointer(PointerGrabStartData<D>),
81 Touch(TouchGrabStartData<D>),
82 TabletTool(TabletToolGrabStartData<D>),
83}
84
85impl<D: SeatHandler + TabletSeatHandler> AnyStartData<D> {
86 pub fn location(&self) -> Point<f64, Logical> {
87 match self {
88 AnyStartData::Pointer(x) => x.location,
89 AnyStartData::Touch(x) => x.location,
90 AnyStartData::TabletTool(x) => x.location,
91 }
92 }
93
94 pub fn unwrap_pointer(&self) -> &PointerGrabStartData<D> {
95 match self {
96 AnyStartData::Pointer(x) => x,
97 AnyStartData::Touch(_) | AnyStartData::TabletTool(_) => {
98 panic!("start_data is not Pointer")
99 }
100 }
101 }
102
103 pub fn unwrap_touch(&self) -> &TouchGrabStartData<D> {
104 match self {
105 AnyStartData::Pointer(_) | AnyStartData::TabletTool(_) => {
106 panic!("start_data is not Touch")
107 }
108 AnyStartData::Touch(x) => x,
109 }
110 }
111
112 pub fn unwrap_tablet_tool(&self) -> &TabletToolGrabStartData<D> {
113 match self {
114 AnyStartData::Pointer(_) | AnyStartData::Touch(_) => {
115 panic!("start_data is not TabletTool")
116 }
117 AnyStartData::TabletTool(x) => x,
118 }
119 }
120
121 pub fn is_pointer(&self) -> bool {
122 matches!(self, Self::Pointer(_))
123 }
124
125 pub fn is_touch(&self) -> bool {
126 matches!(self, Self::Touch(_))
127 }
128
129 pub fn is_tablet_tool(&self) -> bool {
130 matches!(self, Self::TabletTool(_))
131 }
132}
133
134impl State {
135 pub fn process_input_event<I: InputBackend + 'static>(&mut self, event: InputEvent<I>)
136 where
137 I::Device: 'static, // Needed for downcasting.
138 {
139 let _span = tracy_client::span!("process_input_event");
140
141 // Make sure some logic like workspace clean-up has a chance to run before doing actions.
142 self.niri.advance_animations();
143
144 if self.niri.monitors_active {
145 // Notify the idle-notifier of activity.
146 if should_notify_activity(&event) {
147 self.niri.notify_activity();
148 }
149 } else {
150 // Power on monitors if they were off.
151 if should_activate_monitors(&event) {
152 self.niri.activate_monitors(&mut self.backend);
153
154 // Notify the idle-notifier of activity only if we're also powering on the
155 // monitors.
156 self.niri.notify_activity();
157 }
158 }
159
160 if should_reset_pointer_inactivity_timer(&event) {
161 self.niri.reset_pointer_inactivity_timer();
162 }
163
164 let hide_hotkey_overlay =
165 self.niri.hotkey_overlay.is_open() && should_hide_hotkey_overlay(&event);
166
167 let hide_exit_confirm_dialog =
168 self.niri.exit_confirm_dialog.is_open() && should_hide_exit_confirm_dialog(&event);
169
170 let mut consumed_by_a11y = false;
171 use InputEvent::*;
172 match event {
173 DeviceAdded { device } => self.on_device_added(device),
174 DeviceRemoved { device } => self.on_device_removed(device),
175 Keyboard { event } => self.on_keyboard::<I>(event, &mut consumed_by_a11y),
176 PointerMotion { event } => self.on_pointer_motion::<I>(event),
177 PointerMotionAbsolute { event } => self.on_pointer_motion_absolute::<I>(event),
178 PointerButton { event } => self.on_pointer_button::<I>(event),
179 PointerAxis { event } => self.on_pointer_axis::<I>(event),
180 TabletToolAxis { event } => self.on_tablet_tool_axis::<I>(event),
181 TabletToolTip { event } => self.on_tablet_tool_tip::<I>(event),
182 TabletToolProximity { event } => self.on_tablet_tool_proximity::<I>(event),
183 TabletToolButton { event } => self.on_tablet_tool_button::<I>(event),
184 GestureSwipeBegin { event } => self.on_gesture_swipe_begin::<I>(event),
185 GestureSwipeUpdate { event } => self.on_gesture_swipe_update::<I>(event),
186 GestureSwipeEnd { event } => self.on_gesture_swipe_end::<I>(event),
187 GesturePinchBegin { event } => self.on_gesture_pinch_begin::<I>(event),
188 GesturePinchUpdate { event } => self.on_gesture_pinch_update::<I>(event),
189 GesturePinchEnd { event } => self.on_gesture_pinch_end::<I>(event),
190 GestureHoldBegin { event } => self.on_gesture_hold_begin::<I>(event),
191 GestureHoldEnd { event } => self.on_gesture_hold_end::<I>(event),
192 TouchDown { event } => self.on_touch_down::<I>(event),
193 TouchMotion { event } => self.on_touch_motion::<I>(event),
194 TouchUp { event } => self.on_touch_up::<I>(event),
195 TouchCancel { event } => self.on_touch_cancel::<I>(event),
196 TouchFrame { event } => self.on_touch_frame::<I>(event),
197 SwitchToggle { event } => self.on_switch_toggle::<I>(event),
198 Special(_) => (),
199 }
200
201 // Don't hide overlays if consumed by a11y, so that you can use the screen reader
202 // navigation keys.
203 if consumed_by_a11y {
204 return;
205 }
206
207 // Do this last so that screenshot still gets it.
208 if hide_hotkey_overlay && self.niri.hotkey_overlay.hide() {
209 self.niri.queue_redraw_all();
210 }
211
212 if hide_exit_confirm_dialog && self.niri.exit_confirm_dialog.hide() {
213 self.niri.queue_redraw_all();
214 }
215 }
216
217 pub fn process_libinput_event(&mut self, event: &mut InputEvent<LibinputInputBackend>) {
218 let _span = tracy_client::span!("process_libinput_event");
219
220 match event {
221 InputEvent::DeviceAdded { device } => {
222 self.niri.devices.insert(device.clone());
223
224 if device.has_capability(input::DeviceCapability::TabletTool) {
225 match device.size() {
226 Some((w, h)) => {
227 let aspect_ratio = w / h;
228 let data = TabletData { aspect_ratio };
229 self.niri.tablets.insert(device.clone(), data);
230 }
231 None => {
232 warn!("tablet tool device has no size");
233 }
234 }
235 }
236
237 if device.has_capability(input::DeviceCapability::Keyboard) {
238 if let Some(led_state) = self
239 .niri
240 .seat
241 .get_keyboard()
242 .map(|keyboard| keyboard.led_state())
243 {
244 device.led_update(led_state.into());
245 }
246 }
247
248 if device.has_capability(input::DeviceCapability::Touch) {
249 self.niri.touch.insert(device.clone());
250 }
251
252 apply_libinput_settings(&self.niri.config.borrow().input, device);
253 }
254 InputEvent::DeviceRemoved { device } => {
255 self.niri.touch.remove(device);
256 self.niri.tablets.remove(device);
257 self.niri.devices.remove(device);
258 }
259 _ => (),
260 }
261 }
262
263 fn on_device_added(&mut self, device: impl Device) {
264 if device.has_capability(DeviceCapability::TabletTool) {
265 let tablet_seat = self.niri.seat.tablet_seat();
266
267 let desc = TabletDescriptor::from(&device);
268 tablet_seat.add_wp_tablet(&self.niri.display_handle, &desc);
269 }
270 if device.has_capability(DeviceCapability::Touch) && self.niri.seat.get_touch().is_none() {
271 self.niri.seat.add_touch();
272 }
273 }
274
275 fn on_device_removed(&mut self, device: impl Device) {
276 if device.has_capability(DeviceCapability::TabletTool) {
277 let tablet_seat = self.niri.seat.tablet_seat();
278
279 let desc = TabletDescriptor::from(&device);
280 tablet_seat.remove_tablet(&desc);
281
282 // If there are no tablets in seat we can remove all tools
283 if tablet_seat.count_tablets() == 0 {
284 tablet_seat.clear_tools();
285 }
286 }
287 if device.has_capability(DeviceCapability::Touch) && self.niri.touch.is_empty() {
288 self.niri.seat.remove_touch();
289 }
290 }
291
292 /// Computes the rectangle that covers all outputs in global space.
293 fn global_bounding_rectangle(&self) -> Option<Rectangle<i32, Logical>> {
294 self.niri.global_space.outputs().fold(
295 None,
296 |acc: Option<Rectangle<i32, Logical>>, output| {
297 self.niri
298 .global_space
299 .output_geometry(output)
300 .map(|geo| acc.map(|acc| acc.merge(geo)).unwrap_or(geo))
301 },
302 )
303 }
304
305 /// Computes the cursor position for the tablet event.
306 ///
307 /// This function handles the tablet output mapping, as well as coordinate clamping and aspect
308 /// ratio correction.
309 fn compute_tablet_position<I: InputBackend>(
310 &self,
311 event: &(impl Event<I> + TabletToolEvent<I>),
312 ) -> Option<Point<f64, Logical>>
313 where
314 I::Device: 'static,
315 {
316 let device_output = event.device().output(self);
317 let device_output = device_output.filter(|output| self.niri.output_exists(output));
318 let device_output = device_output.as_ref();
319 let mapped_output = device_output.or_else(|| self.niri.output_for_tablet());
320
321 // If the tablet is configured to map to the focused window, use that window's geometry on
322 // the mapped output (or on the focused output if no specific output is mapped).
323 let map_to_focused_window = self.niri.config.borrow().input.tablet.map_to_focused_window;
324 // But only if the keyboard focus is on the layout, so that it doesn't trigger on the lock
325 // screen and such.
326 let window_target = if map_to_focused_window && self.niri.keyboard_focus.is_layout() {
327 let output = mapped_output.or_else(|| self.niri.layout.active_output());
328 output.and_then(|output| {
329 let monitor = self.niri.layout.monitor_for_output(output)?;
330 let mut rect = monitor.active_window_visual_rectangle()?;
331 let output_geo = self.niri.global_space.output_geometry(output)?;
332 rect.loc += output_geo.loc.to_f64();
333 Some((rect, output))
334 })
335 } else {
336 None
337 };
338
339 let (target_geo, keep_ratio, px, transform) = if let Some((rect, output)) = window_target {
340 (
341 rect,
342 true,
343 1. / output.current_scale().fractional_scale(),
344 output.current_transform(),
345 )
346 } else if let Some(output) = mapped_output {
347 let geo = self.niri.global_space.output_geometry(output).unwrap();
348 (
349 geo.to_f64(),
350 true,
351 1. / output.current_scale().fractional_scale(),
352 output.current_transform(),
353 )
354 } else {
355 let geo = self.global_bounding_rectangle()?.to_f64();
356
357 // FIXME: this 1 px size should ideally somehow be computed for the rightmost output
358 // corresponding to the position on the right when clamping.
359 let output = self.niri.global_space.outputs().next().unwrap();
360 let scale = output.current_scale().fractional_scale();
361
362 // Do not keep ratio for the unified mode as this is what OpenTabletDriver expects.
363 (geo, false, 1. / scale, Transform::Normal)
364 };
365
366 let mut pos = {
367 let size = transform.invert().transform_size(target_geo.size);
368 transform.transform_point_in(event.position_transformed(size.to_i32_round()), &size)
369 };
370
371 if keep_ratio {
372 pos.x /= target_geo.size.w;
373 pos.y /= target_geo.size.h;
374
375 let device = event.device();
376 if let Some(device) = (&device as &dyn Any).downcast_ref::<input::Device>() {
377 if let Some(data) = self.niri.tablets.get(device) {
378 // This code does the same thing as mutter with "keep aspect ratio" enabled.
379 let size = transform.invert().transform_size(target_geo.size);
380 let output_aspect_ratio = size.w / size.h;
381 let ratio = data.aspect_ratio / output_aspect_ratio;
382
383 if ratio > 1. {
384 pos.x *= ratio;
385 } else {
386 pos.y /= ratio;
387 }
388 }
389 };
390
391 pos.x *= target_geo.size.w;
392 pos.y *= target_geo.size.h;
393 }
394
395 pos.x = pos.x.clamp(0.0, target_geo.size.w - px);
396 pos.y = pos.y.clamp(0.0, target_geo.size.h - px);
397 Some(pos + target_geo.loc)
398 }
399
400 fn is_inhibiting_shortcuts(&self) -> bool {
401 self.niri
402 .keyboard_focus
403 .surface()
404 .and_then(|surface| {
405 self.niri
406 .keyboard_shortcuts_inhibiting_surfaces
407 .get(surface)
408 })
409 .is_some_and(KeyboardShortcutsInhibitor::is_active)
410 }
411
412 fn on_keyboard<I: InputBackend>(
413 &mut self,
414 event: I::KeyboardKeyEvent,
415 consumed_by_a11y: &mut bool,
416 ) {
417 let mod_key = self.backend.mod_key(&self.niri.config.borrow());
418
419 let serial = SERIAL_COUNTER.next_serial();
420 let time = Event::time_msec(&event);
421 let pressed = event.state() == KeyState::Pressed;
422
423 // Stop bind key repeat on any release. This won't work 100% correctly in cases like:
424 // 1. Press Mod
425 // 2. Press Left (repeat starts)
426 // 3. Press PgDown (new repeat starts)
427 // 4. Release Left (PgDown repeat stops)
428 // But it's good enough for now.
429 // FIXME: handle this properly.
430 if !pressed {
431 if let Some(token) = self.niri.bind_repeat_timer.take() {
432 self.niri.event_loop.remove(token);
433 }
434 }
435
436 if pressed {
437 self.hide_cursor_if_needed();
438 }
439
440 let is_inhibiting_shortcuts = self.is_inhibiting_shortcuts();
441
442 // Accessibility modifier grabs should override XKB state changes (e.g. Caps Lock), so we
443 // need to process them before keyboard.input() below.
444 //
445 // Other accessibility-grabbed keys should still update our XKB state, but not cause any
446 // other changes.
447 #[cfg(feature = "dbus")]
448 let block = {
449 let block = self.a11y_process_key(
450 Duration::from_millis(u64::from(time)),
451 event.key_code(),
452 event.state(),
453 );
454 if block != KbMonBlock::Pass {
455 *consumed_by_a11y = true;
456 }
457 // The accessibility modifier first press must not change XKB state, so we return
458 // early here.
459 if block == KbMonBlock::ModifierFirstPress {
460 return;
461 }
462 block
463 };
464 #[cfg(not(feature = "dbus"))]
465 let _ = consumed_by_a11y;
466
467 let Some(Some(bind)) = self.niri.seat.get_keyboard().unwrap().input(
468 self,
469 event.key_code(),
470 event.state(),
471 serial,
472 time,
473 |this, mods, keysym| {
474 let key_code = event.key_code();
475 let modified = keysym.modified_sym();
476 let raw = keysym.raw_latin_sym_or_raw_current_sym();
477 let modifiers = modifiers_from_state(*mods);
478
479 // After updating XKB state from accessibility-grabbed keys, return right away and
480 // don't handle them.
481 #[cfg(feature = "dbus")]
482 if block != KbMonBlock::Pass {
483 // HACK: there's a slight problem with this code. Here we filter out keys
484 // consumed by accessibility from getting sent to the Wayland client. However,
485 // the Wayland client can still receive these keys from the wl_keyboard
486 // enter/modifiers events. In particular, this can easily happen when opening
487 // the Orca actions menu with Orca + Shift + A: in most cases, when this menu
488 // opens, Shift is still held down, so the menu receives it in
489 // wl_keyboard.enter/modifiers. Then the menu won't react to Enter presses
490 // until the user taps Shift again to "release" it (since the initial Shift
491 // release will be intercepted here).
492 //
493 // I don't think there's any good way of dealing with this apart from keeping a
494 // separate xkb state for accessibility, so that we can track the pressed
495 // modifiers without accidentally leaking them to wl_keyboard.enter. So for now
496 // let's forward modifier releases to the clients here to deal with the most
497 // common case.
498 if !pressed
499 && matches!(
500 modified,
501 Keysym::Shift_L
502 | Keysym::Shift_R
503 | Keysym::Control_L
504 | Keysym::Control_R
505 | Keysym::Super_L
506 | Keysym::Super_R
507 | Keysym::Alt_L
508 | Keysym::Alt_R
509 )
510 {
511 return FilterResult::Forward;
512 } else {
513 return FilterResult::Intercept(None);
514 }
515 }
516
517 if this.niri.exit_confirm_dialog.is_open() && pressed {
518 if raw == Some(Keysym::Return) {
519 info!("quitting after confirming exit dialog");
520 this.niri.stop_signal.stop();
521 }
522
523 // Don't send this press to any clients.
524 this.niri.suppressed_keys.insert(key_code);
525 return FilterResult::Intercept(None);
526 }
527
528 // Check if all modifiers were released while the MRU UI was open. If so, close the
529 // UI (which will also transfer the focus to the current MRU UI selection).
530 if this.niri.window_mru_ui.is_open() && !pressed && modifiers.is_empty() {
531 this.do_action(Action::MruConfirm, false);
532
533 if this.niri.suppressed_keys.remove(&key_code) {
534 return FilterResult::Intercept(None);
535 } else {
536 return FilterResult::Forward;
537 }
538 }
539
540 if pressed && raw == Some(Keysym::Escape) {
541 // Cancel certain grabs on Escape.
542 let pointer = this.niri.seat.get_pointer().unwrap();
543 if pointer
544 .with_grab(|_, grab| Self::grab_can_be_cancelled_with_esc(grab))
545 .unwrap_or(false)
546 {
547 pointer.unset_grab(this, serial, time);
548 this.niri.suppressed_keys.insert(key_code);
549 return FilterResult::Intercept(None);
550 }
551 }
552
553 if let Some(Keysym::space) = raw {
554 this.niri.screenshot_ui.set_space_down(pressed);
555 }
556
557 let res = {
558 let config = this.niri.config.borrow();
559 let bindings =
560 make_binds_iter(&config, &mut this.niri.window_mru_ui, modifiers);
561
562 should_intercept_key(
563 &mut this.niri.suppressed_keys,
564 bindings,
565 mod_key,
566 key_code,
567 modified,
568 raw,
569 pressed,
570 *mods,
571 &this.niri.screenshot_ui,
572 this.niri.config.borrow().input.disable_power_key_handling,
573 is_inhibiting_shortcuts,
574 )
575 };
576
577 if matches!(res, FilterResult::Forward) {
578 // If we didn't find any bind, try other hardcoded keys.
579 if this.niri.keyboard_focus.is_overview() && pressed {
580 if let Some(bind) = raw.and_then(|raw| hardcoded_overview_bind(raw, *mods))
581 {
582 this.niri.suppressed_keys.insert(key_code);
583 return FilterResult::Intercept(Some(bind));
584 }
585 }
586
587 // Interaction with the active window, immediately update the active window's
588 // focus timestamp without waiting for a possible pending MRU lock-in delay.
589 this.niri.mru_apply_keyboard_commit();
590 }
591
592 res
593 },
594 ) else {
595 return;
596 };
597
598 if !pressed {
599 return;
600 }
601
602 self.handle_bind(bind.clone());
603
604 self.start_key_repeat(bind);
605 }
606
607 fn start_key_repeat(&mut self, bind: Bind) {
608 if !bind.repeat {
609 return;
610 }
611
612 // Stop the previous key repeat if any.
613 if let Some(token) = self.niri.bind_repeat_timer.take() {
614 self.niri.event_loop.remove(token);
615 }
616
617 let config = self.niri.config.borrow();
618 let config = &config.input.keyboard;
619
620 let repeat_rate = config.repeat_rate;
621 if repeat_rate == 0 {
622 return;
623 }
624 let repeat_duration = Duration::from_secs_f64(1. / f64::from(repeat_rate));
625
626 let repeat_timer =
627 Timer::from_duration(Duration::from_millis(u64::from(config.repeat_delay)));
628
629 let token = self
630 .niri
631 .event_loop
632 .insert_source(repeat_timer, move |_, _, state| {
633 state.handle_bind(bind.clone());
634 TimeoutAction::ToDuration(repeat_duration)
635 })
636 .unwrap();
637
638 self.niri.bind_repeat_timer = Some(token);
639 }
640
641 fn hide_cursor_if_needed(&mut self) {
642 // If the pointer is already invisible, don't reset it back to Hidden causing one frame
643 // of hover.
644 if !self.niri.pointer_visibility.is_visible() {
645 return;
646 }
647
648 if !self.niri.config.borrow().cursor.hide_when_typing {
649 return;
650 }
651
652 // niri keeps this set only while actively using a tablet, which means the cursor position
653 // is likely to change almost immediately, causing pointer_visibility to just flicker back
654 // and forth.
655 if self.niri.tablet_cursor_location.is_some() {
656 return;
657 }
658
659 self.niri.pointer_visibility = PointerVisibility::Hidden;
660 self.niri.queue_redraw_all();
661 }
662
663 pub fn handle_bind(&mut self, bind: Bind) {
664 let Some(cooldown) = bind.cooldown else {
665 self.do_action(bind.action, bind.allow_when_locked);
666 return;
667 };
668
669 // Check this first so that it doesn't trigger the cooldown.
670 if self.niri.is_locked() && !(bind.allow_when_locked || allowed_when_locked(&bind.action)) {
671 return;
672 }
673
674 match self.niri.bind_cooldown_timers.entry(bind.key) {
675 // The bind is on cooldown.
676 Entry::Occupied(_) => (),
677 Entry::Vacant(entry) => {
678 let timer = Timer::from_duration(cooldown);
679 let token = self
680 .niri
681 .event_loop
682 .insert_source(timer, move |_, _, state| {
683 if state.niri.bind_cooldown_timers.remove(&bind.key).is_none() {
684 error!("bind cooldown timer entry disappeared");
685 }
686 TimeoutAction::Drop
687 })
688 .unwrap();
689 entry.insert(token);
690
691 self.do_action(bind.action, bind.allow_when_locked);
692 }
693 }
694 }
695
696 pub fn do_action(&mut self, action: Action, allow_when_locked: bool) {
697 if self.niri.is_locked() && !(allow_when_locked || allowed_when_locked(&action)) {
698 return;
699 }
700
701 if let Some(touch) = self.niri.seat.get_touch() {
702 touch.cancel(self);
703 }
704
705 match action {
706 Action::Quit(skip_confirmation) => {
707 if !skip_confirmation && self.niri.exit_confirm_dialog.show() {
708 self.niri.queue_redraw_all();
709 return;
710 }
711
712 info!("quitting as requested");
713 self.niri.stop_signal.stop()
714 }
715 Action::ChangeVt(vt) => {
716 self.backend.change_vt(vt);
717 // Changing VT may not deliver the key releases, so clear the state.
718 self.niri.suppressed_keys.clear();
719 }
720 Action::Suspend => {
721 self.backend.suspend();
722 // Suspend may not deliver the key releases, so clear the state.
723 self.niri.suppressed_keys.clear();
724 }
725 Action::PowerOffMonitors => {
726 self.niri.deactivate_monitors(&mut self.backend);
727 }
728 Action::PowerOnMonitors => {
729 self.niri.activate_monitors(&mut self.backend);
730 }
731 Action::ToggleDebugTint => {
732 self.backend.toggle_debug_tint();
733 self.niri.queue_redraw_all();
734 }
735 Action::DebugToggleOpaqueRegions => {
736 self.niri.debug_draw_opaque_regions = !self.niri.debug_draw_opaque_regions;
737 self.niri.queue_redraw_all();
738 }
739 Action::DebugToggleDamage => {
740 self.niri.debug_toggle_damage();
741 }
742 Action::Spawn(command) => {
743 let (token, _) = self.niri.activation_state.create_external_token(None);
744 spawn(command, Some(token.clone()));
745 }
746 Action::SpawnSh(command) => {
747 let (token, _) = self.niri.activation_state.create_external_token(None);
748 spawn_sh(command, Some(token.clone()));
749 }
750 Action::DoScreenTransition(delay_ms) => {
751 self.backend.with_primary_renderer(|renderer| {
752 self.niri.do_screen_transition(renderer, delay_ms);
753 });
754 }
755 Action::ScreenshotScreen(write_to_disk, show_pointer, path) => {
756 let active = self.niri.layout.active_output().cloned();
757 if let Some(active) = active {
758 self.backend.with_primary_renderer(|renderer| {
759 if let Err(err) = self.niri.screenshot(
760 renderer,
761 &active,
762 write_to_disk,
763 show_pointer,
764 path,
765 ) {
766 warn!("error taking screenshot: {err:?}");
767 }
768 });
769 }
770 }
771 Action::ConfirmScreenshot { write_to_disk } => {
772 self.confirm_screenshot(write_to_disk);
773 }
774 Action::CancelScreenshot => {
775 if !self.niri.screenshot_ui.is_open() {
776 return;
777 }
778
779 self.niri.screenshot_ui.close();
780 self.niri
781 .cursor_manager
782 .set_cursor_image(CursorImageStatus::default_named());
783 self.niri.queue_redraw_all();
784 }
785 Action::ScreenshotTogglePointer => {
786 self.niri.screenshot_ui.toggle_pointer();
787 self.niri.queue_redraw_all();
788 }
789 Action::Screenshot(show_cursor, path) => {
790 self.open_screenshot_ui(show_cursor, path);
791 self.niri.cancel_mru();
792 }
793 Action::ScreenshotWindow(write_to_disk, show_pointer, path) => {
794 let focus = self.niri.layout.focus_with_output();
795 if let Some((mapped, output)) = focus {
796 self.backend.with_primary_renderer(|renderer| {
797 if let Err(err) = self.niri.screenshot_window(
798 renderer,
799 output,
800 mapped,
801 write_to_disk,
802 show_pointer,
803 path,
804 ) {
805 warn!("error taking screenshot: {err:?}");
806 }
807 });
808 }
809 }
810 Action::ScreenshotWindowById {
811 id,
812 write_to_disk,
813 show_pointer,
814 path,
815 } => {
816 let mut windows = self.niri.layout.windows();
817 let window = windows.find(|(_, m)| m.id().get() == id);
818 if let Some((Some(monitor), mapped)) = window {
819 let output = monitor.output();
820 self.backend.with_primary_renderer(|renderer| {
821 if let Err(err) = self.niri.screenshot_window(
822 renderer,
823 output,
824 mapped,
825 write_to_disk,
826 show_pointer,
827 path,
828 ) {
829 warn!("error taking screenshot: {err:?}");
830 }
831 });
832 }
833 }
834 Action::ToggleKeyboardShortcutsInhibit => {
835 if let Some(inhibitor) = self.niri.keyboard_focus.surface().and_then(|surface| {
836 self.niri
837 .keyboard_shortcuts_inhibiting_surfaces
838 .get(surface)
839 }) {
840 if inhibitor.is_active() {
841 inhibitor.inactivate();
842 } else {
843 inhibitor.activate();
844 }
845 }
846 }
847 Action::CloseWindow => {
848 if let Some(mapped) = self.niri.layout.focus() {
849 mapped.toplevel().send_close();
850 }
851 }
852 Action::CloseWindowById(id) => {
853 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
854 if let Some((_, mapped)) = window {
855 mapped.toplevel().send_close();
856 }
857 }
858 Action::FullscreenWindow => {
859 let focus = self.niri.layout.focus().map(|m| m.window.clone());
860 if let Some(window) = focus {
861 self.niri.layout.toggle_fullscreen(&window);
862 // FIXME: granular
863 self.niri.queue_redraw_all();
864 }
865 }
866 Action::FullscreenWindowById(id) => {
867 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
868 let window = window.map(|(_, m)| m.window.clone());
869 if let Some(window) = window {
870 self.niri.layout.toggle_fullscreen(&window);
871 // FIXME: granular
872 self.niri.queue_redraw_all();
873 }
874 }
875 Action::ToggleWindowedFullscreen => {
876 let focus = self.niri.layout.focus().map(|m| m.window.clone());
877 if let Some(window) = focus {
878 self.niri.layout.toggle_windowed_fullscreen(&window);
879 // FIXME: granular
880 self.niri.queue_redraw_all();
881 }
882 }
883 Action::ToggleWindowedFullscreenById(id) => {
884 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
885 let window = window.map(|(_, m)| m.window.clone());
886 if let Some(window) = window {
887 self.niri.layout.toggle_windowed_fullscreen(&window);
888 // FIXME: granular
889 self.niri.queue_redraw_all();
890 }
891 }
892 Action::FocusWindow(id) => {
893 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
894 let window = window.map(|(_, m)| m.window.clone());
895 if let Some(window) = window {
896 self.focus_window(&window);
897 }
898 }
899 Action::FocusWindowInColumn(index) => {
900 self.niri.layout.focus_window_in_column(index);
901 self.maybe_warp_cursor_to_focus();
902 self.niri.layer_shell_on_demand_focus = None;
903 // FIXME: granular
904 self.niri.queue_redraw_all();
905 }
906 Action::FocusWindowPrevious => {
907 let current = self.niri.layout.focus().map(|win| win.id());
908 if let Some(window) = self
909 .niri
910 .layout
911 .windows()
912 .map(|(_, win)| win)
913 .filter(|win| Some(win.id()) != current)
914 .max_by_key(|win| win.get_focus_timestamp())
915 .map(|win| win.window.clone())
916 {
917 // Commit current focus so repeated focus-window-previous works as expected.
918 self.niri.mru_apply_keyboard_commit();
919
920 self.focus_window(&window);
921 }
922 }
923 Action::SwitchLayout(action) => {
924 let keyboard = &self.niri.seat.get_keyboard().unwrap();
925 keyboard.with_xkb_state(self, |mut state| match action {
926 LayoutSwitchTarget::Next => state.cycle_next_layout(),
927 LayoutSwitchTarget::Prev => state.cycle_prev_layout(),
928 LayoutSwitchTarget::Index(layout) => {
929 let num_layouts = state.xkb().lock().unwrap().layouts().count();
930 if usize::from(layout) >= num_layouts {
931 warn!("requested layout doesn't exist")
932 } else {
933 state.set_layout(Layout(layout.into()))
934 }
935 }
936 });
937 }
938 Action::MoveColumnLeft => {
939 if self.niri.screenshot_ui.is_open() {
940 self.niri.screenshot_ui.move_left();
941 } else {
942 self.niri.layout.move_left();
943 self.maybe_warp_cursor_to_focus();
944 }
945
946 // FIXME: granular
947 self.niri.queue_redraw_all();
948 }
949 Action::MoveColumnRight => {
950 if self.niri.screenshot_ui.is_open() {
951 self.niri.screenshot_ui.move_right();
952 } else {
953 self.niri.layout.move_right();
954 self.maybe_warp_cursor_to_focus();
955 }
956
957 // FIXME: granular
958 self.niri.queue_redraw_all();
959 }
960 Action::MoveColumnToFirst => {
961 self.niri.layout.move_column_to_first();
962 self.maybe_warp_cursor_to_focus();
963 // FIXME: granular
964 self.niri.queue_redraw_all();
965 }
966 Action::MoveColumnToLast => {
967 self.niri.layout.move_column_to_last();
968 self.maybe_warp_cursor_to_focus();
969 // FIXME: granular
970 self.niri.queue_redraw_all();
971 }
972 Action::MoveColumnLeftOrToMonitorLeft => {
973 if self.niri.screenshot_ui.is_open() {
974 self.niri.screenshot_ui.move_left();
975 } else if let Some(output) = self.niri.output_left() {
976 if self.niri.layout.move_column_left_or_to_output(&output)
977 && !self.maybe_warp_cursor_to_focus_centered()
978 {
979 self.move_cursor_to_output(&output);
980 } else {
981 self.maybe_warp_cursor_to_focus();
982 }
983 } else {
984 self.niri.layout.move_left();
985 self.maybe_warp_cursor_to_focus();
986 }
987
988 // FIXME: granular
989 self.niri.queue_redraw_all();
990 }
991 Action::MoveColumnRightOrToMonitorRight => {
992 if self.niri.screenshot_ui.is_open() {
993 self.niri.screenshot_ui.move_right();
994 } else if let Some(output) = self.niri.output_right() {
995 if self.niri.layout.move_column_right_or_to_output(&output)
996 && !self.maybe_warp_cursor_to_focus_centered()
997 {
998 self.move_cursor_to_output(&output);
999 } else {
1000 self.maybe_warp_cursor_to_focus();
1001 }
1002 } else {
1003 self.niri.layout.move_right();
1004 self.maybe_warp_cursor_to_focus();
1005 }
1006
1007 // FIXME: granular
1008 self.niri.queue_redraw_all();
1009 }
1010 Action::MoveWindowDown => {
1011 if self.niri.screenshot_ui.is_open() {
1012 self.niri.screenshot_ui.move_down();
1013 } else {
1014 self.niri.layout.move_down();
1015 self.maybe_warp_cursor_to_focus();
1016 }
1017
1018 // FIXME: granular
1019 self.niri.queue_redraw_all();
1020 }
1021 Action::MoveWindowUp => {
1022 if self.niri.screenshot_ui.is_open() {
1023 self.niri.screenshot_ui.move_up();
1024 } else {
1025 self.niri.layout.move_up();
1026 self.maybe_warp_cursor_to_focus();
1027 }
1028
1029 // FIXME: granular
1030 self.niri.queue_redraw_all();
1031 }
1032 Action::MoveWindowDownOrToWorkspaceDown => {
1033 if self.niri.screenshot_ui.is_open() {
1034 self.niri.screenshot_ui.move_down();
1035 } else {
1036 self.niri.layout.move_down_or_to_workspace_down();
1037 self.maybe_warp_cursor_to_focus();
1038 }
1039 // FIXME: granular
1040 self.niri.queue_redraw_all();
1041 }
1042 Action::MoveWindowUpOrToWorkspaceUp => {
1043 if self.niri.screenshot_ui.is_open() {
1044 self.niri.screenshot_ui.move_up();
1045 } else {
1046 self.niri.layout.move_up_or_to_workspace_up();
1047 self.maybe_warp_cursor_to_focus();
1048 }
1049 // FIXME: granular
1050 self.niri.queue_redraw_all();
1051 }
1052 Action::ConsumeOrExpelWindowLeft => {
1053 self.niri.layout.consume_or_expel_window_left(None);
1054 self.maybe_warp_cursor_to_focus();
1055 // FIXME: granular
1056 self.niri.queue_redraw_all();
1057 }
1058 Action::ConsumeOrExpelWindowLeftById(id) => {
1059 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1060 let window = window.map(|(_, m)| m.window.clone());
1061 if let Some(window) = window {
1062 self.niri.layout.consume_or_expel_window_left(Some(&window));
1063 self.maybe_warp_cursor_to_focus();
1064 // FIXME: granular
1065 self.niri.queue_redraw_all();
1066 }
1067 }
1068 Action::ConsumeOrExpelWindowRight => {
1069 self.niri.layout.consume_or_expel_window_right(None);
1070 self.maybe_warp_cursor_to_focus();
1071 // FIXME: granular
1072 self.niri.queue_redraw_all();
1073 }
1074 Action::ConsumeOrExpelWindowRightById(id) => {
1075 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1076 let window = window.map(|(_, m)| m.window.clone());
1077 if let Some(window) = window {
1078 self.niri
1079 .layout
1080 .consume_or_expel_window_right(Some(&window));
1081 self.maybe_warp_cursor_to_focus();
1082 // FIXME: granular
1083 self.niri.queue_redraw_all();
1084 }
1085 }
1086 Action::FocusColumnLeft => {
1087 self.niri.layout.focus_left();
1088 self.maybe_warp_cursor_to_focus();
1089 self.niri.layer_shell_on_demand_focus = None;
1090 // FIXME: granular
1091 self.niri.queue_redraw_all();
1092 }
1093 Action::FocusColumnLeftUnderMouse => {
1094 if let Some((output, ws)) = self.niri.workspace_under_cursor(true) {
1095 let ws_id = ws.id();
1096 let ws = {
1097 let mut workspaces = self.niri.layout.workspaces_mut();
1098 workspaces.find(|ws| ws.id() == ws_id).unwrap()
1099 };
1100 ws.focus_left();
1101 self.maybe_warp_cursor_to_focus();
1102 self.niri.layer_shell_on_demand_focus = None;
1103 self.niri.queue_redraw(&output);
1104 }
1105 }
1106 Action::FocusColumnRight => {
1107 self.niri.layout.focus_right();
1108 self.maybe_warp_cursor_to_focus();
1109 self.niri.layer_shell_on_demand_focus = None;
1110 // FIXME: granular
1111 self.niri.queue_redraw_all();
1112 }
1113 Action::FocusColumnRightUnderMouse => {
1114 if let Some((output, ws)) = self.niri.workspace_under_cursor(true) {
1115 let ws_id = ws.id();
1116 let ws = {
1117 let mut workspaces = self.niri.layout.workspaces_mut();
1118 workspaces.find(|ws| ws.id() == ws_id).unwrap()
1119 };
1120 ws.focus_right();
1121 self.maybe_warp_cursor_to_focus();
1122 self.niri.layer_shell_on_demand_focus = None;
1123 self.niri.queue_redraw(&output);
1124 }
1125 }
1126 Action::FocusColumnFirst => {
1127 self.niri.layout.focus_column_first();
1128 self.maybe_warp_cursor_to_focus();
1129 self.niri.layer_shell_on_demand_focus = None;
1130 // FIXME: granular
1131 self.niri.queue_redraw_all();
1132 }
1133 Action::FocusColumnLast => {
1134 self.niri.layout.focus_column_last();
1135 self.maybe_warp_cursor_to_focus();
1136 self.niri.layer_shell_on_demand_focus = None;
1137 // FIXME: granular
1138 self.niri.queue_redraw_all();
1139 }
1140 Action::FocusColumnRightOrFirst => {
1141 self.niri.layout.focus_column_right_or_first();
1142 self.maybe_warp_cursor_to_focus();
1143 self.niri.layer_shell_on_demand_focus = None;
1144 // FIXME: granular
1145 self.niri.queue_redraw_all();
1146 }
1147 Action::FocusColumnLeftOrLast => {
1148 self.niri.layout.focus_column_left_or_last();
1149 self.maybe_warp_cursor_to_focus();
1150 self.niri.layer_shell_on_demand_focus = None;
1151 // FIXME: granular
1152 self.niri.queue_redraw_all();
1153 }
1154 Action::FocusColumn(index) => {
1155 self.niri.layout.focus_column(index);
1156 self.maybe_warp_cursor_to_focus();
1157 self.niri.layer_shell_on_demand_focus = None;
1158 // FIXME: granular
1159 self.niri.queue_redraw_all();
1160 }
1161 Action::FocusWindowOrMonitorUp => {
1162 if let Some(output) = self.niri.output_up() {
1163 if self.niri.layout.focus_window_up_or_output(&output)
1164 && !self.maybe_warp_cursor_to_focus_centered()
1165 {
1166 self.move_cursor_to_output(&output);
1167 } else {
1168 self.maybe_warp_cursor_to_focus();
1169 }
1170 } else {
1171 self.niri.layout.focus_up();
1172 self.maybe_warp_cursor_to_focus();
1173 }
1174 self.niri.layer_shell_on_demand_focus = None;
1175
1176 // FIXME: granular
1177 self.niri.queue_redraw_all();
1178 }
1179 Action::FocusWindowOrMonitorDown => {
1180 if let Some(output) = self.niri.output_down() {
1181 if self.niri.layout.focus_window_down_or_output(&output)
1182 && !self.maybe_warp_cursor_to_focus_centered()
1183 {
1184 self.move_cursor_to_output(&output);
1185 } else {
1186 self.maybe_warp_cursor_to_focus();
1187 }
1188 } else {
1189 self.niri.layout.focus_down();
1190 self.maybe_warp_cursor_to_focus();
1191 }
1192 self.niri.layer_shell_on_demand_focus = None;
1193
1194 // FIXME: granular
1195 self.niri.queue_redraw_all();
1196 }
1197 Action::FocusColumnOrMonitorLeft => {
1198 if let Some(output) = self.niri.output_left() {
1199 if self.niri.layout.focus_column_left_or_output(&output)
1200 && !self.maybe_warp_cursor_to_focus_centered()
1201 {
1202 self.move_cursor_to_output(&output);
1203 } else {
1204 self.maybe_warp_cursor_to_focus();
1205 }
1206 } else {
1207 self.niri.layout.focus_left();
1208 self.maybe_warp_cursor_to_focus();
1209 }
1210 self.niri.layer_shell_on_demand_focus = None;
1211
1212 // FIXME: granular
1213 self.niri.queue_redraw_all();
1214 }
1215 Action::FocusColumnOrMonitorRight => {
1216 if let Some(output) = self.niri.output_right() {
1217 if self.niri.layout.focus_column_right_or_output(&output)
1218 && !self.maybe_warp_cursor_to_focus_centered()
1219 {
1220 self.move_cursor_to_output(&output);
1221 } else {
1222 self.maybe_warp_cursor_to_focus();
1223 }
1224 } else {
1225 self.niri.layout.focus_right();
1226 self.maybe_warp_cursor_to_focus();
1227 }
1228 self.niri.layer_shell_on_demand_focus = None;
1229
1230 // FIXME: granular
1231 self.niri.queue_redraw_all();
1232 }
1233 Action::FocusWindowDown => {
1234 self.niri.layout.focus_down();
1235 self.maybe_warp_cursor_to_focus();
1236 self.niri.layer_shell_on_demand_focus = None;
1237 // FIXME: granular
1238 self.niri.queue_redraw_all();
1239 }
1240 Action::FocusWindowUp => {
1241 self.niri.layout.focus_up();
1242 self.maybe_warp_cursor_to_focus();
1243 self.niri.layer_shell_on_demand_focus = None;
1244 // FIXME: granular
1245 self.niri.queue_redraw_all();
1246 }
1247 Action::FocusWindowDownOrColumnLeft => {
1248 self.niri.layout.focus_down_or_left();
1249 self.maybe_warp_cursor_to_focus();
1250 self.niri.layer_shell_on_demand_focus = None;
1251 // FIXME: granular
1252 self.niri.queue_redraw_all();
1253 }
1254 Action::FocusWindowDownOrColumnRight => {
1255 self.niri.layout.focus_down_or_right();
1256 self.maybe_warp_cursor_to_focus();
1257 self.niri.layer_shell_on_demand_focus = None;
1258 // FIXME: granular
1259 self.niri.queue_redraw_all();
1260 }
1261 Action::FocusWindowUpOrColumnLeft => {
1262 self.niri.layout.focus_up_or_left();
1263 self.maybe_warp_cursor_to_focus();
1264 self.niri.layer_shell_on_demand_focus = None;
1265 // FIXME: granular
1266 self.niri.queue_redraw_all();
1267 }
1268 Action::FocusWindowUpOrColumnRight => {
1269 self.niri.layout.focus_up_or_right();
1270 self.maybe_warp_cursor_to_focus();
1271 self.niri.layer_shell_on_demand_focus = None;
1272 // FIXME: granular
1273 self.niri.queue_redraw_all();
1274 }
1275 Action::FocusWindowOrWorkspaceDown => {
1276 self.niri.layout.focus_window_or_workspace_down();
1277 self.maybe_warp_cursor_to_focus();
1278 self.niri.layer_shell_on_demand_focus = None;
1279 // FIXME: granular
1280 self.niri.queue_redraw_all();
1281 }
1282 Action::FocusWindowOrWorkspaceUp => {
1283 self.niri.layout.focus_window_or_workspace_up();
1284 self.maybe_warp_cursor_to_focus();
1285 self.niri.layer_shell_on_demand_focus = None;
1286 // FIXME: granular
1287 self.niri.queue_redraw_all();
1288 }
1289 Action::FocusWindowTop => {
1290 self.niri.layout.focus_window_top();
1291 self.maybe_warp_cursor_to_focus();
1292 self.niri.layer_shell_on_demand_focus = None;
1293 // FIXME: granular
1294 self.niri.queue_redraw_all();
1295 }
1296 Action::FocusWindowBottom => {
1297 self.niri.layout.focus_window_bottom();
1298 self.maybe_warp_cursor_to_focus();
1299 self.niri.layer_shell_on_demand_focus = None;
1300 // FIXME: granular
1301 self.niri.queue_redraw_all();
1302 }
1303 Action::FocusWindowDownOrTop => {
1304 self.niri.layout.focus_window_down_or_top();
1305 self.maybe_warp_cursor_to_focus();
1306 self.niri.layer_shell_on_demand_focus = None;
1307 // FIXME: granular
1308 self.niri.queue_redraw_all();
1309 }
1310 Action::FocusWindowUpOrBottom => {
1311 self.niri.layout.focus_window_up_or_bottom();
1312 self.maybe_warp_cursor_to_focus();
1313 self.niri.layer_shell_on_demand_focus = None;
1314 // FIXME: granular
1315 self.niri.queue_redraw_all();
1316 }
1317 Action::MoveWindowToWorkspaceDown(focus) => {
1318 self.niri.layout.move_to_workspace_down(focus);
1319 self.maybe_warp_cursor_to_focus();
1320 // FIXME: granular
1321 self.niri.queue_redraw_all();
1322 }
1323 Action::MoveWindowToWorkspaceUp(focus) => {
1324 self.niri.layout.move_to_workspace_up(focus);
1325 self.maybe_warp_cursor_to_focus();
1326 // FIXME: granular
1327 self.niri.queue_redraw_all();
1328 }
1329 Action::MoveWindowToWorkspace(reference, focus) => {
1330 if let Some((mut output, index)) =
1331 self.niri.find_output_and_workspace_index(reference)
1332 {
1333 // The source output is always the active output, so if the target output is
1334 // also the active output, we don't need to use move_to_output().
1335 if let Some(active) = self.niri.layout.active_output() {
1336 if output.as_ref() == Some(active) {
1337 output = None;
1338 }
1339 }
1340
1341 let activate = if focus {
1342 ActivateWindow::Smart
1343 } else {
1344 ActivateWindow::No
1345 };
1346
1347 if let Some(output) = output {
1348 self.niri
1349 .layout
1350 .move_to_output(None, &output, Some(index), activate);
1351
1352 if focus {
1353 if !self.maybe_warp_cursor_to_focus_centered() {
1354 self.move_cursor_to_output(&output);
1355 }
1356 } else {
1357 self.maybe_warp_cursor_to_focus();
1358 }
1359 } else {
1360 self.niri.layout.move_to_workspace(None, index, activate);
1361 self.maybe_warp_cursor_to_focus();
1362 }
1363
1364 // FIXME: granular
1365 self.niri.queue_redraw_all();
1366 }
1367 }
1368 Action::MoveWindowToWorkspaceById {
1369 window_id: id,
1370 reference,
1371 focus,
1372 } => {
1373 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1374 let window = window.map(|(_, m)| m.window.clone());
1375 if let Some(window) = window {
1376 if let Some((output, index)) =
1377 self.niri.find_output_and_workspace_index(reference)
1378 {
1379 let target_was_active = self
1380 .niri
1381 .layout
1382 .active_output()
1383 .is_some_and(|active| output.as_ref() == Some(active));
1384
1385 let activate = if focus {
1386 ActivateWindow::Smart
1387 } else {
1388 ActivateWindow::No
1389 };
1390
1391 if let Some(output) = output {
1392 self.niri.layout.move_to_output(
1393 Some(&window),
1394 &output,
1395 Some(index),
1396 activate,
1397 );
1398
1399 // If the active output changed (window was moved and focused).
1400 #[allow(clippy::collapsible_if)]
1401 if !target_was_active
1402 && self.niri.layout.active_output() == Some(&output)
1403 {
1404 if !self.maybe_warp_cursor_to_focus_centered() {
1405 self.move_cursor_to_output(&output);
1406 }
1407 }
1408 } else {
1409 self.niri
1410 .layout
1411 .move_to_workspace(Some(&window), index, activate);
1412
1413 // If we focused the target window.
1414 let new_focus = self.niri.layout.focus();
1415 if new_focus.is_some_and(|win| win.window == window) {
1416 self.maybe_warp_cursor_to_focus();
1417 }
1418 }
1419
1420 // FIXME: granular
1421 self.niri.queue_redraw_all();
1422 }
1423 }
1424 }
1425 Action::MoveColumnToWorkspaceDown(focus) => {
1426 self.niri.layout.move_column_to_workspace_down(focus);
1427 self.maybe_warp_cursor_to_focus();
1428 // FIXME: granular
1429 self.niri.queue_redraw_all();
1430 }
1431 Action::MoveColumnToWorkspaceUp(focus) => {
1432 self.niri.layout.move_column_to_workspace_up(focus);
1433 self.maybe_warp_cursor_to_focus();
1434 // FIXME: granular
1435 self.niri.queue_redraw_all();
1436 }
1437 Action::MoveColumnToWorkspace(reference, focus) => {
1438 if let Some((mut output, index)) =
1439 self.niri.find_output_and_workspace_index(reference)
1440 {
1441 if let Some(active) = self.niri.layout.active_output() {
1442 if output.as_ref() == Some(active) {
1443 output = None;
1444 }
1445 }
1446
1447 if let Some(output) = output {
1448 self.niri
1449 .layout
1450 .move_column_to_output(&output, Some(index), focus);
1451 if focus && !self.maybe_warp_cursor_to_focus_centered() {
1452 self.move_cursor_to_output(&output);
1453 }
1454 } else {
1455 self.niri.layout.move_column_to_workspace(index, focus);
1456 if focus {
1457 self.maybe_warp_cursor_to_focus();
1458 }
1459 }
1460
1461 // FIXME: granular
1462 self.niri.queue_redraw_all();
1463 }
1464 }
1465 Action::MoveColumnToIndex(idx) => {
1466 self.niri.layout.move_column_to_index(idx);
1467 self.maybe_warp_cursor_to_focus();
1468 // FIXME: granular
1469 self.niri.queue_redraw_all();
1470 }
1471 Action::FocusWorkspaceDown => {
1472 self.niri.layout.switch_workspace_down();
1473 self.maybe_warp_cursor_to_focus();
1474 self.niri.layer_shell_on_demand_focus = None;
1475 // FIXME: granular
1476 self.niri.queue_redraw_all();
1477 }
1478 Action::FocusWorkspaceDownUnderMouse => {
1479 if let Some(output) = self.niri.output_under_cursor() {
1480 if let Some(mon) = self.niri.layout.monitor_for_output_mut(&output) {
1481 mon.switch_workspace_down();
1482 self.maybe_warp_cursor_to_focus();
1483 self.niri.layer_shell_on_demand_focus = None;
1484 self.niri.queue_redraw(&output);
1485 }
1486 }
1487 }
1488 Action::FocusWorkspaceUp => {
1489 self.niri.layout.switch_workspace_up();
1490 self.maybe_warp_cursor_to_focus();
1491 self.niri.layer_shell_on_demand_focus = None;
1492 // FIXME: granular
1493 self.niri.queue_redraw_all();
1494 }
1495 Action::FocusWorkspaceUpUnderMouse => {
1496 if let Some(output) = self.niri.output_under_cursor() {
1497 if let Some(mon) = self.niri.layout.monitor_for_output_mut(&output) {
1498 mon.switch_workspace_up();
1499 self.maybe_warp_cursor_to_focus();
1500 self.niri.layer_shell_on_demand_focus = None;
1501 self.niri.queue_redraw(&output);
1502 }
1503 }
1504 }
1505 Action::FocusWorkspace(reference) => {
1506 if let Some((mut output, index)) =
1507 self.niri.find_output_and_workspace_index(reference)
1508 {
1509 if let Some(active) = self.niri.layout.active_output() {
1510 if output.as_ref() == Some(active) {
1511 output = None;
1512 }
1513 }
1514
1515 if let Some(output) = output {
1516 self.niri.layout.focus_output(&output);
1517 self.niri.layout.switch_workspace(index);
1518 if !self.maybe_warp_cursor_to_focus_centered() {
1519 self.move_cursor_to_output(&output);
1520 }
1521 } else {
1522 let config = &self.niri.config;
1523 if config.borrow().input.workspace_auto_back_and_forth {
1524 self.niri.layout.switch_workspace_auto_back_and_forth(index);
1525 } else {
1526 self.niri.layout.switch_workspace(index);
1527 }
1528 self.maybe_warp_cursor_to_focus();
1529 }
1530 self.niri.layer_shell_on_demand_focus = None;
1531
1532 // FIXME: granular
1533 self.niri.queue_redraw_all();
1534 }
1535 }
1536 Action::FocusWorkspacePrevious => {
1537 self.niri.layout.switch_workspace_previous();
1538 self.maybe_warp_cursor_to_focus();
1539 self.niri.layer_shell_on_demand_focus = None;
1540 // FIXME: granular
1541 self.niri.queue_redraw_all();
1542 }
1543 Action::MoveWorkspaceDown => {
1544 self.niri.layout.move_workspace_down();
1545 // FIXME: granular
1546 self.niri.queue_redraw_all();
1547 }
1548 Action::MoveWorkspaceUp => {
1549 self.niri.layout.move_workspace_up();
1550 // FIXME: granular
1551 self.niri.queue_redraw_all();
1552 }
1553 Action::MoveWorkspaceToIndex(new_idx) => {
1554 let new_idx = new_idx.saturating_sub(1);
1555 self.niri.layout.move_workspace_to_idx(None, new_idx);
1556 // FIXME: granular
1557 self.niri.queue_redraw_all();
1558 }
1559 Action::MoveWorkspaceToIndexByRef { new_idx, reference } => {
1560 if let Some(res) = self.niri.find_output_and_workspace_index(reference) {
1561 let new_idx = new_idx.saturating_sub(1);
1562 self.niri.layout.move_workspace_to_idx(Some(res), new_idx);
1563 // FIXME: granular
1564 self.niri.queue_redraw_all();
1565 }
1566 }
1567 Action::SetWorkspaceName(name) => {
1568 self.niri.layout.set_workspace_name(name, None);
1569 }
1570 Action::SetWorkspaceNameByRef { name, reference } => {
1571 self.niri.layout.set_workspace_name(name, Some(reference));
1572 }
1573 Action::UnsetWorkspaceName => {
1574 self.niri.layout.unset_workspace_name(None);
1575 }
1576 Action::UnsetWorkSpaceNameByRef(reference) => {
1577 self.niri.layout.unset_workspace_name(Some(reference));
1578 }
1579 Action::ConsumeWindowIntoColumn => {
1580 self.niri.layout.consume_into_column();
1581 // This does not cause immediate focus or window size change, so warping mouse to
1582 // focus won't do anything here.
1583 // FIXME: granular
1584 self.niri.queue_redraw_all();
1585 }
1586 Action::ExpelWindowFromColumn => {
1587 self.niri.layout.expel_from_column();
1588 self.maybe_warp_cursor_to_focus();
1589 // FIXME: granular
1590 self.niri.queue_redraw_all();
1591 }
1592 Action::SwapWindowRight => {
1593 self.niri
1594 .layout
1595 .swap_window_in_direction(ScrollDirection::Right);
1596 self.maybe_warp_cursor_to_focus();
1597 // FIXME: granular
1598 self.niri.queue_redraw_all();
1599 }
1600 Action::SwapWindowLeft => {
1601 self.niri
1602 .layout
1603 .swap_window_in_direction(ScrollDirection::Left);
1604 self.maybe_warp_cursor_to_focus();
1605 // FIXME: granular
1606 self.niri.queue_redraw_all();
1607 }
1608 Action::ToggleColumnTabbedDisplay => {
1609 self.niri.layout.toggle_column_tabbed_display();
1610 self.maybe_warp_cursor_to_focus();
1611 // FIXME: granular
1612 self.niri.queue_redraw_all();
1613 }
1614 Action::SetColumnDisplay(display) => {
1615 self.niri.layout.set_column_display(display);
1616 self.maybe_warp_cursor_to_focus();
1617 // FIXME: granular
1618 self.niri.queue_redraw_all();
1619 }
1620 Action::SwitchPresetColumnWidth => {
1621 self.niri.layout.toggle_width(true);
1622 }
1623 Action::SwitchPresetColumnWidthBack => {
1624 self.niri.layout.toggle_width(false);
1625 }
1626 Action::SwitchPresetWindowWidth => {
1627 self.niri.layout.toggle_window_width(None, true);
1628 }
1629 Action::SwitchPresetWindowWidthBack => {
1630 self.niri.layout.toggle_window_width(None, false);
1631 }
1632 Action::SwitchPresetWindowWidthById(id) => {
1633 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1634 let window = window.map(|(_, m)| m.window.clone());
1635 if let Some(window) = window {
1636 self.niri.layout.toggle_window_width(Some(&window), true);
1637 }
1638 }
1639 Action::SwitchPresetWindowWidthBackById(id) => {
1640 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1641 let window = window.map(|(_, m)| m.window.clone());
1642 if let Some(window) = window {
1643 self.niri.layout.toggle_window_width(Some(&window), false);
1644 }
1645 }
1646 Action::SwitchPresetWindowHeight => {
1647 self.niri.layout.toggle_window_height(None, true);
1648 }
1649 Action::SwitchPresetWindowHeightBack => {
1650 self.niri.layout.toggle_window_height(None, false);
1651 }
1652 Action::SwitchPresetWindowHeightById(id) => {
1653 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1654 let window = window.map(|(_, m)| m.window.clone());
1655 if let Some(window) = window {
1656 self.niri.layout.toggle_window_height(Some(&window), true);
1657 }
1658 }
1659 Action::SwitchPresetWindowHeightBackById(id) => {
1660 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1661 let window = window.map(|(_, m)| m.window.clone());
1662 if let Some(window) = window {
1663 self.niri.layout.toggle_window_height(Some(&window), false);
1664 }
1665 }
1666 Action::CenterColumn => {
1667 self.niri.layout.center_column();
1668 // FIXME: granular
1669 self.niri.queue_redraw_all();
1670 }
1671 Action::CenterWindow => {
1672 self.niri.layout.center_window(None);
1673 // FIXME: granular
1674 self.niri.queue_redraw_all();
1675 }
1676 Action::CenterWindowById(id) => {
1677 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1678 let window = window.map(|(_, m)| m.window.clone());
1679 if let Some(window) = window {
1680 self.niri.layout.center_window(Some(&window));
1681 // FIXME: granular
1682 self.niri.queue_redraw_all();
1683 }
1684 }
1685 Action::CenterVisibleColumns => {
1686 self.niri.layout.center_visible_columns();
1687 // FIXME: granular
1688 self.niri.queue_redraw_all();
1689 }
1690 Action::MaximizeColumn => {
1691 self.niri.layout.toggle_full_width();
1692 }
1693 Action::MaximizeWindowToEdges => {
1694 let focus = self.niri.layout.focus().map(|m| m.window.clone());
1695 if let Some(window) = focus {
1696 self.niri.layout.toggle_maximized(&window);
1697 // FIXME: granular
1698 self.niri.queue_redraw_all();
1699 }
1700 }
1701 Action::MaximizeWindowToEdgesById(id) => {
1702 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1703 let window = window.map(|(_, m)| m.window.clone());
1704 if let Some(window) = window {
1705 self.niri.layout.toggle_maximized(&window);
1706 // FIXME: granular
1707 self.niri.queue_redraw_all();
1708 }
1709 }
1710 Action::FocusMonitorLeft => {
1711 if let Some(output) = self.niri.output_left() {
1712 self.niri.layout.focus_output(&output);
1713 if !self.maybe_warp_cursor_to_focus_centered() {
1714 self.move_cursor_to_output(&output);
1715 }
1716 self.niri.layer_shell_on_demand_focus = None;
1717 }
1718 }
1719 Action::FocusMonitorRight => {
1720 if let Some(output) = self.niri.output_right() {
1721 self.niri.layout.focus_output(&output);
1722 if !self.maybe_warp_cursor_to_focus_centered() {
1723 self.move_cursor_to_output(&output);
1724 }
1725 self.niri.layer_shell_on_demand_focus = None;
1726 }
1727 }
1728 Action::FocusMonitorDown => {
1729 if let Some(output) = self.niri.output_down() {
1730 self.niri.layout.focus_output(&output);
1731 if !self.maybe_warp_cursor_to_focus_centered() {
1732 self.move_cursor_to_output(&output);
1733 }
1734 self.niri.layer_shell_on_demand_focus = None;
1735 }
1736 }
1737 Action::FocusMonitorUp => {
1738 if let Some(output) = self.niri.output_up() {
1739 self.niri.layout.focus_output(&output);
1740 if !self.maybe_warp_cursor_to_focus_centered() {
1741 self.move_cursor_to_output(&output);
1742 }
1743 self.niri.layer_shell_on_demand_focus = None;
1744 }
1745 }
1746 Action::FocusMonitorPrevious => {
1747 if let Some(output) = self.niri.output_previous() {
1748 self.niri.layout.focus_output(&output);
1749 if !self.maybe_warp_cursor_to_focus_centered() {
1750 self.move_cursor_to_output(&output);
1751 }
1752 self.niri.layer_shell_on_demand_focus = None;
1753 }
1754 }
1755 Action::FocusMonitorNext => {
1756 if let Some(output) = self.niri.output_next() {
1757 self.niri.layout.focus_output(&output);
1758 if !self.maybe_warp_cursor_to_focus_centered() {
1759 self.move_cursor_to_output(&output);
1760 }
1761 self.niri.layer_shell_on_demand_focus = None;
1762 }
1763 }
1764 Action::FocusMonitor(output) => {
1765 if let Some(output) = self.niri.output_by_name_match(&output).cloned() {
1766 self.niri.layout.focus_output(&output);
1767 if !self.maybe_warp_cursor_to_focus_centered() {
1768 self.move_cursor_to_output(&output);
1769 }
1770 self.niri.layer_shell_on_demand_focus = None;
1771 }
1772 }
1773 Action::MoveWindowToMonitorLeft => {
1774 if let Some(current_output) = self.niri.screenshot_ui.selection_output() {
1775 if let Some(target_output) = self.niri.output_left_of(current_output) {
1776 self.move_cursor_to_output(&target_output);
1777 self.niri.screenshot_ui.move_to_output(target_output);
1778 }
1779 } else if let Some(output) = self.niri.output_left() {
1780 self.niri
1781 .layout
1782 .move_to_output(None, &output, None, ActivateWindow::Smart);
1783 self.niri.layout.focus_output(&output);
1784 if !self.maybe_warp_cursor_to_focus_centered() {
1785 self.move_cursor_to_output(&output);
1786 }
1787 }
1788 }
1789 Action::MoveWindowToMonitorRight => {
1790 if let Some(current_output) = self.niri.screenshot_ui.selection_output() {
1791 if let Some(target_output) = self.niri.output_right_of(current_output) {
1792 self.move_cursor_to_output(&target_output);
1793 self.niri.screenshot_ui.move_to_output(target_output);
1794 }
1795 } else if let Some(output) = self.niri.output_right() {
1796 self.niri
1797 .layout
1798 .move_to_output(None, &output, None, ActivateWindow::Smart);
1799 self.niri.layout.focus_output(&output);
1800 if !self.maybe_warp_cursor_to_focus_centered() {
1801 self.move_cursor_to_output(&output);
1802 }
1803 }
1804 }
1805 Action::MoveWindowToMonitorDown => {
1806 if let Some(current_output) = self.niri.screenshot_ui.selection_output() {
1807 if let Some(target_output) = self.niri.output_down_of(current_output) {
1808 self.move_cursor_to_output(&target_output);
1809 self.niri.screenshot_ui.move_to_output(target_output);
1810 }
1811 } else if let Some(output) = self.niri.output_down() {
1812 self.niri
1813 .layout
1814 .move_to_output(None, &output, None, ActivateWindow::Smart);
1815 self.niri.layout.focus_output(&output);
1816 if !self.maybe_warp_cursor_to_focus_centered() {
1817 self.move_cursor_to_output(&output);
1818 }
1819 }
1820 }
1821 Action::MoveWindowToMonitorUp => {
1822 if let Some(current_output) = self.niri.screenshot_ui.selection_output() {
1823 if let Some(target_output) = self.niri.output_up_of(current_output) {
1824 self.move_cursor_to_output(&target_output);
1825 self.niri.screenshot_ui.move_to_output(target_output);
1826 }
1827 } else if let Some(output) = self.niri.output_up() {
1828 self.niri
1829 .layout
1830 .move_to_output(None, &output, None, ActivateWindow::Smart);
1831 self.niri.layout.focus_output(&output);
1832 if !self.maybe_warp_cursor_to_focus_centered() {
1833 self.move_cursor_to_output(&output);
1834 }
1835 }
1836 }
1837 Action::MoveWindowToMonitorPrevious => {
1838 if let Some(current_output) = self.niri.screenshot_ui.selection_output() {
1839 if let Some(target_output) = self.niri.output_previous_of(current_output) {
1840 self.move_cursor_to_output(&target_output);
1841 self.niri.screenshot_ui.move_to_output(target_output);
1842 }
1843 } else if let Some(output) = self.niri.output_previous() {
1844 self.niri
1845 .layout
1846 .move_to_output(None, &output, None, ActivateWindow::Smart);
1847 self.niri.layout.focus_output(&output);
1848 if !self.maybe_warp_cursor_to_focus_centered() {
1849 self.move_cursor_to_output(&output);
1850 }
1851 }
1852 }
1853 Action::MoveWindowToMonitorNext => {
1854 if let Some(current_output) = self.niri.screenshot_ui.selection_output() {
1855 if let Some(target_output) = self.niri.output_next_of(current_output) {
1856 self.move_cursor_to_output(&target_output);
1857 self.niri.screenshot_ui.move_to_output(target_output);
1858 }
1859 } else if let Some(output) = self.niri.output_next() {
1860 self.niri
1861 .layout
1862 .move_to_output(None, &output, None, ActivateWindow::Smart);
1863 self.niri.layout.focus_output(&output);
1864 if !self.maybe_warp_cursor_to_focus_centered() {
1865 self.move_cursor_to_output(&output);
1866 }
1867 }
1868 }
1869 Action::MoveWindowToMonitor(output) => {
1870 if let Some(output) = self.niri.output_by_name_match(&output).cloned() {
1871 if self.niri.screenshot_ui.is_open() {
1872 self.move_cursor_to_output(&output);
1873 self.niri.screenshot_ui.move_to_output(output);
1874 } else {
1875 self.niri
1876 .layout
1877 .move_to_output(None, &output, None, ActivateWindow::Smart);
1878 self.niri.layout.focus_output(&output);
1879 if !self.maybe_warp_cursor_to_focus_centered() {
1880 self.move_cursor_to_output(&output);
1881 }
1882 }
1883 }
1884 }
1885 Action::MoveWindowToMonitorById { id, output } => {
1886 if let Some(output) = self.niri.output_by_name_match(&output).cloned() {
1887 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1888 let window = window.map(|(_, m)| m.window.clone());
1889
1890 if let Some(window) = window {
1891 let target_was_active = self
1892 .niri
1893 .layout
1894 .active_output()
1895 .is_some_and(|active| output == *active);
1896
1897 self.niri.layout.move_to_output(
1898 Some(&window),
1899 &output,
1900 None,
1901 ActivateWindow::Smart,
1902 );
1903
1904 // If the active output changed (window was moved and focused).
1905 #[allow(clippy::collapsible_if)]
1906 if !target_was_active && self.niri.layout.active_output() == Some(&output) {
1907 if !self.maybe_warp_cursor_to_focus_centered() {
1908 self.move_cursor_to_output(&output);
1909 }
1910 }
1911 }
1912 }
1913 }
1914 Action::MoveColumnToMonitorLeft => {
1915 if let Some(current_output) = self.niri.screenshot_ui.selection_output() {
1916 if let Some(target_output) = self.niri.output_left_of(current_output) {
1917 self.move_cursor_to_output(&target_output);
1918 self.niri.screenshot_ui.move_to_output(target_output);
1919 }
1920 } else if let Some(output) = self.niri.output_left() {
1921 self.niri.layout.move_column_to_output(&output, None, true);
1922 self.niri.layout.focus_output(&output);
1923 if !self.maybe_warp_cursor_to_focus_centered() {
1924 self.move_cursor_to_output(&output);
1925 }
1926 }
1927 }
1928 Action::MoveColumnToMonitorRight => {
1929 if let Some(current_output) = self.niri.screenshot_ui.selection_output() {
1930 if let Some(target_output) = self.niri.output_right_of(current_output) {
1931 self.move_cursor_to_output(&target_output);
1932 self.niri.screenshot_ui.move_to_output(target_output);
1933 }
1934 } else if let Some(output) = self.niri.output_right() {
1935 self.niri.layout.move_column_to_output(&output, None, true);
1936 self.niri.layout.focus_output(&output);
1937 if !self.maybe_warp_cursor_to_focus_centered() {
1938 self.move_cursor_to_output(&output);
1939 }
1940 }
1941 }
1942 Action::MoveColumnToMonitorDown => {
1943 if let Some(current_output) = self.niri.screenshot_ui.selection_output() {
1944 if let Some(target_output) = self.niri.output_down_of(current_output) {
1945 self.move_cursor_to_output(&target_output);
1946 self.niri.screenshot_ui.move_to_output(target_output);
1947 }
1948 } else if let Some(output) = self.niri.output_down() {
1949 self.niri.layout.move_column_to_output(&output, None, true);
1950 self.niri.layout.focus_output(&output);
1951 if !self.maybe_warp_cursor_to_focus_centered() {
1952 self.move_cursor_to_output(&output);
1953 }
1954 }
1955 }
1956 Action::MoveColumnToMonitorUp => {
1957 if let Some(current_output) = self.niri.screenshot_ui.selection_output() {
1958 if let Some(target_output) = self.niri.output_up_of(current_output) {
1959 self.move_cursor_to_output(&target_output);
1960 self.niri.screenshot_ui.move_to_output(target_output);
1961 }
1962 } else if let Some(output) = self.niri.output_up() {
1963 self.niri.layout.move_column_to_output(&output, None, true);
1964 self.niri.layout.focus_output(&output);
1965 if !self.maybe_warp_cursor_to_focus_centered() {
1966 self.move_cursor_to_output(&output);
1967 }
1968 }
1969 }
1970 Action::MoveColumnToMonitorPrevious => {
1971 if let Some(current_output) = self.niri.screenshot_ui.selection_output() {
1972 if let Some(target_output) = self.niri.output_previous_of(current_output) {
1973 self.move_cursor_to_output(&target_output);
1974 self.niri.screenshot_ui.move_to_output(target_output);
1975 }
1976 } else if let Some(output) = self.niri.output_previous() {
1977 self.niri.layout.move_column_to_output(&output, None, true);
1978 self.niri.layout.focus_output(&output);
1979 if !self.maybe_warp_cursor_to_focus_centered() {
1980 self.move_cursor_to_output(&output);
1981 }
1982 }
1983 }
1984 Action::MoveColumnToMonitorNext => {
1985 if let Some(current_output) = self.niri.screenshot_ui.selection_output() {
1986 if let Some(target_output) = self.niri.output_next_of(current_output) {
1987 self.move_cursor_to_output(&target_output);
1988 self.niri.screenshot_ui.move_to_output(target_output);
1989 }
1990 } else if let Some(output) = self.niri.output_next() {
1991 self.niri.layout.move_column_to_output(&output, None, true);
1992 self.niri.layout.focus_output(&output);
1993 if !self.maybe_warp_cursor_to_focus_centered() {
1994 self.move_cursor_to_output(&output);
1995 }
1996 }
1997 }
1998 Action::MoveColumnToMonitor(output) => {
1999 if let Some(output) = self.niri.output_by_name_match(&output).cloned() {
2000 if self.niri.screenshot_ui.is_open() {
2001 self.move_cursor_to_output(&output);
2002 self.niri.screenshot_ui.move_to_output(output);
2003 } else {
2004 self.niri.layout.move_column_to_output(&output, None, true);
2005 self.niri.layout.focus_output(&output);
2006 if !self.maybe_warp_cursor_to_focus_centered() {
2007 self.move_cursor_to_output(&output);
2008 }
2009 }
2010 }
2011 }
2012 Action::SetColumnWidth(change) => {
2013 if self.niri.screenshot_ui.is_open() {
2014 self.niri.screenshot_ui.set_width(change);
2015
2016 // FIXME: granular
2017 self.niri.queue_redraw_all();
2018 } else {
2019 self.niri.layout.set_column_width(change);
2020 }
2021 }
2022 Action::SetWindowWidth(change) => {
2023 if self.niri.screenshot_ui.is_open() {
2024 self.niri.screenshot_ui.set_width(change);
2025
2026 // FIXME: granular
2027 self.niri.queue_redraw_all();
2028 } else {
2029 self.niri.layout.set_window_width(None, change);
2030 }
2031 }
2032 Action::SetWindowWidthById { id, change } => {
2033 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
2034 let window = window.map(|(_, m)| m.window.clone());
2035 if let Some(window) = window {
2036 self.niri.layout.set_window_width(Some(&window), change);
2037 }
2038 }
2039 Action::SetWindowHeight(change) => {
2040 if self.niri.screenshot_ui.is_open() {
2041 self.niri.screenshot_ui.set_height(change);
2042
2043 // FIXME: granular
2044 self.niri.queue_redraw_all();
2045 } else {
2046 self.niri.layout.set_window_height(None, change);
2047 }
2048 }
2049 Action::SetWindowHeightById { id, change } => {
2050 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
2051 let window = window.map(|(_, m)| m.window.clone());
2052 if let Some(window) = window {
2053 self.niri.layout.set_window_height(Some(&window), change);
2054 }
2055 }
2056 Action::ResetWindowHeight => {
2057 self.niri.layout.reset_window_height(None);
2058 }
2059 Action::ResetWindowHeightById(id) => {
2060 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
2061 let window = window.map(|(_, m)| m.window.clone());
2062 if let Some(window) = window {
2063 self.niri.layout.reset_window_height(Some(&window));
2064 }
2065 }
2066 Action::ExpandColumnToAvailableWidth => {
2067 self.niri.layout.expand_column_to_available_width();
2068 }
2069 Action::ShowHotkeyOverlay => {
2070 if self.niri.hotkey_overlay.show() {
2071 self.niri.queue_redraw_all();
2072
2073 #[cfg(feature = "dbus")]
2074 self.niri.a11y_announce_hotkey_overlay();
2075 }
2076 }
2077 Action::MoveWorkspaceToMonitorLeft => {
2078 if let Some(output) = self.niri.output_left() {
2079 self.niri.layout.move_workspace_to_output(&output);
2080 if !self.maybe_warp_cursor_to_focus_centered() {
2081 self.move_cursor_to_output(&output);
2082 }
2083 }
2084 }
2085 Action::MoveWorkspaceToMonitorRight => {
2086 if let Some(output) = self.niri.output_right() {
2087 self.niri.layout.move_workspace_to_output(&output);
2088 if !self.maybe_warp_cursor_to_focus_centered() {
2089 self.move_cursor_to_output(&output);
2090 }
2091 }
2092 }
2093 Action::MoveWorkspaceToMonitorDown => {
2094 if let Some(output) = self.niri.output_down() {
2095 self.niri.layout.move_workspace_to_output(&output);
2096 if !self.maybe_warp_cursor_to_focus_centered() {
2097 self.move_cursor_to_output(&output);
2098 }
2099 }
2100 }
2101 Action::MoveWorkspaceToMonitorUp => {
2102 if let Some(output) = self.niri.output_up() {
2103 self.niri.layout.move_workspace_to_output(&output);
2104 if !self.maybe_warp_cursor_to_focus_centered() {
2105 self.move_cursor_to_output(&output);
2106 }
2107 }
2108 }
2109 Action::MoveWorkspaceToMonitorPrevious => {
2110 if let Some(output) = self.niri.output_previous() {
2111 self.niri.layout.move_workspace_to_output(&output);
2112 if !self.maybe_warp_cursor_to_focus_centered() {
2113 self.move_cursor_to_output(&output);
2114 }
2115 }
2116 }
2117 Action::MoveWorkspaceToMonitorNext => {
2118 if let Some(output) = self.niri.output_next() {
2119 self.niri.layout.move_workspace_to_output(&output);
2120 if !self.maybe_warp_cursor_to_focus_centered() {
2121 self.move_cursor_to_output(&output);
2122 }
2123 }
2124 }
2125 Action::MoveWorkspaceToMonitor(new_output) => {
2126 if let Some(new_output) = self.niri.output_by_name_match(&new_output).cloned() {
2127 if self.niri.layout.move_workspace_to_output(&new_output)
2128 && !self.maybe_warp_cursor_to_focus_centered()
2129 {
2130 self.move_cursor_to_output(&new_output);
2131 }
2132 }
2133 }
2134 Action::MoveWorkspaceToMonitorByRef {
2135 output_name,
2136 reference,
2137 } => {
2138 if let Some((output, old_idx)) =
2139 self.niri.find_output_and_workspace_index(reference)
2140 {
2141 if let Some(new_output) = self.niri.output_by_name_match(&output_name).cloned()
2142 {
2143 if self.niri.layout.move_workspace_to_output_by_id(
2144 old_idx,
2145 output,
2146 &new_output,
2147 ) {
2148 // Cursor warp already calls `queue_redraw_all`
2149 if !self.maybe_warp_cursor_to_focus_centered() {
2150 self.move_cursor_to_output(&new_output);
2151 }
2152 }
2153 }
2154 }
2155 }
2156 Action::ToggleWindowFloating => {
2157 self.niri.layout.toggle_window_floating(None);
2158 // FIXME: granular
2159 self.niri.queue_redraw_all();
2160 }
2161 Action::ToggleWindowFloatingById(id) => {
2162 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
2163 let window = window.map(|(_, m)| m.window.clone());
2164 if let Some(window) = window {
2165 self.niri.layout.toggle_window_floating(Some(&window));
2166 // FIXME: granular
2167 self.niri.queue_redraw_all();
2168 }
2169 }
2170 Action::MoveWindowToFloating => {
2171 self.niri.layout.set_window_floating(None, true);
2172 // FIXME: granular
2173 self.niri.queue_redraw_all();
2174 }
2175 Action::MoveWindowToFloatingById(id) => {
2176 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
2177 let window = window.map(|(_, m)| m.window.clone());
2178 if let Some(window) = window {
2179 self.niri.layout.set_window_floating(Some(&window), true);
2180 // FIXME: granular
2181 self.niri.queue_redraw_all();
2182 }
2183 }
2184 Action::MoveWindowToTiling => {
2185 self.niri.layout.set_window_floating(None, false);
2186 // FIXME: granular
2187 self.niri.queue_redraw_all();
2188 }
2189 Action::MoveWindowToTilingById(id) => {
2190 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
2191 let window = window.map(|(_, m)| m.window.clone());
2192 if let Some(window) = window {
2193 self.niri.layout.set_window_floating(Some(&window), false);
2194 // FIXME: granular
2195 self.niri.queue_redraw_all();
2196 }
2197 }
2198 Action::FocusFloating => {
2199 self.niri.layout.focus_floating();
2200 self.maybe_warp_cursor_to_focus();
2201 // FIXME: granular
2202 self.niri.queue_redraw_all();
2203 }
2204 Action::FocusTiling => {
2205 self.niri.layout.focus_tiling();
2206 self.maybe_warp_cursor_to_focus();
2207 // FIXME: granular
2208 self.niri.queue_redraw_all();
2209 }
2210 Action::SwitchFocusBetweenFloatingAndTiling => {
2211 self.niri.layout.switch_focus_floating_tiling();
2212 self.maybe_warp_cursor_to_focus();
2213 // FIXME: granular
2214 self.niri.queue_redraw_all();
2215 }
2216 Action::MoveFloatingWindowById { id, x, y } => {
2217 let window = if let Some(id) = id {
2218 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
2219 let window = window.map(|(_, m)| m.window.clone());
2220 if window.is_none() {
2221 return;
2222 }
2223 window
2224 } else {
2225 None
2226 };
2227
2228 self.niri
2229 .layout
2230 .move_floating_window(window.as_ref(), x, y, true);
2231 // FIXME: granular
2232 self.niri.queue_redraw_all();
2233 }
2234 Action::ToggleWindowRuleOpacity => {
2235 let active_window = self
2236 .niri
2237 .layout
2238 .active_workspace_mut()
2239 .and_then(|ws| ws.active_window_mut());
2240 if let Some(window) = active_window {
2241 if window.rules().opacity.is_some_and(|o| o != 1.) {
2242 window.toggle_ignore_opacity_window_rule();
2243 // FIXME: granular
2244 self.niri.queue_redraw_all();
2245 }
2246 }
2247 }
2248 Action::ToggleWindowRuleOpacityById(id) => {
2249 let window = self
2250 .niri
2251 .layout
2252 .workspaces_mut()
2253 .find_map(|ws| ws.windows_mut().find(|w| w.id().get() == id));
2254 if let Some(window) = window {
2255 if window.rules().opacity.is_some_and(|o| o != 1.) {
2256 window.toggle_ignore_opacity_window_rule();
2257 // FIXME: granular
2258 self.niri.queue_redraw_all();
2259 }
2260 }
2261 }
2262 Action::SetDynamicCastWindow => {
2263 let id = self
2264 .niri
2265 .layout
2266 .active_workspace()
2267 .and_then(|ws| ws.active_window())
2268 .map(|mapped| mapped.id().get());
2269 if let Some(id) = id {
2270 self.set_dynamic_cast_target(CastTarget::Window { id });
2271 }
2272 }
2273 Action::SetDynamicCastWindowById(id) => {
2274 let layout = &self.niri.layout;
2275 if layout.windows().any(|(_, mapped)| mapped.id().get() == id) {
2276 self.set_dynamic_cast_target(CastTarget::Window { id });
2277 }
2278 }
2279 Action::SetDynamicCastMonitor(output) => {
2280 let output = match output {
2281 None => self.niri.layout.active_output(),
2282 Some(name) => self.niri.output_by_name_match(&name),
2283 };
2284 if let Some(output) = output {
2285 self.set_dynamic_cast_target(CastTarget::output(output));
2286 }
2287 }
2288 Action::ClearDynamicCastTarget => {
2289 self.set_dynamic_cast_target(CastTarget::Nothing);
2290 }
2291 Action::StopCast(session_id) => {
2292 self.niri.stop_cast(CastSessionId::from(session_id));
2293 }
2294 Action::ToggleOverview => {
2295 self.niri.layout.toggle_overview();
2296 self.niri.queue_redraw_all();
2297 }
2298 Action::OpenOverview => {
2299 if self.niri.layout.open_overview() {
2300 self.niri.queue_redraw_all();
2301 }
2302 }
2303 Action::CloseOverview => {
2304 if self.niri.layout.close_overview() {
2305 self.niri.queue_redraw_all();
2306 }
2307 }
2308 Action::ToggleWindowUrgent(id) => {
2309 let window = self
2310 .niri
2311 .layout
2312 .workspaces_mut()
2313 .find_map(|ws| ws.windows_mut().find(|w| w.id().get() == id));
2314 if let Some(window) = window {
2315 let urgent = window.is_urgent();
2316 window.set_urgent(!urgent);
2317 }
2318 self.niri.queue_redraw_all();
2319 }
2320 Action::SetWindowUrgent(id) => {
2321 let window = self
2322 .niri
2323 .layout
2324 .workspaces_mut()
2325 .find_map(|ws| ws.windows_mut().find(|w| w.id().get() == id));
2326 if let Some(window) = window {
2327 window.set_urgent(true);
2328 }
2329 self.niri.queue_redraw_all();
2330 }
2331 Action::UnsetWindowUrgent(id) => {
2332 let window = self
2333 .niri
2334 .layout
2335 .workspaces_mut()
2336 .find_map(|ws| ws.windows_mut().find(|w| w.id().get() == id));
2337 if let Some(window) = window {
2338 window.set_urgent(false);
2339 }
2340 self.niri.queue_redraw_all();
2341 }
2342 Action::LoadConfigFile(path) => {
2343 if let Some(watcher) = &self.niri.config_file_watcher {
2344 watcher.load_config(path);
2345 }
2346 }
2347 Action::MruConfirm => {
2348 self.confirm_mru();
2349 }
2350 Action::MruCancel => {
2351 self.niri.cancel_mru();
2352 }
2353 Action::MruAdvance {
2354 direction,
2355 scope,
2356 filter,
2357 } => {
2358 if self.niri.window_mru_ui.is_open() {
2359 self.niri.window_mru_ui.advance(direction, filter);
2360 self.niri.queue_redraw_mru_output();
2361 } else if self.niri.config.borrow().recent_windows.on {
2362 self.niri.mru_apply_keyboard_commit();
2363
2364 let config = self.niri.config.borrow();
2365 let scope = scope.unwrap_or(self.niri.window_mru_ui.scope());
2366
2367 let mut wmru = WindowMru::new(&self.niri);
2368 if !wmru.is_empty() {
2369 wmru.set_scope(scope);
2370 if let Some(filter) = filter {
2371 wmru.set_filter(filter);
2372 }
2373
2374 if let Some(output) = self.niri.layout.active_output() {
2375 self.niri.window_mru_ui.open(
2376 self.niri.clock.clone(),
2377 wmru,
2378 output.clone(),
2379 );
2380
2381 // Only select the *next* window if some window (which should be the
2382 // first one) is already focused. If nothing is focused, keep the first
2383 // window (which is logically the "previously selected" one).
2384 let keep_first = direction == MruDirection::Forward
2385 && self.niri.layout.focus().is_none();
2386 if !keep_first {
2387 self.niri.window_mru_ui.advance(direction, None);
2388 }
2389
2390 drop(config);
2391 self.niri.queue_redraw_all();
2392 }
2393 }
2394 }
2395 }
2396 Action::MruCloseCurrentWindow => {
2397 if self.niri.window_mru_ui.is_open() {
2398 if let Some(id) = self.niri.window_mru_ui.current_window_id() {
2399 if let Some(w) = self.niri.find_window_by_id(id) {
2400 if let Some(tl) = w.toplevel() {
2401 tl.send_close();
2402 }
2403 }
2404 }
2405 }
2406 }
2407 Action::MruFirst => {
2408 if self.niri.window_mru_ui.is_open() {
2409 self.niri.window_mru_ui.first();
2410 self.niri.queue_redraw_mru_output();
2411 }
2412 }
2413 Action::MruLast => {
2414 if self.niri.window_mru_ui.is_open() {
2415 self.niri.window_mru_ui.last();
2416 self.niri.queue_redraw_mru_output();
2417 }
2418 }
2419 Action::MruSetScope(scope) => {
2420 if self.niri.window_mru_ui.is_open() {
2421 self.niri.window_mru_ui.set_scope(scope);
2422 self.niri.queue_redraw_mru_output();
2423 }
2424 }
2425 Action::MruCycleScope => {
2426 if self.niri.window_mru_ui.is_open() {
2427 self.niri.window_mru_ui.cycle_scope();
2428 self.niri.queue_redraw_mru_output();
2429 }
2430 }
2431 }
2432 }
2433
2434 fn on_pointer_motion<I: InputBackend>(&mut self, event: I::PointerMotionEvent) {
2435 let was_inside_hot_corner = self.niri.pointer_inside_hot_corner;
2436 // Any of the early returns here mean that the pointer is not inside the hot corner.
2437 self.niri.pointer_inside_hot_corner = false;
2438
2439 // We need an output to be able to move the pointer.
2440 if self.niri.global_space.outputs().next().is_none() {
2441 return;
2442 }
2443
2444 let serial = SERIAL_COUNTER.next_serial();
2445
2446 let pointer = self.niri.seat.get_pointer().unwrap();
2447
2448 let pos = pointer.current_location();
2449
2450 // We have an output, so we can compute the new location and focus.
2451 let mut new_pos = pos + event.delta();
2452
2453 // We received an event for the regular pointer, so show it now.
2454 self.niri.pointer_visibility = PointerVisibility::Visible;
2455 self.niri.tablet_cursor_location = None;
2456
2457 // Check if we have an active pointer constraint.
2458 //
2459 // FIXME: ideally this should use the pointer focus with up-to-date global location.
2460 let mut pointer_confined = None;
2461 if let Some(under) = &self.niri.pointer_contents.surface {
2462 // No need to check if the pointer focus surface matches, because here we're checking
2463 // for an already-active constraint, and the constraint is deactivated when the focused
2464 // surface changes.
2465 let pos_within_surface = pos - under.1;
2466
2467 let mut pointer_locked = false;
2468 with_pointer_constraint(&under.0, &pointer, |constraint| {
2469 let Some(constraint) = constraint else { return };
2470 if !constraint.is_active() {
2471 return;
2472 }
2473
2474 // Constraint does not apply if not within region.
2475 if let Some(region) = constraint.region() {
2476 if !region.contains(pos_within_surface.to_i32_round()) {
2477 return;
2478 }
2479 }
2480
2481 match &*constraint {
2482 PointerConstraint::Locked(_locked) => {
2483 pointer_locked = true;
2484 }
2485 PointerConstraint::Confined(confine) => {
2486 pointer_confined = Some((under.clone(), confine.region().cloned()));
2487 }
2488 }
2489 });
2490
2491 // If the pointer is locked, only send relative motion.
2492 if pointer_locked {
2493 pointer.relative_motion(
2494 self,
2495 Some(under.clone()),
2496 &RelativeMotionEvent {
2497 delta: event.delta(),
2498 delta_unaccel: event.delta_unaccel(),
2499 utime: event.time(),
2500 },
2501 );
2502
2503 pointer.frame(self);
2504
2505 // I guess a redraw to hide the tablet cursor could be nice? Doesn't matter too
2506 // much here I think.
2507 return;
2508 }
2509 }
2510
2511 // Warp pointer across the screen during the spatial movement grabs.
2512 let spatial_grab = pointer.with_grab(|_, grab| {
2513 let grab = grab.as_any();
2514 if let Some(grab) = grab.downcast_ref::<SpatialMovementGrab>() {
2515 if let Some(output) = grab.view_offset_output() {
2516 return Some((output.clone(), true));
2517 } else if let Some(output) = grab.workspace_switch_output() {
2518 return Some((output.clone(), false));
2519 }
2520 } else if let Some(grab) = grab.downcast_ref::<MoveGrab>() {
2521 if let Some(output) = grab.view_offset_output() {
2522 return Some((output.clone(), true));
2523 }
2524 }
2525 None
2526 });
2527 if let Some((output, horizontal)) = spatial_grab.flatten() {
2528 if let Some(geo) = self.niri.global_space.output_geometry(&output) {
2529 let geo = geo.to_f64();
2530 if horizontal {
2531 new_pos.x = (new_pos.x - geo.loc.x).rem_euclid(geo.size.w) + geo.loc.x;
2532 new_pos.y = new_pos.y.clamp(geo.loc.y, geo.loc.y + geo.size.h - 1.);
2533 } else {
2534 new_pos.x = new_pos.x.clamp(geo.loc.x, geo.loc.x + geo.size.w - 1.);
2535 new_pos.y = (new_pos.y - geo.loc.y).rem_euclid(geo.size.h) + geo.loc.y;
2536 }
2537 }
2538 }
2539
2540 if self
2541 .niri
2542 .global_space
2543 .output_under(new_pos)
2544 .next()
2545 .is_none()
2546 {
2547 // We ended up outside the outputs and need to clip the movement.
2548 if let Some(output) = self.niri.global_space.output_under(pos).next() {
2549 // The pointer was previously on some output. Clip the movement against its
2550 // boundaries.
2551 let geom = self.niri.global_space.output_geometry(output).unwrap();
2552 new_pos.x = new_pos
2553 .x
2554 .clamp(geom.loc.x as f64, (geom.loc.x + geom.size.w - 1) as f64);
2555 new_pos.y = new_pos
2556 .y
2557 .clamp(geom.loc.y as f64, (geom.loc.y + geom.size.h - 1) as f64);
2558 } else {
2559 // The pointer was not on any output in the first place. Find one for it.
2560 // Let's do the simple thing and just put it on the first output.
2561 let output = self.niri.global_space.outputs().next().unwrap();
2562 let geom = self.niri.global_space.output_geometry(output).unwrap();
2563 new_pos = center(geom).to_f64();
2564 }
2565 }
2566
2567 if let Some(output) = self.niri.screenshot_ui.selection_output() {
2568 let geom = self.niri.global_space.output_geometry(output).unwrap();
2569 let point = (new_pos - geom.loc.to_f64())
2570 .to_physical(output.current_scale().fractional_scale())
2571 .to_i32_round::<i32>();
2572
2573 self.niri.screenshot_ui.pointer_motion(point, None);
2574 }
2575
2576 if let Some(mru_output) = self.niri.window_mru_ui.output() {
2577 if let Some((output, pos_within_output)) = self.niri.output_under(new_pos) {
2578 if mru_output == output {
2579 self.niri.window_mru_ui.pointer_motion(pos_within_output);
2580 }
2581 }
2582 }
2583
2584 let under = self.niri.contents_under(new_pos);
2585
2586 // Handle confined pointer.
2587 if let Some((focus_surface, region)) = pointer_confined {
2588 let mut prevent = false;
2589
2590 // Prevent the pointer from leaving the focused surface.
2591 if Some(&focus_surface.0) != under.surface.as_ref().map(|(s, _)| s) {
2592 prevent = true;
2593 }
2594
2595 // Prevent the pointer from leaving the confine region, if any.
2596 if let Some(region) = region {
2597 let new_pos_within_surface = new_pos - focus_surface.1;
2598 if !region.contains(new_pos_within_surface.to_i32_round()) {
2599 prevent = true;
2600 }
2601 }
2602
2603 if prevent {
2604 pointer.relative_motion(
2605 self,
2606 Some(focus_surface),
2607 &RelativeMotionEvent {
2608 delta: event.delta(),
2609 delta_unaccel: event.delta_unaccel(),
2610 utime: event.time(),
2611 },
2612 );
2613
2614 pointer.frame(self);
2615
2616 return;
2617 }
2618 }
2619
2620 self.niri.handle_focus_follows_mouse(&under);
2621
2622 self.niri.pointer_contents.clone_from(&under);
2623
2624 pointer.motion(
2625 self,
2626 under.surface.clone(),
2627 &MotionEvent {
2628 location: new_pos,
2629 serial,
2630 time: event.time_msec(),
2631 },
2632 );
2633
2634 pointer.relative_motion(
2635 self,
2636 under.surface,
2637 &RelativeMotionEvent {
2638 delta: event.delta(),
2639 delta_unaccel: event.delta_unaccel(),
2640 utime: event.time(),
2641 },
2642 );
2643
2644 pointer.frame(self);
2645
2646 // contents_under() will return no surface when the hot corner should trigger, so
2647 // pointer.motion() will set the current focus to None.
2648 if under.hot_corner && pointer.current_focus().is_none() {
2649 if !was_inside_hot_corner
2650 && pointer
2651 .with_grab(|_, grab| grab_allows_hot_corner(grab))
2652 .unwrap_or(true)
2653 {
2654 self.niri.layout.toggle_overview();
2655 }
2656 self.niri.pointer_inside_hot_corner = true;
2657 }
2658
2659 // Activate a new confinement if necessary.
2660 self.niri.maybe_activate_pointer_constraint();
2661
2662 // Inform the layout of an ongoing DnD operation.
2663 let is_dnd_grab = pointer
2664 .with_grab(|_, grab| Self::is_dnd_grab(grab.as_any()))
2665 .unwrap_or(false);
2666 if is_dnd_grab {
2667 if let Some((output, pos_within_output)) = self.niri.output_under(new_pos) {
2668 let output = output.clone();
2669 self.niri.layout.dnd_update(output, pos_within_output);
2670 }
2671 }
2672
2673 // Notify a11y.
2674 #[cfg(feature = "dbus")]
2675 self.a11y_notify_pointer_motion();
2676
2677 // Redraw to update the cursor position.
2678 // FIXME: redraw only outputs overlapping the cursor.
2679 self.niri.queue_redraw_all();
2680 }
2681
2682 fn on_pointer_motion_absolute<I: InputBackend>(
2683 &mut self,
2684 event: I::PointerMotionAbsoluteEvent,
2685 ) {
2686 let was_inside_hot_corner = self.niri.pointer_inside_hot_corner;
2687 // Any of the early returns here mean that the pointer is not inside the hot corner.
2688 self.niri.pointer_inside_hot_corner = false;
2689
2690 let Some(pos) = self.compute_absolute_location(&event, None).or_else(|| {
2691 self.global_bounding_rectangle().map(|output_geo| {
2692 event.position_transformed(output_geo.size) + output_geo.loc.to_f64()
2693 })
2694 }) else {
2695 return;
2696 };
2697
2698 let serial = SERIAL_COUNTER.next_serial();
2699
2700 let pointer = self.niri.seat.get_pointer().unwrap();
2701
2702 if let Some(output) = self.niri.screenshot_ui.selection_output() {
2703 let geom = self.niri.global_space.output_geometry(output).unwrap();
2704 let point = (pos - geom.loc.to_f64())
2705 .to_physical(output.current_scale().fractional_scale())
2706 .to_i32_round::<i32>();
2707
2708 self.niri.screenshot_ui.pointer_motion(point, None);
2709 }
2710
2711 if let Some(mru_output) = self.niri.window_mru_ui.output() {
2712 if let Some((output, pos_within_output)) = self.niri.output_under(pos) {
2713 if mru_output == output {
2714 self.niri.window_mru_ui.pointer_motion(pos_within_output);
2715 }
2716 }
2717 }
2718
2719 let under = self.niri.contents_under(pos);
2720
2721 self.niri.handle_focus_follows_mouse(&under);
2722
2723 self.niri.pointer_contents.clone_from(&under);
2724
2725 pointer.motion(
2726 self,
2727 under.surface,
2728 &MotionEvent {
2729 location: pos,
2730 serial,
2731 time: event.time_msec(),
2732 },
2733 );
2734
2735 pointer.frame(self);
2736
2737 // contents_under() will return no surface when the hot corner should trigger, so
2738 // pointer.motion() will set the current focus to None.
2739 if under.hot_corner && pointer.current_focus().is_none() {
2740 if !was_inside_hot_corner
2741 && pointer
2742 .with_grab(|_, grab| grab_allows_hot_corner(grab))
2743 .unwrap_or(true)
2744 {
2745 self.niri.layout.toggle_overview();
2746 }
2747 self.niri.pointer_inside_hot_corner = true;
2748 }
2749
2750 self.niri.maybe_activate_pointer_constraint();
2751
2752 // We moved the pointer, show it.
2753 self.niri.pointer_visibility = PointerVisibility::Visible;
2754
2755 // We moved the regular pointer, so show it now.
2756 self.niri.tablet_cursor_location = None;
2757
2758 // Inform the layout of an ongoing DnD operation.
2759 let is_dnd_grab = pointer
2760 .with_grab(|_, grab| Self::is_dnd_grab(grab.as_any()))
2761 .unwrap_or(false);
2762 if is_dnd_grab {
2763 if let Some((output, pos_within_output)) = self.niri.output_under(pos) {
2764 let output = output.clone();
2765 self.niri.layout.dnd_update(output, pos_within_output);
2766 }
2767 }
2768
2769 // Notify a11y.
2770 #[cfg(feature = "dbus")]
2771 self.a11y_notify_pointer_motion();
2772
2773 // Redraw to update the cursor position.
2774 // FIXME: redraw only outputs overlapping the cursor.
2775 self.niri.queue_redraw_all();
2776 }
2777
2778 fn on_pointer_button<I: InputBackend>(&mut self, event: I::PointerButtonEvent) {
2779 let pointer = self.niri.seat.get_pointer().unwrap();
2780
2781 let serial = SERIAL_COUNTER.next_serial();
2782
2783 let button = event.button();
2784
2785 let button_code = event.button_code();
2786
2787 let button_state = event.state();
2788
2789 let mod_key = self.backend.mod_key(&self.niri.config.borrow());
2790
2791 // Ignore release events for mouse clicks that triggered a bind.
2792 if self.niri.suppressed_buttons.remove(&button_code) {
2793 return;
2794 }
2795
2796 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
2797 let modifiers = modifiers_from_state(mods);
2798 let mod_down = modifiers.contains(mod_key.to_modifiers());
2799
2800 if ButtonState::Pressed == button_state {
2801 let mut is_mru_open = false;
2802 if let Some(mru_output) = self.niri.window_mru_ui.output() {
2803 is_mru_open = true;
2804 if let Some(MouseButton::Left) = button {
2805 let location = pointer.current_location();
2806 let (output, pos_within_output) = self.niri.output_under(location).unwrap();
2807 if mru_output == output {
2808 let id = self.niri.window_mru_ui.pointer_motion(pos_within_output);
2809 if id.is_some() {
2810 self.confirm_mru();
2811 } else {
2812 self.niri.cancel_mru();
2813 }
2814 } else {
2815 self.niri.cancel_mru();
2816 }
2817
2818 self.niri.suppressed_buttons.insert(button_code);
2819 return;
2820 }
2821 }
2822
2823 if is_mru_open || self.niri.mods_with_mouse_binds.contains(&modifiers) {
2824 if let Some(bind) = match button {
2825 Some(MouseButton::Left) => Some(Trigger::MouseLeft),
2826 Some(MouseButton::Right) => Some(Trigger::MouseRight),
2827 Some(MouseButton::Middle) => Some(Trigger::MouseMiddle),
2828 Some(MouseButton::Back) => Some(Trigger::MouseBack),
2829 Some(MouseButton::Forward) => Some(Trigger::MouseForward),
2830 _ => None,
2831 }
2832 .and_then(|trigger| {
2833 let config = self.niri.config.borrow();
2834 let bindings =
2835 make_binds_iter(&config, &mut self.niri.window_mru_ui, modifiers);
2836 find_configured_bind(bindings, mod_key, trigger, mods)
2837 })
2838 .filter(|bind| {
2839 !self.niri.screenshot_ui.is_open() || allowed_during_screenshot(&bind.action)
2840 }) {
2841 self.niri.suppressed_buttons.insert(button_code);
2842 self.handle_bind(bind.clone());
2843 return;
2844 };
2845 }
2846
2847 // We received an event for the regular pointer, so show it now.
2848 self.niri.pointer_visibility = PointerVisibility::Visible;
2849 self.niri.tablet_cursor_location = None;
2850
2851 let is_overview_open = self.niri.layout.is_overview_open();
2852
2853 if is_overview_open && !pointer.is_grabbed() && button == Some(MouseButton::Right) {
2854 if let Some((output, ws)) = self.niri.workspace_under_cursor(true) {
2855 let ws_id = ws.id();
2856 let ws_idx = self.niri.layout.find_workspace_by_id(ws_id).unwrap().0;
2857
2858 self.niri.layout.focus_output(&output);
2859
2860 let location = pointer.current_location();
2861 let start_data = PointerGrabStartData {
2862 focus: None,
2863 button: button_code,
2864 location,
2865 };
2866 self.niri
2867 .layout
2868 .view_offset_gesture_begin(&output, Some(ws_idx), false);
2869 let grab = SpatialMovementGrab::new(start_data, output, ws_id, true);
2870 pointer.set_grab(self, grab, serial, Focus::Clear);
2871 self.niri
2872 .cursor_manager
2873 .set_cursor_image(CursorImageStatus::Named(CursorIcon::AllScroll));
2874
2875 // FIXME: granular.
2876 self.niri.queue_redraw_all();
2877 return;
2878 }
2879 }
2880
2881 if button == Some(MouseButton::Middle) && !pointer.is_grabbed() && mod_down {
2882 let output_ws = if is_overview_open {
2883 self.niri.workspace_under_cursor(true)
2884 } else {
2885 // We don't want to accidentally "catch" the wrong workspace during
2886 // animations.
2887 self.niri.output_under_cursor().and_then(|output| {
2888 let mon = self.niri.layout.monitor_for_output(&output)?;
2889 Some((output, mon.active_workspace_ref()))
2890 })
2891 };
2892
2893 if let Some((output, ws)) = output_ws {
2894 let ws_id = ws.id();
2895
2896 self.niri.layout.focus_output(&output);
2897
2898 let location = pointer.current_location();
2899 let start_data = PointerGrabStartData {
2900 focus: None,
2901 button: button_code,
2902 location,
2903 };
2904 let grab = SpatialMovementGrab::new(start_data, output, ws_id, false);
2905 pointer.set_grab(self, grab, serial, Focus::Clear);
2906 self.niri
2907 .cursor_manager
2908 .set_cursor_image(CursorImageStatus::Named(CursorIcon::AllScroll));
2909
2910 // FIXME: granular.
2911 self.niri.queue_redraw_all();
2912
2913 // Don't activate the window under the cursor to avoid unnecessary
2914 // scrolling when e.g. Mod+MMB clicking on a partially off-screen window.
2915 return;
2916 }
2917 }
2918
2919 if let Some(mapped) = self.niri.window_under_cursor() {
2920 let window = mapped.window.clone();
2921
2922 // Check if we need to start an interactive move.
2923 if button == Some(MouseButton::Left) && !pointer.is_grabbed() {
2924 if is_overview_open || mod_down {
2925 let location = pointer.current_location();
2926
2927 if !is_overview_open {
2928 self.niri.layout.activate_window(&window);
2929 }
2930
2931 let start_data = PointerGrabStartData {
2932 focus: None,
2933 button: button_code,
2934 location,
2935 };
2936 let start_data = AnyStartData::Pointer(start_data);
2937 let icon = CursorIcon::Grabbing;
2938 if let Some(grab) =
2939 MoveGrab::new(self, start_data, window.clone(), false, Some(icon))
2940 {
2941 pointer.set_grab(self, grab, serial, Focus::Clear);
2942
2943 // Set the cursor to Grabbing right away for Mod+LMB since it doesn't
2944 // do any other gesture.
2945 //
2946 // In the overview, we click to activate window and close the overview,
2947 // in this case setting the cursor right away would be distracting.
2948 if !is_overview_open {
2949 self.niri
2950 .cursor_manager
2951 .set_cursor_image(CursorImageStatus::Named(icon));
2952 }
2953 }
2954 }
2955 }
2956 // Check if we need to start an interactive resize.
2957 else if button == Some(MouseButton::Right) && !pointer.is_grabbed() && mod_down {
2958 let location = pointer.current_location();
2959 let (output, pos_within_output) = self.niri.output_under(location).unwrap();
2960 let edges = self
2961 .niri
2962 .layout
2963 .resize_edges_under(output, pos_within_output)
2964 .unwrap_or(ResizeEdge::empty());
2965
2966 if !edges.is_empty() {
2967 // See if we got a double resize-click gesture.
2968 // FIXME: deduplicate with resize_request in xdg-shell somehow.
2969 let time = get_monotonic_time();
2970 let last_cell = mapped.last_interactive_resize_start();
2971 let mut last = last_cell.get();
2972 last_cell.set(Some((time, edges)));
2973
2974 // Floating windows don't have either of the double-resize-click
2975 // gestures, so just allow it to resize.
2976 if mapped.is_floating() {
2977 last = None;
2978 last_cell.set(None);
2979 }
2980
2981 if let Some((last_time, last_edges)) = last {
2982 if time.saturating_sub(last_time) <= DOUBLE_CLICK_TIME {
2983 // Allow quick resize after a triple click.
2984 last_cell.set(None);
2985
2986 let intersection = edges.intersection(last_edges);
2987 if intersection.intersects(ResizeEdge::LEFT_RIGHT) {
2988 // FIXME: don't activate once we can pass specific windows
2989 // to actions.
2990 self.niri.layout.activate_window(&window);
2991 self.niri.layout.toggle_full_width();
2992 }
2993 if intersection.intersects(ResizeEdge::TOP_BOTTOM) {
2994 self.niri.layout.activate_window(&window);
2995 self.niri.layout.reset_window_height(Some(&window));
2996 }
2997 // FIXME: granular.
2998 self.niri.queue_redraw_all();
2999 return;
3000 }
3001 }
3002
3003 self.niri.layout.activate_window(&window);
3004
3005 if self
3006 .niri
3007 .layout
3008 .interactive_resize_begin(window.clone(), edges)
3009 {
3010 let start_data = PointerGrabStartData {
3011 focus: None,
3012 button: button_code,
3013 location,
3014 };
3015 let start_data = AnyStartData::Pointer(start_data);
3016 let grab = ResizeGrab::new(start_data, window.clone());
3017 pointer.set_grab(self, grab, serial, Focus::Clear);
3018 self.niri
3019 .cursor_manager
3020 .set_cursor_image(CursorImageStatus::Named(edges.cursor_icon()));
3021 }
3022 }
3023 }
3024
3025 if !is_overview_open {
3026 self.niri.layout.activate_window(&window);
3027 }
3028
3029 // FIXME: granular.
3030 self.niri.queue_redraw_all();
3031 } else if let Some((output, ws)) = is_overview_open
3032 .then(|| self.niri.workspace_under_cursor(false))
3033 .flatten()
3034 {
3035 let ws_idx = self.niri.layout.find_workspace_by_id(ws.id()).unwrap().0;
3036
3037 self.niri.layout.focus_output(&output);
3038 self.niri.layout.toggle_overview_to_workspace(ws_idx);
3039
3040 // FIXME: granular.
3041 self.niri.queue_redraw_all();
3042 } else if let Some(output) = self.niri.output_under_cursor() {
3043 self.niri.layout.focus_output(&output);
3044
3045 // FIXME: granular.
3046 self.niri.queue_redraw_all();
3047 }
3048 };
3049
3050 self.update_pointer_contents();
3051
3052 if ButtonState::Pressed == button_state {
3053 let layer_under = self.niri.pointer_contents.layer.clone();
3054 self.niri.focus_layer_surface_if_on_demand(layer_under);
3055 }
3056
3057 if button == Some(MouseButton::Left) && self.niri.screenshot_ui.is_open() {
3058 if button_state == ButtonState::Pressed {
3059 let pos = pointer.current_location();
3060
3061 // If we'll be moving the existing selection, use the selection output.
3062 let output = if mod_down {
3063 self.niri.screenshot_ui.selection_output()
3064 } else {
3065 self.niri.output_under(pos).map(|(out, _)| out)
3066 };
3067
3068 if let Some(output) = output.cloned() {
3069 let geom = self.niri.global_space.output_geometry(&output).unwrap();
3070 let point = (pos - geom.loc.to_f64())
3071 .to_physical(output.current_scale().fractional_scale())
3072 .to_i32_round();
3073
3074 if self
3075 .niri
3076 .screenshot_ui
3077 .pointer_down(output, point, None, mod_down)
3078 {
3079 self.niri.queue_redraw_all();
3080 }
3081 }
3082 } else if let Some(capture) = self.niri.screenshot_ui.pointer_up(None) {
3083 if capture {
3084 self.confirm_screenshot(true);
3085 } else {
3086 self.niri.queue_redraw_all();
3087 }
3088 }
3089 }
3090
3091 pointer.button(
3092 self,
3093 &ButtonEvent {
3094 button: button_code,
3095 state: button_state,
3096 serial,
3097 time: event.time_msec(),
3098 },
3099 );
3100 pointer.frame(self);
3101 }
3102
3103 fn on_pointer_axis<I: InputBackend>(&mut self, event: I::PointerAxisEvent) {
3104 let pointer = &self.niri.seat.get_pointer().unwrap();
3105
3106 let source = event.source();
3107
3108 let mod_key = self.backend.mod_key(&self.niri.config.borrow());
3109
3110 // We received an event for the regular pointer, so show it now. This is also needed for
3111 // update_pointer_contents() below to return the real contents, necessary for the pointer
3112 // axis event to reach the window.
3113 self.niri.pointer_visibility = PointerVisibility::Visible;
3114 self.niri.tablet_cursor_location = None;
3115
3116 let timestamp = Duration::from_micros(event.time());
3117
3118 let horizontal_amount_v120 = event.amount_v120(Axis::Horizontal);
3119 let vertical_amount_v120 = event.amount_v120(Axis::Vertical);
3120
3121 let is_overview_open = self.niri.layout.is_overview_open();
3122
3123 // We should only handle scrolling in the overview if the pointer is not over a (top or
3124 // overlay) layer surface.
3125 let should_handle_in_overview = if is_overview_open {
3126 // FIXME: ideally this should happen after updating the pointer contents, which happens
3127 // below. However, our pointer actions are supposed to act on the old surface, before
3128 // updating the pointer contents.
3129 pointer
3130 .current_focus()
3131 .map(|surface| self.niri.find_root_shell_surface(&surface))
3132 .is_none_or(|root| {
3133 !self
3134 .niri
3135 .mapped_layer_surfaces
3136 .keys()
3137 .any(|layer| *layer.wl_surface() == root)
3138 })
3139 } else {
3140 false
3141 };
3142
3143 let is_mru_open = self.niri.window_mru_ui.is_open();
3144
3145 // Handle wheel scroll bindings.
3146 if source == AxisSource::Wheel {
3147 // If we have a scroll bind with current modifiers, then accumulate and don't pass to
3148 // Wayland. If there's no bind, reset the accumulator.
3149 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
3150 let modifiers = modifiers_from_state(mods);
3151 let should_handle = should_handle_in_overview
3152 || is_mru_open
3153 || self.niri.mods_with_wheel_binds.contains(&modifiers);
3154 if should_handle {
3155 let horizontal = horizontal_amount_v120.unwrap_or(0.);
3156 let ticks = self.niri.horizontal_wheel_tracker.accumulate(horizontal);
3157 if ticks != 0 {
3158 let (bind_left, bind_right) =
3159 if should_handle_in_overview && modifiers.is_empty() {
3160 let bind_left = Some(Bind {
3161 key: Key {
3162 trigger: Trigger::WheelScrollLeft,
3163 modifiers: Modifiers::empty(),
3164 },
3165 action: Action::FocusColumnLeftUnderMouse,
3166 repeat: true,
3167 cooldown: None,
3168 allow_when_locked: false,
3169 allow_inhibiting: false,
3170 hotkey_overlay_title: None,
3171 });
3172 let bind_right = Some(Bind {
3173 key: Key {
3174 trigger: Trigger::WheelScrollRight,
3175 modifiers: Modifiers::empty(),
3176 },
3177 action: Action::FocusColumnRightUnderMouse,
3178 repeat: true,
3179 cooldown: None,
3180 allow_when_locked: false,
3181 allow_inhibiting: false,
3182 hotkey_overlay_title: None,
3183 });
3184 (bind_left, bind_right)
3185 } else {
3186 let config = self.niri.config.borrow();
3187 let bindings =
3188 make_binds_iter(&config, &mut self.niri.window_mru_ui, modifiers);
3189 let bind_left = find_configured_bind(
3190 bindings.clone(),
3191 mod_key,
3192 Trigger::WheelScrollLeft,
3193 mods,
3194 )
3195 .filter(|bind| {
3196 !self.niri.screenshot_ui.is_open()
3197 || allowed_during_screenshot(&bind.action)
3198 });
3199 let bind_right = find_configured_bind(
3200 bindings,
3201 mod_key,
3202 Trigger::WheelScrollRight,
3203 mods,
3204 )
3205 .filter(|bind| {
3206 !self.niri.screenshot_ui.is_open()
3207 || allowed_during_screenshot(&bind.action)
3208 });
3209 (bind_left, bind_right)
3210 };
3211
3212 if let Some(right) = bind_right {
3213 for _ in 0..ticks {
3214 self.handle_bind(right.clone());
3215 }
3216 }
3217 if let Some(left) = bind_left {
3218 for _ in ticks..0 {
3219 self.handle_bind(left.clone());
3220 }
3221 }
3222 }
3223
3224 let vertical = vertical_amount_v120.unwrap_or(0.);
3225 let ticks = self.niri.vertical_wheel_tracker.accumulate(vertical);
3226 if ticks != 0 {
3227 let (bind_up, bind_down) = if should_handle_in_overview && modifiers.is_empty()
3228 {
3229 let bind_up = Some(Bind {
3230 key: Key {
3231 trigger: Trigger::WheelScrollUp,
3232 modifiers: Modifiers::empty(),
3233 },
3234 action: Action::FocusWorkspaceUpUnderMouse,
3235 repeat: true,
3236 cooldown: Some(Duration::from_millis(50)),
3237 allow_when_locked: false,
3238 allow_inhibiting: false,
3239 hotkey_overlay_title: None,
3240 });
3241 let bind_down = Some(Bind {
3242 key: Key {
3243 trigger: Trigger::WheelScrollDown,
3244 modifiers: Modifiers::empty(),
3245 },
3246 action: Action::FocusWorkspaceDownUnderMouse,
3247 repeat: true,
3248 cooldown: Some(Duration::from_millis(50)),
3249 allow_when_locked: false,
3250 allow_inhibiting: false,
3251 hotkey_overlay_title: None,
3252 });
3253 (bind_up, bind_down)
3254 } else if should_handle_in_overview && modifiers == Modifiers::SHIFT {
3255 let bind_up = Some(Bind {
3256 key: Key {
3257 trigger: Trigger::WheelScrollUp,
3258 modifiers: Modifiers::empty(),
3259 },
3260 action: Action::FocusColumnLeftUnderMouse,
3261 repeat: true,
3262 cooldown: Some(Duration::from_millis(50)),
3263 allow_when_locked: false,
3264 allow_inhibiting: false,
3265 hotkey_overlay_title: None,
3266 });
3267 let bind_down = Some(Bind {
3268 key: Key {
3269 trigger: Trigger::WheelScrollDown,
3270 modifiers: Modifiers::empty(),
3271 },
3272 action: Action::FocusColumnRightUnderMouse,
3273 repeat: true,
3274 cooldown: Some(Duration::from_millis(50)),
3275 allow_when_locked: false,
3276 allow_inhibiting: false,
3277 hotkey_overlay_title: None,
3278 });
3279 (bind_up, bind_down)
3280 } else {
3281 let config = self.niri.config.borrow();
3282 let bindings =
3283 make_binds_iter(&config, &mut self.niri.window_mru_ui, modifiers);
3284 let bind_up = find_configured_bind(
3285 bindings.clone(),
3286 mod_key,
3287 Trigger::WheelScrollUp,
3288 mods,
3289 )
3290 .filter(|bind| {
3291 !self.niri.screenshot_ui.is_open()
3292 || allowed_during_screenshot(&bind.action)
3293 });
3294 let bind_down =
3295 find_configured_bind(bindings, mod_key, Trigger::WheelScrollDown, mods)
3296 .filter(|bind| {
3297 !self.niri.screenshot_ui.is_open()
3298 || allowed_during_screenshot(&bind.action)
3299 });
3300 (bind_up, bind_down)
3301 };
3302
3303 if let Some(down) = bind_down {
3304 for _ in 0..ticks {
3305 self.handle_bind(down.clone());
3306 }
3307 }
3308 if let Some(up) = bind_up {
3309 for _ in ticks..0 {
3310 self.handle_bind(up.clone());
3311 }
3312 }
3313 }
3314
3315 return;
3316 } else {
3317 self.niri.horizontal_wheel_tracker.reset();
3318 self.niri.vertical_wheel_tracker.reset();
3319 }
3320 }
3321
3322 let horizontal_amount = event.amount(Axis::Horizontal);
3323 let vertical_amount = event.amount(Axis::Vertical);
3324
3325 // Handle touchpad and continuous scroll bindings.
3326 if source == AxisSource::Finger || source == AxisSource::Continuous {
3327 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
3328 let modifiers = modifiers_from_state(mods);
3329
3330 let horizontal = horizontal_amount.unwrap_or(0.);
3331 let vertical = vertical_amount.unwrap_or(0.);
3332
3333 if should_handle_in_overview && modifiers.is_empty() {
3334 let mut redraw = false;
3335
3336 let action = self
3337 .niri
3338 .overview_scroll_swipe_gesture
3339 .update(horizontal, vertical);
3340 let is_vertical = self.niri.overview_scroll_swipe_gesture.is_vertical();
3341
3342 if action.end() {
3343 if is_vertical {
3344 redraw |= self
3345 .niri
3346 .layout
3347 .workspace_switch_gesture_end(Some(true))
3348 .is_some();
3349 } else {
3350 redraw |= self
3351 .niri
3352 .layout
3353 .view_offset_gesture_end(Some(true))
3354 .is_some();
3355 }
3356 } else {
3357 // Maybe begin, then update.
3358 if is_vertical {
3359 if action.begin() {
3360 if let Some(output) = self.niri.output_under_cursor() {
3361 self.niri
3362 .layout
3363 .workspace_switch_gesture_begin(&output, true);
3364 redraw = true;
3365 }
3366 }
3367
3368 let res = self
3369 .niri
3370 .layout
3371 .workspace_switch_gesture_update(vertical, timestamp, true);
3372 if let Some(Some(_)) = res {
3373 redraw = true;
3374 }
3375 } else {
3376 if action.begin() {
3377 if let Some((output, ws)) = self.niri.workspace_under_cursor(true) {
3378 let ws_id = ws.id();
3379 let ws_idx =
3380 self.niri.layout.find_workspace_by_id(ws_id).unwrap().0;
3381
3382 self.niri.layout.view_offset_gesture_begin(
3383 &output,
3384 Some(ws_idx),
3385 true,
3386 );
3387 redraw = true;
3388 }
3389 }
3390
3391 let res = self
3392 .niri
3393 .layout
3394 .view_offset_gesture_update(horizontal, timestamp, true);
3395 if let Some(Some(_)) = res {
3396 redraw = true;
3397 }
3398 }
3399 }
3400
3401 if redraw {
3402 self.niri.queue_redraw_all();
3403 }
3404
3405 return;
3406 } else {
3407 let mut redraw = false;
3408 if self.niri.overview_scroll_swipe_gesture.reset() {
3409 if self.niri.overview_scroll_swipe_gesture.is_vertical() {
3410 redraw |= self
3411 .niri
3412 .layout
3413 .workspace_switch_gesture_end(Some(true))
3414 .is_some();
3415 } else {
3416 redraw |= self
3417 .niri
3418 .layout
3419 .view_offset_gesture_end(Some(true))
3420 .is_some();
3421 }
3422 }
3423 if redraw {
3424 self.niri.queue_redraw_all();
3425 }
3426 }
3427
3428 if is_mru_open || self.niri.mods_with_finger_scroll_binds.contains(&modifiers) {
3429 let ticks = self
3430 .niri
3431 .horizontal_finger_scroll_tracker
3432 .accumulate(horizontal);
3433 if ticks != 0 {
3434 let config = self.niri.config.borrow();
3435 let bindings =
3436 make_binds_iter(&config, &mut self.niri.window_mru_ui, modifiers);
3437 let bind_left = find_configured_bind(
3438 bindings.clone(),
3439 mod_key,
3440 Trigger::TouchpadScrollLeft,
3441 mods,
3442 )
3443 .filter(|bind| {
3444 !self.niri.screenshot_ui.is_open()
3445 || allowed_during_screenshot(&bind.action)
3446 });
3447 let bind_right =
3448 find_configured_bind(bindings, mod_key, Trigger::TouchpadScrollRight, mods)
3449 .filter(|bind| {
3450 !self.niri.screenshot_ui.is_open()
3451 || allowed_during_screenshot(&bind.action)
3452 });
3453 drop(config);
3454
3455 if let Some(right) = bind_right {
3456 for _ in 0..ticks {
3457 self.handle_bind(right.clone());
3458 }
3459 }
3460 if let Some(left) = bind_left {
3461 for _ in ticks..0 {
3462 self.handle_bind(left.clone());
3463 }
3464 }
3465 }
3466
3467 let ticks = self
3468 .niri
3469 .vertical_finger_scroll_tracker
3470 .accumulate(vertical);
3471 if ticks != 0 {
3472 let config = self.niri.config.borrow();
3473 let bindings =
3474 make_binds_iter(&config, &mut self.niri.window_mru_ui, modifiers);
3475 let bind_up = find_configured_bind(
3476 bindings.clone(),
3477 mod_key,
3478 Trigger::TouchpadScrollUp,
3479 mods,
3480 )
3481 .filter(|bind| {
3482 !self.niri.screenshot_ui.is_open()
3483 || allowed_during_screenshot(&bind.action)
3484 });
3485 let bind_down =
3486 find_configured_bind(bindings, mod_key, Trigger::TouchpadScrollDown, mods)
3487 .filter(|bind| {
3488 !self.niri.screenshot_ui.is_open()
3489 || allowed_during_screenshot(&bind.action)
3490 });
3491 drop(config);
3492
3493 if let Some(down) = bind_down {
3494 for _ in 0..ticks {
3495 self.handle_bind(down.clone());
3496 }
3497 }
3498 if let Some(up) = bind_up {
3499 for _ in ticks..0 {
3500 self.handle_bind(up.clone());
3501 }
3502 }
3503 }
3504
3505 return;
3506 } else {
3507 self.niri.horizontal_finger_scroll_tracker.reset();
3508 self.niri.vertical_finger_scroll_tracker.reset();
3509 }
3510 }
3511
3512 self.update_pointer_contents();
3513
3514 let device_scroll_factor = {
3515 let config = self.niri.config.borrow();
3516 match source {
3517 AxisSource::Wheel => config.input.mouse.scroll_factor,
3518 AxisSource::Finger => config.input.touchpad.scroll_factor,
3519 _ => None,
3520 }
3521 };
3522
3523 // Get window-specific scroll factor
3524 let window_scroll_factor = pointer
3525 .current_focus()
3526 .map(|focused| self.niri.find_root_shell_surface(&focused))
3527 .and_then(|root| self.niri.layout.find_window_and_output(&root).unzip().0)
3528 .and_then(|window| window.rules().scroll_factor)
3529 .unwrap_or(1.);
3530
3531 // Determine final scroll factors based on configuration
3532 let (horizontal_factor, vertical_factor) = device_scroll_factor
3533 .map(|x| x.h_v_factors())
3534 .unwrap_or((1.0, 1.0));
3535 let (horizontal_factor, vertical_factor) = (
3536 horizontal_factor * window_scroll_factor,
3537 vertical_factor * window_scroll_factor,
3538 );
3539
3540 let horizontal_amount = horizontal_amount.unwrap_or_else(|| {
3541 // Winit backend, discrete scrolling.
3542 horizontal_amount_v120.unwrap_or(0.0) / 120. * 15.
3543 }) * horizontal_factor;
3544
3545 let vertical_amount = vertical_amount.unwrap_or_else(|| {
3546 // Winit backend, discrete scrolling.
3547 vertical_amount_v120.unwrap_or(0.0) / 120. * 15.
3548 }) * vertical_factor;
3549
3550 let horizontal_amount_v120 = horizontal_amount_v120.map(|x| x * horizontal_factor);
3551 let vertical_amount_v120 = vertical_amount_v120.map(|x| x * vertical_factor);
3552
3553 let mut frame = AxisFrame::new(event.time_msec()).source(source);
3554 if horizontal_amount != 0.0 {
3555 frame = frame
3556 .relative_direction(Axis::Horizontal, event.relative_direction(Axis::Horizontal));
3557 frame = frame.value(Axis::Horizontal, horizontal_amount);
3558 if let Some(v120) = horizontal_amount_v120 {
3559 frame = frame.v120(Axis::Horizontal, v120 as i32);
3560 }
3561 }
3562 if vertical_amount != 0.0 {
3563 frame =
3564 frame.relative_direction(Axis::Vertical, event.relative_direction(Axis::Vertical));
3565 frame = frame.value(Axis::Vertical, vertical_amount);
3566 if let Some(v120) = vertical_amount_v120 {
3567 frame = frame.v120(Axis::Vertical, v120 as i32);
3568 }
3569 }
3570
3571 if source == AxisSource::Finger {
3572 if event.amount(Axis::Horizontal) == Some(0.0) {
3573 frame = frame.stop(Axis::Horizontal);
3574 }
3575 if event.amount(Axis::Vertical) == Some(0.0) {
3576 frame = frame.stop(Axis::Vertical);
3577 }
3578 }
3579
3580 pointer.axis(self, frame);
3581 pointer.frame(self);
3582 }
3583
3584 fn on_tablet_tool_axis<I: InputBackend>(&mut self, event: I::TabletToolAxisEvent)
3585 where
3586 I::Device: 'static, // Needed for downcasting.
3587 {
3588 let Some(pos) = self.compute_tablet_position(&event) else {
3589 return;
3590 };
3591
3592 if let Some(output) = self.niri.screenshot_ui.selection_output() {
3593 let geom = self.niri.global_space.output_geometry(output).unwrap();
3594 let point = (pos - geom.loc.to_f64())
3595 .to_physical(output.current_scale().fractional_scale())
3596 .to_i32_round::<i32>();
3597
3598 self.niri.screenshot_ui.pointer_motion(point, None);
3599 }
3600
3601 if let Some(mru_output) = self.niri.window_mru_ui.output() {
3602 if let Some((output, pos_within_output)) = self.niri.output_under(pos) {
3603 if mru_output == output {
3604 self.niri.window_mru_ui.pointer_motion(pos_within_output);
3605 }
3606 }
3607 }
3608
3609 let under = self.niri.contents_under(pos);
3610
3611 let tablet_seat = self.niri.seat.tablet_seat();
3612 let tool = tablet_seat.get_tool(&event.tool());
3613 if let Some(tool) = tool {
3614 let time = event.time_msec();
3615
3616 let frame = tablet::tool::AxisFrame {
3617 pressure: event.pressure_has_changed().then(|| event.pressure()),
3618 distance: event.distance_has_changed().then(|| event.distance()),
3619 tilt: event.tilt_has_changed().then(|| event.tilt()),
3620 rotation: event.rotation_has_changed().then(|| event.rotation()),
3621 slider: event.slider_has_changed().then(|| event.slider_position()),
3622 wheel: event
3623 .wheel_has_changed()
3624 .then(|| (event.wheel_delta(), event.wheel_delta_discrete())),
3625 };
3626 tool.axis(self, frame);
3627
3628 tool.motion(
3629 self,
3630 under.surface,
3631 &tablet::tool::MotionEvent {
3632 location: pos,
3633 serial: SERIAL_COUNTER.next_serial(),
3634 time,
3635 },
3636 );
3637
3638 tool.frame(self, time);
3639
3640 self.niri.pointer_visibility = PointerVisibility::Visible;
3641 self.niri.tablet_cursor_location = Some(pos);
3642 }
3643
3644 // Redraw to update the cursor position.
3645 // FIXME: redraw only outputs overlapping the cursor.
3646 self.niri.queue_redraw_all();
3647 }
3648
3649 fn on_tablet_tool_tip<I: InputBackend>(&mut self, event: I::TabletToolTipEvent) {
3650 let tool = self.niri.seat.tablet_seat().get_tool(&event.tool());
3651
3652 let Some(tool) = tool else {
3653 return;
3654 };
3655 let tip_state = event.tip_state();
3656
3657 let serial = SERIAL_COUNTER.next_serial();
3658 let time = event.time_msec();
3659
3660 match tip_state {
3661 TabletToolTipState::Down => {
3662 if let Some(pos) = self.niri.tablet_cursor_location {
3663 let under = self.niri.contents_under(pos);
3664
3665 let mod_key = self.backend.mod_key(&self.niri.config.borrow());
3666 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
3667 let modifiers = modifiers_from_state(mods);
3668 let mod_down = modifiers.contains(mod_key.to_modifiers());
3669
3670 if self.niri.screenshot_ui.is_open() {
3671 // If we'll be moving the existing selection, use the selection output.
3672 let output = if mod_down {
3673 self.niri.screenshot_ui.selection_output()
3674 } else {
3675 under.output.as_ref()
3676 };
3677
3678 if let Some(output) = output.cloned() {
3679 let geom = self.niri.global_space.output_geometry(&output).unwrap();
3680 let point = (pos - geom.loc.to_f64())
3681 .to_physical(output.current_scale().fractional_scale())
3682 .to_i32_round();
3683
3684 if self
3685 .niri
3686 .screenshot_ui
3687 .pointer_down(output, point, None, mod_down)
3688 {
3689 self.niri.queue_redraw_all();
3690 }
3691 }
3692 } else if let Some(mru_output) = self.niri.window_mru_ui.output() {
3693 if let Some((output, pos_within_output)) = self.niri.output_under(pos) {
3694 if mru_output == output {
3695 let id = self.niri.window_mru_ui.pointer_motion(pos_within_output);
3696 if id.is_some() {
3697 self.confirm_mru();
3698 } else {
3699 self.niri.cancel_mru();
3700 }
3701 } else {
3702 self.niri.cancel_mru();
3703 }
3704 }
3705 } else if !tool.is_grabbed() {
3706 if self.niri.layout.is_overview_open()
3707 && !mod_down
3708 && under.layer.is_none()
3709 && under.output.is_some()
3710 {
3711 let (output, pos_within_output) = self.niri.output_under(pos).unwrap();
3712 let output = output.clone();
3713
3714 let mut matched_narrow = true;
3715 let mut ws = self.niri.workspace_under(false, pos);
3716 if ws.is_none() {
3717 matched_narrow = false;
3718 ws = self.niri.workspace_under(true, pos);
3719 }
3720 let ws_id = ws.map(|(_, ws)| ws.id());
3721
3722 let mapped = self.niri.window_under(pos);
3723 let window = mapped.map(|mapped| mapped.window.clone());
3724
3725 let start_data = TabletToolGrabStartData {
3726 focus: None,
3727 trigger: tablet::tool::GrabTrigger::Tip,
3728 location: pos,
3729 };
3730 let start_data = AnyStartData::TabletTool(start_data);
3731 let start_timestamp = Duration::from_micros(event.time());
3732 let grab = TouchOverviewGrab::new(
3733 start_data,
3734 start_timestamp,
3735 output,
3736 pos_within_output,
3737 ws_id,
3738 matched_narrow,
3739 window,
3740 );
3741 tool.set_grab(self, grab, time, serial, Focus::Clear);
3742 } else if let Some((window, _)) = under.window {
3743 self.niri.layout.activate_window(&window);
3744
3745 // Check if we need to start a tablet tool move grab.
3746 if mod_down {
3747 let start_data = TabletToolGrabStartData {
3748 focus: None,
3749 trigger: tablet::tool::GrabTrigger::Tip,
3750 location: pos,
3751 };
3752 let start_data = AnyStartData::TabletTool(start_data);
3753 let icon = CursorIcon::Grabbing;
3754 if let Some(grab) = MoveGrab::new(
3755 self,
3756 start_data,
3757 window.clone(),
3758 true,
3759 Some(icon),
3760 ) {
3761 tool.set_grab(self, grab, time, serial, Focus::Clear);
3762 }
3763 }
3764
3765 // FIXME: granular.
3766 self.niri.queue_redraw_all();
3767 } else if let Some(output) = under.output {
3768 self.niri.layout.focus_output(&output);
3769
3770 // FIXME: granular.
3771 self.niri.queue_redraw_all();
3772 }
3773 self.niri.focus_layer_surface_if_on_demand(under.layer);
3774 }
3775 }
3776
3777 tool.down(self, &tablet::tool::DownEvent { serial, time });
3778 }
3779 TabletToolTipState::Up => {
3780 if let Some(capture) = self.niri.screenshot_ui.pointer_up(None) {
3781 if capture {
3782 self.confirm_screenshot(true);
3783 } else {
3784 self.niri.queue_redraw_all();
3785 }
3786 }
3787
3788 tool.up(self, &tablet::tool::UpEvent { serial, time });
3789 }
3790 }
3791
3792 tool.frame(self, time);
3793 }
3794
3795 fn on_tablet_tool_proximity<I: InputBackend>(&mut self, event: I::TabletToolProximityEvent)
3796 where
3797 I::Device: 'static, // Needed for downcasting.
3798 {
3799 let Some(pos) = self.compute_tablet_position(&event) else {
3800 return;
3801 };
3802
3803 let under = self.niri.contents_under(pos);
3804
3805 let tablet_seat = self.niri.seat.tablet_seat();
3806 let display_handle = self.niri.display_handle.clone();
3807 let tool = tablet_seat
3808 .get_tool(&event.tool())
3809 .unwrap_or_else(|| tablet_seat.add_wp_tool(self, &display_handle, &event.tool()));
3810 let tablet = tablet_seat.get_tablet(&TabletDescriptor::from(&event.device()));
3811 if let Some(tablet) = tablet {
3812 let serial = SERIAL_COUNTER.next_serial();
3813 let time = event.time_msec();
3814
3815 match event.state() {
3816 ProximityState::In => {
3817 let frame = tablet::tool::AxisFrame {
3818 pressure: event.pressure_has_changed().then(|| event.pressure()),
3819 distance: event.distance_has_changed().then(|| event.distance()),
3820 tilt: event.tilt_has_changed().then(|| event.tilt()),
3821 rotation: event.rotation_has_changed().then(|| event.rotation()),
3822 slider: event.slider_has_changed().then(|| event.slider_position()),
3823 wheel: event
3824 .wheel_has_changed()
3825 .then(|| (event.wheel_delta(), event.wheel_delta_discrete())),
3826 };
3827
3828 tool.proximity_in(
3829 self,
3830 under.surface,
3831 tablet,
3832 &tablet::tool::ProximityInEvent {
3833 location: pos,
3834 axis: Some(frame),
3835 serial,
3836 time,
3837 },
3838 );
3839
3840 // Is proximity in usually immediatelly followed by other events like button? If
3841 // so, then it might be worth delaying this frame() until the loop callback to
3842 // batch all of them in.
3843 tool.frame(self, time);
3844
3845 self.niri.pointer_visibility = PointerVisibility::Visible;
3846 self.niri.tablet_cursor_location = Some(pos);
3847 }
3848 ProximityState::Out => {
3849 tool.proximity_out(self, &tablet::tool::ProximityOutEvent { serial, time });
3850 tool.frame(self, time);
3851
3852 // Move the mouse pointer here to avoid discontinuity.
3853 //
3854 // Plus, Wayland SDL2 currently warps the pointer into some weird
3855 // location on proximity out, so this should help it a little.
3856 if let Some(pos) = self.niri.tablet_cursor_location {
3857 self.move_cursor(pos);
3858 }
3859
3860 self.niri.pointer_visibility = PointerVisibility::Visible;
3861 self.niri.tablet_cursor_location = None;
3862 }
3863 }
3864
3865 // FIXME: granular.
3866 self.niri.queue_redraw_all();
3867 }
3868 }
3869
3870 fn on_tablet_tool_button<I: InputBackend>(&mut self, event: I::TabletToolButtonEvent) {
3871 const BTN_STYLUS3: u32 = 0x149;
3872 const BTN_STYLUS: u32 = 0x14b;
3873 const BTN_STYLUS2: u32 = 0x14c;
3874
3875 let tool = self.niri.seat.tablet_seat().get_tool(&event.tool());
3876
3877 if let Some(tool) = tool {
3878 let button = event.button();
3879
3880 if self.niri.suppressed_buttons.remove(&button) {
3881 return;
3882 }
3883
3884 let trigger = match button {
3885 BTN_STYLUS => Some(Trigger::TabletStylusButton1),
3886 BTN_STYLUS2 => Some(Trigger::TabletStylusButton2),
3887 BTN_STYLUS3 => Some(Trigger::TabletStylusButton3),
3888 _ => None,
3889 };
3890
3891 if let Some(trigger) = trigger {
3892 if event.button_state() == ButtonState::Pressed {
3893 let mod_key = self.backend.mod_key(&self.niri.config.borrow());
3894 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
3895 let modifiers = modifiers_from_state(mods);
3896
3897 if self.niri.mods_with_tablet_stylus_binds.contains(&modifiers) {
3898 let bind = {
3899 let config = self.niri.config.borrow();
3900 let bindings = config.binds.0.iter();
3901 find_configured_bind(bindings, mod_key, trigger, mods)
3902 }
3903 .filter(|bind| {
3904 !self.niri.screenshot_ui.is_open()
3905 || allowed_during_screenshot(&bind.action)
3906 });
3907 if let Some(bind) = bind {
3908 self.niri.suppressed_buttons.insert(button);
3909 self.handle_bind(bind.clone());
3910 return;
3911 }
3912 }
3913 }
3914 }
3915
3916 let time = event.time_msec();
3917
3918 tool.button(
3919 self,
3920 &tablet::tool::ButtonEvent {
3921 serial: SERIAL_COUNTER.next_serial(),
3922 button,
3923 state: event.button_state(),
3924 time,
3925 },
3926 );
3927
3928 tool.frame(self, time);
3929 }
3930 }
3931
3932 fn on_gesture_swipe_begin<I: InputBackend>(&mut self, event: I::GestureSwipeBeginEvent) {
3933 if self.niri.window_mru_ui.is_open() {
3934 // Don't start swipe gestures while in the MRU.
3935 return;
3936 }
3937
3938 if event.fingers() == 3 {
3939 self.niri.gesture_swipe_3f_cumulative = Some((0., 0.));
3940
3941 // We handled this event.
3942 return;
3943 } else if event.fingers() == 4 {
3944 self.niri.layout.overview_gesture_begin();
3945 self.niri.queue_redraw_all();
3946
3947 // We handled this event.
3948 return;
3949 }
3950
3951 let serial = SERIAL_COUNTER.next_serial();
3952 let pointer = self.niri.seat.get_pointer().unwrap();
3953
3954 if self.update_pointer_contents() {
3955 pointer.frame(self);
3956 }
3957
3958 pointer.gesture_swipe_begin(
3959 self,
3960 &GestureSwipeBeginEvent {
3961 serial,
3962 time: event.time_msec(),
3963 fingers: event.fingers(),
3964 },
3965 );
3966 }
3967
3968 fn on_gesture_swipe_update<I: InputBackend + 'static>(
3969 &mut self,
3970 event: I::GestureSwipeUpdateEvent,
3971 ) where
3972 I::Device: 'static,
3973 {
3974 let mut delta_x = event.delta_x();
3975 let mut delta_y = event.delta_y();
3976
3977 if let Some(libinput_event) =
3978 (&event as &dyn Any).downcast_ref::<input::event::gesture::GestureSwipeUpdateEvent>()
3979 {
3980 delta_x = libinput_event.dx_unaccelerated();
3981 delta_y = libinput_event.dy_unaccelerated();
3982 }
3983
3984 let uninverted_delta_y = delta_y;
3985
3986 let device = event.device();
3987 if let Some(device) = (&device as &dyn Any).downcast_ref::<input::Device>() {
3988 if device.config_scroll_natural_scroll_enabled() {
3989 delta_x = -delta_x;
3990 delta_y = -delta_y;
3991 }
3992 }
3993
3994 let is_overview_open = self.niri.layout.is_overview_open();
3995
3996 if let Some((cx, cy)) = &mut self.niri.gesture_swipe_3f_cumulative {
3997 *cx += delta_x;
3998 *cy += delta_y;
3999
4000 // Check if the gesture moved far enough to decide. Threshold copied from GNOME Shell.
4001 let (cx, cy) = (*cx, *cy);
4002 if cx * cx + cy * cy >= 16. * 16. {
4003 self.niri.gesture_swipe_3f_cumulative = None;
4004
4005 if let Some(output) = self.niri.output_under_cursor() {
4006 if cx.abs() > cy.abs() {
4007 let output_ws = if is_overview_open {
4008 self.niri.workspace_under_cursor(true)
4009 } else {
4010 // We don't want to accidentally "catch" the wrong workspace during
4011 // animations.
4012 self.niri.output_under_cursor().and_then(|output| {
4013 let mon = self.niri.layout.monitor_for_output(&output)?;
4014 Some((output, mon.active_workspace_ref()))
4015 })
4016 };
4017
4018 if let Some((output, ws)) = output_ws {
4019 let ws_idx = self.niri.layout.find_workspace_by_id(ws.id()).unwrap().0;
4020 self.niri
4021 .layout
4022 .view_offset_gesture_begin(&output, Some(ws_idx), true);
4023 }
4024 } else {
4025 self.niri
4026 .layout
4027 .workspace_switch_gesture_begin(&output, true);
4028 }
4029 }
4030 }
4031 }
4032
4033 let timestamp = Duration::from_micros(event.time());
4034
4035 let mut handled = false;
4036 let res = self
4037 .niri
4038 .layout
4039 .workspace_switch_gesture_update(delta_y, timestamp, true);
4040 if let Some(output) = res {
4041 if let Some(output) = output {
4042 self.niri.queue_redraw(&output);
4043 }
4044 handled = true;
4045 }
4046
4047 let res = self
4048 .niri
4049 .layout
4050 .view_offset_gesture_update(delta_x, timestamp, true);
4051 if let Some(output) = res {
4052 if let Some(output) = output {
4053 self.niri.queue_redraw(&output);
4054 }
4055 handled = true;
4056 }
4057
4058 let res = self
4059 .niri
4060 .layout
4061 .overview_gesture_update(-uninverted_delta_y, timestamp);
4062 if let Some(redraw) = res {
4063 if redraw {
4064 self.niri.queue_redraw_all();
4065 }
4066 handled = true;
4067 }
4068
4069 if handled {
4070 // We handled this event.
4071 return;
4072 }
4073
4074 let pointer = self.niri.seat.get_pointer().unwrap();
4075
4076 if self.update_pointer_contents() {
4077 pointer.frame(self);
4078 }
4079
4080 pointer.gesture_swipe_update(
4081 self,
4082 &GestureSwipeUpdateEvent {
4083 time: event.time_msec(),
4084 delta: event.delta(),
4085 },
4086 );
4087 }
4088
4089 fn on_gesture_swipe_end<I: InputBackend>(&mut self, event: I::GestureSwipeEndEvent) {
4090 self.niri.gesture_swipe_3f_cumulative = None;
4091
4092 let mut handled = false;
4093 let res = self.niri.layout.workspace_switch_gesture_end(Some(true));
4094 if let Some(output) = res {
4095 self.niri.queue_redraw(&output);
4096 handled = true;
4097 }
4098
4099 let res = self.niri.layout.view_offset_gesture_end(Some(true));
4100 if let Some(output) = res {
4101 self.niri.queue_redraw(&output);
4102 handled = true;
4103 }
4104
4105 let res = self.niri.layout.overview_gesture_end();
4106 if res {
4107 self.niri.queue_redraw_all();
4108 handled = true;
4109 }
4110
4111 if handled {
4112 // We handled this event.
4113 return;
4114 }
4115
4116 let serial = SERIAL_COUNTER.next_serial();
4117 let pointer = self.niri.seat.get_pointer().unwrap();
4118
4119 if self.update_pointer_contents() {
4120 pointer.frame(self);
4121 }
4122
4123 pointer.gesture_swipe_end(
4124 self,
4125 &GestureSwipeEndEvent {
4126 serial,
4127 time: event.time_msec(),
4128 cancelled: event.cancelled(),
4129 },
4130 );
4131 }
4132
4133 fn on_gesture_pinch_begin<I: InputBackend>(&mut self, event: I::GesturePinchBeginEvent) {
4134 let serial = SERIAL_COUNTER.next_serial();
4135 let pointer = self.niri.seat.get_pointer().unwrap();
4136
4137 if self.update_pointer_contents() {
4138 pointer.frame(self);
4139 }
4140
4141 pointer.gesture_pinch_begin(
4142 self,
4143 &GesturePinchBeginEvent {
4144 serial,
4145 time: event.time_msec(),
4146 fingers: event.fingers(),
4147 },
4148 );
4149 }
4150
4151 fn on_gesture_pinch_update<I: InputBackend>(&mut self, event: I::GesturePinchUpdateEvent) {
4152 let pointer = self.niri.seat.get_pointer().unwrap();
4153
4154 if self.update_pointer_contents() {
4155 pointer.frame(self);
4156 }
4157
4158 pointer.gesture_pinch_update(
4159 self,
4160 &GesturePinchUpdateEvent {
4161 time: event.time_msec(),
4162 delta: event.delta(),
4163 scale: event.scale(),
4164 rotation: event.rotation(),
4165 },
4166 );
4167 }
4168
4169 fn on_gesture_pinch_end<I: InputBackend>(&mut self, event: I::GesturePinchEndEvent) {
4170 let serial = SERIAL_COUNTER.next_serial();
4171 let pointer = self.niri.seat.get_pointer().unwrap();
4172
4173 if self.update_pointer_contents() {
4174 pointer.frame(self);
4175 }
4176
4177 pointer.gesture_pinch_end(
4178 self,
4179 &GesturePinchEndEvent {
4180 serial,
4181 time: event.time_msec(),
4182 cancelled: event.cancelled(),
4183 },
4184 );
4185 }
4186
4187 fn on_gesture_hold_begin<I: InputBackend>(&mut self, event: I::GestureHoldBeginEvent) {
4188 let serial = SERIAL_COUNTER.next_serial();
4189 let pointer = self.niri.seat.get_pointer().unwrap();
4190
4191 if self.update_pointer_contents() {
4192 pointer.frame(self);
4193 }
4194
4195 pointer.gesture_hold_begin(
4196 self,
4197 &GestureHoldBeginEvent {
4198 serial,
4199 time: event.time_msec(),
4200 fingers: event.fingers(),
4201 },
4202 );
4203 }
4204
4205 fn on_gesture_hold_end<I: InputBackend>(&mut self, event: I::GestureHoldEndEvent) {
4206 let serial = SERIAL_COUNTER.next_serial();
4207 let pointer = self.niri.seat.get_pointer().unwrap();
4208
4209 if self.update_pointer_contents() {
4210 pointer.frame(self);
4211 }
4212
4213 pointer.gesture_hold_end(
4214 self,
4215 &GestureHoldEndEvent {
4216 serial,
4217 time: event.time_msec(),
4218 cancelled: event.cancelled(),
4219 },
4220 );
4221 }
4222
4223 fn compute_absolute_location<I: InputBackend>(
4224 &self,
4225 evt: &impl AbsolutePositionEvent<I>,
4226 fallback_output: Option<&Output>,
4227 ) -> Option<Point<f64, Logical>> {
4228 let output = evt.device().output(self);
4229 let output = output.filter(|output| self.niri.output_exists(output));
4230 let output = output.as_ref().or(fallback_output)?;
4231 let output_geo = self.niri.global_space.output_geometry(output).unwrap();
4232 let transform = output.current_transform();
4233 let size = transform.invert().transform_size(output_geo.size);
4234 Some(
4235 transform.transform_point_in(evt.position_transformed(size), &size.to_f64())
4236 + output_geo.loc.to_f64(),
4237 )
4238 }
4239
4240 /// Computes the cursor position for the touch event.
4241 ///
4242 /// This function handles the touch output mapping, as well as coordinate transform
4243 fn compute_touch_location<I: InputBackend>(
4244 &self,
4245 evt: &impl AbsolutePositionEvent<I>,
4246 ) -> Option<Point<f64, Logical>> {
4247 self.compute_absolute_location(evt, self.niri.output_for_touch())
4248 }
4249
4250 fn on_touch_down<I: InputBackend>(&mut self, evt: I::TouchDownEvent) {
4251 let Some(handle) = self.niri.seat.get_touch() else {
4252 return;
4253 };
4254 let Some(pos) = self.compute_touch_location(&evt) else {
4255 return;
4256 };
4257 let slot = evt.slot();
4258
4259 let serial = SERIAL_COUNTER.next_serial();
4260
4261 let under = self.niri.contents_under(pos);
4262
4263 let mod_key = self.backend.mod_key(&self.niri.config.borrow());
4264 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
4265 let mods = modifiers_from_state(mods);
4266 let mod_down = mods.contains(mod_key.to_modifiers());
4267
4268 if self.niri.screenshot_ui.is_open() {
4269 // If we'll be moving the existing selection, use the selection output.
4270 let output = if mod_down {
4271 self.niri.screenshot_ui.selection_output()
4272 } else {
4273 under.output.as_ref()
4274 };
4275
4276 if let Some(output) = output.cloned() {
4277 let geom = self.niri.global_space.output_geometry(&output).unwrap();
4278 let point = (pos - geom.loc.to_f64())
4279 .to_physical(output.current_scale().fractional_scale())
4280 .to_i32_round();
4281
4282 if self
4283 .niri
4284 .screenshot_ui
4285 .pointer_down(output, point, Some(slot), mod_down)
4286 {
4287 self.niri.queue_redraw_all();
4288 }
4289 }
4290 } else if let Some(mru_output) = self.niri.window_mru_ui.output() {
4291 if let Some((output, pos_within_output)) = self.niri.output_under(pos) {
4292 if mru_output == output {
4293 let id = self.niri.window_mru_ui.pointer_motion(pos_within_output);
4294 if id.is_some() {
4295 self.confirm_mru();
4296 } else {
4297 self.niri.cancel_mru();
4298 }
4299 } else {
4300 self.niri.cancel_mru();
4301 }
4302 }
4303 } else if !handle.is_grabbed() {
4304 if self.niri.layout.is_overview_open()
4305 && !mod_down
4306 && under.layer.is_none()
4307 && under.output.is_some()
4308 {
4309 let (output, pos_within_output) = self.niri.output_under(pos).unwrap();
4310 let output = output.clone();
4311
4312 let mut matched_narrow = true;
4313 let mut ws = self.niri.workspace_under(false, pos);
4314 if ws.is_none() {
4315 matched_narrow = false;
4316 ws = self.niri.workspace_under(true, pos);
4317 }
4318 let ws_id = ws.map(|(_, ws)| ws.id());
4319
4320 let mapped = self.niri.window_under(pos);
4321 let window = mapped.map(|mapped| mapped.window.clone());
4322
4323 let start_data = TouchGrabStartData {
4324 focus: None,
4325 slot,
4326 location: pos,
4327 };
4328 let start_data = AnyStartData::Touch(start_data);
4329 let start_timestamp = Duration::from_micros(evt.time());
4330 let grab = TouchOverviewGrab::new(
4331 start_data,
4332 start_timestamp,
4333 output,
4334 pos_within_output,
4335 ws_id,
4336 matched_narrow,
4337 window,
4338 );
4339 handle.set_grab(self, grab, serial);
4340 } else if let Some((window, _)) = under.window {
4341 self.niri.layout.activate_window(&window);
4342
4343 // Check if we need to start a touch move grab.
4344 if mod_down {
4345 let start_data = TouchGrabStartData {
4346 focus: None,
4347 slot,
4348 location: pos,
4349 };
4350 let start_data = AnyStartData::Touch(start_data);
4351 if let Some(grab) = MoveGrab::new(self, start_data, window.clone(), true, None)
4352 {
4353 handle.set_grab(self, grab, serial);
4354 }
4355 }
4356
4357 // FIXME: granular.
4358 self.niri.queue_redraw_all();
4359 } else if let Some(output) = under.output {
4360 self.niri.layout.focus_output(&output);
4361
4362 // FIXME: granular.
4363 self.niri.queue_redraw_all();
4364 }
4365 self.niri.focus_layer_surface_if_on_demand(under.layer);
4366 };
4367
4368 handle.down(
4369 self,
4370 under.surface,
4371 &DownEvent {
4372 slot,
4373 location: pos,
4374 serial,
4375 time: evt.time_msec(),
4376 },
4377 );
4378
4379 // We're using touch, hide the pointer.
4380 self.niri.pointer_visibility = PointerVisibility::Disabled;
4381 }
4382 fn on_touch_up<I: InputBackend>(&mut self, evt: I::TouchUpEvent) {
4383 let Some(handle) = self.niri.seat.get_touch() else {
4384 return;
4385 };
4386 let slot = evt.slot();
4387
4388 if let Some(capture) = self.niri.screenshot_ui.pointer_up(Some(slot)) {
4389 if capture {
4390 self.confirm_screenshot(true);
4391 } else {
4392 self.niri.queue_redraw_all();
4393 }
4394 }
4395
4396 let serial = SERIAL_COUNTER.next_serial();
4397 handle.up(
4398 self,
4399 &UpEvent {
4400 slot,
4401 serial,
4402 time: evt.time_msec(),
4403 },
4404 )
4405 }
4406 fn on_touch_motion<I: InputBackend>(&mut self, evt: I::TouchMotionEvent) {
4407 let Some(handle) = self.niri.seat.get_touch() else {
4408 return;
4409 };
4410 let Some(pos) = self.compute_touch_location(&evt) else {
4411 return;
4412 };
4413 let slot = evt.slot();
4414
4415 if let Some(output) = self.niri.screenshot_ui.selection_output().cloned() {
4416 let geom = self.niri.global_space.output_geometry(&output).unwrap();
4417 let point = (pos - geom.loc.to_f64())
4418 .to_physical(output.current_scale().fractional_scale())
4419 .to_i32_round::<i32>();
4420
4421 self.niri.screenshot_ui.pointer_motion(point, Some(slot));
4422 self.niri.queue_redraw(&output);
4423 }
4424
4425 let under = self.niri.contents_under(pos);
4426 handle.motion(
4427 self,
4428 under.surface,
4429 &TouchMotionEvent {
4430 slot,
4431 location: pos,
4432 time: evt.time_msec(),
4433 },
4434 );
4435
4436 // Inform the layout of an ongoing DnD operation.
4437 let is_dnd_grab = handle
4438 .with_grab(|_, grab| Self::is_dnd_grab(grab.as_any()))
4439 .unwrap_or(false);
4440 if is_dnd_grab {
4441 if let Some((output, pos_within_output)) = self.niri.output_under(pos) {
4442 let output = output.clone();
4443 self.niri.layout.dnd_update(output, pos_within_output);
4444 }
4445 }
4446 }
4447 fn on_touch_frame<I: InputBackend>(&mut self, _evt: I::TouchFrameEvent) {
4448 let Some(handle) = self.niri.seat.get_touch() else {
4449 return;
4450 };
4451 handle.frame(self);
4452 }
4453 fn on_touch_cancel<I: InputBackend>(&mut self, _evt: I::TouchCancelEvent) {
4454 let Some(handle) = self.niri.seat.get_touch() else {
4455 return;
4456 };
4457 handle.cancel(self);
4458 }
4459
4460 fn on_switch_toggle<I: InputBackend>(&mut self, evt: I::SwitchToggleEvent) {
4461 let Some(switch) = evt.switch() else {
4462 return;
4463 };
4464
4465 if switch == Switch::Lid {
4466 let is_closed = evt.state() == SwitchState::On;
4467 trace!("lid switch {}", if is_closed { "closed" } else { "opened" });
4468 self.set_lid_closed(is_closed);
4469 }
4470
4471 let action = {
4472 let bindings = &self.niri.config.borrow().switch_events;
4473 find_configured_switch_action(bindings, switch, evt.state())
4474 };
4475
4476 if let Some(action) = action {
4477 self.do_action(action, true);
4478 }
4479 }
4480
4481 pub fn is_dnd_grab(grab: &dyn Any) -> bool {
4482 // Normal DnD
4483 grab.is::<DnDGrab<Self, WlDataSource, WlSurface>>()
4484 // Null-source DnD: weston-dnd --self-only
4485 || grab.is::<DnDGrab<Self, WlSurface, WlSurface>>()
4486 }
4487
4488 fn grab_can_be_cancelled_with_esc(grab: &(dyn PointerGrab<State> + 'static)) -> bool {
4489 let grab = grab.as_any();
4490
4491 grab.is::<PickWindowGrab>() || grab.is::<PickColorGrab>() || Self::is_dnd_grab(grab)
4492 }
4493}
4494
4495/// Check whether the key should be intercepted and mark intercepted
4496/// pressed keys as `suppressed`, thus preventing `releases` corresponding
4497/// to them from being delivered.
4498#[allow(clippy::too_many_arguments)]
4499fn should_intercept_key<'a>(
4500 suppressed_keys: &mut HashSet<Keycode>,
4501 bindings: impl IntoIterator<Item = &'a Bind>,
4502 mod_key: ModKey,
4503 key_code: Keycode,
4504 modified: Keysym,
4505 raw: Option<Keysym>,
4506 pressed: bool,
4507 mods: ModifiersState,
4508 screenshot_ui: &ScreenshotUi,
4509 disable_power_key_handling: bool,
4510 is_inhibiting_shortcuts: bool,
4511) -> FilterResult<Option<Bind>> {
4512 // Actions are only triggered on presses, release of the key
4513 // shouldn't try to intercept anything unless we have marked
4514 // the key to suppress.
4515 if !pressed && !suppressed_keys.contains(&key_code) {
4516 return FilterResult::Forward;
4517 }
4518
4519 let mut final_bind = find_bind(
4520 bindings,
4521 mod_key,
4522 modified,
4523 raw,
4524 mods,
4525 disable_power_key_handling,
4526 );
4527
4528 // Allow only a subset of compositor actions while the screenshot UI is open, since the user
4529 // cannot see the screen.
4530 if screenshot_ui.is_open() {
4531 let mut use_screenshot_ui_action = true;
4532
4533 if let Some(bind) = &final_bind {
4534 if allowed_during_screenshot(&bind.action) {
4535 use_screenshot_ui_action = false;
4536 }
4537 }
4538
4539 if use_screenshot_ui_action {
4540 if let Some(raw) = raw {
4541 final_bind = screenshot_ui.action(raw, mods).map(|action| Bind {
4542 key: Key {
4543 trigger: Trigger::Keysym(raw),
4544 // Not entirely correct but it doesn't matter in how we currently use it.
4545 modifiers: Modifiers::empty(),
4546 },
4547 action,
4548 repeat: true,
4549 cooldown: None,
4550 allow_when_locked: false,
4551 // The screenshot UI owns the focus anyway, so this doesn't really matter.
4552 // But logically, nothing can inhibit its actions. Only opening it can be
4553 // inhibited.
4554 allow_inhibiting: false,
4555 hotkey_overlay_title: None,
4556 });
4557 }
4558 }
4559 }
4560
4561 match (final_bind, pressed) {
4562 (Some(bind), true) => {
4563 if is_inhibiting_shortcuts && bind.allow_inhibiting {
4564 FilterResult::Forward
4565 } else {
4566 suppressed_keys.insert(key_code);
4567 FilterResult::Intercept(Some(bind))
4568 }
4569 }
4570 (_, false) => {
4571 // By this point, we know that the key was suppressed on press. Even if we're inhibiting
4572 // shortcuts, we should still suppress the release.
4573 // But we don't need to check for shortcuts inhibition here, because
4574 // if it was inhibited on press (forwarded to the client), it wouldn't be suppressed,
4575 // so the release would already have been forwarded at the start of this function.
4576 suppressed_keys.remove(&key_code);
4577 FilterResult::Intercept(None)
4578 }
4579 (None, true) => FilterResult::Forward,
4580 }
4581}
4582
4583fn find_bind<'a>(
4584 bindings: impl IntoIterator<Item = &'a Bind>,
4585 mod_key: ModKey,
4586 modified: Keysym,
4587 raw: Option<Keysym>,
4588 mods: ModifiersState,
4589 disable_power_key_handling: bool,
4590) -> Option<Bind> {
4591 use keysyms::*;
4592
4593 // Handle hardcoded binds.
4594 #[allow(non_upper_case_globals)] // wat
4595 let hardcoded_action = match modified.raw() {
4596 modified @ KEY_XF86Switch_VT_1..=KEY_XF86Switch_VT_12 => {
4597 let vt = (modified - KEY_XF86Switch_VT_1 + 1) as i32;
4598 Some(Action::ChangeVt(vt))
4599 }
4600 KEY_XF86PowerOff if !disable_power_key_handling => Some(Action::Suspend),
4601 _ => None,
4602 };
4603
4604 if let Some(action) = hardcoded_action {
4605 return Some(Bind {
4606 key: Key {
4607 // Not entirely correct but it doesn't matter in how we currently use it.
4608 trigger: Trigger::Keysym(modified),
4609 modifiers: Modifiers::empty(),
4610 },
4611 action,
4612 repeat: true,
4613 cooldown: None,
4614 allow_when_locked: false,
4615 // In a worst-case scenario, the user has no way to unlock the compositor and a
4616 // misbehaving client has a keyboard shortcuts inhibitor, "jailing" the user.
4617 // The user must always be able to change VTs to recover from such a situation.
4618 // It also makes no sense to inhibit the default power key handling.
4619 // Hardcoded binds must never be inhibited.
4620 allow_inhibiting: false,
4621 hotkey_overlay_title: None,
4622 });
4623 }
4624
4625 let trigger = Trigger::Keysym(raw?);
4626 find_configured_bind(bindings, mod_key, trigger, mods)
4627}
4628
4629fn find_configured_bind<'a>(
4630 bindings: impl IntoIterator<Item = &'a Bind>,
4631 mod_key: ModKey,
4632 trigger: Trigger,
4633 mods: ModifiersState,
4634) -> Option<Bind> {
4635 // Handle configured binds.
4636 let mut modifiers = modifiers_from_state(mods);
4637
4638 let mod_down = modifiers_from_state(mods).contains(mod_key.to_modifiers());
4639 if mod_down {
4640 modifiers |= Modifiers::COMPOSITOR;
4641 }
4642
4643 for bind in bindings {
4644 if bind.key.trigger != trigger {
4645 continue;
4646 }
4647
4648 let mut bind_modifiers = bind.key.modifiers;
4649 if bind_modifiers.contains(Modifiers::COMPOSITOR) {
4650 bind_modifiers |= mod_key.to_modifiers();
4651 } else if bind_modifiers.contains(mod_key.to_modifiers()) {
4652 bind_modifiers |= Modifiers::COMPOSITOR;
4653 }
4654
4655 if bind_modifiers == modifiers {
4656 return Some(bind.clone());
4657 }
4658 }
4659
4660 None
4661}
4662
4663fn find_configured_switch_action(
4664 bindings: &SwitchBinds,
4665 switch: Switch,
4666 state: SwitchState,
4667) -> Option<Action> {
4668 let switch_action = match (switch, state) {
4669 (Switch::Lid, SwitchState::Off) => &bindings.lid_open,
4670 (Switch::Lid, SwitchState::On) => &bindings.lid_close,
4671 (Switch::TabletMode, SwitchState::Off) => &bindings.tablet_mode_off,
4672 (Switch::TabletMode, SwitchState::On) => &bindings.tablet_mode_on,
4673 _ => unreachable!(),
4674 };
4675 switch_action
4676 .as_ref()
4677 .map(|switch_action| Action::Spawn(switch_action.spawn.clone()))
4678}
4679
4680fn modifiers_from_state(mods: ModifiersState) -> Modifiers {
4681 let mut modifiers = Modifiers::empty();
4682 if mods.ctrl {
4683 modifiers |= Modifiers::CTRL;
4684 }
4685 if mods.shift {
4686 modifiers |= Modifiers::SHIFT;
4687 }
4688 if mods.alt {
4689 modifiers |= Modifiers::ALT;
4690 }
4691 if mods.logo {
4692 modifiers |= Modifiers::SUPER;
4693 }
4694 if mods.iso_level3_shift {
4695 modifiers |= Modifiers::ISO_LEVEL3_SHIFT;
4696 }
4697 if mods.iso_level5_shift {
4698 modifiers |= Modifiers::ISO_LEVEL5_SHIFT;
4699 }
4700 modifiers
4701}
4702
4703fn should_activate_monitors<I: InputBackend>(event: &InputEvent<I>) -> bool {
4704 match event {
4705 InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true,
4706 InputEvent::PointerButton { event } if event.state() == ButtonState::Pressed => true,
4707 InputEvent::PointerMotion { .. }
4708 | InputEvent::PointerMotionAbsolute { .. }
4709 | InputEvent::PointerAxis { .. }
4710 | InputEvent::GestureSwipeBegin { .. }
4711 | InputEvent::GesturePinchBegin { .. }
4712 | InputEvent::GestureHoldBegin { .. }
4713 | InputEvent::TouchDown { .. }
4714 | InputEvent::TouchMotion { .. }
4715 | InputEvent::TabletToolAxis { .. }
4716 | InputEvent::TabletToolProximity { .. }
4717 | InputEvent::TabletToolTip { .. }
4718 | InputEvent::TabletToolButton { .. } => true,
4719 // Ignore events like device additions and removals, key releases, gesture ends.
4720 _ => false,
4721 }
4722}
4723
4724fn should_hide_hotkey_overlay<I: InputBackend>(event: &InputEvent<I>) -> bool {
4725 match event {
4726 InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true,
4727 InputEvent::PointerButton { event } if event.state() == ButtonState::Pressed => true,
4728 InputEvent::PointerAxis { .. }
4729 | InputEvent::GestureSwipeBegin { .. }
4730 | InputEvent::GesturePinchBegin { .. }
4731 | InputEvent::TouchDown { .. }
4732 | InputEvent::TouchMotion { .. }
4733 | InputEvent::TabletToolTip { .. }
4734 | InputEvent::TabletToolButton { .. } => true,
4735 _ => false,
4736 }
4737}
4738
4739fn should_hide_exit_confirm_dialog<I: InputBackend>(event: &InputEvent<I>) -> bool {
4740 match event {
4741 InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true,
4742 InputEvent::PointerButton { event } if event.state() == ButtonState::Pressed => true,
4743 InputEvent::PointerAxis { .. }
4744 | InputEvent::GestureSwipeBegin { .. }
4745 | InputEvent::GesturePinchBegin { .. }
4746 | InputEvent::TouchDown { .. }
4747 | InputEvent::TouchMotion { .. }
4748 | InputEvent::TabletToolTip { .. }
4749 | InputEvent::TabletToolButton { .. } => true,
4750 _ => false,
4751 }
4752}
4753
4754fn should_notify_activity<I: InputBackend>(event: &InputEvent<I>) -> bool {
4755 !matches!(
4756 event,
4757 InputEvent::DeviceAdded { .. } | InputEvent::DeviceRemoved { .. }
4758 )
4759}
4760
4761fn should_reset_pointer_inactivity_timer<I: InputBackend>(event: &InputEvent<I>) -> bool {
4762 matches!(
4763 event,
4764 InputEvent::PointerAxis { .. }
4765 | InputEvent::PointerButton { .. }
4766 | InputEvent::PointerMotion { .. }
4767 | InputEvent::PointerMotionAbsolute { .. }
4768 | InputEvent::TabletToolAxis { .. }
4769 | InputEvent::TabletToolButton { .. }
4770 | InputEvent::TabletToolProximity { .. }
4771 | InputEvent::TabletToolTip { .. }
4772 )
4773}
4774
4775fn allowed_when_locked(action: &Action) -> bool {
4776 matches!(
4777 action,
4778 Action::Quit(_)
4779 | Action::ChangeVt(_)
4780 | Action::Suspend
4781 | Action::PowerOffMonitors
4782 | Action::PowerOnMonitors
4783 | Action::SwitchLayout(_)
4784 | Action::ToggleKeyboardShortcutsInhibit
4785 )
4786}
4787
4788fn allowed_during_screenshot(action: &Action) -> bool {
4789 matches!(
4790 action,
4791 Action::Quit(_)
4792 | Action::ChangeVt(_)
4793 | Action::Suspend
4794 | Action::PowerOffMonitors
4795 | Action::PowerOnMonitors
4796 // Intended for binds such as volume up/down, lock the screen, etc.
4797 | Action::Spawn(_)
4798 | Action::SpawnSh(_)
4799 // The screenshot UI can handle these.
4800 | Action::MoveColumnLeft
4801 | Action::MoveColumnLeftOrToMonitorLeft
4802 | Action::MoveColumnRight
4803 | Action::MoveColumnRightOrToMonitorRight
4804 | Action::MoveWindowUp
4805 | Action::MoveWindowUpOrToWorkspaceUp
4806 | Action::MoveWindowDown
4807 | Action::MoveWindowDownOrToWorkspaceDown
4808 | Action::MoveColumnToMonitorLeft
4809 | Action::MoveColumnToMonitorRight
4810 | Action::MoveColumnToMonitorUp
4811 | Action::MoveColumnToMonitorDown
4812 | Action::MoveColumnToMonitorPrevious
4813 | Action::MoveColumnToMonitorNext
4814 | Action::MoveColumnToMonitor(_)
4815 | Action::MoveWindowToMonitorLeft
4816 | Action::MoveWindowToMonitorRight
4817 | Action::MoveWindowToMonitorUp
4818 | Action::MoveWindowToMonitorDown
4819 | Action::MoveWindowToMonitorPrevious
4820 | Action::MoveWindowToMonitorNext
4821 | Action::MoveWindowToMonitor(_)
4822 | Action::SetWindowWidth(_)
4823 | Action::SetWindowHeight(_)
4824 | Action::SetColumnWidth(_)
4825 )
4826}
4827
4828fn hardcoded_overview_bind(raw: Keysym, mods: ModifiersState) -> Option<Bind> {
4829 let mods = modifiers_from_state(mods);
4830 if !mods.is_empty() {
4831 return None;
4832 }
4833
4834 let mut repeat = true;
4835 let action = match raw {
4836 Keysym::Escape | Keysym::Return => {
4837 repeat = false;
4838 Action::ToggleOverview
4839 }
4840 Keysym::Left => Action::FocusColumnLeft,
4841 Keysym::Right => Action::FocusColumnRight,
4842 Keysym::Up => Action::FocusWindowOrWorkspaceUp,
4843 Keysym::Down => Action::FocusWindowOrWorkspaceDown,
4844 _ => {
4845 return None;
4846 }
4847 };
4848
4849 Some(Bind {
4850 key: Key {
4851 trigger: Trigger::Keysym(raw),
4852 modifiers: Modifiers::empty(),
4853 },
4854 action,
4855 repeat,
4856 cooldown: None,
4857 allow_when_locked: false,
4858 allow_inhibiting: false,
4859 hotkey_overlay_title: None,
4860 })
4861}
4862
4863pub fn apply_libinput_settings(config: &niri_config::Input, device: &mut input::Device) {
4864 // According to Mutter code, this setting is specific to touchpads.
4865 let is_touchpad = device.config_tap_finger_count() > 0;
4866 if is_touchpad {
4867 let c = &config.touchpad;
4868 let _ = device.config_send_events_set_mode(if c.off {
4869 input::SendEventsMode::DISABLED
4870 } else if c.disabled_on_external_mouse {
4871 input::SendEventsMode::DISABLED_ON_EXTERNAL_MOUSE
4872 } else {
4873 input::SendEventsMode::ENABLED
4874 });
4875 let _ = device.config_tap_set_enabled(c.tap);
4876 let _ = device.config_dwt_set_enabled(c.dwt);
4877 let _ = device.config_dwtp_set_enabled(c.dwtp);
4878 let _ = device.config_tap_set_drag_lock_enabled(if c.drag_lock {
4879 input::DragLockState::EnabledTimeout
4880 } else {
4881 input::DragLockState::Disabled
4882 });
4883 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
4884 let _ = device.config_accel_set_speed(c.accel_speed.0);
4885 let _ = device.config_left_handed_set(c.left_handed);
4886 let _ = device.config_middle_emulation_set_enabled(c.middle_emulation);
4887
4888 if let Some(drag) = c.drag {
4889 let _ = device.config_tap_set_drag_enabled(drag);
4890 } else {
4891 let default = device.config_tap_default_drag_enabled();
4892 let _ = device.config_tap_set_drag_enabled(default);
4893 }
4894
4895 if let Some(accel_profile) = c.accel_profile {
4896 let _ = device.config_accel_set_profile(accel_profile.into());
4897 } else if let Some(default) = device.config_accel_default_profile() {
4898 let _ = device.config_accel_set_profile(default);
4899 }
4900
4901 if let Some(method) = c.scroll_method {
4902 let _ = device.config_scroll_set_method(method.into());
4903
4904 if method == niri_config::ScrollMethod::OnButtonDown {
4905 if let Some(button) = c.scroll_button {
4906 let _ = device.config_scroll_set_button(button);
4907 }
4908 let _ = device.config_scroll_set_button_lock(if c.scroll_button_lock {
4909 input::ScrollButtonLockState::Enabled
4910 } else {
4911 input::ScrollButtonLockState::Disabled
4912 });
4913 }
4914 } else if let Some(default) = device.config_scroll_default_method() {
4915 let _ = device.config_scroll_set_method(default);
4916
4917 if default == input::ScrollMethod::OnButtonDown {
4918 if let Some(button) = c.scroll_button {
4919 let _ = device.config_scroll_set_button(button);
4920 }
4921 let _ = device.config_scroll_set_button_lock(if c.scroll_button_lock {
4922 input::ScrollButtonLockState::Enabled
4923 } else {
4924 input::ScrollButtonLockState::Disabled
4925 });
4926 }
4927 }
4928
4929 if let Some(tap_button_map) = c.tap_button_map {
4930 let _ = device.config_tap_set_button_map(tap_button_map.into());
4931 } else if let Some(default) = device.config_tap_default_button_map() {
4932 let _ = device.config_tap_set_button_map(default);
4933 }
4934
4935 if let Some(method) = c.click_method {
4936 let _ = device.config_click_set_method(method.into());
4937 } else if let Some(default) = device.config_click_default_method() {
4938 let _ = device.config_click_set_method(default);
4939 }
4940 }
4941
4942 // This is how Mutter tells apart mice.
4943 let mut is_trackball = false;
4944 let mut is_trackpoint = false;
4945 if let Some(udev_device) = unsafe { device.udev_device() } {
4946 if udev_device.property_value("ID_INPUT_TRACKBALL").is_some() {
4947 is_trackball = true;
4948 }
4949 if udev_device
4950 .property_value("ID_INPUT_POINTINGSTICK")
4951 .is_some()
4952 {
4953 is_trackpoint = true;
4954 }
4955 }
4956
4957 let is_mouse = device.has_capability(input::DeviceCapability::Pointer)
4958 && !is_touchpad
4959 && !is_trackball
4960 && !is_trackpoint;
4961 if is_mouse {
4962 let c = &config.mouse;
4963 let _ = device.config_send_events_set_mode(if c.off {
4964 input::SendEventsMode::DISABLED
4965 } else {
4966 input::SendEventsMode::ENABLED
4967 });
4968 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
4969 let _ = device.config_accel_set_speed(c.accel_speed.0);
4970 let _ = device.config_left_handed_set(c.left_handed);
4971 let _ = device.config_middle_emulation_set_enabled(c.middle_emulation);
4972
4973 if let Some(accel_profile) = c.accel_profile {
4974 let _ = device.config_accel_set_profile(accel_profile.into());
4975 } else if let Some(default) = device.config_accel_default_profile() {
4976 let _ = device.config_accel_set_profile(default);
4977 }
4978
4979 if let Some(method) = c.scroll_method {
4980 let _ = device.config_scroll_set_method(method.into());
4981
4982 if method == niri_config::ScrollMethod::OnButtonDown {
4983 if let Some(button) = c.scroll_button {
4984 let _ = device.config_scroll_set_button(button);
4985 }
4986 let _ = device.config_scroll_set_button_lock(if c.scroll_button_lock {
4987 input::ScrollButtonLockState::Enabled
4988 } else {
4989 input::ScrollButtonLockState::Disabled
4990 });
4991 }
4992 } else if let Some(default) = device.config_scroll_default_method() {
4993 let _ = device.config_scroll_set_method(default);
4994
4995 if default == input::ScrollMethod::OnButtonDown {
4996 if let Some(button) = c.scroll_button {
4997 let _ = device.config_scroll_set_button(button);
4998 }
4999 let _ = device.config_scroll_set_button_lock(if c.scroll_button_lock {
5000 input::ScrollButtonLockState::Enabled
5001 } else {
5002 input::ScrollButtonLockState::Disabled
5003 });
5004 }
5005 }
5006 }
5007
5008 if is_trackball {
5009 let c = &config.trackball;
5010 let _ = device.config_send_events_set_mode(if c.off {
5011 input::SendEventsMode::DISABLED
5012 } else {
5013 input::SendEventsMode::ENABLED
5014 });
5015 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
5016 let _ = device.config_accel_set_speed(c.accel_speed.0);
5017 let _ = device.config_middle_emulation_set_enabled(c.middle_emulation);
5018 let _ = device.config_left_handed_set(c.left_handed);
5019
5020 if let Some(accel_profile) = c.accel_profile {
5021 let _ = device.config_accel_set_profile(accel_profile.into());
5022 } else if let Some(default) = device.config_accel_default_profile() {
5023 let _ = device.config_accel_set_profile(default);
5024 }
5025
5026 if let Some(method) = c.scroll_method {
5027 let _ = device.config_scroll_set_method(method.into());
5028
5029 if method == niri_config::ScrollMethod::OnButtonDown {
5030 if let Some(button) = c.scroll_button {
5031 let _ = device.config_scroll_set_button(button);
5032 }
5033 let _ = device.config_scroll_set_button_lock(if c.scroll_button_lock {
5034 input::ScrollButtonLockState::Enabled
5035 } else {
5036 input::ScrollButtonLockState::Disabled
5037 });
5038 }
5039 } else if let Some(default) = device.config_scroll_default_method() {
5040 let _ = device.config_scroll_set_method(default);
5041
5042 if default == input::ScrollMethod::OnButtonDown {
5043 if let Some(button) = c.scroll_button {
5044 let _ = device.config_scroll_set_button(button);
5045 }
5046 let _ = device.config_scroll_set_button_lock(if c.scroll_button_lock {
5047 input::ScrollButtonLockState::Enabled
5048 } else {
5049 input::ScrollButtonLockState::Disabled
5050 });
5051 }
5052 }
5053 }
5054
5055 if is_trackpoint {
5056 let c = &config.trackpoint;
5057 let _ = device.config_send_events_set_mode(if c.off {
5058 input::SendEventsMode::DISABLED
5059 } else {
5060 input::SendEventsMode::ENABLED
5061 });
5062 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
5063 let _ = device.config_accel_set_speed(c.accel_speed.0);
5064 let _ = device.config_left_handed_set(c.left_handed);
5065 let _ = device.config_middle_emulation_set_enabled(c.middle_emulation);
5066
5067 if let Some(accel_profile) = c.accel_profile {
5068 let _ = device.config_accel_set_profile(accel_profile.into());
5069 } else if let Some(default) = device.config_accel_default_profile() {
5070 let _ = device.config_accel_set_profile(default);
5071 }
5072
5073 if let Some(method) = c.scroll_method {
5074 let _ = device.config_scroll_set_method(method.into());
5075
5076 if method == niri_config::ScrollMethod::OnButtonDown {
5077 if let Some(button) = c.scroll_button {
5078 let _ = device.config_scroll_set_button(button);
5079 }
5080 let _ = device.config_scroll_set_button_lock(if c.scroll_button_lock {
5081 input::ScrollButtonLockState::Enabled
5082 } else {
5083 input::ScrollButtonLockState::Disabled
5084 });
5085 }
5086 } else if let Some(default) = device.config_scroll_default_method() {
5087 let _ = device.config_scroll_set_method(default);
5088
5089 if default == input::ScrollMethod::OnButtonDown {
5090 if let Some(button) = c.scroll_button {
5091 let _ = device.config_scroll_set_button(button);
5092 }
5093 let _ = device.config_scroll_set_button_lock(if c.scroll_button_lock {
5094 input::ScrollButtonLockState::Enabled
5095 } else {
5096 input::ScrollButtonLockState::Disabled
5097 });
5098 }
5099 }
5100 }
5101
5102 let is_tablet = device.has_capability(input::DeviceCapability::TabletTool);
5103 if is_tablet {
5104 let c = &config.tablet;
5105 let _ = device.config_send_events_set_mode(if c.off {
5106 input::SendEventsMode::DISABLED
5107 } else {
5108 input::SendEventsMode::ENABLED
5109 });
5110
5111 #[rustfmt::skip]
5112 const IDENTITY_MATRIX: [f32; 6] = [
5113 1., 0., 0.,
5114 0., 1., 0.,
5115 ];
5116
5117 let _ = device.config_calibration_set_matrix(
5118 c.calibration_matrix
5119 .as_deref()
5120 .and_then(|m| m.try_into().ok())
5121 .or(device.config_calibration_default_matrix())
5122 .unwrap_or(IDENTITY_MATRIX),
5123 );
5124
5125 let _ = device.config_left_handed_set(c.left_handed);
5126 }
5127
5128 let is_touch = device.has_capability(input::DeviceCapability::Touch);
5129 if is_touch {
5130 let c = &config.touch;
5131 let _ = device.config_send_events_set_mode(if c.off {
5132 input::SendEventsMode::DISABLED
5133 } else {
5134 input::SendEventsMode::ENABLED
5135 });
5136
5137 #[rustfmt::skip]
5138 const IDENTITY_MATRIX: [f32; 6] = [
5139 1., 0., 0.,
5140 0., 1., 0.,
5141 ];
5142
5143 let _ = device.config_calibration_set_matrix(
5144 c.calibration_matrix
5145 .as_deref()
5146 .and_then(|m| m.try_into().ok())
5147 .or(device.config_calibration_default_matrix())
5148 .unwrap_or(IDENTITY_MATRIX),
5149 );
5150 }
5151}
5152
5153pub fn mods_with_binds(mod_key: ModKey, binds: &Binds, triggers: &[Trigger]) -> HashSet<Modifiers> {
5154 let mut rv = HashSet::new();
5155 for bind in &binds.0 {
5156 if !triggers.contains(&bind.key.trigger) {
5157 continue;
5158 }
5159
5160 let mut mods = bind.key.modifiers;
5161 if mods.contains(Modifiers::COMPOSITOR) {
5162 mods.remove(Modifiers::COMPOSITOR);
5163 mods.insert(mod_key.to_modifiers());
5164 }
5165
5166 rv.insert(mods);
5167 }
5168
5169 rv
5170}
5171
5172pub fn mods_with_mouse_binds(mod_key: ModKey, binds: &Binds) -> HashSet<Modifiers> {
5173 mods_with_binds(
5174 mod_key,
5175 binds,
5176 &[
5177 Trigger::MouseLeft,
5178 Trigger::MouseRight,
5179 Trigger::MouseMiddle,
5180 Trigger::MouseBack,
5181 Trigger::MouseForward,
5182 ],
5183 )
5184}
5185
5186pub fn mods_with_wheel_binds(mod_key: ModKey, binds: &Binds) -> HashSet<Modifiers> {
5187 mods_with_binds(
5188 mod_key,
5189 binds,
5190 &[
5191 Trigger::WheelScrollUp,
5192 Trigger::WheelScrollDown,
5193 Trigger::WheelScrollLeft,
5194 Trigger::WheelScrollRight,
5195 ],
5196 )
5197}
5198
5199pub fn mods_with_finger_scroll_binds(mod_key: ModKey, binds: &Binds) -> HashSet<Modifiers> {
5200 mods_with_binds(
5201 mod_key,
5202 binds,
5203 &[
5204 Trigger::TouchpadScrollUp,
5205 Trigger::TouchpadScrollDown,
5206 Trigger::TouchpadScrollLeft,
5207 Trigger::TouchpadScrollRight,
5208 ],
5209 )
5210}
5211
5212pub fn mods_with_tablet_stylus_binds(mod_key: ModKey, binds: &Binds) -> HashSet<Modifiers> {
5213 mods_with_binds(
5214 mod_key,
5215 binds,
5216 &[
5217 Trigger::TabletStylusButton1,
5218 Trigger::TabletStylusButton2,
5219 Trigger::TabletStylusButton3,
5220 ],
5221 )
5222}
5223
5224fn grab_allows_hot_corner(grab: &(dyn PointerGrab<State> + 'static)) -> bool {
5225 let grab = grab.as_any();
5226
5227 // We lean on the blocklist approach here since it's not a terribly big deal if hot corner
5228 // works where it shouldn't, but it could prevent some workflows if the hot corner doesn't work
5229 // when it should.
5230 //
5231 // Some notable grabs not mentioned here:
5232 // - DnDGrab allows hot corner to DnD across workspaces.
5233 // - ClickGrab keeps pointer focus on the window, so the hot corner doesn't trigger.
5234 // - Touch grabs: touch doesn't trigger the hot corner.
5235 if grab.is::<ResizeGrab>() || grab.is::<SpatialMovementGrab>() {
5236 return false;
5237 }
5238
5239 if let Some(grab) = grab.downcast_ref::<MoveGrab>() {
5240 // Window move allows hot corner to DnD across workspaces.
5241 if !grab.is_move() {
5242 return false;
5243 }
5244 }
5245
5246 true
5247}
5248
5249/// Returns an iterator over bindings.
5250///
5251/// Includes dynamically populated bindings like the MRU UI.
5252fn make_binds_iter<'a>(
5253 config: &'a Config,
5254 mru: &'a mut WindowMruUi,
5255 mods: Modifiers,
5256) -> impl Iterator<Item = &'a Bind> + Clone {
5257 // Figure out the binds to use depending on whether the MRU is enabled and/or open.
5258 let general_binds = (!mru.is_open()).then_some(config.binds.0.iter());
5259 let general_binds = general_binds.into_iter().flatten();
5260
5261 let mru_binds =
5262 (config.recent_windows.on || mru.is_open()).then_some(config.recent_windows.binds.iter());
5263 let mru_binds = mru_binds.into_iter().flatten();
5264
5265 let mru_open_binds = mru.is_open().then(|| mru.opened_bindings(mods));
5266 let mru_open_binds = mru_open_binds.into_iter().flatten();
5267
5268 // General binds take precedence over the MRU binds.
5269 general_binds.chain(mru_binds).chain(mru_open_binds)
5270}
5271
5272#[cfg(test)]
5273mod tests {
5274 use std::cell::Cell;
5275
5276 use super::*;
5277 use crate::animation::Clock;
5278
5279 #[test]
5280 fn bindings_suppress_keys() {
5281 let close_keysym = Keysym::q;
5282 let bindings = Binds(vec![Bind {
5283 key: Key {
5284 trigger: Trigger::Keysym(close_keysym),
5285 modifiers: Modifiers::COMPOSITOR | Modifiers::CTRL,
5286 },
5287 action: Action::CloseWindow,
5288 repeat: true,
5289 cooldown: None,
5290 allow_when_locked: false,
5291 allow_inhibiting: true,
5292 hotkey_overlay_title: None,
5293 }]);
5294
5295 let comp_mod = ModKey::Super;
5296 let mut suppressed_keys = HashSet::new();
5297
5298 let screenshot_ui = ScreenshotUi::new(Clock::default(), Default::default());
5299 let disable_power_key_handling = false;
5300 let is_inhibiting_shortcuts = Cell::new(false);
5301
5302 // The key_code we pick is arbitrary, the only thing
5303 // that matters is that they are different between cases.
5304
5305 let close_key_code = Keycode::from(close_keysym.raw() + 8u32);
5306 let close_key_event = |suppr: &mut HashSet<Keycode>, mods: ModifiersState, pressed| {
5307 should_intercept_key(
5308 suppr,
5309 &bindings.0,
5310 comp_mod,
5311 close_key_code,
5312 close_keysym,
5313 Some(close_keysym),
5314 pressed,
5315 mods,
5316 &screenshot_ui,
5317 disable_power_key_handling,
5318 is_inhibiting_shortcuts.get(),
5319 )
5320 };
5321
5322 // Key event with the code which can't trigger any action.
5323 let none_key_event = |suppr: &mut HashSet<Keycode>, mods: ModifiersState, pressed| {
5324 should_intercept_key(
5325 suppr,
5326 &bindings.0,
5327 comp_mod,
5328 Keycode::from(Keysym::l.raw() + 8),
5329 Keysym::l,
5330 Some(Keysym::l),
5331 pressed,
5332 mods,
5333 &screenshot_ui,
5334 disable_power_key_handling,
5335 is_inhibiting_shortcuts.get(),
5336 )
5337 };
5338
5339 let mut mods = ModifiersState {
5340 logo: true,
5341 ctrl: true,
5342 ..Default::default()
5343 };
5344
5345 // Action press/release.
5346
5347 let filter = close_key_event(&mut suppressed_keys, mods, true);
5348 assert!(matches!(
5349 filter,
5350 FilterResult::Intercept(Some(Bind {
5351 action: Action::CloseWindow,
5352 ..
5353 }))
5354 ));
5355 assert!(suppressed_keys.contains(&close_key_code));
5356
5357 let filter = close_key_event(&mut suppressed_keys, mods, false);
5358 assert!(matches!(filter, FilterResult::Intercept(None)));
5359 assert!(suppressed_keys.is_empty());
5360
5361 // Remove mod to make it for a binding.
5362
5363 mods.shift = true;
5364 let filter = close_key_event(&mut suppressed_keys, mods, true);
5365 assert!(matches!(filter, FilterResult::Forward));
5366
5367 mods.shift = false;
5368 let filter = close_key_event(&mut suppressed_keys, mods, false);
5369 assert!(matches!(filter, FilterResult::Forward));
5370
5371 // Just none press/release.
5372
5373 let filter = none_key_event(&mut suppressed_keys, mods, true);
5374 assert!(matches!(filter, FilterResult::Forward));
5375
5376 let filter = none_key_event(&mut suppressed_keys, mods, false);
5377 assert!(matches!(filter, FilterResult::Forward));
5378
5379 // Press action, press arbitrary, release action, release arbitrary.
5380
5381 let filter = close_key_event(&mut suppressed_keys, mods, true);
5382 assert!(matches!(
5383 filter,
5384 FilterResult::Intercept(Some(Bind {
5385 action: Action::CloseWindow,
5386 ..
5387 }))
5388 ));
5389
5390 let filter = none_key_event(&mut suppressed_keys, mods, true);
5391 assert!(matches!(filter, FilterResult::Forward));
5392
5393 let filter = close_key_event(&mut suppressed_keys, mods, false);
5394 assert!(matches!(filter, FilterResult::Intercept(None)));
5395
5396 let filter = none_key_event(&mut suppressed_keys, mods, false);
5397 assert!(matches!(filter, FilterResult::Forward));
5398
5399 // Trigger and remove all mods.
5400
5401 let filter = close_key_event(&mut suppressed_keys, mods, true);
5402 assert!(matches!(
5403 filter,
5404 FilterResult::Intercept(Some(Bind {
5405 action: Action::CloseWindow,
5406 ..
5407 }))
5408 ));
5409
5410 mods = Default::default();
5411 let filter = close_key_event(&mut suppressed_keys, mods, false);
5412 assert!(matches!(filter, FilterResult::Intercept(None)));
5413
5414 // Ensure that no keys are being suppressed.
5415 assert!(suppressed_keys.is_empty());
5416
5417 // Now test shortcut inhibiting.
5418
5419 // With inhibited shortcuts, we don't intercept our shortcut.
5420 is_inhibiting_shortcuts.set(true);
5421
5422 mods = ModifiersState {
5423 logo: true,
5424 ctrl: true,
5425 ..Default::default()
5426 };
5427
5428 let filter = close_key_event(&mut suppressed_keys, mods, true);
5429 assert!(matches!(filter, FilterResult::Forward));
5430 assert!(suppressed_keys.is_empty());
5431
5432 let filter = close_key_event(&mut suppressed_keys, mods, false);
5433 assert!(matches!(filter, FilterResult::Forward));
5434 assert!(suppressed_keys.is_empty());
5435
5436 // Toggle it off after pressing the shortcut.
5437 let filter = close_key_event(&mut suppressed_keys, mods, true);
5438 assert!(matches!(filter, FilterResult::Forward));
5439 assert!(suppressed_keys.is_empty());
5440
5441 is_inhibiting_shortcuts.set(false);
5442
5443 let filter = close_key_event(&mut suppressed_keys, mods, false);
5444 assert!(matches!(filter, FilterResult::Forward));
5445 assert!(suppressed_keys.is_empty());
5446
5447 // Toggle it on after pressing the shortcut.
5448 let filter = close_key_event(&mut suppressed_keys, mods, true);
5449 assert!(matches!(
5450 filter,
5451 FilterResult::Intercept(Some(Bind {
5452 action: Action::CloseWindow,
5453 ..
5454 }))
5455 ));
5456 assert!(suppressed_keys.contains(&close_key_code));
5457
5458 is_inhibiting_shortcuts.set(true);
5459
5460 let filter = close_key_event(&mut suppressed_keys, mods, false);
5461 assert!(matches!(filter, FilterResult::Intercept(None)));
5462 assert!(suppressed_keys.is_empty());
5463 }
5464
5465 #[test]
5466 fn comp_mod_handling() {
5467 let bindings = Binds(vec![
5468 Bind {
5469 key: Key {
5470 trigger: Trigger::Keysym(Keysym::q),
5471 modifiers: Modifiers::COMPOSITOR,
5472 },
5473 action: Action::CloseWindow,
5474 repeat: true,
5475 cooldown: None,
5476 allow_when_locked: false,
5477 allow_inhibiting: true,
5478 hotkey_overlay_title: None,
5479 },
5480 Bind {
5481 key: Key {
5482 trigger: Trigger::Keysym(Keysym::h),
5483 modifiers: Modifiers::SUPER,
5484 },
5485 action: Action::FocusColumnLeft,
5486 repeat: true,
5487 cooldown: None,
5488 allow_when_locked: false,
5489 allow_inhibiting: true,
5490 hotkey_overlay_title: None,
5491 },
5492 Bind {
5493 key: Key {
5494 trigger: Trigger::Keysym(Keysym::j),
5495 modifiers: Modifiers::empty(),
5496 },
5497 action: Action::FocusWindowDown,
5498 repeat: true,
5499 cooldown: None,
5500 allow_when_locked: false,
5501 allow_inhibiting: true,
5502 hotkey_overlay_title: None,
5503 },
5504 Bind {
5505 key: Key {
5506 trigger: Trigger::Keysym(Keysym::k),
5507 modifiers: Modifiers::COMPOSITOR | Modifiers::SUPER,
5508 },
5509 action: Action::FocusWindowUp,
5510 repeat: true,
5511 cooldown: None,
5512 allow_when_locked: false,
5513 allow_inhibiting: true,
5514 hotkey_overlay_title: None,
5515 },
5516 Bind {
5517 key: Key {
5518 trigger: Trigger::Keysym(Keysym::l),
5519 modifiers: Modifiers::SUPER | Modifiers::ALT,
5520 },
5521 action: Action::FocusColumnRight,
5522 repeat: true,
5523 cooldown: None,
5524 allow_when_locked: false,
5525 allow_inhibiting: true,
5526 hotkey_overlay_title: None,
5527 },
5528 ]);
5529
5530 assert_eq!(
5531 find_configured_bind(
5532 &bindings.0,
5533 ModKey::Super,
5534 Trigger::Keysym(Keysym::q),
5535 ModifiersState {
5536 logo: true,
5537 ..Default::default()
5538 }
5539 )
5540 .as_ref(),
5541 Some(&bindings.0[0])
5542 );
5543 assert_eq!(
5544 find_configured_bind(
5545 &bindings.0,
5546 ModKey::Super,
5547 Trigger::Keysym(Keysym::q),
5548 ModifiersState::default(),
5549 ),
5550 None,
5551 );
5552
5553 assert_eq!(
5554 find_configured_bind(
5555 &bindings.0,
5556 ModKey::Super,
5557 Trigger::Keysym(Keysym::h),
5558 ModifiersState {
5559 logo: true,
5560 ..Default::default()
5561 }
5562 )
5563 .as_ref(),
5564 Some(&bindings.0[1])
5565 );
5566 assert_eq!(
5567 find_configured_bind(
5568 &bindings.0,
5569 ModKey::Super,
5570 Trigger::Keysym(Keysym::h),
5571 ModifiersState::default(),
5572 ),
5573 None,
5574 );
5575
5576 assert_eq!(
5577 find_configured_bind(
5578 &bindings.0,
5579 ModKey::Super,
5580 Trigger::Keysym(Keysym::j),
5581 ModifiersState {
5582 logo: true,
5583 ..Default::default()
5584 }
5585 ),
5586 None,
5587 );
5588 assert_eq!(
5589 find_configured_bind(
5590 &bindings.0,
5591 ModKey::Super,
5592 Trigger::Keysym(Keysym::j),
5593 ModifiersState::default(),
5594 )
5595 .as_ref(),
5596 Some(&bindings.0[2])
5597 );
5598
5599 assert_eq!(
5600 find_configured_bind(
5601 &bindings.0,
5602 ModKey::Super,
5603 Trigger::Keysym(Keysym::k),
5604 ModifiersState {
5605 logo: true,
5606 ..Default::default()
5607 }
5608 )
5609 .as_ref(),
5610 Some(&bindings.0[3])
5611 );
5612 assert_eq!(
5613 find_configured_bind(
5614 &bindings.0,
5615 ModKey::Super,
5616 Trigger::Keysym(Keysym::k),
5617 ModifiersState::default(),
5618 ),
5619 None,
5620 );
5621
5622 assert_eq!(
5623 find_configured_bind(
5624 &bindings.0,
5625 ModKey::Super,
5626 Trigger::Keysym(Keysym::l),
5627 ModifiersState {
5628 logo: true,
5629 alt: true,
5630 ..Default::default()
5631 }
5632 )
5633 .as_ref(),
5634 Some(&bindings.0[4])
5635 );
5636 assert_eq!(
5637 find_configured_bind(
5638 &bindings.0,
5639 ModKey::Super,
5640 Trigger::Keysym(Keysym::l),
5641 ModifiersState {
5642 logo: true,
5643 ..Default::default()
5644 },
5645 ),
5646 None,
5647 );
5648 }
5649}