forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9d8f4f8Ivan Molodetskikh1 month ago2997 commits

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