forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB2d82fddIvan Molodetskikh1 year ago2536 commits

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