forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9ff2f83Ivan Molodetskikh1 year ago2099 commits

mod.rs4691 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 button == Some(MouseButton::Left) && self.niri.screenshot_ui.is_open() {
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 let down = button_state == ButtonState::Pressed;
2582
2583 if self.niri.screenshot_ui.pointer_button(output, point, down) {
2584 self.niri.queue_redraw_all();
2585 }
2586 }
2587 }
2588
2589 pointer.button(
2590 self,
2591 &ButtonEvent {
2592 button: button_code,
2593 state: button_state,
2594 serial,
2595 time: event.time_msec(),
2596 },
2597 );
2598 pointer.frame(self);
2599 }
2600
2601 fn on_pointer_axis<I: InputBackend>(&mut self, event: I::PointerAxisEvent) {
2602 let pointer = &self.niri.seat.get_pointer().unwrap();
2603
2604 let source = event.source();
2605
2606 let mod_key = self.backend.mod_key(&self.niri.config.borrow());
2607
2608 // We received an event for the regular pointer, so show it now. This is also needed for
2609 // update_pointer_contents() below to return the real contents, necessary for the pointer
2610 // axis event to reach the window.
2611 self.niri.pointer_visibility = PointerVisibility::Visible;
2612 self.niri.tablet_cursor_location = None;
2613
2614 let timestamp = Duration::from_micros(event.time());
2615
2616 let horizontal_amount_v120 = event.amount_v120(Axis::Horizontal);
2617 let vertical_amount_v120 = event.amount_v120(Axis::Vertical);
2618
2619 let is_overview_open = self.niri.layout.is_overview_open();
2620
2621 // We should only handle scrolling in the overview if the pointer is not over a (top or
2622 // overlay) layer surface.
2623 let should_handle_in_overview = if is_overview_open {
2624 // FIXME: ideally this should happen after updating the pointer contents, which happens
2625 // below. However, our pointer actions are supposed to act on the old surface, before
2626 // updating the pointer contents.
2627 pointer
2628 .current_focus()
2629 .map(|surface| self.niri.find_root_shell_surface(&surface))
2630 .map_or(true, |root| {
2631 !self
2632 .niri
2633 .mapped_layer_surfaces
2634 .keys()
2635 .any(|layer| *layer.wl_surface() == root)
2636 })
2637 } else {
2638 false
2639 };
2640
2641 // Handle wheel scroll bindings.
2642 if source == AxisSource::Wheel {
2643 // If we have a scroll bind with current modifiers, then accumulate and don't pass to
2644 // Wayland. If there's no bind, reset the accumulator.
2645 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
2646 let modifiers = modifiers_from_state(mods);
2647 let should_handle =
2648 should_handle_in_overview || self.niri.mods_with_wheel_binds.contains(&modifiers);
2649 if should_handle {
2650 let horizontal = horizontal_amount_v120.unwrap_or(0.);
2651 let ticks = self.niri.horizontal_wheel_tracker.accumulate(horizontal);
2652 if ticks != 0 {
2653 let (bind_left, bind_right) = if should_handle_in_overview
2654 && modifiers.is_empty()
2655 {
2656 let bind_left = Some(Bind {
2657 key: Key {
2658 trigger: Trigger::WheelScrollLeft,
2659 modifiers: Modifiers::empty(),
2660 },
2661 action: Action::FocusColumnLeftUnderMouse,
2662 repeat: true,
2663 cooldown: None,
2664 allow_when_locked: false,
2665 allow_inhibiting: false,
2666 hotkey_overlay_title: None,
2667 });
2668 let bind_right = Some(Bind {
2669 key: Key {
2670 trigger: Trigger::WheelScrollRight,
2671 modifiers: Modifiers::empty(),
2672 },
2673 action: Action::FocusColumnRightUnderMouse,
2674 repeat: true,
2675 cooldown: None,
2676 allow_when_locked: false,
2677 allow_inhibiting: false,
2678 hotkey_overlay_title: None,
2679 });
2680 (bind_left, bind_right)
2681 } else {
2682 let config = self.niri.config.borrow();
2683 let bindings = &config.binds;
2684 let bind_left =
2685 find_configured_bind(bindings, mod_key, Trigger::WheelScrollLeft, mods);
2686 let bind_right = find_configured_bind(
2687 bindings,
2688 mod_key,
2689 Trigger::WheelScrollRight,
2690 mods,
2691 );
2692 (bind_left, bind_right)
2693 };
2694
2695 if let Some(right) = bind_right {
2696 for _ in 0..ticks {
2697 self.handle_bind(right.clone());
2698 }
2699 }
2700 if let Some(left) = bind_left {
2701 for _ in ticks..0 {
2702 self.handle_bind(left.clone());
2703 }
2704 }
2705 }
2706
2707 let vertical = vertical_amount_v120.unwrap_or(0.);
2708 let ticks = self.niri.vertical_wheel_tracker.accumulate(vertical);
2709 if ticks != 0 {
2710 let (bind_up, bind_down) = if should_handle_in_overview && modifiers.is_empty()
2711 {
2712 let bind_up = Some(Bind {
2713 key: Key {
2714 trigger: Trigger::WheelScrollUp,
2715 modifiers: Modifiers::empty(),
2716 },
2717 action: Action::FocusWorkspaceUpUnderMouse,
2718 repeat: true,
2719 cooldown: Some(Duration::from_millis(50)),
2720 allow_when_locked: false,
2721 allow_inhibiting: false,
2722 hotkey_overlay_title: None,
2723 });
2724 let bind_down = Some(Bind {
2725 key: Key {
2726 trigger: Trigger::WheelScrollDown,
2727 modifiers: Modifiers::empty(),
2728 },
2729 action: Action::FocusWorkspaceDownUnderMouse,
2730 repeat: true,
2731 cooldown: Some(Duration::from_millis(50)),
2732 allow_when_locked: false,
2733 allow_inhibiting: false,
2734 hotkey_overlay_title: None,
2735 });
2736 (bind_up, bind_down)
2737 } else if should_handle_in_overview && modifiers == Modifiers::SHIFT {
2738 let bind_up = Some(Bind {
2739 key: Key {
2740 trigger: Trigger::WheelScrollUp,
2741 modifiers: Modifiers::empty(),
2742 },
2743 action: Action::FocusColumnLeftUnderMouse,
2744 repeat: true,
2745 cooldown: Some(Duration::from_millis(50)),
2746 allow_when_locked: false,
2747 allow_inhibiting: false,
2748 hotkey_overlay_title: None,
2749 });
2750 let bind_down = Some(Bind {
2751 key: Key {
2752 trigger: Trigger::WheelScrollDown,
2753 modifiers: Modifiers::empty(),
2754 },
2755 action: Action::FocusColumnRightUnderMouse,
2756 repeat: true,
2757 cooldown: Some(Duration::from_millis(50)),
2758 allow_when_locked: false,
2759 allow_inhibiting: false,
2760 hotkey_overlay_title: None,
2761 });
2762 (bind_up, bind_down)
2763 } else {
2764 let config = self.niri.config.borrow();
2765 let bindings = &config.binds;
2766 let bind_up =
2767 find_configured_bind(bindings, mod_key, Trigger::WheelScrollUp, mods);
2768 let bind_down =
2769 find_configured_bind(bindings, mod_key, Trigger::WheelScrollDown, mods);
2770 (bind_up, bind_down)
2771 };
2772
2773 if let Some(down) = bind_down {
2774 for _ in 0..ticks {
2775 self.handle_bind(down.clone());
2776 }
2777 }
2778 if let Some(up) = bind_up {
2779 for _ in ticks..0 {
2780 self.handle_bind(up.clone());
2781 }
2782 }
2783 }
2784
2785 return;
2786 } else {
2787 self.niri.horizontal_wheel_tracker.reset();
2788 self.niri.vertical_wheel_tracker.reset();
2789 }
2790 }
2791
2792 let horizontal_amount = event.amount(Axis::Horizontal);
2793 let vertical_amount = event.amount(Axis::Vertical);
2794
2795 // Handle touchpad scroll bindings.
2796 if source == AxisSource::Finger {
2797 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
2798 let modifiers = modifiers_from_state(mods);
2799
2800 let horizontal = horizontal_amount.unwrap_or(0.);
2801 let vertical = vertical_amount.unwrap_or(0.);
2802
2803 if should_handle_in_overview && modifiers.is_empty() {
2804 let mut redraw = false;
2805
2806 let action = self
2807 .niri
2808 .overview_scroll_swipe_gesture
2809 .update(horizontal, vertical);
2810 let is_vertical = self.niri.overview_scroll_swipe_gesture.is_vertical();
2811
2812 if action.end() {
2813 if is_vertical {
2814 redraw |= self
2815 .niri
2816 .layout
2817 .workspace_switch_gesture_end(Some(true))
2818 .is_some();
2819 } else {
2820 redraw |= self
2821 .niri
2822 .layout
2823 .view_offset_gesture_end(Some(true))
2824 .is_some();
2825 }
2826 } else {
2827 // Maybe begin, then update.
2828 if is_vertical {
2829 if action.begin() {
2830 if let Some(output) = self.niri.output_under_cursor() {
2831 self.niri
2832 .layout
2833 .workspace_switch_gesture_begin(&output, true);
2834 redraw = true;
2835 }
2836 }
2837
2838 let res = self
2839 .niri
2840 .layout
2841 .workspace_switch_gesture_update(vertical, timestamp, true);
2842 if let Some(Some(_)) = res {
2843 redraw = true;
2844 }
2845 } else {
2846 if action.begin() {
2847 if let Some((output, ws)) = self.niri.workspace_under_cursor(true) {
2848 let ws_id = ws.id();
2849 let ws_idx =
2850 self.niri.layout.find_workspace_by_id(ws_id).unwrap().0;
2851
2852 self.niri.layout.view_offset_gesture_begin(
2853 &output,
2854 Some(ws_idx),
2855 true,
2856 );
2857 redraw = true;
2858 }
2859 }
2860
2861 let res = self
2862 .niri
2863 .layout
2864 .view_offset_gesture_update(horizontal, timestamp, true);
2865 if let Some(Some(_)) = res {
2866 redraw = true;
2867 }
2868 }
2869 }
2870
2871 if redraw {
2872 self.niri.queue_redraw_all();
2873 }
2874
2875 return;
2876 } else {
2877 let mut redraw = false;
2878 if self.niri.overview_scroll_swipe_gesture.reset() {
2879 if self.niri.overview_scroll_swipe_gesture.is_vertical() {
2880 redraw |= self
2881 .niri
2882 .layout
2883 .workspace_switch_gesture_end(Some(true))
2884 .is_some();
2885 } else {
2886 redraw |= self
2887 .niri
2888 .layout
2889 .view_offset_gesture_end(Some(true))
2890 .is_some();
2891 }
2892 }
2893 if redraw {
2894 self.niri.queue_redraw_all();
2895 }
2896 }
2897
2898 if self.niri.mods_with_finger_scroll_binds.contains(&modifiers) {
2899 let ticks = self
2900 .niri
2901 .horizontal_finger_scroll_tracker
2902 .accumulate(horizontal);
2903 if ticks != 0 {
2904 let config = self.niri.config.borrow();
2905 let bindings = &config.binds;
2906 let bind_left =
2907 find_configured_bind(bindings, mod_key, Trigger::TouchpadScrollLeft, mods);
2908 let bind_right =
2909 find_configured_bind(bindings, mod_key, Trigger::TouchpadScrollRight, mods);
2910 drop(config);
2911
2912 if let Some(right) = bind_right {
2913 for _ in 0..ticks {
2914 self.handle_bind(right.clone());
2915 }
2916 }
2917 if let Some(left) = bind_left {
2918 for _ in ticks..0 {
2919 self.handle_bind(left.clone());
2920 }
2921 }
2922 }
2923
2924 let ticks = self
2925 .niri
2926 .vertical_finger_scroll_tracker
2927 .accumulate(vertical);
2928 if ticks != 0 {
2929 let config = self.niri.config.borrow();
2930 let bindings = &config.binds;
2931 let bind_up =
2932 find_configured_bind(bindings, mod_key, Trigger::TouchpadScrollUp, mods);
2933 let bind_down =
2934 find_configured_bind(bindings, mod_key, Trigger::TouchpadScrollDown, mods);
2935 drop(config);
2936
2937 if let Some(down) = bind_down {
2938 for _ in 0..ticks {
2939 self.handle_bind(down.clone());
2940 }
2941 }
2942 if let Some(up) = bind_up {
2943 for _ in ticks..0 {
2944 self.handle_bind(up.clone());
2945 }
2946 }
2947 }
2948
2949 return;
2950 } else {
2951 self.niri.horizontal_finger_scroll_tracker.reset();
2952 self.niri.vertical_finger_scroll_tracker.reset();
2953 }
2954 }
2955
2956 self.update_pointer_contents();
2957
2958 let scroll_factor = match source {
2959 AxisSource::Wheel => self.niri.config.borrow().input.mouse.scroll_factor,
2960 AxisSource::Finger => self.niri.config.borrow().input.touchpad.scroll_factor,
2961 _ => None,
2962 };
2963 let scroll_factor = scroll_factor.map(|x| x.0).unwrap_or(1.);
2964
2965 let window_scroll_factor = pointer
2966 .current_focus()
2967 .map(|focused| self.niri.find_root_shell_surface(&focused))
2968 .and_then(|root| self.niri.layout.find_window_and_output(&root).unzip().0)
2969 .and_then(|window| window.rules().scroll_factor);
2970 let scroll_factor = scroll_factor * window_scroll_factor.unwrap_or(1.);
2971
2972 let horizontal_amount = horizontal_amount.unwrap_or_else(|| {
2973 // Winit backend, discrete scrolling.
2974 horizontal_amount_v120.unwrap_or(0.0) / 120. * 15.
2975 }) * scroll_factor;
2976 let vertical_amount = vertical_amount.unwrap_or_else(|| {
2977 // Winit backend, discrete scrolling.
2978 vertical_amount_v120.unwrap_or(0.0) / 120. * 15.
2979 }) * scroll_factor;
2980
2981 let horizontal_amount_v120 = horizontal_amount_v120.map(|x| x * scroll_factor);
2982 let vertical_amount_v120 = vertical_amount_v120.map(|x| x * scroll_factor);
2983
2984 let mut frame = AxisFrame::new(event.time_msec()).source(source);
2985 if horizontal_amount != 0.0 {
2986 frame = frame
2987 .relative_direction(Axis::Horizontal, event.relative_direction(Axis::Horizontal));
2988 frame = frame.value(Axis::Horizontal, horizontal_amount);
2989 if let Some(v120) = horizontal_amount_v120 {
2990 frame = frame.v120(Axis::Horizontal, v120 as i32);
2991 }
2992 }
2993 if vertical_amount != 0.0 {
2994 frame =
2995 frame.relative_direction(Axis::Vertical, event.relative_direction(Axis::Vertical));
2996 frame = frame.value(Axis::Vertical, vertical_amount);
2997 if let Some(v120) = vertical_amount_v120 {
2998 frame = frame.v120(Axis::Vertical, v120 as i32);
2999 }
3000 }
3001
3002 if source == AxisSource::Finger {
3003 if event.amount(Axis::Horizontal) == Some(0.0) {
3004 frame = frame.stop(Axis::Horizontal);
3005 }
3006 if event.amount(Axis::Vertical) == Some(0.0) {
3007 frame = frame.stop(Axis::Vertical);
3008 }
3009 }
3010
3011 pointer.axis(self, frame);
3012 pointer.frame(self);
3013 }
3014
3015 fn on_tablet_tool_axis<I: InputBackend>(&mut self, event: I::TabletToolAxisEvent)
3016 where
3017 I::Device: 'static, // Needed for downcasting.
3018 {
3019 let Some(pos) = self.compute_tablet_position(&event) else {
3020 return;
3021 };
3022
3023 let under = self.niri.contents_under(pos);
3024
3025 let tablet_seat = self.niri.seat.tablet_seat();
3026 let tablet = tablet_seat.get_tablet(&TabletDescriptor::from(&event.device()));
3027 let tool = tablet_seat.get_tool(&event.tool());
3028 if let (Some(tablet), Some(tool)) = (tablet, tool) {
3029 if event.pressure_has_changed() {
3030 tool.pressure(event.pressure());
3031 }
3032 if event.distance_has_changed() {
3033 tool.distance(event.distance());
3034 }
3035 if event.tilt_has_changed() {
3036 tool.tilt(event.tilt());
3037 }
3038 if event.slider_has_changed() {
3039 tool.slider_position(event.slider_position());
3040 }
3041 if event.rotation_has_changed() {
3042 tool.rotation(event.rotation());
3043 }
3044 if event.wheel_has_changed() {
3045 tool.wheel(event.wheel_delta(), event.wheel_delta_discrete());
3046 }
3047
3048 tool.motion(
3049 pos,
3050 under.surface,
3051 &tablet,
3052 SERIAL_COUNTER.next_serial(),
3053 event.time_msec(),
3054 );
3055
3056 self.niri.pointer_visibility = PointerVisibility::Visible;
3057 self.niri.tablet_cursor_location = Some(pos);
3058 }
3059
3060 // Redraw to update the cursor position.
3061 // FIXME: redraw only outputs overlapping the cursor.
3062 self.niri.queue_redraw_all();
3063 }
3064
3065 fn on_tablet_tool_tip<I: InputBackend>(&mut self, event: I::TabletToolTipEvent) {
3066 let tool = self.niri.seat.tablet_seat().get_tool(&event.tool());
3067
3068 if let Some(tool) = tool {
3069 let is_overview_open = self.niri.layout.is_overview_open();
3070
3071 match event.tip_state() {
3072 TabletToolTipState::Down => {
3073 let serial = SERIAL_COUNTER.next_serial();
3074 tool.tip_down(serial, event.time_msec());
3075
3076 if let Some(pos) = self.niri.tablet_cursor_location {
3077 let under = self.niri.contents_under(pos);
3078 if let Some((window, _)) = under.window {
3079 if let Some(output) = is_overview_open.then_some(under.output).flatten()
3080 {
3081 let mut workspaces = self.niri.layout.workspaces();
3082 if let Some(ws_idx) = workspaces.find_map(|(_, ws_idx, ws)| {
3083 ws.windows().any(|w| w.window == window).then_some(ws_idx)
3084 }) {
3085 drop(workspaces);
3086 self.niri.layout.focus_output(&output);
3087 self.niri.layout.toggle_overview_to_workspace(ws_idx);
3088 }
3089 }
3090
3091 self.niri.layout.activate_window(&window);
3092
3093 // FIXME: granular.
3094 self.niri.queue_redraw_all();
3095 } else if let Some((output, ws)) = is_overview_open
3096 .then(|| self.niri.workspace_under(false, pos))
3097 .flatten()
3098 {
3099 let ws_idx = self.niri.layout.find_workspace_by_id(ws.id()).unwrap().0;
3100
3101 self.niri.layout.focus_output(&output);
3102 self.niri.layout.toggle_overview_to_workspace(ws_idx);
3103
3104 // FIXME: granular.
3105 self.niri.queue_redraw_all();
3106 } else if let Some(output) = under.output {
3107 self.niri.layout.focus_output(&output);
3108
3109 // FIXME: granular.
3110 self.niri.queue_redraw_all();
3111 }
3112 self.niri.focus_layer_surface_if_on_demand(under.layer);
3113 }
3114 }
3115 TabletToolTipState::Up => {
3116 tool.tip_up(event.time_msec());
3117 }
3118 }
3119 }
3120 }
3121
3122 fn on_tablet_tool_proximity<I: InputBackend>(&mut self, event: I::TabletToolProximityEvent)
3123 where
3124 I::Device: 'static, // Needed for downcasting.
3125 {
3126 let Some(pos) = self.compute_tablet_position(&event) else {
3127 return;
3128 };
3129
3130 let under = self.niri.contents_under(pos);
3131
3132 let tablet_seat = self.niri.seat.tablet_seat();
3133 let display_handle = self.niri.display_handle.clone();
3134 let tool = tablet_seat.add_tool::<Self>(self, &display_handle, &event.tool());
3135 let tablet = tablet_seat.get_tablet(&TabletDescriptor::from(&event.device()));
3136 if let Some(tablet) = tablet {
3137 match event.state() {
3138 ProximityState::In => {
3139 if let Some(under) = under.surface {
3140 tool.proximity_in(
3141 pos,
3142 under,
3143 &tablet,
3144 SERIAL_COUNTER.next_serial(),
3145 event.time_msec(),
3146 );
3147 }
3148 self.niri.pointer_visibility = PointerVisibility::Visible;
3149 self.niri.tablet_cursor_location = Some(pos);
3150 }
3151 ProximityState::Out => {
3152 tool.proximity_out(event.time_msec());
3153
3154 // Move the mouse pointer here to avoid discontinuity.
3155 //
3156 // Plus, Wayland SDL2 currently warps the pointer into some weird
3157 // location on proximity out, so this should help it a little.
3158 if let Some(pos) = self.niri.tablet_cursor_location {
3159 self.move_cursor(pos);
3160 }
3161
3162 self.niri.pointer_visibility = PointerVisibility::Visible;
3163 self.niri.tablet_cursor_location = None;
3164 }
3165 }
3166
3167 // FIXME: granular.
3168 self.niri.queue_redraw_all();
3169 }
3170 }
3171
3172 fn on_tablet_tool_button<I: InputBackend>(&mut self, event: I::TabletToolButtonEvent) {
3173 let tool = self.niri.seat.tablet_seat().get_tool(&event.tool());
3174
3175 if let Some(tool) = tool {
3176 tool.button(
3177 event.button(),
3178 event.button_state(),
3179 SERIAL_COUNTER.next_serial(),
3180 event.time_msec(),
3181 );
3182 }
3183 }
3184
3185 fn on_gesture_swipe_begin<I: InputBackend>(&mut self, event: I::GestureSwipeBeginEvent) {
3186 if event.fingers() == 3 {
3187 self.niri.gesture_swipe_3f_cumulative = Some((0., 0.));
3188
3189 // We handled this event.
3190 return;
3191 } else if event.fingers() == 4 {
3192 self.niri.layout.overview_gesture_begin();
3193 self.niri.queue_redraw_all();
3194
3195 // We handled this event.
3196 return;
3197 }
3198
3199 let serial = SERIAL_COUNTER.next_serial();
3200 let pointer = self.niri.seat.get_pointer().unwrap();
3201
3202 if self.update_pointer_contents() {
3203 pointer.frame(self);
3204 }
3205
3206 pointer.gesture_swipe_begin(
3207 self,
3208 &GestureSwipeBeginEvent {
3209 serial,
3210 time: event.time_msec(),
3211 fingers: event.fingers(),
3212 },
3213 );
3214 }
3215
3216 fn on_gesture_swipe_update<I: InputBackend + 'static>(
3217 &mut self,
3218 event: I::GestureSwipeUpdateEvent,
3219 ) where
3220 I::Device: 'static,
3221 {
3222 let mut delta_x = event.delta_x();
3223 let mut delta_y = event.delta_y();
3224
3225 if let Some(libinput_event) =
3226 (&event as &dyn Any).downcast_ref::<input::event::gesture::GestureSwipeUpdateEvent>()
3227 {
3228 delta_x = libinput_event.dx_unaccelerated();
3229 delta_y = libinput_event.dy_unaccelerated();
3230 }
3231
3232 let uninverted_delta_y = delta_y;
3233
3234 let device = event.device();
3235 if let Some(device) = (&device as &dyn Any).downcast_ref::<input::Device>() {
3236 if device.config_scroll_natural_scroll_enabled() {
3237 delta_x = -delta_x;
3238 delta_y = -delta_y;
3239 }
3240 }
3241
3242 let is_overview_open = self.niri.layout.is_overview_open();
3243
3244 if let Some((cx, cy)) = &mut self.niri.gesture_swipe_3f_cumulative {
3245 *cx += delta_x;
3246 *cy += delta_y;
3247
3248 // Check if the gesture moved far enough to decide. Threshold copied from GNOME Shell.
3249 let (cx, cy) = (*cx, *cy);
3250 if cx * cx + cy * cy >= 16. * 16. {
3251 self.niri.gesture_swipe_3f_cumulative = None;
3252
3253 if let Some(output) = self.niri.output_under_cursor() {
3254 if cx.abs() > cy.abs() {
3255 let output_ws = if is_overview_open {
3256 self.niri.workspace_under_cursor(true)
3257 } else {
3258 // We don't want to accidentally "catch" the wrong workspace during
3259 // animations.
3260 self.niri.output_under_cursor().and_then(|output| {
3261 let mon = self.niri.layout.monitor_for_output(&output)?;
3262 Some((output, mon.active_workspace_ref()))
3263 })
3264 };
3265
3266 if let Some((output, ws)) = output_ws {
3267 let ws_idx = self.niri.layout.find_workspace_by_id(ws.id()).unwrap().0;
3268 self.niri
3269 .layout
3270 .view_offset_gesture_begin(&output, Some(ws_idx), true);
3271 }
3272 } else {
3273 self.niri
3274 .layout
3275 .workspace_switch_gesture_begin(&output, true);
3276 }
3277 }
3278 }
3279 }
3280
3281 let timestamp = Duration::from_micros(event.time());
3282
3283 let mut handled = false;
3284 let res = self
3285 .niri
3286 .layout
3287 .workspace_switch_gesture_update(delta_y, timestamp, true);
3288 if let Some(output) = res {
3289 if let Some(output) = output {
3290 self.niri.queue_redraw(&output);
3291 }
3292 handled = true;
3293 }
3294
3295 let res = self
3296 .niri
3297 .layout
3298 .view_offset_gesture_update(delta_x, timestamp, true);
3299 if let Some(output) = res {
3300 if let Some(output) = output {
3301 self.niri.queue_redraw(&output);
3302 }
3303 handled = true;
3304 }
3305
3306 let res = self
3307 .niri
3308 .layout
3309 .overview_gesture_update(-uninverted_delta_y, timestamp);
3310 if let Some(redraw) = res {
3311 if redraw {
3312 self.niri.queue_redraw_all();
3313 }
3314 handled = true;
3315 }
3316
3317 if handled {
3318 // We handled this event.
3319 return;
3320 }
3321
3322 let pointer = self.niri.seat.get_pointer().unwrap();
3323
3324 if self.update_pointer_contents() {
3325 pointer.frame(self);
3326 }
3327
3328 pointer.gesture_swipe_update(
3329 self,
3330 &GestureSwipeUpdateEvent {
3331 time: event.time_msec(),
3332 delta: event.delta(),
3333 },
3334 );
3335 }
3336
3337 fn on_gesture_swipe_end<I: InputBackend>(&mut self, event: I::GestureSwipeEndEvent) {
3338 self.niri.gesture_swipe_3f_cumulative = None;
3339
3340 let mut handled = false;
3341 let res = self.niri.layout.workspace_switch_gesture_end(Some(true));
3342 if let Some(output) = res {
3343 self.niri.queue_redraw(&output);
3344 handled = true;
3345 }
3346
3347 let res = self.niri.layout.view_offset_gesture_end(Some(true));
3348 if let Some(output) = res {
3349 self.niri.queue_redraw(&output);
3350 handled = true;
3351 }
3352
3353 let res = self.niri.layout.overview_gesture_end();
3354 if res {
3355 self.niri.queue_redraw_all();
3356 handled = true;
3357 }
3358
3359 if handled {
3360 // We handled this event.
3361 return;
3362 }
3363
3364 let serial = SERIAL_COUNTER.next_serial();
3365 let pointer = self.niri.seat.get_pointer().unwrap();
3366
3367 if self.update_pointer_contents() {
3368 pointer.frame(self);
3369 }
3370
3371 pointer.gesture_swipe_end(
3372 self,
3373 &GestureSwipeEndEvent {
3374 serial,
3375 time: event.time_msec(),
3376 cancelled: event.cancelled(),
3377 },
3378 );
3379 }
3380
3381 fn on_gesture_pinch_begin<I: InputBackend>(&mut self, event: I::GesturePinchBeginEvent) {
3382 let serial = SERIAL_COUNTER.next_serial();
3383 let pointer = self.niri.seat.get_pointer().unwrap();
3384
3385 if self.update_pointer_contents() {
3386 pointer.frame(self);
3387 }
3388
3389 pointer.gesture_pinch_begin(
3390 self,
3391 &GesturePinchBeginEvent {
3392 serial,
3393 time: event.time_msec(),
3394 fingers: event.fingers(),
3395 },
3396 );
3397 }
3398
3399 fn on_gesture_pinch_update<I: InputBackend>(&mut self, event: I::GesturePinchUpdateEvent) {
3400 let pointer = self.niri.seat.get_pointer().unwrap();
3401
3402 if self.update_pointer_contents() {
3403 pointer.frame(self);
3404 }
3405
3406 pointer.gesture_pinch_update(
3407 self,
3408 &GesturePinchUpdateEvent {
3409 time: event.time_msec(),
3410 delta: event.delta(),
3411 scale: event.scale(),
3412 rotation: event.rotation(),
3413 },
3414 );
3415 }
3416
3417 fn on_gesture_pinch_end<I: InputBackend>(&mut self, event: I::GesturePinchEndEvent) {
3418 let serial = SERIAL_COUNTER.next_serial();
3419 let pointer = self.niri.seat.get_pointer().unwrap();
3420
3421 if self.update_pointer_contents() {
3422 pointer.frame(self);
3423 }
3424
3425 pointer.gesture_pinch_end(
3426 self,
3427 &GesturePinchEndEvent {
3428 serial,
3429 time: event.time_msec(),
3430 cancelled: event.cancelled(),
3431 },
3432 );
3433 }
3434
3435 fn on_gesture_hold_begin<I: InputBackend>(&mut self, event: I::GestureHoldBeginEvent) {
3436 let serial = SERIAL_COUNTER.next_serial();
3437 let pointer = self.niri.seat.get_pointer().unwrap();
3438
3439 if self.update_pointer_contents() {
3440 pointer.frame(self);
3441 }
3442
3443 pointer.gesture_hold_begin(
3444 self,
3445 &GestureHoldBeginEvent {
3446 serial,
3447 time: event.time_msec(),
3448 fingers: event.fingers(),
3449 },
3450 );
3451 }
3452
3453 fn on_gesture_hold_end<I: InputBackend>(&mut self, event: I::GestureHoldEndEvent) {
3454 let serial = SERIAL_COUNTER.next_serial();
3455 let pointer = self.niri.seat.get_pointer().unwrap();
3456
3457 if self.update_pointer_contents() {
3458 pointer.frame(self);
3459 }
3460
3461 pointer.gesture_hold_end(
3462 self,
3463 &GestureHoldEndEvent {
3464 serial,
3465 time: event.time_msec(),
3466 cancelled: event.cancelled(),
3467 },
3468 );
3469 }
3470
3471 fn compute_absolute_location<I: InputBackend>(
3472 &self,
3473 evt: &impl AbsolutePositionEvent<I>,
3474 fallback_output: Option<&Output>,
3475 ) -> Option<Point<f64, Logical>> {
3476 let output = evt.device().output(self);
3477 let output = output.as_ref().or(fallback_output)?;
3478 let output_geo = self.niri.global_space.output_geometry(output).unwrap();
3479 let transform = output.current_transform();
3480 let size = transform.invert().transform_size(output_geo.size);
3481 Some(
3482 transform.transform_point_in(evt.position_transformed(size), &size.to_f64())
3483 + output_geo.loc.to_f64(),
3484 )
3485 }
3486
3487 /// Computes the cursor position for the touch event.
3488 ///
3489 /// This function handles the touch output mapping, as well as coordinate transform
3490 fn compute_touch_location<I: InputBackend>(
3491 &self,
3492 evt: &impl AbsolutePositionEvent<I>,
3493 ) -> Option<Point<f64, Logical>> {
3494 self.compute_absolute_location(evt, self.niri.output_for_touch())
3495 }
3496
3497 fn on_touch_down<I: InputBackend>(&mut self, evt: I::TouchDownEvent) {
3498 let Some(handle) = self.niri.seat.get_touch() else {
3499 return;
3500 };
3501 let Some(touch_location) = self.compute_touch_location(&evt) else {
3502 return;
3503 };
3504
3505 let serial = SERIAL_COUNTER.next_serial();
3506
3507 let under = self.niri.contents_under(touch_location);
3508
3509 let mod_key = self.backend.mod_key(&self.niri.config.borrow());
3510
3511 if !handle.is_grabbed() {
3512 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
3513 let mods = modifiers_from_state(mods);
3514 let mod_down = mods.contains(mod_key.to_modifiers());
3515
3516 if self.niri.layout.is_overview_open() && !mod_down && under.layer.is_none() {
3517 let (output, pos_within_output) = self.niri.output_under(touch_location).unwrap();
3518 let output = output.clone();
3519
3520 let mut matched_narrow = true;
3521 let mut ws = self.niri.workspace_under(false, touch_location);
3522 if ws.is_none() {
3523 matched_narrow = false;
3524 ws = self.niri.workspace_under(true, touch_location);
3525 }
3526 let ws_id = ws.map(|(_, ws)| ws.id());
3527
3528 let mapped = self.niri.window_under(touch_location);
3529 let window = mapped.map(|mapped| mapped.window.clone());
3530
3531 let start_data = TouchGrabStartData {
3532 focus: None,
3533 slot: evt.slot(),
3534 location: touch_location,
3535 };
3536 let start_timestamp = Duration::from_micros(evt.time());
3537 let grab = TouchOverviewGrab::new(
3538 start_data,
3539 start_timestamp,
3540 output,
3541 pos_within_output,
3542 ws_id,
3543 matched_narrow,
3544 window,
3545 );
3546 handle.set_grab(self, grab, serial);
3547 } else if let Some((window, _)) = under.window {
3548 self.niri.layout.activate_window(&window);
3549
3550 // Check if we need to start an interactive move.
3551 if mod_down {
3552 let (output, pos_within_output) =
3553 self.niri.output_under(touch_location).unwrap();
3554 let output = output.clone();
3555
3556 if self.niri.layout.interactive_move_begin(
3557 window.clone(),
3558 &output,
3559 pos_within_output,
3560 ) {
3561 let start_data = TouchGrabStartData {
3562 focus: None,
3563 slot: evt.slot(),
3564 location: touch_location,
3565 };
3566 let grab = TouchMoveGrab::new(start_data, window.clone());
3567 handle.set_grab(self, grab, serial);
3568 }
3569 }
3570
3571 // FIXME: granular.
3572 self.niri.queue_redraw_all();
3573 } else if let Some(output) = under.output {
3574 self.niri.layout.focus_output(&output);
3575
3576 // FIXME: granular.
3577 self.niri.queue_redraw_all();
3578 }
3579 self.niri.focus_layer_surface_if_on_demand(under.layer);
3580 };
3581
3582 handle.down(
3583 self,
3584 under.surface,
3585 &DownEvent {
3586 slot: evt.slot(),
3587 location: touch_location,
3588 serial,
3589 time: evt.time_msec(),
3590 },
3591 );
3592
3593 // We're using touch, hide the pointer.
3594 self.niri.pointer_visibility = PointerVisibility::Disabled;
3595 }
3596 fn on_touch_up<I: InputBackend>(&mut self, evt: I::TouchUpEvent) {
3597 let Some(handle) = self.niri.seat.get_touch() else {
3598 return;
3599 };
3600 let serial = SERIAL_COUNTER.next_serial();
3601 handle.up(
3602 self,
3603 &UpEvent {
3604 slot: evt.slot(),
3605 serial,
3606 time: evt.time_msec(),
3607 },
3608 )
3609 }
3610 fn on_touch_motion<I: InputBackend>(&mut self, evt: I::TouchMotionEvent) {
3611 let Some(handle) = self.niri.seat.get_touch() else {
3612 return;
3613 };
3614 let Some(touch_location) = self.compute_touch_location(&evt) else {
3615 return;
3616 };
3617 let under = self.niri.contents_under(touch_location);
3618 handle.motion(
3619 self,
3620 under.surface,
3621 &TouchMotionEvent {
3622 slot: evt.slot(),
3623 location: touch_location,
3624 time: evt.time_msec(),
3625 },
3626 );
3627
3628 // Inform the layout of an ongoing DnD operation.
3629 let mut is_dnd_grab = false;
3630 handle.with_grab(|_, grab| {
3631 is_dnd_grab = grab.as_any().downcast_ref::<DnDGrab<Self>>().is_some();
3632 });
3633 if is_dnd_grab {
3634 if let Some((output, pos_within_output)) = self.niri.output_under(touch_location) {
3635 let output = output.clone();
3636 self.niri.layout.dnd_update(output, pos_within_output);
3637 }
3638 }
3639 }
3640 fn on_touch_frame<I: InputBackend>(&mut self, _evt: I::TouchFrameEvent) {
3641 let Some(handle) = self.niri.seat.get_touch() else {
3642 return;
3643 };
3644 handle.frame(self);
3645 }
3646 fn on_touch_cancel<I: InputBackend>(&mut self, _evt: I::TouchCancelEvent) {
3647 let Some(handle) = self.niri.seat.get_touch() else {
3648 return;
3649 };
3650 handle.cancel(self);
3651 }
3652
3653 fn on_switch_toggle<I: InputBackend>(&mut self, evt: I::SwitchToggleEvent) {
3654 let Some(switch) = evt.switch() else {
3655 return;
3656 };
3657
3658 if switch == Switch::Lid {
3659 let is_closed = evt.state() == SwitchState::On;
3660 debug!("lid switch {}", if is_closed { "closed" } else { "opened" });
3661 self.niri.is_lid_closed = is_closed;
3662 self.backend.on_output_config_changed(&mut self.niri);
3663 }
3664
3665 let action = {
3666 let bindings = &self.niri.config.borrow().switch_events;
3667 find_configured_switch_action(bindings, switch, evt.state())
3668 };
3669
3670 if let Some(action) = action {
3671 self.do_action(action, true);
3672 }
3673 }
3674}
3675
3676/// Check whether the key should be intercepted and mark intercepted
3677/// pressed keys as `suppressed`, thus preventing `releases` corresponding
3678/// to them from being delivered.
3679#[allow(clippy::too_many_arguments)]
3680fn should_intercept_key(
3681 suppressed_keys: &mut HashSet<Keycode>,
3682 bindings: &Binds,
3683 mod_key: ModKey,
3684 key_code: Keycode,
3685 modified: Keysym,
3686 raw: Option<Keysym>,
3687 pressed: bool,
3688 mods: ModifiersState,
3689 screenshot_ui: &ScreenshotUi,
3690 disable_power_key_handling: bool,
3691 is_inhibiting_shortcuts: bool,
3692) -> FilterResult<Option<Bind>> {
3693 // Actions are only triggered on presses, release of the key
3694 // shouldn't try to intercept anything unless we have marked
3695 // the key to suppress.
3696 if !pressed && !suppressed_keys.contains(&key_code) {
3697 return FilterResult::Forward;
3698 }
3699
3700 let mut final_bind = find_bind(
3701 bindings,
3702 mod_key,
3703 modified,
3704 raw,
3705 mods,
3706 disable_power_key_handling,
3707 );
3708
3709 // Allow only a subset of compositor actions while the screenshot UI is open, since the user
3710 // cannot see the screen.
3711 if screenshot_ui.is_open() {
3712 let mut use_screenshot_ui_action = true;
3713
3714 if let Some(bind) = &final_bind {
3715 if allowed_during_screenshot(&bind.action) {
3716 use_screenshot_ui_action = false;
3717 }
3718 }
3719
3720 if use_screenshot_ui_action {
3721 if let Some(raw) = raw {
3722 final_bind = screenshot_ui.action(raw, mods).map(|action| Bind {
3723 key: Key {
3724 trigger: Trigger::Keysym(raw),
3725 // Not entirely correct but it doesn't matter in how we currently use it.
3726 modifiers: Modifiers::empty(),
3727 },
3728 action,
3729 repeat: true,
3730 cooldown: None,
3731 allow_when_locked: false,
3732 // The screenshot UI owns the focus anyway, so this doesn't really matter.
3733 // But logically, nothing can inhibit its actions. Only opening it can be
3734 // inhibited.
3735 allow_inhibiting: false,
3736 hotkey_overlay_title: None,
3737 });
3738 }
3739 }
3740 }
3741
3742 match (final_bind, pressed) {
3743 (Some(bind), true) => {
3744 if is_inhibiting_shortcuts && bind.allow_inhibiting {
3745 FilterResult::Forward
3746 } else {
3747 suppressed_keys.insert(key_code);
3748 FilterResult::Intercept(Some(bind))
3749 }
3750 }
3751 (_, false) => {
3752 // By this point, we know that the key was suppressed on press. Even if we're inhibiting
3753 // shortcuts, we should still suppress the release.
3754 // But we don't need to check for shortcuts inhibition here, because
3755 // if it was inhibited on press (forwarded to the client), it wouldn't be suppressed,
3756 // so the release would already have been forwarded at the start of this function.
3757 suppressed_keys.remove(&key_code);
3758 FilterResult::Intercept(None)
3759 }
3760 (None, true) => FilterResult::Forward,
3761 }
3762}
3763
3764fn find_bind(
3765 bindings: &Binds,
3766 mod_key: ModKey,
3767 modified: Keysym,
3768 raw: Option<Keysym>,
3769 mods: ModifiersState,
3770 disable_power_key_handling: bool,
3771) -> Option<Bind> {
3772 use keysyms::*;
3773
3774 // Handle hardcoded binds.
3775 #[allow(non_upper_case_globals)] // wat
3776 let hardcoded_action = match modified.raw() {
3777 modified @ KEY_XF86Switch_VT_1..=KEY_XF86Switch_VT_12 => {
3778 let vt = (modified - KEY_XF86Switch_VT_1 + 1) as i32;
3779 Some(Action::ChangeVt(vt))
3780 }
3781 KEY_XF86PowerOff if !disable_power_key_handling => Some(Action::Suspend),
3782 _ => None,
3783 };
3784
3785 if let Some(action) = hardcoded_action {
3786 return Some(Bind {
3787 key: Key {
3788 // Not entirely correct but it doesn't matter in how we currently use it.
3789 trigger: Trigger::Keysym(modified),
3790 modifiers: Modifiers::empty(),
3791 },
3792 action,
3793 repeat: true,
3794 cooldown: None,
3795 allow_when_locked: false,
3796 // In a worst-case scenario, the user has no way to unlock the compositor and a
3797 // misbehaving client has a keyboard shortcuts inhibitor, "jailing" the user.
3798 // The user must always be able to change VTs to recover from such a situation.
3799 // It also makes no sense to inhibit the default power key handling.
3800 // Hardcoded binds must never be inhibited.
3801 allow_inhibiting: false,
3802 hotkey_overlay_title: None,
3803 });
3804 }
3805
3806 let trigger = Trigger::Keysym(raw?);
3807 find_configured_bind(bindings, mod_key, trigger, mods)
3808}
3809
3810fn find_configured_bind(
3811 bindings: &Binds,
3812 mod_key: ModKey,
3813 trigger: Trigger,
3814 mods: ModifiersState,
3815) -> Option<Bind> {
3816 // Handle configured binds.
3817 let mut modifiers = modifiers_from_state(mods);
3818
3819 let mod_down = modifiers_from_state(mods).contains(mod_key.to_modifiers());
3820 if mod_down {
3821 modifiers |= Modifiers::COMPOSITOR;
3822 }
3823
3824 for bind in &bindings.0 {
3825 if bind.key.trigger != trigger {
3826 continue;
3827 }
3828
3829 let mut bind_modifiers = bind.key.modifiers;
3830 if bind_modifiers.contains(Modifiers::COMPOSITOR) {
3831 bind_modifiers |= mod_key.to_modifiers();
3832 } else if bind_modifiers.contains(mod_key.to_modifiers()) {
3833 bind_modifiers |= Modifiers::COMPOSITOR;
3834 }
3835
3836 if bind_modifiers == modifiers {
3837 return Some(bind.clone());
3838 }
3839 }
3840
3841 None
3842}
3843
3844fn find_configured_switch_action(
3845 bindings: &SwitchBinds,
3846 switch: Switch,
3847 state: SwitchState,
3848) -> Option<Action> {
3849 let switch_action = match (switch, state) {
3850 (Switch::Lid, SwitchState::Off) => &bindings.lid_open,
3851 (Switch::Lid, SwitchState::On) => &bindings.lid_close,
3852 (Switch::TabletMode, SwitchState::Off) => &bindings.tablet_mode_off,
3853 (Switch::TabletMode, SwitchState::On) => &bindings.tablet_mode_on,
3854 _ => unreachable!(),
3855 };
3856 switch_action
3857 .as_ref()
3858 .map(|switch_action| Action::Spawn(switch_action.spawn.clone()))
3859}
3860
3861fn modifiers_from_state(mods: ModifiersState) -> Modifiers {
3862 let mut modifiers = Modifiers::empty();
3863 if mods.ctrl {
3864 modifiers |= Modifiers::CTRL;
3865 }
3866 if mods.shift {
3867 modifiers |= Modifiers::SHIFT;
3868 }
3869 if mods.alt {
3870 modifiers |= Modifiers::ALT;
3871 }
3872 if mods.logo {
3873 modifiers |= Modifiers::SUPER;
3874 }
3875 if mods.iso_level3_shift {
3876 modifiers |= Modifiers::ISO_LEVEL3_SHIFT;
3877 }
3878 if mods.iso_level5_shift {
3879 modifiers |= Modifiers::ISO_LEVEL5_SHIFT;
3880 }
3881 modifiers
3882}
3883
3884fn should_activate_monitors<I: InputBackend>(event: &InputEvent<I>) -> bool {
3885 match event {
3886 InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true,
3887 InputEvent::PointerButton { event } if event.state() == ButtonState::Pressed => true,
3888 InputEvent::PointerMotion { .. }
3889 | InputEvent::PointerMotionAbsolute { .. }
3890 | InputEvent::PointerAxis { .. }
3891 | InputEvent::GestureSwipeBegin { .. }
3892 | InputEvent::GesturePinchBegin { .. }
3893 | InputEvent::GestureHoldBegin { .. }
3894 | InputEvent::TouchDown { .. }
3895 | InputEvent::TouchMotion { .. }
3896 | InputEvent::TabletToolAxis { .. }
3897 | InputEvent::TabletToolProximity { .. }
3898 | InputEvent::TabletToolTip { .. }
3899 | InputEvent::TabletToolButton { .. } => true,
3900 // Ignore events like device additions and removals, key releases, gesture ends.
3901 _ => false,
3902 }
3903}
3904
3905fn should_hide_hotkey_overlay<I: InputBackend>(event: &InputEvent<I>) -> bool {
3906 match event {
3907 InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true,
3908 InputEvent::PointerButton { event } if event.state() == ButtonState::Pressed => true,
3909 InputEvent::PointerAxis { .. }
3910 | InputEvent::GestureSwipeBegin { .. }
3911 | InputEvent::GesturePinchBegin { .. }
3912 | InputEvent::TouchDown { .. }
3913 | InputEvent::TouchMotion { .. }
3914 | InputEvent::TabletToolTip { .. }
3915 | InputEvent::TabletToolButton { .. } => true,
3916 _ => false,
3917 }
3918}
3919
3920fn should_hide_exit_confirm_dialog<I: InputBackend>(event: &InputEvent<I>) -> bool {
3921 match event {
3922 InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true,
3923 InputEvent::PointerButton { event } if event.state() == ButtonState::Pressed => true,
3924 InputEvent::PointerAxis { .. }
3925 | InputEvent::GestureSwipeBegin { .. }
3926 | InputEvent::GesturePinchBegin { .. }
3927 | InputEvent::TouchDown { .. }
3928 | InputEvent::TouchMotion { .. }
3929 | InputEvent::TabletToolTip { .. }
3930 | InputEvent::TabletToolButton { .. } => true,
3931 _ => false,
3932 }
3933}
3934
3935fn should_notify_activity<I: InputBackend>(event: &InputEvent<I>) -> bool {
3936 !matches!(
3937 event,
3938 InputEvent::DeviceAdded { .. } | InputEvent::DeviceRemoved { .. }
3939 )
3940}
3941
3942fn should_reset_pointer_inactivity_timer<I: InputBackend>(event: &InputEvent<I>) -> bool {
3943 matches!(
3944 event,
3945 InputEvent::PointerAxis { .. }
3946 | InputEvent::PointerButton { .. }
3947 | InputEvent::PointerMotion { .. }
3948 | InputEvent::PointerMotionAbsolute { .. }
3949 | InputEvent::TabletToolAxis { .. }
3950 | InputEvent::TabletToolButton { .. }
3951 | InputEvent::TabletToolProximity { .. }
3952 | InputEvent::TabletToolTip { .. }
3953 )
3954}
3955
3956fn allowed_when_locked(action: &Action) -> bool {
3957 matches!(
3958 action,
3959 Action::Quit(_)
3960 | Action::ChangeVt(_)
3961 | Action::Suspend
3962 | Action::PowerOffMonitors
3963 | Action::PowerOnMonitors
3964 | Action::SwitchLayout(_)
3965 | Action::ToggleKeyboardShortcutsInhibit
3966 )
3967}
3968
3969fn allowed_during_screenshot(action: &Action) -> bool {
3970 matches!(
3971 action,
3972 Action::Quit(_)
3973 | Action::ChangeVt(_)
3974 | Action::Suspend
3975 | Action::PowerOffMonitors
3976 | Action::PowerOnMonitors
3977 // The screenshot UI can handle these.
3978 | Action::MoveColumnLeft
3979 | Action::MoveColumnRight
3980 | Action::MoveWindowUp
3981 | Action::MoveWindowDown
3982 | Action::SetWindowWidth(_)
3983 | Action::SetWindowHeight(_)
3984 | Action::SetColumnWidth(_)
3985 )
3986}
3987
3988fn hardcoded_overview_bind(raw: Keysym, mods: ModifiersState) -> Option<Bind> {
3989 let mods = modifiers_from_state(mods);
3990 if !mods.is_empty() {
3991 return None;
3992 }
3993
3994 let mut repeat = true;
3995 let action = match raw {
3996 Keysym::Escape | Keysym::Return => {
3997 repeat = false;
3998 Action::ToggleOverview
3999 }
4000 Keysym::Left => Action::FocusColumnLeft,
4001 Keysym::Right => Action::FocusColumnRight,
4002 Keysym::Up => Action::FocusWindowOrWorkspaceUp,
4003 Keysym::Down => Action::FocusWindowOrWorkspaceDown,
4004 _ => {
4005 return None;
4006 }
4007 };
4008
4009 Some(Bind {
4010 key: Key {
4011 trigger: Trigger::Keysym(raw),
4012 modifiers: Modifiers::empty(),
4013 },
4014 action,
4015 repeat,
4016 cooldown: None,
4017 allow_when_locked: false,
4018 allow_inhibiting: false,
4019 hotkey_overlay_title: None,
4020 })
4021}
4022
4023pub fn apply_libinput_settings(config: &niri_config::Input, device: &mut input::Device) {
4024 // According to Mutter code, this setting is specific to touchpads.
4025 let is_touchpad = device.config_tap_finger_count() > 0;
4026 if is_touchpad {
4027 let c = &config.touchpad;
4028 let _ = device.config_send_events_set_mode(if c.off {
4029 input::SendEventsMode::DISABLED
4030 } else if c.disabled_on_external_mouse {
4031 input::SendEventsMode::DISABLED_ON_EXTERNAL_MOUSE
4032 } else {
4033 input::SendEventsMode::ENABLED
4034 });
4035 let _ = device.config_tap_set_enabled(c.tap);
4036 let _ = device.config_dwt_set_enabled(c.dwt);
4037 let _ = device.config_dwtp_set_enabled(c.dwtp);
4038 let _ = device.config_tap_set_drag_lock_enabled(c.drag_lock);
4039 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
4040 let _ = device.config_accel_set_speed(c.accel_speed);
4041 let _ = device.config_left_handed_set(c.left_handed);
4042 let _ = device.config_middle_emulation_set_enabled(c.middle_emulation);
4043
4044 if let Some(drag) = c.drag {
4045 let _ = device.config_tap_set_drag_enabled(drag);
4046 } else {
4047 let default = device.config_tap_default_drag_enabled();
4048 let _ = device.config_tap_set_drag_enabled(default);
4049 }
4050
4051 if let Some(accel_profile) = c.accel_profile {
4052 let _ = device.config_accel_set_profile(accel_profile.into());
4053 } else if let Some(default) = device.config_accel_default_profile() {
4054 let _ = device.config_accel_set_profile(default);
4055 }
4056
4057 if let Some(method) = c.scroll_method {
4058 let _ = device.config_scroll_set_method(method.into());
4059
4060 if method == niri_config::ScrollMethod::OnButtonDown {
4061 if let Some(button) = c.scroll_button {
4062 let _ = device.config_scroll_set_button(button);
4063 }
4064 }
4065 } else if let Some(default) = device.config_scroll_default_method() {
4066 let _ = device.config_scroll_set_method(default);
4067
4068 if default == input::ScrollMethod::OnButtonDown {
4069 if let Some(button) = c.scroll_button {
4070 let _ = device.config_scroll_set_button(button);
4071 }
4072 }
4073 }
4074
4075 if let Some(tap_button_map) = c.tap_button_map {
4076 let _ = device.config_tap_set_button_map(tap_button_map.into());
4077 } else if let Some(default) = device.config_tap_default_button_map() {
4078 let _ = device.config_tap_set_button_map(default);
4079 }
4080
4081 if let Some(method) = c.click_method {
4082 let _ = device.config_click_set_method(method.into());
4083 } else if let Some(default) = device.config_click_default_method() {
4084 let _ = device.config_click_set_method(default);
4085 }
4086 }
4087
4088 // This is how Mutter tells apart mice.
4089 let mut is_trackball = false;
4090 let mut is_trackpoint = false;
4091 if let Some(udev_device) = unsafe { device.udev_device() } {
4092 if udev_device.property_value("ID_INPUT_TRACKBALL").is_some() {
4093 is_trackball = true;
4094 }
4095 if udev_device
4096 .property_value("ID_INPUT_POINTINGSTICK")
4097 .is_some()
4098 {
4099 is_trackpoint = true;
4100 }
4101 }
4102
4103 let is_mouse = device.has_capability(input::DeviceCapability::Pointer)
4104 && !is_touchpad
4105 && !is_trackball
4106 && !is_trackpoint;
4107 if is_mouse {
4108 let c = &config.mouse;
4109 let _ = device.config_send_events_set_mode(if c.off {
4110 input::SendEventsMode::DISABLED
4111 } else {
4112 input::SendEventsMode::ENABLED
4113 });
4114 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
4115 let _ = device.config_accel_set_speed(c.accel_speed);
4116 let _ = device.config_left_handed_set(c.left_handed);
4117 let _ = device.config_middle_emulation_set_enabled(c.middle_emulation);
4118
4119 if let Some(accel_profile) = c.accel_profile {
4120 let _ = device.config_accel_set_profile(accel_profile.into());
4121 } else if let Some(default) = device.config_accel_default_profile() {
4122 let _ = device.config_accel_set_profile(default);
4123 }
4124
4125 if let Some(method) = c.scroll_method {
4126 let _ = device.config_scroll_set_method(method.into());
4127
4128 if method == niri_config::ScrollMethod::OnButtonDown {
4129 if let Some(button) = c.scroll_button {
4130 let _ = device.config_scroll_set_button(button);
4131 }
4132 }
4133 } else if let Some(default) = device.config_scroll_default_method() {
4134 let _ = device.config_scroll_set_method(default);
4135
4136 if default == input::ScrollMethod::OnButtonDown {
4137 if let Some(button) = c.scroll_button {
4138 let _ = device.config_scroll_set_button(button);
4139 }
4140 }
4141 }
4142 }
4143
4144 if is_trackball {
4145 let c = &config.trackball;
4146 let _ = device.config_send_events_set_mode(if c.off {
4147 input::SendEventsMode::DISABLED
4148 } else {
4149 input::SendEventsMode::ENABLED
4150 });
4151 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
4152 let _ = device.config_accel_set_speed(c.accel_speed);
4153 let _ = device.config_middle_emulation_set_enabled(c.middle_emulation);
4154 let _ = device.config_left_handed_set(c.left_handed);
4155
4156 if let Some(accel_profile) = c.accel_profile {
4157 let _ = device.config_accel_set_profile(accel_profile.into());
4158 } else if let Some(default) = device.config_accel_default_profile() {
4159 let _ = device.config_accel_set_profile(default);
4160 }
4161
4162 if let Some(method) = c.scroll_method {
4163 let _ = device.config_scroll_set_method(method.into());
4164
4165 if method == niri_config::ScrollMethod::OnButtonDown {
4166 if let Some(button) = c.scroll_button {
4167 let _ = device.config_scroll_set_button(button);
4168 }
4169 }
4170 } else if let Some(default) = device.config_scroll_default_method() {
4171 let _ = device.config_scroll_set_method(default);
4172
4173 if default == input::ScrollMethod::OnButtonDown {
4174 if let Some(button) = c.scroll_button {
4175 let _ = device.config_scroll_set_button(button);
4176 }
4177 }
4178 }
4179 }
4180
4181 if is_trackpoint {
4182 let c = &config.trackpoint;
4183 let _ = device.config_send_events_set_mode(if c.off {
4184 input::SendEventsMode::DISABLED
4185 } else {
4186 input::SendEventsMode::ENABLED
4187 });
4188 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
4189 let _ = device.config_accel_set_speed(c.accel_speed);
4190 let _ = device.config_left_handed_set(c.left_handed);
4191 let _ = device.config_middle_emulation_set_enabled(c.middle_emulation);
4192
4193 if let Some(accel_profile) = c.accel_profile {
4194 let _ = device.config_accel_set_profile(accel_profile.into());
4195 } else if let Some(default) = device.config_accel_default_profile() {
4196 let _ = device.config_accel_set_profile(default);
4197 }
4198
4199 if let Some(method) = c.scroll_method {
4200 let _ = device.config_scroll_set_method(method.into());
4201
4202 if method == niri_config::ScrollMethod::OnButtonDown {
4203 if let Some(button) = c.scroll_button {
4204 let _ = device.config_scroll_set_button(button);
4205 }
4206 }
4207 } else if let Some(default) = device.config_scroll_default_method() {
4208 let _ = device.config_scroll_set_method(default);
4209
4210 if default == input::ScrollMethod::OnButtonDown {
4211 if let Some(button) = c.scroll_button {
4212 let _ = device.config_scroll_set_button(button);
4213 }
4214 }
4215 }
4216 }
4217
4218 let is_tablet = device.has_capability(input::DeviceCapability::TabletTool);
4219 if is_tablet {
4220 let c = &config.tablet;
4221 let _ = device.config_send_events_set_mode(if c.off {
4222 input::SendEventsMode::DISABLED
4223 } else {
4224 input::SendEventsMode::ENABLED
4225 });
4226
4227 #[rustfmt::skip]
4228 const IDENTITY_MATRIX: [f32; 6] = [
4229 1., 0., 0.,
4230 0., 1., 0.,
4231 ];
4232
4233 let _ = device.config_calibration_set_matrix(
4234 c.calibration_matrix
4235 .as_deref()
4236 .and_then(|m| m.try_into().ok())
4237 .or(device.config_calibration_default_matrix())
4238 .unwrap_or(IDENTITY_MATRIX),
4239 );
4240
4241 let _ = device.config_left_handed_set(c.left_handed);
4242 }
4243
4244 let is_touch = device.has_capability(input::DeviceCapability::Touch);
4245 if is_touch {
4246 let c = &config.touch;
4247 let _ = device.config_send_events_set_mode(if c.off {
4248 input::SendEventsMode::DISABLED
4249 } else {
4250 input::SendEventsMode::ENABLED
4251 });
4252 }
4253}
4254
4255pub fn mods_with_binds(mod_key: ModKey, binds: &Binds, triggers: &[Trigger]) -> HashSet<Modifiers> {
4256 let mut rv = HashSet::new();
4257 for bind in &binds.0 {
4258 if !triggers.iter().any(|trigger| bind.key.trigger == *trigger) {
4259 continue;
4260 }
4261
4262 let mut mods = bind.key.modifiers;
4263 if mods.contains(Modifiers::COMPOSITOR) {
4264 mods.remove(Modifiers::COMPOSITOR);
4265 mods.insert(mod_key.to_modifiers());
4266 }
4267
4268 rv.insert(mods);
4269 }
4270
4271 rv
4272}
4273
4274pub fn mods_with_mouse_binds(mod_key: ModKey, binds: &Binds) -> HashSet<Modifiers> {
4275 mods_with_binds(
4276 mod_key,
4277 binds,
4278 &[
4279 Trigger::MouseLeft,
4280 Trigger::MouseRight,
4281 Trigger::MouseMiddle,
4282 Trigger::MouseBack,
4283 Trigger::MouseForward,
4284 ],
4285 )
4286}
4287
4288pub fn mods_with_wheel_binds(mod_key: ModKey, binds: &Binds) -> HashSet<Modifiers> {
4289 mods_with_binds(
4290 mod_key,
4291 binds,
4292 &[
4293 Trigger::WheelScrollUp,
4294 Trigger::WheelScrollDown,
4295 Trigger::WheelScrollLeft,
4296 Trigger::WheelScrollRight,
4297 ],
4298 )
4299}
4300
4301pub fn mods_with_finger_scroll_binds(mod_key: ModKey, binds: &Binds) -> HashSet<Modifiers> {
4302 mods_with_binds(
4303 mod_key,
4304 binds,
4305 &[
4306 Trigger::TouchpadScrollUp,
4307 Trigger::TouchpadScrollDown,
4308 Trigger::TouchpadScrollLeft,
4309 Trigger::TouchpadScrollRight,
4310 ],
4311 )
4312}
4313
4314#[cfg(test)]
4315mod tests {
4316 use std::cell::Cell;
4317
4318 use super::*;
4319 use crate::animation::Clock;
4320
4321 #[test]
4322 fn bindings_suppress_keys() {
4323 let close_keysym = Keysym::q;
4324 let bindings = Binds(vec![Bind {
4325 key: Key {
4326 trigger: Trigger::Keysym(close_keysym),
4327 modifiers: Modifiers::COMPOSITOR | Modifiers::CTRL,
4328 },
4329 action: Action::CloseWindow,
4330 repeat: true,
4331 cooldown: None,
4332 allow_when_locked: false,
4333 allow_inhibiting: true,
4334 hotkey_overlay_title: None,
4335 }]);
4336
4337 let comp_mod = ModKey::Super;
4338 let mut suppressed_keys = HashSet::new();
4339
4340 let screenshot_ui = ScreenshotUi::new(Clock::default(), Default::default());
4341 let disable_power_key_handling = false;
4342 let is_inhibiting_shortcuts = Cell::new(false);
4343
4344 // The key_code we pick is arbitrary, the only thing
4345 // that matters is that they are different between cases.
4346
4347 let close_key_code = Keycode::from(close_keysym.raw() + 8u32);
4348 let close_key_event = |suppr: &mut HashSet<Keycode>, mods: ModifiersState, pressed| {
4349 should_intercept_key(
4350 suppr,
4351 &bindings,
4352 comp_mod,
4353 close_key_code,
4354 close_keysym,
4355 Some(close_keysym),
4356 pressed,
4357 mods,
4358 &screenshot_ui,
4359 disable_power_key_handling,
4360 is_inhibiting_shortcuts.get(),
4361 )
4362 };
4363
4364 // Key event with the code which can't trigger any action.
4365 let none_key_event = |suppr: &mut HashSet<Keycode>, mods: ModifiersState, pressed| {
4366 should_intercept_key(
4367 suppr,
4368 &bindings,
4369 comp_mod,
4370 Keycode::from(Keysym::l.raw() + 8),
4371 Keysym::l,
4372 Some(Keysym::l),
4373 pressed,
4374 mods,
4375 &screenshot_ui,
4376 disable_power_key_handling,
4377 is_inhibiting_shortcuts.get(),
4378 )
4379 };
4380
4381 let mut mods = ModifiersState {
4382 logo: true,
4383 ctrl: true,
4384 ..Default::default()
4385 };
4386
4387 // Action press/release.
4388
4389 let filter = close_key_event(&mut suppressed_keys, mods, true);
4390 assert!(matches!(
4391 filter,
4392 FilterResult::Intercept(Some(Bind {
4393 action: Action::CloseWindow,
4394 ..
4395 }))
4396 ));
4397 assert!(suppressed_keys.contains(&close_key_code));
4398
4399 let filter = close_key_event(&mut suppressed_keys, mods, false);
4400 assert!(matches!(filter, FilterResult::Intercept(None)));
4401 assert!(suppressed_keys.is_empty());
4402
4403 // Remove mod to make it for a binding.
4404
4405 mods.shift = true;
4406 let filter = close_key_event(&mut suppressed_keys, mods, true);
4407 assert!(matches!(filter, FilterResult::Forward));
4408
4409 mods.shift = false;
4410 let filter = close_key_event(&mut suppressed_keys, mods, false);
4411 assert!(matches!(filter, FilterResult::Forward));
4412
4413 // Just none press/release.
4414
4415 let filter = none_key_event(&mut suppressed_keys, mods, true);
4416 assert!(matches!(filter, FilterResult::Forward));
4417
4418 let filter = none_key_event(&mut suppressed_keys, mods, false);
4419 assert!(matches!(filter, FilterResult::Forward));
4420
4421 // Press action, press arbitrary, release action, release arbitrary.
4422
4423 let filter = close_key_event(&mut suppressed_keys, mods, true);
4424 assert!(matches!(
4425 filter,
4426 FilterResult::Intercept(Some(Bind {
4427 action: Action::CloseWindow,
4428 ..
4429 }))
4430 ));
4431
4432 let filter = none_key_event(&mut suppressed_keys, mods, true);
4433 assert!(matches!(filter, FilterResult::Forward));
4434
4435 let filter = close_key_event(&mut suppressed_keys, mods, false);
4436 assert!(matches!(filter, FilterResult::Intercept(None)));
4437
4438 let filter = none_key_event(&mut suppressed_keys, mods, false);
4439 assert!(matches!(filter, FilterResult::Forward));
4440
4441 // Trigger and remove all mods.
4442
4443 let filter = close_key_event(&mut suppressed_keys, mods, true);
4444 assert!(matches!(
4445 filter,
4446 FilterResult::Intercept(Some(Bind {
4447 action: Action::CloseWindow,
4448 ..
4449 }))
4450 ));
4451
4452 mods = Default::default();
4453 let filter = close_key_event(&mut suppressed_keys, mods, false);
4454 assert!(matches!(filter, FilterResult::Intercept(None)));
4455
4456 // Ensure that no keys are being suppressed.
4457 assert!(suppressed_keys.is_empty());
4458
4459 // Now test shortcut inhibiting.
4460
4461 // With inhibited shortcuts, we don't intercept our shortcut.
4462 is_inhibiting_shortcuts.set(true);
4463
4464 mods = ModifiersState {
4465 logo: true,
4466 ctrl: true,
4467 ..Default::default()
4468 };
4469
4470 let filter = close_key_event(&mut suppressed_keys, mods, true);
4471 assert!(matches!(filter, FilterResult::Forward));
4472 assert!(suppressed_keys.is_empty());
4473
4474 let filter = close_key_event(&mut suppressed_keys, mods, false);
4475 assert!(matches!(filter, FilterResult::Forward));
4476 assert!(suppressed_keys.is_empty());
4477
4478 // Toggle it off after pressing the shortcut.
4479 let filter = close_key_event(&mut suppressed_keys, mods, true);
4480 assert!(matches!(filter, FilterResult::Forward));
4481 assert!(suppressed_keys.is_empty());
4482
4483 is_inhibiting_shortcuts.set(false);
4484
4485 let filter = close_key_event(&mut suppressed_keys, mods, false);
4486 assert!(matches!(filter, FilterResult::Forward));
4487 assert!(suppressed_keys.is_empty());
4488
4489 // Toggle it on after pressing the shortcut.
4490 let filter = close_key_event(&mut suppressed_keys, mods, true);
4491 assert!(matches!(
4492 filter,
4493 FilterResult::Intercept(Some(Bind {
4494 action: Action::CloseWindow,
4495 ..
4496 }))
4497 ));
4498 assert!(suppressed_keys.contains(&close_key_code));
4499
4500 is_inhibiting_shortcuts.set(true);
4501
4502 let filter = close_key_event(&mut suppressed_keys, mods, false);
4503 assert!(matches!(filter, FilterResult::Intercept(None)));
4504 assert!(suppressed_keys.is_empty());
4505 }
4506
4507 #[test]
4508 fn comp_mod_handling() {
4509 let bindings = Binds(vec![
4510 Bind {
4511 key: Key {
4512 trigger: Trigger::Keysym(Keysym::q),
4513 modifiers: Modifiers::COMPOSITOR,
4514 },
4515 action: Action::CloseWindow,
4516 repeat: true,
4517 cooldown: None,
4518 allow_when_locked: false,
4519 allow_inhibiting: true,
4520 hotkey_overlay_title: None,
4521 },
4522 Bind {
4523 key: Key {
4524 trigger: Trigger::Keysym(Keysym::h),
4525 modifiers: Modifiers::SUPER,
4526 },
4527 action: Action::FocusColumnLeft,
4528 repeat: true,
4529 cooldown: None,
4530 allow_when_locked: false,
4531 allow_inhibiting: true,
4532 hotkey_overlay_title: None,
4533 },
4534 Bind {
4535 key: Key {
4536 trigger: Trigger::Keysym(Keysym::j),
4537 modifiers: Modifiers::empty(),
4538 },
4539 action: Action::FocusWindowDown,
4540 repeat: true,
4541 cooldown: None,
4542 allow_when_locked: false,
4543 allow_inhibiting: true,
4544 hotkey_overlay_title: None,
4545 },
4546 Bind {
4547 key: Key {
4548 trigger: Trigger::Keysym(Keysym::k),
4549 modifiers: Modifiers::COMPOSITOR | Modifiers::SUPER,
4550 },
4551 action: Action::FocusWindowUp,
4552 repeat: true,
4553 cooldown: None,
4554 allow_when_locked: false,
4555 allow_inhibiting: true,
4556 hotkey_overlay_title: None,
4557 },
4558 Bind {
4559 key: Key {
4560 trigger: Trigger::Keysym(Keysym::l),
4561 modifiers: Modifiers::SUPER | Modifiers::ALT,
4562 },
4563 action: Action::FocusColumnRight,
4564 repeat: true,
4565 cooldown: None,
4566 allow_when_locked: false,
4567 allow_inhibiting: true,
4568 hotkey_overlay_title: None,
4569 },
4570 ]);
4571
4572 assert_eq!(
4573 find_configured_bind(
4574 &bindings,
4575 ModKey::Super,
4576 Trigger::Keysym(Keysym::q),
4577 ModifiersState {
4578 logo: true,
4579 ..Default::default()
4580 }
4581 )
4582 .as_ref(),
4583 Some(&bindings.0[0])
4584 );
4585 assert_eq!(
4586 find_configured_bind(
4587 &bindings,
4588 ModKey::Super,
4589 Trigger::Keysym(Keysym::q),
4590 ModifiersState::default(),
4591 ),
4592 None,
4593 );
4594
4595 assert_eq!(
4596 find_configured_bind(
4597 &bindings,
4598 ModKey::Super,
4599 Trigger::Keysym(Keysym::h),
4600 ModifiersState {
4601 logo: true,
4602 ..Default::default()
4603 }
4604 )
4605 .as_ref(),
4606 Some(&bindings.0[1])
4607 );
4608 assert_eq!(
4609 find_configured_bind(
4610 &bindings,
4611 ModKey::Super,
4612 Trigger::Keysym(Keysym::h),
4613 ModifiersState::default(),
4614 ),
4615 None,
4616 );
4617
4618 assert_eq!(
4619 find_configured_bind(
4620 &bindings,
4621 ModKey::Super,
4622 Trigger::Keysym(Keysym::j),
4623 ModifiersState {
4624 logo: true,
4625 ..Default::default()
4626 }
4627 ),
4628 None,
4629 );
4630 assert_eq!(
4631 find_configured_bind(
4632 &bindings,
4633 ModKey::Super,
4634 Trigger::Keysym(Keysym::j),
4635 ModifiersState::default(),
4636 )
4637 .as_ref(),
4638 Some(&bindings.0[2])
4639 );
4640
4641 assert_eq!(
4642 find_configured_bind(
4643 &bindings,
4644 ModKey::Super,
4645 Trigger::Keysym(Keysym::k),
4646 ModifiersState {
4647 logo: true,
4648 ..Default::default()
4649 }
4650 )
4651 .as_ref(),
4652 Some(&bindings.0[3])
4653 );
4654 assert_eq!(
4655 find_configured_bind(
4656 &bindings,
4657 ModKey::Super,
4658 Trigger::Keysym(Keysym::k),
4659 ModifiersState::default(),
4660 ),
4661 None,
4662 );
4663
4664 assert_eq!(
4665 find_configured_bind(
4666 &bindings,
4667 ModKey::Super,
4668 Trigger::Keysym(Keysym::l),
4669 ModifiersState {
4670 logo: true,
4671 alt: true,
4672 ..Default::default()
4673 }
4674 )
4675 .as_ref(),
4676 Some(&bindings.0[4])
4677 );
4678 assert_eq!(
4679 find_configured_bind(
4680 &bindings,
4681 ModKey::Super,
4682 Trigger::Keysym(Keysym::l),
4683 ModifiersState {
4684 logo: true,
4685 ..Default::default()
4686 },
4687 ),
4688 None,
4689 );
4690 }
4691}