forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB6c9705dIvan Molodetskikh1 year ago2085 commits

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