forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB66583cdIvan Molodetskikh1 year ago2489 commits

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