forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBdde9214Ivan Molodetskikh1 year ago1835 commits

mod.rs3891 lines, 147.8 KiBHistoryRawDownload
1use std::any::Any;
2use std::cmp::min;
3use std::collections::hash_map::Entry;
4use std::collections::HashSet;
5use std::time::Duration;
6
7use calloop::timer::{TimeoutAction, Timer};
8use input::event::gesture::GestureEventCoordinates as _;
9use niri_config::{Action, Bind, Binds, Key, Modifiers, SwitchBinds, Trigger};
10use niri_ipc::LayoutSwitchTarget;
11use smithay::backend::input::{
12 AbsolutePositionEvent, Axis, AxisSource, ButtonState, Device, DeviceCapability, Event,
13 GestureBeginEvent, GestureEndEvent, GesturePinchUpdateEvent as _, GestureSwipeUpdateEvent as _,
14 InputEvent, KeyState, KeyboardKeyEvent, Keycode, MouseButton, PointerAxisEvent,
15 PointerButtonEvent, PointerMotionEvent, ProximityState, Switch, SwitchState, SwitchToggleEvent,
16 TabletToolButtonEvent, TabletToolEvent, TabletToolProximityEvent, TabletToolTipEvent,
17 TabletToolTipState, TouchEvent,
18};
19use smithay::backend::libinput::LibinputInputBackend;
20use smithay::input::keyboard::{keysyms, FilterResult, Keysym, Layout, ModifiersState};
21use smithay::input::pointer::{
22 AxisFrame, ButtonEvent, CursorIcon, CursorImageStatus, Focus, GestureHoldBeginEvent,
23 GestureHoldEndEvent, GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent,
24 GestureSwipeBeginEvent, GestureSwipeEndEvent, GestureSwipeUpdateEvent,
25 GrabStartData as PointerGrabStartData, MotionEvent, RelativeMotionEvent,
26};
27use smithay::input::touch::{
28 DownEvent, GrabStartData as TouchGrabStartData, MotionEvent as TouchMotionEvent, UpEvent,
29};
30use smithay::input::SeatHandler;
31use smithay::output::Output;
32use smithay::utils::{Logical, Point, Rectangle, Transform, SERIAL_COUNTER};
33use smithay::wayland::keyboard_shortcuts_inhibit::KeyboardShortcutsInhibitor;
34use smithay::wayland::pointer_constraints::{with_pointer_constraint, PointerConstraint};
35use smithay::wayland::tablet_manager::{TabletDescriptor, TabletSeatTrait};
36use touch_move_grab::TouchMoveGrab;
37
38use self::move_grab::MoveGrab;
39use self::resize_grab::ResizeGrab;
40use self::spatial_movement_grab::SpatialMovementGrab;
41use crate::layout::scrolling::ScrollDirection;
42use crate::layout::LayoutElement as _;
43use crate::niri::State;
44use crate::ui::screenshot_ui::ScreenshotUi;
45use crate::utils::spawning::spawn;
46use crate::utils::{center, get_monotonic_time, ResizeEdge};
47
48pub mod backend_ext;
49pub mod move_grab;
50pub mod resize_grab;
51pub mod scroll_tracker;
52pub mod spatial_movement_grab;
53pub mod swipe_tracker;
54pub mod touch_move_grab;
55pub mod touch_resize_grab;
56
57use backend_ext::{NiriInputBackend as InputBackend, NiriInputDevice as _};
58
59pub const DOUBLE_CLICK_TIME: Duration = Duration::from_millis(400);
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum CompositorMod {
63 Super,
64 Alt,
65}
66
67#[derive(Debug, Clone, Copy, PartialEq)]
68pub struct TabletData {
69 pub aspect_ratio: f64,
70}
71
72pub enum PointerOrTouchStartData<D: SeatHandler> {
73 Pointer(PointerGrabStartData<D>),
74 Touch(TouchGrabStartData<D>),
75}
76
77impl<D: SeatHandler> PointerOrTouchStartData<D> {
78 pub fn location(&self) -> Point<f64, Logical> {
79 match self {
80 PointerOrTouchStartData::Pointer(x) => x.location,
81 PointerOrTouchStartData::Touch(x) => x.location,
82 }
83 }
84}
85
86impl State {
87 pub fn process_input_event<I: InputBackend + 'static>(&mut self, event: InputEvent<I>)
88 where
89 I::Device: 'static, // Needed for downcasting.
90 {
91 let _span = tracy_client::span!("process_input_event");
92
93 // Make sure some logic like workspace clean-up has a chance to run before doing actions.
94 self.niri.advance_animations();
95
96 if self.niri.monitors_active {
97 // Notify the idle-notifier of activity.
98 if should_notify_activity(&event) {
99 let _span = tracy_client::span!("IdleNotifierState::notify_activity");
100 self.niri
101 .idle_notifier_state
102 .notify_activity(&self.niri.seat);
103 }
104 } else {
105 // Power on monitors if they were off.
106 if should_activate_monitors(&event) {
107 self.niri.activate_monitors(&mut self.backend);
108
109 // Notify the idle-notifier of activity only if we're also powering on the
110 // monitors.
111 self.niri
112 .idle_notifier_state
113 .notify_activity(&self.niri.seat);
114 }
115 }
116
117 if should_reset_pointer_inactivity_timer(&event) {
118 self.niri.reset_pointer_inactivity_timer();
119 }
120
121 let hide_hotkey_overlay =
122 self.niri.hotkey_overlay.is_open() && should_hide_hotkey_overlay(&event);
123
124 let hide_exit_confirm_dialog = self
125 .niri
126 .exit_confirm_dialog
127 .as_ref()
128 .is_some_and(|d| d.is_open())
129 && should_hide_exit_confirm_dialog(&event);
130
131 use InputEvent::*;
132 match event {
133 DeviceAdded { device } => self.on_device_added(device),
134 DeviceRemoved { device } => self.on_device_removed(device),
135 Keyboard { event } => self.on_keyboard::<I>(event),
136 PointerMotion { event } => self.on_pointer_motion::<I>(event),
137 PointerMotionAbsolute { event } => self.on_pointer_motion_absolute::<I>(event),
138 PointerButton { event } => self.on_pointer_button::<I>(event),
139 PointerAxis { event } => self.on_pointer_axis::<I>(event),
140 TabletToolAxis { event } => self.on_tablet_tool_axis::<I>(event),
141 TabletToolTip { event } => self.on_tablet_tool_tip::<I>(event),
142 TabletToolProximity { event } => self.on_tablet_tool_proximity::<I>(event),
143 TabletToolButton { event } => self.on_tablet_tool_button::<I>(event),
144 GestureSwipeBegin { event } => self.on_gesture_swipe_begin::<I>(event),
145 GestureSwipeUpdate { event } => self.on_gesture_swipe_update::<I>(event),
146 GestureSwipeEnd { event } => self.on_gesture_swipe_end::<I>(event),
147 GesturePinchBegin { event } => self.on_gesture_pinch_begin::<I>(event),
148 GesturePinchUpdate { event } => self.on_gesture_pinch_update::<I>(event),
149 GesturePinchEnd { event } => self.on_gesture_pinch_end::<I>(event),
150 GestureHoldBegin { event } => self.on_gesture_hold_begin::<I>(event),
151 GestureHoldEnd { event } => self.on_gesture_hold_end::<I>(event),
152 TouchDown { event } => self.on_touch_down::<I>(event),
153 TouchMotion { event } => self.on_touch_motion::<I>(event),
154 TouchUp { event } => self.on_touch_up::<I>(event),
155 TouchCancel { event } => self.on_touch_cancel::<I>(event),
156 TouchFrame { event } => self.on_touch_frame::<I>(event),
157 SwitchToggle { event } => self.on_switch_toggle::<I>(event),
158 Special(_) => (),
159 }
160
161 // Do this last so that screenshot still gets it.
162 // FIXME: do this in a less cursed fashion somehow.
163 if hide_hotkey_overlay && self.niri.hotkey_overlay.hide() {
164 self.niri.queue_redraw_all();
165 }
166
167 if let Some(dialog) = &mut self.niri.exit_confirm_dialog {
168 if hide_exit_confirm_dialog && dialog.hide() {
169 self.niri.queue_redraw_all();
170 }
171 }
172 }
173
174 pub fn process_libinput_event(&mut self, event: &mut InputEvent<LibinputInputBackend>) {
175 let _span = tracy_client::span!("process_libinput_event");
176
177 match event {
178 InputEvent::DeviceAdded { device } => {
179 self.niri.devices.insert(device.clone());
180
181 if device.has_capability(input::DeviceCapability::TabletTool) {
182 match device.size() {
183 Some((w, h)) => {
184 let aspect_ratio = w / h;
185 let data = TabletData { aspect_ratio };
186 self.niri.tablets.insert(device.clone(), data);
187 }
188 None => {
189 warn!("tablet tool device has no size");
190 }
191 }
192 }
193
194 if device.has_capability(input::DeviceCapability::Keyboard) {
195 if let Some(led_state) = self
196 .niri
197 .seat
198 .get_keyboard()
199 .map(|keyboard| keyboard.led_state())
200 {
201 device.led_update(led_state.into());
202 }
203 }
204
205 if device.has_capability(input::DeviceCapability::Touch) {
206 self.niri.touch.insert(device.clone());
207 }
208
209 apply_libinput_settings(&self.niri.config.borrow().input, device);
210 }
211 InputEvent::DeviceRemoved { device } => {
212 self.niri.touch.remove(device);
213 self.niri.tablets.remove(device);
214 self.niri.devices.remove(device);
215 }
216 _ => (),
217 }
218 }
219
220 fn on_device_added(&mut self, device: impl Device) {
221 if device.has_capability(DeviceCapability::TabletTool) {
222 let tablet_seat = self.niri.seat.tablet_seat();
223
224 let desc = TabletDescriptor::from(&device);
225 tablet_seat.add_tablet::<Self>(&self.niri.display_handle, &desc);
226 }
227 if device.has_capability(DeviceCapability::Touch) && self.niri.seat.get_touch().is_none() {
228 self.niri.seat.add_touch();
229 }
230 }
231
232 fn on_device_removed(&mut self, device: impl Device) {
233 if device.has_capability(DeviceCapability::TabletTool) {
234 let tablet_seat = self.niri.seat.tablet_seat();
235
236 let desc = TabletDescriptor::from(&device);
237 tablet_seat.remove_tablet(&desc);
238
239 // If there are no tablets in seat we can remove all tools
240 if tablet_seat.count_tablets() == 0 {
241 tablet_seat.clear_tools();
242 }
243 }
244 if device.has_capability(DeviceCapability::Touch) && self.niri.touch.is_empty() {
245 self.niri.seat.remove_touch();
246 }
247 }
248
249 /// Computes the rectangle that covers all outputs in global space.
250 fn global_bounding_rectangle(&self) -> Option<Rectangle<i32, Logical>> {
251 self.niri.global_space.outputs().fold(
252 None,
253 |acc: Option<Rectangle<i32, Logical>>, output| {
254 self.niri
255 .global_space
256 .output_geometry(output)
257 .map(|geo| acc.map(|acc| acc.merge(geo)).unwrap_or(geo))
258 },
259 )
260 }
261
262 /// Computes the cursor position for the tablet event.
263 ///
264 /// This function handles the tablet output mapping, as well as coordinate clamping and aspect
265 /// ratio correction.
266 fn compute_tablet_position<I: InputBackend>(
267 &self,
268 event: &(impl Event<I> + TabletToolEvent<I>),
269 ) -> Option<Point<f64, Logical>>
270 where
271 I::Device: 'static,
272 {
273 let device_output = event.device().output(self);
274 let device_output = device_output.as_ref();
275 let (target_geo, keep_ratio, px, transform) =
276 if let Some(output) = device_output.or_else(|| self.niri.output_for_tablet()) {
277 (
278 self.niri.global_space.output_geometry(output).unwrap(),
279 true,
280 1. / output.current_scale().fractional_scale(),
281 output.current_transform(),
282 )
283 } else {
284 let geo = self.global_bounding_rectangle()?;
285
286 // FIXME: this 1 px size should ideally somehow be computed for the rightmost output
287 // corresponding to the position on the right when clamping.
288 let output = self.niri.global_space.outputs().next().unwrap();
289 let scale = output.current_scale().fractional_scale();
290
291 // Do not keep ratio for the unified mode as this is what OpenTabletDriver expects.
292 (geo, false, 1. / scale, Transform::Normal)
293 };
294
295 let mut pos = {
296 let size = transform.invert().transform_size(target_geo.size);
297 transform.transform_point_in(event.position_transformed(size), &size.to_f64())
298 };
299
300 if keep_ratio {
301 pos.x /= target_geo.size.w as f64;
302 pos.y /= target_geo.size.h as f64;
303
304 let device = event.device();
305 if let Some(device) = (&device as &dyn Any).downcast_ref::<input::Device>() {
306 if let Some(data) = self.niri.tablets.get(device) {
307 // This code does the same thing as mutter with "keep aspect ratio" enabled.
308 let size = transform.invert().transform_size(target_geo.size);
309 let output_aspect_ratio = size.w as f64 / size.h as f64;
310 let ratio = data.aspect_ratio / output_aspect_ratio;
311
312 if ratio > 1. {
313 pos.x *= ratio;
314 } else {
315 pos.y /= ratio;
316 }
317 }
318 };
319
320 pos.x *= target_geo.size.w as f64;
321 pos.y *= target_geo.size.h as f64;
322 }
323
324 pos.x = pos.x.clamp(0.0, target_geo.size.w as f64 - px);
325 pos.y = pos.y.clamp(0.0, target_geo.size.h as f64 - px);
326 Some(pos + target_geo.loc.to_f64())
327 }
328
329 fn is_inhibiting_shortcuts(&self) -> bool {
330 self.niri
331 .keyboard_focus
332 .surface()
333 .and_then(|surface| {
334 self.niri
335 .keyboard_shortcuts_inhibiting_surfaces
336 .get(surface)
337 })
338 .is_some_and(KeyboardShortcutsInhibitor::is_active)
339 }
340
341 fn on_keyboard<I: InputBackend>(&mut self, event: I::KeyboardKeyEvent) {
342 let comp_mod = self.backend.mod_key();
343
344 let serial = SERIAL_COUNTER.next_serial();
345 let time = Event::time_msec(&event);
346 let pressed = event.state() == KeyState::Pressed;
347
348 // Stop bind key repeat on any release. This won't work 100% correctly in cases like:
349 // 1. Press Mod
350 // 2. Press Left (repeat starts)
351 // 3. Press PgDown (new repeat starts)
352 // 4. Release Left (PgDown repeat stops)
353 // But it's good enough for now.
354 // FIXME: handle this properly.
355 if !pressed {
356 if let Some(token) = self.niri.bind_repeat_timer.take() {
357 self.niri.event_loop.remove(token);
358 }
359 }
360
361 if pressed {
362 self.hide_cursor_if_needed();
363 }
364
365 let is_inhibiting_shortcuts = self.is_inhibiting_shortcuts();
366
367 let Some(Some(bind)) = self.niri.seat.get_keyboard().unwrap().input(
368 self,
369 event.key_code(),
370 event.state(),
371 serial,
372 time,
373 |this, mods, keysym| {
374 let bindings = &this.niri.config.borrow().binds;
375 let key_code = event.key_code();
376 let modified = keysym.modified_sym();
377 let raw = keysym.raw_latin_sym_or_raw_current_sym();
378
379 if let Some(dialog) = &this.niri.exit_confirm_dialog {
380 if dialog.is_open() && pressed && raw == Some(Keysym::Return) {
381 info!("quitting after confirming exit dialog");
382 this.niri.stop_signal.stop();
383 }
384 }
385
386 should_intercept_key(
387 &mut this.niri.suppressed_keys,
388 bindings,
389 comp_mod,
390 key_code,
391 modified,
392 raw,
393 pressed,
394 *mods,
395 &this.niri.screenshot_ui,
396 this.niri.config.borrow().input.disable_power_key_handling,
397 is_inhibiting_shortcuts,
398 )
399 },
400 ) else {
401 return;
402 };
403
404 if !pressed {
405 return;
406 }
407
408 self.handle_bind(bind.clone());
409
410 self.start_key_repeat(bind);
411 }
412
413 fn start_key_repeat(&mut self, bind: Bind) {
414 if !bind.repeat {
415 return;
416 }
417
418 // Stop the previous key repeat if any.
419 if let Some(token) = self.niri.bind_repeat_timer.take() {
420 self.niri.event_loop.remove(token);
421 }
422
423 let config = self.niri.config.borrow();
424 let config = &config.input.keyboard;
425
426 let repeat_rate = config.repeat_rate;
427 if repeat_rate == 0 {
428 return;
429 }
430 let repeat_duration = Duration::from_secs_f64(1. / f64::from(repeat_rate));
431
432 let repeat_timer =
433 Timer::from_duration(Duration::from_millis(u64::from(config.repeat_delay)));
434
435 let token = self
436 .niri
437 .event_loop
438 .insert_source(repeat_timer, move |_, _, state| {
439 state.handle_bind(bind.clone());
440 TimeoutAction::ToDuration(repeat_duration)
441 })
442 .unwrap();
443
444 self.niri.bind_repeat_timer = Some(token);
445 }
446
447 fn hide_cursor_if_needed(&mut self) {
448 if !self.niri.config.borrow().cursor.hide_when_typing {
449 return;
450 }
451
452 // niri keeps this set only while actively using a tablet, which means the cursor position
453 // is likely to change almost immediately, causing pointer_hidden to just flicker back and
454 // forth.
455 if self.niri.tablet_cursor_location.is_some() {
456 return;
457 }
458
459 self.niri.pointer_hidden = true;
460 self.niri.queue_redraw_all();
461 }
462
463 pub fn handle_bind(&mut self, bind: Bind) {
464 let Some(cooldown) = bind.cooldown else {
465 self.do_action(bind.action, bind.allow_when_locked);
466 return;
467 };
468
469 // Check this first so that it doesn't trigger the cooldown.
470 if self.niri.is_locked() && !(bind.allow_when_locked || allowed_when_locked(&bind.action)) {
471 return;
472 }
473
474 match self.niri.bind_cooldown_timers.entry(bind.key) {
475 // The bind is on cooldown.
476 Entry::Occupied(_) => (),
477 Entry::Vacant(entry) => {
478 let timer = Timer::from_duration(cooldown);
479 let token = self
480 .niri
481 .event_loop
482 .insert_source(timer, move |_, _, state| {
483 if state.niri.bind_cooldown_timers.remove(&bind.key).is_none() {
484 error!("bind cooldown timer entry disappeared");
485 }
486 TimeoutAction::Drop
487 })
488 .unwrap();
489 entry.insert(token);
490
491 self.do_action(bind.action, bind.allow_when_locked);
492 }
493 }
494 }
495
496 pub fn do_action(&mut self, action: Action, allow_when_locked: bool) {
497 if self.niri.is_locked() && !(allow_when_locked || allowed_when_locked(&action)) {
498 return;
499 }
500
501 if let Some(touch) = self.niri.seat.get_touch() {
502 touch.cancel(self);
503 }
504
505 match action {
506 Action::Quit(skip_confirmation) => {
507 if !skip_confirmation {
508 if let Some(dialog) = &mut self.niri.exit_confirm_dialog {
509 if dialog.show() {
510 self.niri.queue_redraw_all();
511 }
512 return;
513 }
514 }
515
516 info!("quitting as requested");
517 self.niri.stop_signal.stop()
518 }
519 Action::ChangeVt(vt) => {
520 self.backend.change_vt(vt);
521 // Changing VT may not deliver the key releases, so clear the state.
522 self.niri.suppressed_keys.clear();
523 }
524 Action::Suspend => {
525 self.backend.suspend();
526 // Suspend may not deliver the key releases, so clear the state.
527 self.niri.suppressed_keys.clear();
528 }
529 Action::PowerOffMonitors => {
530 self.niri.deactivate_monitors(&mut self.backend);
531 }
532 Action::PowerOnMonitors => {
533 self.niri.activate_monitors(&mut self.backend);
534 }
535 Action::ToggleDebugTint => {
536 self.backend.toggle_debug_tint();
537 self.niri.queue_redraw_all();
538 }
539 Action::DebugToggleOpaqueRegions => {
540 self.niri.debug_draw_opaque_regions = !self.niri.debug_draw_opaque_regions;
541 self.niri.queue_redraw_all();
542 }
543 Action::DebugToggleDamage => {
544 self.niri.debug_toggle_damage();
545 }
546 Action::Spawn(command) => {
547 let (token, _) = self.niri.activation_state.create_external_token(None);
548 spawn(command, Some(token.clone()));
549 }
550 Action::DoScreenTransition(delay_ms) => {
551 self.backend.with_primary_renderer(|renderer| {
552 self.niri.do_screen_transition(renderer, delay_ms);
553 });
554 }
555 Action::ScreenshotScreen(write_to_disk) => {
556 let active = self.niri.layout.active_output().cloned();
557 if let Some(active) = active {
558 self.backend.with_primary_renderer(|renderer| {
559 if let Err(err) = self.niri.screenshot(renderer, &active, write_to_disk) {
560 warn!("error taking screenshot: {err:?}");
561 }
562 });
563 }
564 }
565 Action::ConfirmScreenshot { write_to_disk } => {
566 if !self.niri.screenshot_ui.is_open() {
567 return;
568 }
569
570 self.backend.with_primary_renderer(|renderer| {
571 match self.niri.screenshot_ui.capture(renderer) {
572 Ok((size, pixels)) => {
573 if let Err(err) = self.niri.save_screenshot(size, pixels, write_to_disk)
574 {
575 warn!("error saving screenshot: {err:?}");
576 }
577 }
578 Err(err) => {
579 warn!("error capturing screenshot: {err:?}");
580 }
581 }
582 });
583
584 self.niri.screenshot_ui.close();
585 self.niri
586 .cursor_manager
587 .set_cursor_image(CursorImageStatus::default_named());
588 self.niri.queue_redraw_all();
589 }
590 Action::CancelScreenshot => {
591 if !self.niri.screenshot_ui.is_open() {
592 return;
593 }
594
595 self.niri.screenshot_ui.close();
596 self.niri
597 .cursor_manager
598 .set_cursor_image(CursorImageStatus::default_named());
599 self.niri.queue_redraw_all();
600 }
601 Action::ScreenshotTogglePointer => {
602 self.niri.screenshot_ui.toggle_pointer();
603 self.niri.queue_redraw_all();
604 }
605 Action::Screenshot => {
606 self.open_screenshot_ui();
607 }
608 Action::ScreenshotWindow(write_to_disk) => {
609 let focus = self.niri.layout.focus_with_output();
610 if let Some((mapped, output)) = focus {
611 self.backend.with_primary_renderer(|renderer| {
612 if let Err(err) =
613 self.niri
614 .screenshot_window(renderer, output, mapped, write_to_disk)
615 {
616 warn!("error taking screenshot: {err:?}");
617 }
618 });
619 }
620 }
621 Action::ScreenshotWindowById { id, write_to_disk } => {
622 let mut windows = self.niri.layout.windows();
623 let window = windows.find(|(_, m)| m.id().get() == id);
624 if let Some((Some(monitor), mapped)) = window {
625 let output = monitor.output();
626 self.backend.with_primary_renderer(|renderer| {
627 if let Err(err) =
628 self.niri
629 .screenshot_window(renderer, output, mapped, write_to_disk)
630 {
631 warn!("error taking screenshot: {err:?}");
632 }
633 });
634 }
635 }
636 Action::ToggleKeyboardShortcutsInhibit => {
637 if let Some(inhibitor) = self.niri.keyboard_focus.surface().and_then(|surface| {
638 self.niri
639 .keyboard_shortcuts_inhibiting_surfaces
640 .get(surface)
641 }) {
642 if inhibitor.is_active() {
643 inhibitor.inactivate();
644 } else {
645 inhibitor.activate();
646 }
647 }
648 }
649 Action::CloseWindow => {
650 if let Some(mapped) = self.niri.layout.focus() {
651 mapped.toplevel().send_close();
652 }
653 }
654 Action::CloseWindowById(id) => {
655 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
656 if let Some((_, mapped)) = window {
657 mapped.toplevel().send_close();
658 }
659 }
660 Action::FullscreenWindow => {
661 let focus = self.niri.layout.focus().map(|m| m.window.clone());
662 if let Some(window) = focus {
663 self.niri.layout.toggle_fullscreen(&window);
664 // FIXME: granular
665 self.niri.queue_redraw_all();
666 }
667 }
668 Action::FullscreenWindowById(id) => {
669 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
670 let window = window.map(|(_, m)| m.window.clone());
671 if let Some(window) = window {
672 self.niri.layout.toggle_fullscreen(&window);
673 // FIXME: granular
674 self.niri.queue_redraw_all();
675 }
676 }
677 Action::FocusWindow(id) => {
678 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
679 let window = window.map(|(_, m)| m.window.clone());
680 if let Some(window) = window {
681 self.focus_window(&window);
682 }
683 }
684 Action::FocusWindowInColumn(index) => {
685 self.niri.layout.focus_window_in_column(index);
686 self.maybe_warp_cursor_to_focus();
687 self.niri.layer_shell_on_demand_focus = None;
688 // FIXME: granular
689 self.niri.queue_redraw_all();
690 }
691 Action::FocusWindowPrevious => {
692 if let Some(window) = self.niri.previously_focused_window.clone() {
693 self.focus_window(&window);
694 }
695 }
696 Action::SwitchLayout(action) => {
697 let keyboard = &self.niri.seat.get_keyboard().unwrap();
698 keyboard.with_xkb_state(self, |mut state| match action {
699 LayoutSwitchTarget::Next => state.cycle_next_layout(),
700 LayoutSwitchTarget::Prev => state.cycle_prev_layout(),
701 LayoutSwitchTarget::Index(layout) => {
702 let num_layouts = state.xkb().lock().unwrap().layouts().count();
703 if usize::from(layout) >= num_layouts {
704 warn!("requested layout doesn't exist")
705 } else {
706 state.set_layout(Layout(layout.into()))
707 }
708 }
709 });
710 }
711 Action::MoveColumnLeft => {
712 self.niri.layout.move_left();
713 self.maybe_warp_cursor_to_focus();
714 // FIXME: granular
715 self.niri.queue_redraw_all();
716 }
717 Action::MoveColumnRight => {
718 self.niri.layout.move_right();
719 self.maybe_warp_cursor_to_focus();
720 // FIXME: granular
721 self.niri.queue_redraw_all();
722 }
723 Action::MoveColumnToFirst => {
724 self.niri.layout.move_column_to_first();
725 self.maybe_warp_cursor_to_focus();
726 // FIXME: granular
727 self.niri.queue_redraw_all();
728 }
729 Action::MoveColumnToLast => {
730 self.niri.layout.move_column_to_last();
731 self.maybe_warp_cursor_to_focus();
732 // FIXME: granular
733 self.niri.queue_redraw_all();
734 }
735 Action::MoveColumnLeftOrToMonitorLeft => {
736 if let Some(output) = self.niri.output_left() {
737 if self.niri.layout.move_column_left_or_to_output(&output)
738 && !self.maybe_warp_cursor_to_focus_centered()
739 {
740 self.move_cursor_to_output(&output);
741 } else {
742 self.maybe_warp_cursor_to_focus();
743 }
744 } else {
745 self.niri.layout.move_left();
746 self.maybe_warp_cursor_to_focus();
747 }
748
749 // FIXME: granular
750 self.niri.queue_redraw_all();
751 }
752 Action::MoveColumnRightOrToMonitorRight => {
753 if let Some(output) = self.niri.output_right() {
754 if self.niri.layout.move_column_right_or_to_output(&output)
755 && !self.maybe_warp_cursor_to_focus_centered()
756 {
757 self.move_cursor_to_output(&output);
758 } else {
759 self.maybe_warp_cursor_to_focus();
760 }
761 } else {
762 self.niri.layout.move_right();
763 self.maybe_warp_cursor_to_focus();
764 }
765
766 // FIXME: granular
767 self.niri.queue_redraw_all();
768 }
769 Action::MoveWindowDown => {
770 self.niri.layout.move_down();
771 self.maybe_warp_cursor_to_focus();
772 // FIXME: granular
773 self.niri.queue_redraw_all();
774 }
775 Action::MoveWindowUp => {
776 self.niri.layout.move_up();
777 self.maybe_warp_cursor_to_focus();
778 // FIXME: granular
779 self.niri.queue_redraw_all();
780 }
781 Action::MoveWindowDownOrToWorkspaceDown => {
782 self.niri.layout.move_down_or_to_workspace_down();
783 self.maybe_warp_cursor_to_focus();
784 // FIXME: granular
785 self.niri.queue_redraw_all();
786 }
787 Action::MoveWindowUpOrToWorkspaceUp => {
788 self.niri.layout.move_up_or_to_workspace_up();
789 self.maybe_warp_cursor_to_focus();
790 // FIXME: granular
791 self.niri.queue_redraw_all();
792 }
793 Action::ConsumeOrExpelWindowLeft => {
794 self.niri.layout.consume_or_expel_window_left(None);
795 self.maybe_warp_cursor_to_focus();
796 // FIXME: granular
797 self.niri.queue_redraw_all();
798 }
799 Action::ConsumeOrExpelWindowLeftById(id) => {
800 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
801 let window = window.map(|(_, m)| m.window.clone());
802 if let Some(window) = window {
803 self.niri.layout.consume_or_expel_window_left(Some(&window));
804 self.maybe_warp_cursor_to_focus();
805 // FIXME: granular
806 self.niri.queue_redraw_all();
807 }
808 }
809 Action::ConsumeOrExpelWindowRight => {
810 self.niri.layout.consume_or_expel_window_right(None);
811 self.maybe_warp_cursor_to_focus();
812 // FIXME: granular
813 self.niri.queue_redraw_all();
814 }
815 Action::ConsumeOrExpelWindowRightById(id) => {
816 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
817 let window = window.map(|(_, m)| m.window.clone());
818 if let Some(window) = window {
819 self.niri
820 .layout
821 .consume_or_expel_window_right(Some(&window));
822 self.maybe_warp_cursor_to_focus();
823 // FIXME: granular
824 self.niri.queue_redraw_all();
825 }
826 }
827 Action::FocusColumnLeft => {
828 self.niri.layout.focus_left();
829 self.maybe_warp_cursor_to_focus();
830 self.niri.layer_shell_on_demand_focus = None;
831 // FIXME: granular
832 self.niri.queue_redraw_all();
833 }
834 Action::FocusColumnRight => {
835 self.niri.layout.focus_right();
836 self.maybe_warp_cursor_to_focus();
837 self.niri.layer_shell_on_demand_focus = None;
838 // FIXME: granular
839 self.niri.queue_redraw_all();
840 }
841 Action::FocusColumnFirst => {
842 self.niri.layout.focus_column_first();
843 self.maybe_warp_cursor_to_focus();
844 self.niri.layer_shell_on_demand_focus = None;
845 // FIXME: granular
846 self.niri.queue_redraw_all();
847 }
848 Action::FocusColumnLast => {
849 self.niri.layout.focus_column_last();
850 self.maybe_warp_cursor_to_focus();
851 self.niri.layer_shell_on_demand_focus = None;
852 // FIXME: granular
853 self.niri.queue_redraw_all();
854 }
855 Action::FocusColumnRightOrFirst => {
856 self.niri.layout.focus_column_right_or_first();
857 self.maybe_warp_cursor_to_focus();
858 self.niri.layer_shell_on_demand_focus = None;
859 // FIXME: granular
860 self.niri.queue_redraw_all();
861 }
862 Action::FocusColumnLeftOrLast => {
863 self.niri.layout.focus_column_left_or_last();
864 self.maybe_warp_cursor_to_focus();
865 self.niri.layer_shell_on_demand_focus = None;
866 // FIXME: granular
867 self.niri.queue_redraw_all();
868 }
869 Action::FocusWindowOrMonitorUp => {
870 if let Some(output) = self.niri.output_up() {
871 if self.niri.layout.focus_window_up_or_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.focus_up();
880 self.maybe_warp_cursor_to_focus();
881 }
882 self.niri.layer_shell_on_demand_focus = None;
883
884 // FIXME: granular
885 self.niri.queue_redraw_all();
886 }
887 Action::FocusWindowOrMonitorDown => {
888 if let Some(output) = self.niri.output_down() {
889 if self.niri.layout.focus_window_down_or_output(&output)
890 && !self.maybe_warp_cursor_to_focus_centered()
891 {
892 self.move_cursor_to_output(&output);
893 } else {
894 self.maybe_warp_cursor_to_focus();
895 }
896 } else {
897 self.niri.layout.focus_down();
898 self.maybe_warp_cursor_to_focus();
899 }
900 self.niri.layer_shell_on_demand_focus = None;
901
902 // FIXME: granular
903 self.niri.queue_redraw_all();
904 }
905 Action::FocusColumnOrMonitorLeft => {
906 if let Some(output) = self.niri.output_left() {
907 if self.niri.layout.focus_column_left_or_output(&output)
908 && !self.maybe_warp_cursor_to_focus_centered()
909 {
910 self.move_cursor_to_output(&output);
911 } else {
912 self.maybe_warp_cursor_to_focus();
913 }
914 } else {
915 self.niri.layout.focus_left();
916 self.maybe_warp_cursor_to_focus();
917 }
918 self.niri.layer_shell_on_demand_focus = None;
919
920 // FIXME: granular
921 self.niri.queue_redraw_all();
922 }
923 Action::FocusColumnOrMonitorRight => {
924 if let Some(output) = self.niri.output_right() {
925 if self.niri.layout.focus_column_right_or_output(&output)
926 && !self.maybe_warp_cursor_to_focus_centered()
927 {
928 self.move_cursor_to_output(&output);
929 } else {
930 self.maybe_warp_cursor_to_focus();
931 }
932 } else {
933 self.niri.layout.focus_right();
934 self.maybe_warp_cursor_to_focus();
935 }
936 self.niri.layer_shell_on_demand_focus = None;
937
938 // FIXME: granular
939 self.niri.queue_redraw_all();
940 }
941 Action::FocusWindowDown => {
942 self.niri.layout.focus_down();
943 self.maybe_warp_cursor_to_focus();
944 self.niri.layer_shell_on_demand_focus = None;
945 // FIXME: granular
946 self.niri.queue_redraw_all();
947 }
948 Action::FocusWindowUp => {
949 self.niri.layout.focus_up();
950 self.maybe_warp_cursor_to_focus();
951 self.niri.layer_shell_on_demand_focus = None;
952 // FIXME: granular
953 self.niri.queue_redraw_all();
954 }
955 Action::FocusWindowDownOrColumnLeft => {
956 self.niri.layout.focus_down_or_left();
957 self.maybe_warp_cursor_to_focus();
958 self.niri.layer_shell_on_demand_focus = None;
959 // FIXME: granular
960 self.niri.queue_redraw_all();
961 }
962 Action::FocusWindowDownOrColumnRight => {
963 self.niri.layout.focus_down_or_right();
964 self.maybe_warp_cursor_to_focus();
965 self.niri.layer_shell_on_demand_focus = None;
966 // FIXME: granular
967 self.niri.queue_redraw_all();
968 }
969 Action::FocusWindowUpOrColumnLeft => {
970 self.niri.layout.focus_up_or_left();
971 self.maybe_warp_cursor_to_focus();
972 self.niri.layer_shell_on_demand_focus = None;
973 // FIXME: granular
974 self.niri.queue_redraw_all();
975 }
976 Action::FocusWindowUpOrColumnRight => {
977 self.niri.layout.focus_up_or_right();
978 self.maybe_warp_cursor_to_focus();
979 self.niri.layer_shell_on_demand_focus = None;
980 // FIXME: granular
981 self.niri.queue_redraw_all();
982 }
983 Action::FocusWindowOrWorkspaceDown => {
984 self.niri.layout.focus_window_or_workspace_down();
985 self.maybe_warp_cursor_to_focus();
986 self.niri.layer_shell_on_demand_focus = None;
987 // FIXME: granular
988 self.niri.queue_redraw_all();
989 }
990 Action::FocusWindowOrWorkspaceUp => {
991 self.niri.layout.focus_window_or_workspace_up();
992 self.maybe_warp_cursor_to_focus();
993 self.niri.layer_shell_on_demand_focus = None;
994 // FIXME: granular
995 self.niri.queue_redraw_all();
996 }
997 Action::FocusWindowTop => {
998 self.niri.layout.focus_window_top();
999 self.maybe_warp_cursor_to_focus();
1000 self.niri.layer_shell_on_demand_focus = None;
1001 // FIXME: granular
1002 self.niri.queue_redraw_all();
1003 }
1004 Action::FocusWindowBottom => {
1005 self.niri.layout.focus_window_bottom();
1006 self.maybe_warp_cursor_to_focus();
1007 self.niri.layer_shell_on_demand_focus = None;
1008 // FIXME: granular
1009 self.niri.queue_redraw_all();
1010 }
1011 Action::FocusWindowDownOrTop => {
1012 self.niri.layout.focus_window_down_or_top();
1013 self.maybe_warp_cursor_to_focus();
1014 self.niri.layer_shell_on_demand_focus = None;
1015 // FIXME: granular
1016 self.niri.queue_redraw_all();
1017 }
1018 Action::FocusWindowUpOrBottom => {
1019 self.niri.layout.focus_window_up_or_bottom();
1020 self.maybe_warp_cursor_to_focus();
1021 self.niri.layer_shell_on_demand_focus = None;
1022 // FIXME: granular
1023 self.niri.queue_redraw_all();
1024 }
1025 Action::MoveWindowToWorkspaceDown => {
1026 self.niri.layout.move_to_workspace_down();
1027 self.maybe_warp_cursor_to_focus();
1028 // FIXME: granular
1029 self.niri.queue_redraw_all();
1030 }
1031 Action::MoveWindowToWorkspaceUp => {
1032 self.niri.layout.move_to_workspace_up();
1033 self.maybe_warp_cursor_to_focus();
1034 // FIXME: granular
1035 self.niri.queue_redraw_all();
1036 }
1037 Action::MoveWindowToWorkspace(reference) => {
1038 if let Some((mut output, index)) =
1039 self.niri.find_output_and_workspace_index(reference)
1040 {
1041 // The source output is always the active output, so if the target output is
1042 // also the active output, we don't need to use move_to_output().
1043 if let Some(active) = self.niri.layout.active_output() {
1044 if output.as_ref() == Some(active) {
1045 output = None;
1046 }
1047 }
1048
1049 if let Some(output) = output {
1050 self.niri.layout.move_to_output(None, &output, Some(index));
1051
1052 if !self.maybe_warp_cursor_to_focus_centered() {
1053 self.move_cursor_to_output(&output);
1054 }
1055 } else {
1056 self.niri.layout.move_to_workspace(None, index);
1057 self.maybe_warp_cursor_to_focus();
1058 }
1059
1060 // FIXME: granular
1061 self.niri.queue_redraw_all();
1062 }
1063 }
1064 Action::MoveWindowToWorkspaceById {
1065 window_id: id,
1066 reference,
1067 } => {
1068 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1069 let window = window.map(|(_, m)| m.window.clone());
1070 if let Some(window) = window {
1071 if let Some((output, index)) =
1072 self.niri.find_output_and_workspace_index(reference)
1073 {
1074 let target_was_active = self
1075 .niri
1076 .layout
1077 .active_output()
1078 .is_some_and(|active| output.as_ref() == Some(active));
1079
1080 if let Some(output) = output {
1081 self.niri
1082 .layout
1083 .move_to_output(Some(&window), &output, Some(index));
1084
1085 // If the active output changed (window was moved and focused).
1086 #[allow(clippy::collapsible_if)]
1087 if !target_was_active
1088 && self.niri.layout.active_output() == Some(&output)
1089 {
1090 if !self.maybe_warp_cursor_to_focus_centered() {
1091 self.move_cursor_to_output(&output);
1092 }
1093 }
1094 } else {
1095 self.niri.layout.move_to_workspace(Some(&window), index);
1096
1097 // If we focused the target window.
1098 let new_focus = self.niri.layout.focus();
1099 if new_focus.is_some_and(|win| win.window == window) {
1100 self.maybe_warp_cursor_to_focus();
1101 }
1102 }
1103
1104 // FIXME: granular
1105 self.niri.queue_redraw_all();
1106 }
1107 }
1108 }
1109 Action::MoveColumnToWorkspaceDown => {
1110 self.niri.layout.move_column_to_workspace_down();
1111 self.maybe_warp_cursor_to_focus();
1112 // FIXME: granular
1113 self.niri.queue_redraw_all();
1114 }
1115 Action::MoveColumnToWorkspaceUp => {
1116 self.niri.layout.move_column_to_workspace_up();
1117 self.maybe_warp_cursor_to_focus();
1118 // FIXME: granular
1119 self.niri.queue_redraw_all();
1120 }
1121 Action::MoveColumnToWorkspace(reference) => {
1122 if let Some((mut output, index)) =
1123 self.niri.find_output_and_workspace_index(reference)
1124 {
1125 if let Some(active) = self.niri.layout.active_output() {
1126 if output.as_ref() == Some(active) {
1127 output = None;
1128 }
1129 }
1130
1131 if let Some(output) = output {
1132 self.niri
1133 .layout
1134 .move_column_to_workspace_on_output(&output, index);
1135 if !self.maybe_warp_cursor_to_focus_centered() {
1136 self.move_cursor_to_output(&output);
1137 }
1138 } else {
1139 self.niri.layout.move_column_to_workspace(index);
1140 self.maybe_warp_cursor_to_focus();
1141 }
1142
1143 // FIXME: granular
1144 self.niri.queue_redraw_all();
1145 }
1146 }
1147 Action::FocusWorkspaceDown => {
1148 self.niri.layout.switch_workspace_down();
1149 self.maybe_warp_cursor_to_focus();
1150 self.niri.layer_shell_on_demand_focus = None;
1151 // FIXME: granular
1152 self.niri.queue_redraw_all();
1153 }
1154 Action::FocusWorkspaceUp => {
1155 self.niri.layout.switch_workspace_up();
1156 self.maybe_warp_cursor_to_focus();
1157 self.niri.layer_shell_on_demand_focus = None;
1158 // FIXME: granular
1159 self.niri.queue_redraw_all();
1160 }
1161 Action::FocusWorkspace(reference) => {
1162 if let Some((mut output, index)) =
1163 self.niri.find_output_and_workspace_index(reference)
1164 {
1165 if let Some(active) = self.niri.layout.active_output() {
1166 if output.as_ref() == Some(active) {
1167 output = None;
1168 }
1169 }
1170
1171 if let Some(output) = output {
1172 self.niri.layout.focus_output(&output);
1173 self.niri.layout.switch_workspace(index);
1174 if !self.maybe_warp_cursor_to_focus_centered() {
1175 self.move_cursor_to_output(&output);
1176 }
1177 } else {
1178 let config = &self.niri.config;
1179 if config.borrow().input.workspace_auto_back_and_forth {
1180 self.niri.layout.switch_workspace_auto_back_and_forth(index);
1181 } else {
1182 self.niri.layout.switch_workspace(index);
1183 }
1184 self.maybe_warp_cursor_to_focus();
1185 }
1186 self.niri.layer_shell_on_demand_focus = None;
1187
1188 // FIXME: granular
1189 self.niri.queue_redraw_all();
1190 }
1191 }
1192 Action::FocusWorkspacePrevious => {
1193 self.niri.layout.switch_workspace_previous();
1194 self.maybe_warp_cursor_to_focus();
1195 self.niri.layer_shell_on_demand_focus = None;
1196 // FIXME: granular
1197 self.niri.queue_redraw_all();
1198 }
1199 Action::MoveWorkspaceDown => {
1200 self.niri.layout.move_workspace_down();
1201 // FIXME: granular
1202 self.niri.queue_redraw_all();
1203 }
1204 Action::MoveWorkspaceUp => {
1205 self.niri.layout.move_workspace_up();
1206 // FIXME: granular
1207 self.niri.queue_redraw_all();
1208 }
1209 Action::MoveWorkspaceToIndex(new_idx) => {
1210 self.niri.layout.move_workspace_to_idx(None, new_idx);
1211 // FIXME: granular
1212 self.niri.queue_redraw_all();
1213 }
1214 Action::MoveWorkspaceToIndexByRef { new_idx, reference } => {
1215 if let Some(res) = self.niri.find_output_and_workspace_index(reference) {
1216 self.niri.layout.move_workspace_to_idx(Some(res), new_idx);
1217 // FIXME: granular
1218 self.niri.queue_redraw_all();
1219 }
1220 }
1221 Action::SetWorkspaceName(name) => {
1222 self.niri.layout.set_workspace_name(name, None);
1223 }
1224 Action::SetWorkspaceNameByRef { name, reference } => {
1225 self.niri.layout.set_workspace_name(name, Some(reference));
1226 }
1227 Action::UnsetWorkspaceName => {
1228 self.niri.layout.unset_workspace_name(None);
1229 }
1230 Action::UnsetWorkSpaceNameByRef(reference) => {
1231 self.niri.layout.unset_workspace_name(Some(reference));
1232 }
1233 Action::ConsumeWindowIntoColumn => {
1234 self.niri.layout.consume_into_column();
1235 // This does not cause immediate focus or window size change, so warping mouse to
1236 // focus won't do anything here.
1237 // FIXME: granular
1238 self.niri.queue_redraw_all();
1239 }
1240 Action::ExpelWindowFromColumn => {
1241 self.niri.layout.expel_from_column();
1242 self.maybe_warp_cursor_to_focus();
1243 // FIXME: granular
1244 self.niri.queue_redraw_all();
1245 }
1246 Action::SwapWindowRight => {
1247 self.niri
1248 .layout
1249 .swap_window_in_direction(ScrollDirection::Right);
1250 self.maybe_warp_cursor_to_focus();
1251 // FIXME: granular
1252 self.niri.queue_redraw_all();
1253 }
1254 Action::SwapWindowLeft => {
1255 self.niri
1256 .layout
1257 .swap_window_in_direction(ScrollDirection::Left);
1258 self.maybe_warp_cursor_to_focus();
1259 // FIXME: granular
1260 self.niri.queue_redraw_all();
1261 }
1262 Action::ToggleColumnTabbedDisplay => {
1263 self.niri.layout.toggle_column_tabbed_display();
1264 self.maybe_warp_cursor_to_focus();
1265 // FIXME: granular
1266 self.niri.queue_redraw_all();
1267 }
1268 Action::SetColumnDisplay(display) => {
1269 self.niri.layout.set_column_display(display);
1270 self.maybe_warp_cursor_to_focus();
1271 // FIXME: granular
1272 self.niri.queue_redraw_all();
1273 }
1274 Action::SwitchPresetColumnWidth => {
1275 self.niri.layout.toggle_width();
1276 }
1277 Action::SwitchPresetWindowWidth => {
1278 self.niri.layout.toggle_window_width(None);
1279 }
1280 Action::SwitchPresetWindowWidthById(id) => {
1281 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1282 let window = window.map(|(_, m)| m.window.clone());
1283 if let Some(window) = window {
1284 self.niri.layout.toggle_window_width(Some(&window));
1285 }
1286 }
1287 Action::SwitchPresetWindowHeight => {
1288 self.niri.layout.toggle_window_height(None);
1289 }
1290 Action::SwitchPresetWindowHeightById(id) => {
1291 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1292 let window = window.map(|(_, m)| m.window.clone());
1293 if let Some(window) = window {
1294 self.niri.layout.toggle_window_height(Some(&window));
1295 }
1296 }
1297 Action::CenterColumn => {
1298 self.niri.layout.center_column();
1299 // FIXME: granular
1300 self.niri.queue_redraw_all();
1301 }
1302 Action::CenterWindow => {
1303 self.niri.layout.center_window(None);
1304 // FIXME: granular
1305 self.niri.queue_redraw_all();
1306 }
1307 Action::CenterWindowById(id) => {
1308 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1309 let window = window.map(|(_, m)| m.window.clone());
1310 if let Some(window) = window {
1311 self.niri.layout.center_window(Some(&window));
1312 // FIXME: granular
1313 self.niri.queue_redraw_all();
1314 }
1315 }
1316 Action::MaximizeColumn => {
1317 self.niri.layout.toggle_full_width();
1318 }
1319 Action::FocusMonitorLeft => {
1320 if let Some(output) = self.niri.output_left() {
1321 self.niri.layout.focus_output(&output);
1322 if !self.maybe_warp_cursor_to_focus_centered() {
1323 self.move_cursor_to_output(&output);
1324 }
1325 self.niri.layer_shell_on_demand_focus = None;
1326 }
1327 }
1328 Action::FocusMonitorRight => {
1329 if let Some(output) = self.niri.output_right() {
1330 self.niri.layout.focus_output(&output);
1331 if !self.maybe_warp_cursor_to_focus_centered() {
1332 self.move_cursor_to_output(&output);
1333 }
1334 self.niri.layer_shell_on_demand_focus = None;
1335 }
1336 }
1337 Action::FocusMonitorDown => {
1338 if let Some(output) = self.niri.output_down() {
1339 self.niri.layout.focus_output(&output);
1340 if !self.maybe_warp_cursor_to_focus_centered() {
1341 self.move_cursor_to_output(&output);
1342 }
1343 self.niri.layer_shell_on_demand_focus = None;
1344 }
1345 }
1346 Action::FocusMonitorUp => {
1347 if let Some(output) = self.niri.output_up() {
1348 self.niri.layout.focus_output(&output);
1349 if !self.maybe_warp_cursor_to_focus_centered() {
1350 self.move_cursor_to_output(&output);
1351 }
1352 self.niri.layer_shell_on_demand_focus = None;
1353 }
1354 }
1355 Action::FocusMonitorPrevious => {
1356 if let Some(output) = self.niri.output_previous() {
1357 self.niri.layout.focus_output(&output);
1358 if !self.maybe_warp_cursor_to_focus_centered() {
1359 self.move_cursor_to_output(&output);
1360 }
1361 self.niri.layer_shell_on_demand_focus = None;
1362 }
1363 }
1364 Action::FocusMonitorNext => {
1365 if let Some(output) = self.niri.output_next() {
1366 self.niri.layout.focus_output(&output);
1367 if !self.maybe_warp_cursor_to_focus_centered() {
1368 self.move_cursor_to_output(&output);
1369 }
1370 self.niri.layer_shell_on_demand_focus = None;
1371 }
1372 }
1373 Action::MoveWindowToMonitorLeft => {
1374 if let Some(output) = self.niri.output_left() {
1375 self.niri.layout.move_to_output(None, &output, None);
1376 self.niri.layout.focus_output(&output);
1377 if !self.maybe_warp_cursor_to_focus_centered() {
1378 self.move_cursor_to_output(&output);
1379 }
1380 }
1381 }
1382 Action::MoveWindowToMonitorRight => {
1383 if let Some(output) = self.niri.output_right() {
1384 self.niri.layout.move_to_output(None, &output, None);
1385 self.niri.layout.focus_output(&output);
1386 if !self.maybe_warp_cursor_to_focus_centered() {
1387 self.move_cursor_to_output(&output);
1388 }
1389 }
1390 }
1391 Action::MoveWindowToMonitorDown => {
1392 if let Some(output) = self.niri.output_down() {
1393 self.niri.layout.move_to_output(None, &output, None);
1394 self.niri.layout.focus_output(&output);
1395 if !self.maybe_warp_cursor_to_focus_centered() {
1396 self.move_cursor_to_output(&output);
1397 }
1398 }
1399 }
1400 Action::MoveWindowToMonitorUp => {
1401 if let Some(output) = self.niri.output_up() {
1402 self.niri.layout.move_to_output(None, &output, None);
1403 self.niri.layout.focus_output(&output);
1404 if !self.maybe_warp_cursor_to_focus_centered() {
1405 self.move_cursor_to_output(&output);
1406 }
1407 }
1408 }
1409 Action::MoveWindowToMonitorPrevious => {
1410 if let Some(output) = self.niri.output_previous() {
1411 self.niri.layout.move_to_output(None, &output, None);
1412 self.niri.layout.focus_output(&output);
1413 if !self.maybe_warp_cursor_to_focus_centered() {
1414 self.move_cursor_to_output(&output);
1415 }
1416 }
1417 }
1418 Action::MoveWindowToMonitorNext => {
1419 if let Some(output) = self.niri.output_next() {
1420 self.niri.layout.move_to_output(None, &output, None);
1421 self.niri.layout.focus_output(&output);
1422 if !self.maybe_warp_cursor_to_focus_centered() {
1423 self.move_cursor_to_output(&output);
1424 }
1425 }
1426 }
1427 Action::MoveColumnToMonitorLeft => {
1428 if let Some(output) = self.niri.output_left() {
1429 self.niri.layout.move_column_to_output(&output);
1430 self.niri.layout.focus_output(&output);
1431 if !self.maybe_warp_cursor_to_focus_centered() {
1432 self.move_cursor_to_output(&output);
1433 }
1434 }
1435 }
1436 Action::MoveColumnToMonitorRight => {
1437 if let Some(output) = self.niri.output_right() {
1438 self.niri.layout.move_column_to_output(&output);
1439 self.niri.layout.focus_output(&output);
1440 if !self.maybe_warp_cursor_to_focus_centered() {
1441 self.move_cursor_to_output(&output);
1442 }
1443 }
1444 }
1445 Action::MoveColumnToMonitorDown => {
1446 if let Some(output) = self.niri.output_down() {
1447 self.niri.layout.move_column_to_output(&output);
1448 self.niri.layout.focus_output(&output);
1449 if !self.maybe_warp_cursor_to_focus_centered() {
1450 self.move_cursor_to_output(&output);
1451 }
1452 }
1453 }
1454 Action::MoveColumnToMonitorUp => {
1455 if let Some(output) = self.niri.output_up() {
1456 self.niri.layout.move_column_to_output(&output);
1457 self.niri.layout.focus_output(&output);
1458 if !self.maybe_warp_cursor_to_focus_centered() {
1459 self.move_cursor_to_output(&output);
1460 }
1461 }
1462 }
1463 Action::MoveColumnToMonitorPrevious => {
1464 if let Some(output) = self.niri.output_previous() {
1465 self.niri.layout.move_column_to_output(&output);
1466 self.niri.layout.focus_output(&output);
1467 if !self.maybe_warp_cursor_to_focus_centered() {
1468 self.move_cursor_to_output(&output);
1469 }
1470 }
1471 }
1472 Action::MoveColumnToMonitorNext => {
1473 if let Some(output) = self.niri.output_next() {
1474 self.niri.layout.move_column_to_output(&output);
1475 self.niri.layout.focus_output(&output);
1476 if !self.maybe_warp_cursor_to_focus_centered() {
1477 self.move_cursor_to_output(&output);
1478 }
1479 }
1480 }
1481 Action::SetColumnWidth(change) => {
1482 self.niri.layout.set_column_width(change);
1483 }
1484 Action::SetWindowWidth(change) => {
1485 self.niri.layout.set_window_width(None, change);
1486 }
1487 Action::SetWindowWidthById { id, change } => {
1488 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1489 let window = window.map(|(_, m)| m.window.clone());
1490 if let Some(window) = window {
1491 self.niri.layout.set_window_width(Some(&window), change);
1492 }
1493 }
1494 Action::SetWindowHeight(change) => {
1495 self.niri.layout.set_window_height(None, change);
1496 }
1497 Action::SetWindowHeightById { id, change } => {
1498 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1499 let window = window.map(|(_, m)| m.window.clone());
1500 if let Some(window) = window {
1501 self.niri.layout.set_window_height(Some(&window), change);
1502 }
1503 }
1504 Action::ResetWindowHeight => {
1505 self.niri.layout.reset_window_height(None);
1506 }
1507 Action::ResetWindowHeightById(id) => {
1508 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1509 let window = window.map(|(_, m)| m.window.clone());
1510 if let Some(window) = window {
1511 self.niri.layout.reset_window_height(Some(&window));
1512 }
1513 }
1514 Action::ShowHotkeyOverlay => {
1515 if self.niri.hotkey_overlay.show() {
1516 self.niri.queue_redraw_all();
1517 }
1518 }
1519 Action::MoveWorkspaceToMonitorLeft => {
1520 if let Some(output) = self.niri.output_left() {
1521 self.niri.layout.move_workspace_to_output(&output);
1522 if !self.maybe_warp_cursor_to_focus_centered() {
1523 self.move_cursor_to_output(&output);
1524 }
1525 }
1526 }
1527 Action::MoveWorkspaceToMonitorRight => {
1528 if let Some(output) = self.niri.output_right() {
1529 self.niri.layout.move_workspace_to_output(&output);
1530 if !self.maybe_warp_cursor_to_focus_centered() {
1531 self.move_cursor_to_output(&output);
1532 }
1533 }
1534 }
1535 Action::MoveWorkspaceToMonitorDown => {
1536 if let Some(output) = self.niri.output_down() {
1537 self.niri.layout.move_workspace_to_output(&output);
1538 if !self.maybe_warp_cursor_to_focus_centered() {
1539 self.move_cursor_to_output(&output);
1540 }
1541 }
1542 }
1543 Action::MoveWorkspaceToMonitorUp => {
1544 if let Some(output) = self.niri.output_up() {
1545 self.niri.layout.move_workspace_to_output(&output);
1546 if !self.maybe_warp_cursor_to_focus_centered() {
1547 self.move_cursor_to_output(&output);
1548 }
1549 }
1550 }
1551 Action::MoveWorkspaceToMonitorPrevious => {
1552 if let Some(output) = self.niri.output_previous() {
1553 self.niri.layout.move_workspace_to_output(&output);
1554 if !self.maybe_warp_cursor_to_focus_centered() {
1555 self.move_cursor_to_output(&output);
1556 }
1557 }
1558 }
1559 Action::MoveWorkspaceToMonitorNext => {
1560 if let Some(output) = self.niri.output_next() {
1561 self.niri.layout.move_workspace_to_output(&output);
1562 if !self.maybe_warp_cursor_to_focus_centered() {
1563 self.move_cursor_to_output(&output);
1564 }
1565 }
1566 }
1567 Action::MoveWorkspaceToMonitor(new_output) => {
1568 if let Some(new_output) = self.niri.output_by_name_match(&new_output).cloned() {
1569 if self.niri.layout.move_workspace_to_output(&new_output)
1570 && !self.maybe_warp_cursor_to_focus_centered()
1571 {
1572 self.move_cursor_to_output(&new_output);
1573 }
1574 }
1575 }
1576 Action::MoveWorkspaceToMonitorByRef {
1577 output_name,
1578 reference,
1579 } => {
1580 if let Some((output, old_idx)) =
1581 self.niri.find_output_and_workspace_index(reference)
1582 {
1583 if let Some(new_output) = self.niri.output_by_name_match(&output_name).cloned()
1584 {
1585 if self.niri.layout.move_workspace_to_output_by_id(
1586 old_idx,
1587 output,
1588 new_output.clone(),
1589 ) {
1590 // Cursor warp already calls `queue_redraw_all`
1591 if !self.maybe_warp_cursor_to_focus_centered() {
1592 self.move_cursor_to_output(&new_output);
1593 }
1594 }
1595 }
1596 }
1597 }
1598 Action::ToggleWindowFloating => {
1599 self.niri.layout.toggle_window_floating(None);
1600 // FIXME: granular
1601 self.niri.queue_redraw_all();
1602 }
1603 Action::ToggleWindowFloatingById(id) => {
1604 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1605 let window = window.map(|(_, m)| m.window.clone());
1606 if let Some(window) = window {
1607 self.niri.layout.toggle_window_floating(Some(&window));
1608 // FIXME: granular
1609 self.niri.queue_redraw_all();
1610 }
1611 }
1612 Action::MoveWindowToFloating => {
1613 self.niri.layout.set_window_floating(None, true);
1614 // FIXME: granular
1615 self.niri.queue_redraw_all();
1616 }
1617 Action::MoveWindowToFloatingById(id) => {
1618 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1619 let window = window.map(|(_, m)| m.window.clone());
1620 if let Some(window) = window {
1621 self.niri.layout.set_window_floating(Some(&window), true);
1622 // FIXME: granular
1623 self.niri.queue_redraw_all();
1624 }
1625 }
1626 Action::MoveWindowToTiling => {
1627 self.niri.layout.set_window_floating(None, false);
1628 // FIXME: granular
1629 self.niri.queue_redraw_all();
1630 }
1631 Action::MoveWindowToTilingById(id) => {
1632 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1633 let window = window.map(|(_, m)| m.window.clone());
1634 if let Some(window) = window {
1635 self.niri.layout.set_window_floating(Some(&window), false);
1636 // FIXME: granular
1637 self.niri.queue_redraw_all();
1638 }
1639 }
1640 Action::FocusFloating => {
1641 self.niri.layout.focus_floating();
1642 self.maybe_warp_cursor_to_focus();
1643 // FIXME: granular
1644 self.niri.queue_redraw_all();
1645 }
1646 Action::FocusTiling => {
1647 self.niri.layout.focus_tiling();
1648 self.maybe_warp_cursor_to_focus();
1649 // FIXME: granular
1650 self.niri.queue_redraw_all();
1651 }
1652 Action::SwitchFocusBetweenFloatingAndTiling => {
1653 self.niri.layout.switch_focus_floating_tiling();
1654 self.maybe_warp_cursor_to_focus();
1655 // FIXME: granular
1656 self.niri.queue_redraw_all();
1657 }
1658 Action::MoveFloatingWindowById { id, x, y } => {
1659 let window = if let Some(id) = id {
1660 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1661 let window = window.map(|(_, m)| m.window.clone());
1662 if window.is_none() {
1663 return;
1664 }
1665 window
1666 } else {
1667 None
1668 };
1669
1670 self.niri
1671 .layout
1672 .move_floating_window(window.as_ref(), x, y, true);
1673 // FIXME: granular
1674 self.niri.queue_redraw_all();
1675 }
1676 Action::ToggleWindowRuleOpacity => {
1677 let active_window = self
1678 .niri
1679 .layout
1680 .active_workspace_mut()
1681 .and_then(|ws| ws.active_window_mut());
1682 if let Some(window) = active_window {
1683 if window.rules().opacity.is_some_and(|o| o != 1.) {
1684 window.toggle_ignore_opacity_window_rule();
1685 // FIXME: granular
1686 self.niri.queue_redraw_all();
1687 }
1688 }
1689 }
1690 Action::ToggleWindowRuleOpacityById(id) => {
1691 let window = self
1692 .niri
1693 .layout
1694 .workspaces_mut()
1695 .find_map(|ws| ws.windows_mut().find(|w| w.id().get() == id));
1696 if let Some(window) = window {
1697 if window.rules().opacity.is_some_and(|o| o != 1.) {
1698 window.toggle_ignore_opacity_window_rule();
1699 // FIXME: granular
1700 self.niri.queue_redraw_all();
1701 }
1702 }
1703 }
1704 }
1705 }
1706
1707 fn on_pointer_motion<I: InputBackend>(&mut self, event: I::PointerMotionEvent) {
1708 // We need an output to be able to move the pointer.
1709 if self.niri.global_space.outputs().next().is_none() {
1710 return;
1711 }
1712
1713 let serial = SERIAL_COUNTER.next_serial();
1714
1715 let pointer = self.niri.seat.get_pointer().unwrap();
1716
1717 let pos = pointer.current_location();
1718
1719 // We have an output, so we can compute the new location and focus.
1720 let mut new_pos = pos + event.delta();
1721
1722 // We received an event for the regular pointer, so show it now.
1723 self.niri.pointer_hidden = false;
1724 self.niri.tablet_cursor_location = None;
1725
1726 // Check if we have an active pointer constraint.
1727 //
1728 // FIXME: ideally this should use the pointer focus with up-to-date global location.
1729 let mut pointer_confined = None;
1730 if let Some(under) = &self.niri.pointer_contents.surface {
1731 // No need to check if the pointer focus surface matches, because here we're checking
1732 // for an already-active constraint, and the constraint is deactivated when the focused
1733 // surface changes.
1734 let pos_within_surface = pos - under.1;
1735
1736 let mut pointer_locked = false;
1737 with_pointer_constraint(&under.0, &pointer, |constraint| {
1738 let Some(constraint) = constraint else { return };
1739 if !constraint.is_active() {
1740 return;
1741 }
1742
1743 // Constraint does not apply if not within region.
1744 if let Some(region) = constraint.region() {
1745 if !region.contains(pos_within_surface.to_i32_round()) {
1746 return;
1747 }
1748 }
1749
1750 match &*constraint {
1751 PointerConstraint::Locked(_locked) => {
1752 pointer_locked = true;
1753 }
1754 PointerConstraint::Confined(confine) => {
1755 pointer_confined = Some((under.clone(), confine.region().cloned()));
1756 }
1757 }
1758 });
1759
1760 // If the pointer is locked, only send relative motion.
1761 if pointer_locked {
1762 pointer.relative_motion(
1763 self,
1764 Some(under.clone()),
1765 &RelativeMotionEvent {
1766 delta: event.delta(),
1767 delta_unaccel: event.delta_unaccel(),
1768 utime: event.time(),
1769 },
1770 );
1771
1772 pointer.frame(self);
1773
1774 // I guess a redraw to hide the tablet cursor could be nice? Doesn't matter too
1775 // much here I think.
1776 return;
1777 }
1778 }
1779
1780 if self
1781 .niri
1782 .global_space
1783 .output_under(new_pos)
1784 .next()
1785 .is_none()
1786 {
1787 // We ended up outside the outputs and need to clip the movement.
1788 if let Some(output) = self.niri.global_space.output_under(pos).next() {
1789 // The pointer was previously on some output. Clip the movement against its
1790 // boundaries.
1791 let geom = self.niri.global_space.output_geometry(output).unwrap();
1792 new_pos.x = new_pos
1793 .x
1794 .clamp(geom.loc.x as f64, (geom.loc.x + geom.size.w - 1) as f64);
1795 new_pos.y = new_pos
1796 .y
1797 .clamp(geom.loc.y as f64, (geom.loc.y + geom.size.h - 1) as f64);
1798 } else {
1799 // The pointer was not on any output in the first place. Find one for it.
1800 // Let's do the simple thing and just put it on the first output.
1801 let output = self.niri.global_space.outputs().next().unwrap();
1802 let geom = self.niri.global_space.output_geometry(output).unwrap();
1803 new_pos = center(geom).to_f64();
1804 }
1805 }
1806
1807 if let Some(output) = self.niri.screenshot_ui.selection_output() {
1808 let geom = self.niri.global_space.output_geometry(output).unwrap();
1809 let mut point = (new_pos - geom.loc.to_f64())
1810 .to_physical(output.current_scale().fractional_scale())
1811 .to_i32_round::<i32>();
1812
1813 let size = output.current_mode().unwrap().size;
1814 let transform = output.current_transform();
1815 let size = transform.transform_size(size);
1816 point.x = point.x.clamp(0, size.w - 1);
1817 point.y = point.y.clamp(0, size.h - 1);
1818
1819 self.niri.screenshot_ui.pointer_motion(point);
1820 }
1821
1822 let under = self.niri.contents_under(new_pos);
1823
1824 // Handle confined pointer.
1825 if let Some((focus_surface, region)) = pointer_confined {
1826 let mut prevent = false;
1827
1828 // Prevent the pointer from leaving the focused surface.
1829 if Some(&focus_surface.0) != under.surface.as_ref().map(|(s, _)| s) {
1830 prevent = true;
1831 }
1832
1833 // Prevent the pointer from leaving the confine region, if any.
1834 if let Some(region) = region {
1835 let new_pos_within_surface = new_pos - focus_surface.1;
1836 if !region.contains(new_pos_within_surface.to_i32_round()) {
1837 prevent = true;
1838 }
1839 }
1840
1841 if prevent {
1842 pointer.relative_motion(
1843 self,
1844 Some(focus_surface),
1845 &RelativeMotionEvent {
1846 delta: event.delta(),
1847 delta_unaccel: event.delta_unaccel(),
1848 utime: event.time(),
1849 },
1850 );
1851
1852 pointer.frame(self);
1853
1854 return;
1855 }
1856 }
1857
1858 self.niri.handle_focus_follows_mouse(&under);
1859
1860 self.niri.pointer_contents.clone_from(&under);
1861
1862 pointer.motion(
1863 self,
1864 under.surface.clone(),
1865 &MotionEvent {
1866 location: new_pos,
1867 serial,
1868 time: event.time_msec(),
1869 },
1870 );
1871
1872 pointer.relative_motion(
1873 self,
1874 under.surface,
1875 &RelativeMotionEvent {
1876 delta: event.delta(),
1877 delta_unaccel: event.delta_unaccel(),
1878 utime: event.time(),
1879 },
1880 );
1881
1882 pointer.frame(self);
1883
1884 // Activate a new confinement if necessary.
1885 self.niri.maybe_activate_pointer_constraint();
1886
1887 // Redraw to update the cursor position.
1888 // FIXME: redraw only outputs overlapping the cursor.
1889 self.niri.queue_redraw_all();
1890 }
1891
1892 fn on_pointer_motion_absolute<I: InputBackend>(
1893 &mut self,
1894 event: I::PointerMotionAbsoluteEvent,
1895 ) {
1896 let Some(pos) = self.compute_absolute_location(&event, None).or_else(|| {
1897 self.global_bounding_rectangle().map(|output_geo| {
1898 event.position_transformed(output_geo.size) + output_geo.loc.to_f64()
1899 })
1900 }) else {
1901 return;
1902 };
1903
1904 let serial = SERIAL_COUNTER.next_serial();
1905
1906 let pointer = self.niri.seat.get_pointer().unwrap();
1907
1908 if let Some(output) = self.niri.screenshot_ui.selection_output() {
1909 let geom = self.niri.global_space.output_geometry(output).unwrap();
1910 let mut point = (pos - geom.loc.to_f64())
1911 .to_physical(output.current_scale().fractional_scale())
1912 .to_i32_round::<i32>();
1913
1914 let size = output.current_mode().unwrap().size;
1915 let transform = output.current_transform();
1916 let size = transform.transform_size(size);
1917 point.x = point.x.clamp(0, size.w - 1);
1918 point.y = point.y.clamp(0, size.h - 1);
1919
1920 self.niri.screenshot_ui.pointer_motion(point);
1921 }
1922
1923 let under = self.niri.contents_under(pos);
1924
1925 self.niri.handle_focus_follows_mouse(&under);
1926
1927 self.niri.pointer_contents.clone_from(&under);
1928
1929 pointer.motion(
1930 self,
1931 under.surface,
1932 &MotionEvent {
1933 location: pos,
1934 serial,
1935 time: event.time_msec(),
1936 },
1937 );
1938
1939 pointer.frame(self);
1940
1941 self.niri.maybe_activate_pointer_constraint();
1942
1943 // We moved the pointer, show it.
1944 self.niri.pointer_hidden = false;
1945
1946 // We moved the regular pointer, so show it now.
1947 self.niri.tablet_cursor_location = None;
1948
1949 // Redraw to update the cursor position.
1950 // FIXME: redraw only outputs overlapping the cursor.
1951 self.niri.queue_redraw_all();
1952 }
1953
1954 fn on_pointer_button<I: InputBackend>(&mut self, event: I::PointerButtonEvent) {
1955 let pointer = self.niri.seat.get_pointer().unwrap();
1956
1957 let serial = SERIAL_COUNTER.next_serial();
1958
1959 let button = event.button();
1960
1961 let button_code = event.button_code();
1962
1963 let button_state = event.state();
1964
1965 // Ignore release events for mouse clicks that triggered a bind.
1966 if self.niri.suppressed_buttons.remove(&button_code) {
1967 return;
1968 }
1969
1970 if ButtonState::Pressed == button_state {
1971 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
1972 let modifiers = modifiers_from_state(mods);
1973
1974 if self.niri.mods_with_mouse_binds.contains(&modifiers) {
1975 let comp_mod = self.backend.mod_key();
1976
1977 if let Some(bind) = match button {
1978 Some(MouseButton::Left) => Some(Trigger::MouseLeft),
1979 Some(MouseButton::Right) => Some(Trigger::MouseRight),
1980 Some(MouseButton::Middle) => Some(Trigger::MouseMiddle),
1981 Some(MouseButton::Back) => Some(Trigger::MouseBack),
1982 Some(MouseButton::Forward) => Some(Trigger::MouseForward),
1983 _ => None,
1984 }
1985 .and_then(|trigger| {
1986 let config = self.niri.config.borrow();
1987 let bindings = &config.binds;
1988 find_configured_bind(bindings, comp_mod, trigger, mods)
1989 }) {
1990 self.niri.suppressed_buttons.insert(button_code);
1991 self.handle_bind(bind.clone());
1992 return;
1993 };
1994 }
1995
1996 // We received an event for the regular pointer, so show it now.
1997 self.niri.pointer_hidden = false;
1998 self.niri.tablet_cursor_location = None;
1999
2000 if let Some(mapped) = self.niri.window_under_cursor() {
2001 let window = mapped.window.clone();
2002
2003 // Check if we need to start an interactive move.
2004 if button == Some(MouseButton::Left) && !pointer.is_grabbed() {
2005 let mod_down = match self.backend.mod_key() {
2006 CompositorMod::Super => mods.logo,
2007 CompositorMod::Alt => mods.alt,
2008 };
2009 if mod_down {
2010 let location = pointer.current_location();
2011 let (output, pos_within_output) = self.niri.output_under(location).unwrap();
2012 let output = output.clone();
2013
2014 self.niri.layout.activate_window(&window);
2015
2016 if self.niri.layout.interactive_move_begin(
2017 window.clone(),
2018 &output,
2019 pos_within_output,
2020 ) {
2021 let start_data = PointerGrabStartData {
2022 focus: None,
2023 button: button_code,
2024 location,
2025 };
2026 let grab = MoveGrab::new(start_data, window.clone());
2027 pointer.set_grab(self, grab, serial, Focus::Clear);
2028 self.niri
2029 .cursor_manager
2030 .set_cursor_image(CursorImageStatus::Named(CursorIcon::Move));
2031 }
2032 }
2033 }
2034 // Check if we need to start an interactive resize.
2035 else if button == Some(MouseButton::Right) && !pointer.is_grabbed() {
2036 let mod_down = match self.backend.mod_key() {
2037 CompositorMod::Super => mods.logo,
2038 CompositorMod::Alt => mods.alt,
2039 };
2040 if mod_down {
2041 let location = pointer.current_location();
2042 let (output, pos_within_output) = self.niri.output_under(location).unwrap();
2043 let edges = self
2044 .niri
2045 .layout
2046 .resize_edges_under(output, pos_within_output)
2047 .unwrap();
2048
2049 if !edges.is_empty() {
2050 // See if we got a double resize-click gesture.
2051 // FIXME: deduplicate with resize_request in xdg-shell somehow.
2052 let time = get_monotonic_time();
2053 let last_cell = mapped.last_interactive_resize_start();
2054 let mut last = last_cell.get();
2055 last_cell.set(Some((time, edges)));
2056
2057 // Floating windows don't have either of the double-resize-click
2058 // gestures, so just allow it to resize.
2059 if mapped.is_floating() {
2060 last = None;
2061 last_cell.set(None);
2062 }
2063
2064 if let Some((last_time, last_edges)) = last {
2065 if time.saturating_sub(last_time) <= DOUBLE_CLICK_TIME {
2066 // Allow quick resize after a triple click.
2067 last_cell.set(None);
2068
2069 let intersection = edges.intersection(last_edges);
2070 if intersection.intersects(ResizeEdge::LEFT_RIGHT) {
2071 // FIXME: don't activate once we can pass specific windows
2072 // to actions.
2073 self.niri.layout.activate_window(&window);
2074 self.niri.layout.toggle_full_width();
2075 }
2076 if intersection.intersects(ResizeEdge::TOP_BOTTOM) {
2077 self.niri.layout.activate_window(&window);
2078 self.niri.layout.reset_window_height(Some(&window));
2079 }
2080 // FIXME: granular.
2081 self.niri.queue_redraw_all();
2082 return;
2083 }
2084 }
2085
2086 self.niri.layout.activate_window(&window);
2087
2088 if self
2089 .niri
2090 .layout
2091 .interactive_resize_begin(window.clone(), edges)
2092 {
2093 let start_data = PointerGrabStartData {
2094 focus: None,
2095 button: button_code,
2096 location,
2097 };
2098 let grab = ResizeGrab::new(start_data, window.clone());
2099 pointer.set_grab(self, grab, serial, Focus::Clear);
2100 self.niri.cursor_manager.set_cursor_image(
2101 CursorImageStatus::Named(edges.cursor_icon()),
2102 );
2103 }
2104 }
2105 }
2106 }
2107
2108 self.niri.layout.activate_window(&window);
2109
2110 // FIXME: granular.
2111 self.niri.queue_redraw_all();
2112 } else if let Some(output) = self.niri.output_under_cursor() {
2113 self.niri.layout.activate_output(&output);
2114
2115 // FIXME: granular.
2116 self.niri.queue_redraw_all();
2117 }
2118
2119 if button == Some(MouseButton::Middle) && !pointer.is_grabbed() {
2120 let mod_down = match self.backend.mod_key() {
2121 CompositorMod::Super => mods.logo,
2122 CompositorMod::Alt => mods.alt,
2123 };
2124 if mod_down {
2125 if let Some(output) = self.niri.output_under_cursor() {
2126 let location = pointer.current_location();
2127 let start_data = PointerGrabStartData {
2128 focus: None,
2129 button: button_code,
2130 location,
2131 };
2132 let grab = SpatialMovementGrab::new(start_data, output);
2133 pointer.set_grab(self, grab, serial, Focus::Clear);
2134 self.niri
2135 .cursor_manager
2136 .set_cursor_image(CursorImageStatus::Named(CursorIcon::AllScroll));
2137 }
2138 }
2139 }
2140 };
2141
2142 self.update_pointer_contents();
2143
2144 if ButtonState::Pressed == button_state {
2145 let layer_under = self.niri.pointer_contents.layer.clone();
2146 self.niri.focus_layer_surface_if_on_demand(layer_under);
2147 }
2148
2149 if let Some(button) = button {
2150 let pos = pointer.current_location();
2151 if let Some((output, _)) = self.niri.output_under(pos) {
2152 let output = output.clone();
2153 let geom = self.niri.global_space.output_geometry(&output).unwrap();
2154 let mut point = (pos - geom.loc.to_f64())
2155 .to_physical(output.current_scale().fractional_scale())
2156 .to_i32_round();
2157
2158 let size = output.current_mode().unwrap().size;
2159 let transform = output.current_transform();
2160 let size = transform.transform_size(size);
2161 point.x = min(size.w - 1, point.x);
2162 point.y = min(size.h - 1, point.y);
2163
2164 if self
2165 .niri
2166 .screenshot_ui
2167 .pointer_button(output, point, button, button_state)
2168 {
2169 self.niri.queue_redraw_all();
2170 }
2171 }
2172 }
2173
2174 pointer.button(
2175 self,
2176 &ButtonEvent {
2177 button: button_code,
2178 state: button_state,
2179 serial,
2180 time: event.time_msec(),
2181 },
2182 );
2183 pointer.frame(self);
2184 }
2185
2186 fn on_pointer_axis<I: InputBackend>(&mut self, event: I::PointerAxisEvent) {
2187 let pointer = &self.niri.seat.get_pointer().unwrap();
2188
2189 let source = event.source();
2190
2191 // We received an event for the regular pointer, so show it now. This is also needed for
2192 // update_pointer_contents() below to return the real contents, necessary for the pointer
2193 // axis event to reach the window.
2194 self.niri.pointer_hidden = false;
2195 self.niri.tablet_cursor_location = None;
2196
2197 let horizontal_amount_v120 = event.amount_v120(Axis::Horizontal);
2198 let vertical_amount_v120 = event.amount_v120(Axis::Vertical);
2199
2200 // Handle wheel scroll bindings.
2201 if source == AxisSource::Wheel {
2202 // If we have a scroll bind with current modifiers, then accumulate and don't pass to
2203 // Wayland. If there's no bind, reset the accumulator.
2204 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
2205 let modifiers = modifiers_from_state(mods);
2206 if self.niri.mods_with_wheel_binds.contains(&modifiers) {
2207 let comp_mod = self.backend.mod_key();
2208
2209 let horizontal = horizontal_amount_v120.unwrap_or(0.);
2210 let ticks = self.niri.horizontal_wheel_tracker.accumulate(horizontal);
2211 if ticks != 0 {
2212 let config = self.niri.config.borrow();
2213 let bindings = &config.binds;
2214 let bind_left =
2215 find_configured_bind(bindings, comp_mod, Trigger::WheelScrollLeft, mods);
2216 let bind_right =
2217 find_configured_bind(bindings, comp_mod, Trigger::WheelScrollRight, mods);
2218 drop(config);
2219
2220 if let Some(right) = bind_right {
2221 for _ in 0..ticks {
2222 self.handle_bind(right.clone());
2223 }
2224 }
2225 if let Some(left) = bind_left {
2226 for _ in ticks..0 {
2227 self.handle_bind(left.clone());
2228 }
2229 }
2230 }
2231
2232 let vertical = vertical_amount_v120.unwrap_or(0.);
2233 let ticks = self.niri.vertical_wheel_tracker.accumulate(vertical);
2234 if ticks != 0 {
2235 let config = self.niri.config.borrow();
2236 let bindings = &config.binds;
2237 let bind_up =
2238 find_configured_bind(bindings, comp_mod, Trigger::WheelScrollUp, mods);
2239 let bind_down =
2240 find_configured_bind(bindings, comp_mod, Trigger::WheelScrollDown, mods);
2241 drop(config);
2242
2243 if let Some(down) = bind_down {
2244 for _ in 0..ticks {
2245 self.handle_bind(down.clone());
2246 }
2247 }
2248 if let Some(up) = bind_up {
2249 for _ in ticks..0 {
2250 self.handle_bind(up.clone());
2251 }
2252 }
2253 }
2254
2255 return;
2256 } else {
2257 self.niri.horizontal_wheel_tracker.reset();
2258 self.niri.vertical_wheel_tracker.reset();
2259 }
2260 }
2261
2262 let horizontal_amount = event.amount(Axis::Horizontal);
2263 let vertical_amount = event.amount(Axis::Vertical);
2264
2265 // Handle touchpad scroll bindings.
2266 if source == AxisSource::Finger {
2267 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
2268 let modifiers = modifiers_from_state(mods);
2269 if self.niri.mods_with_finger_scroll_binds.contains(&modifiers) {
2270 let comp_mod = self.backend.mod_key();
2271
2272 let horizontal = horizontal_amount.unwrap_or(0.);
2273 let ticks = self
2274 .niri
2275 .horizontal_finger_scroll_tracker
2276 .accumulate(horizontal);
2277 if ticks != 0 {
2278 let config = self.niri.config.borrow();
2279 let bindings = &config.binds;
2280 let bind_left =
2281 find_configured_bind(bindings, comp_mod, Trigger::TouchpadScrollLeft, mods);
2282 let bind_right = find_configured_bind(
2283 bindings,
2284 comp_mod,
2285 Trigger::TouchpadScrollRight,
2286 mods,
2287 );
2288 drop(config);
2289
2290 if let Some(right) = bind_right {
2291 for _ in 0..ticks {
2292 self.handle_bind(right.clone());
2293 }
2294 }
2295 if let Some(left) = bind_left {
2296 for _ in ticks..0 {
2297 self.handle_bind(left.clone());
2298 }
2299 }
2300 }
2301
2302 let vertical = vertical_amount.unwrap_or(0.);
2303 let ticks = self
2304 .niri
2305 .vertical_finger_scroll_tracker
2306 .accumulate(vertical);
2307 if ticks != 0 {
2308 let config = self.niri.config.borrow();
2309 let bindings = &config.binds;
2310 let bind_up =
2311 find_configured_bind(bindings, comp_mod, Trigger::TouchpadScrollUp, mods);
2312 let bind_down =
2313 find_configured_bind(bindings, comp_mod, Trigger::TouchpadScrollDown, mods);
2314 drop(config);
2315
2316 if let Some(down) = bind_down {
2317 for _ in 0..ticks {
2318 self.handle_bind(down.clone());
2319 }
2320 }
2321 if let Some(up) = bind_up {
2322 for _ in ticks..0 {
2323 self.handle_bind(up.clone());
2324 }
2325 }
2326 }
2327
2328 return;
2329 } else {
2330 self.niri.horizontal_finger_scroll_tracker.reset();
2331 self.niri.vertical_finger_scroll_tracker.reset();
2332 }
2333 }
2334
2335 self.update_pointer_contents();
2336
2337 let scroll_factor = match source {
2338 AxisSource::Wheel => self.niri.config.borrow().input.mouse.scroll_factor,
2339 AxisSource::Finger => self.niri.config.borrow().input.touchpad.scroll_factor,
2340 _ => None,
2341 };
2342 let window_scroll_factor = pointer
2343 .current_focus()
2344 .map(|focused| self.niri.find_root_shell_surface(&focused))
2345 .and_then(|root| self.niri.layout.find_window_and_output(&root).unzip().0)
2346 .and_then(|window| window.rules().scroll_factor);
2347 let scroll_factor =
2348 scroll_factor.map(|x| x.0).unwrap_or(1.) * window_scroll_factor.unwrap_or(1.);
2349
2350 let horizontal_amount = horizontal_amount.unwrap_or_else(|| {
2351 // Winit backend, discrete scrolling.
2352 horizontal_amount_v120.unwrap_or(0.0) / 120. * 15.
2353 }) * scroll_factor;
2354 let vertical_amount = vertical_amount.unwrap_or_else(|| {
2355 // Winit backend, discrete scrolling.
2356 vertical_amount_v120.unwrap_or(0.0) / 120. * 15.
2357 }) * scroll_factor;
2358
2359 let horizontal_amount_v120 = horizontal_amount_v120.map(|x| x * scroll_factor);
2360 let vertical_amount_v120 = vertical_amount_v120.map(|x| x * scroll_factor);
2361
2362 let mut frame = AxisFrame::new(event.time_msec()).source(source);
2363 if horizontal_amount != 0.0 {
2364 frame = frame
2365 .relative_direction(Axis::Horizontal, event.relative_direction(Axis::Horizontal));
2366 frame = frame.value(Axis::Horizontal, horizontal_amount);
2367 if let Some(v120) = horizontal_amount_v120 {
2368 frame = frame.v120(Axis::Horizontal, v120 as i32);
2369 }
2370 }
2371 if vertical_amount != 0.0 {
2372 frame =
2373 frame.relative_direction(Axis::Vertical, event.relative_direction(Axis::Vertical));
2374 frame = frame.value(Axis::Vertical, vertical_amount);
2375 if let Some(v120) = vertical_amount_v120 {
2376 frame = frame.v120(Axis::Vertical, v120 as i32);
2377 }
2378 }
2379
2380 if source == AxisSource::Finger {
2381 if event.amount(Axis::Horizontal) == Some(0.0) {
2382 frame = frame.stop(Axis::Horizontal);
2383 }
2384 if event.amount(Axis::Vertical) == Some(0.0) {
2385 frame = frame.stop(Axis::Vertical);
2386 }
2387 }
2388
2389 pointer.axis(self, frame);
2390 pointer.frame(self);
2391 }
2392
2393 fn on_tablet_tool_axis<I: InputBackend>(&mut self, event: I::TabletToolAxisEvent)
2394 where
2395 I::Device: 'static, // Needed for downcasting.
2396 {
2397 let Some(pos) = self.compute_tablet_position(&event) else {
2398 return;
2399 };
2400
2401 let under = self.niri.contents_under(pos);
2402
2403 let tablet_seat = self.niri.seat.tablet_seat();
2404 let tablet = tablet_seat.get_tablet(&TabletDescriptor::from(&event.device()));
2405 let tool = tablet_seat.get_tool(&event.tool());
2406 if let (Some(tablet), Some(tool)) = (tablet, tool) {
2407 if event.pressure_has_changed() {
2408 tool.pressure(event.pressure());
2409 }
2410 if event.distance_has_changed() {
2411 tool.distance(event.distance());
2412 }
2413 if event.tilt_has_changed() {
2414 tool.tilt(event.tilt());
2415 }
2416 if event.slider_has_changed() {
2417 tool.slider_position(event.slider_position());
2418 }
2419 if event.rotation_has_changed() {
2420 tool.rotation(event.rotation());
2421 }
2422 if event.wheel_has_changed() {
2423 tool.wheel(event.wheel_delta(), event.wheel_delta_discrete());
2424 }
2425
2426 tool.motion(
2427 pos,
2428 under.surface,
2429 &tablet,
2430 SERIAL_COUNTER.next_serial(),
2431 event.time_msec(),
2432 );
2433
2434 self.niri.pointer_hidden = false;
2435 self.niri.tablet_cursor_location = Some(pos);
2436 }
2437
2438 // Redraw to update the cursor position.
2439 // FIXME: redraw only outputs overlapping the cursor.
2440 self.niri.queue_redraw_all();
2441 }
2442
2443 fn on_tablet_tool_tip<I: InputBackend>(&mut self, event: I::TabletToolTipEvent) {
2444 let tool = self.niri.seat.tablet_seat().get_tool(&event.tool());
2445
2446 if let Some(tool) = tool {
2447 match event.tip_state() {
2448 TabletToolTipState::Down => {
2449 let serial = SERIAL_COUNTER.next_serial();
2450 tool.tip_down(serial, event.time_msec());
2451
2452 if let Some(pos) = self.niri.tablet_cursor_location {
2453 let under = self.niri.contents_under(pos);
2454 if let Some((window, _)) = under.window {
2455 self.niri.layout.activate_window(&window);
2456
2457 // FIXME: granular.
2458 self.niri.queue_redraw_all();
2459 } else if let Some(output) = under.output {
2460 self.niri.layout.activate_output(&output);
2461
2462 // FIXME: granular.
2463 self.niri.queue_redraw_all();
2464 }
2465 self.niri.focus_layer_surface_if_on_demand(under.layer);
2466 }
2467 }
2468 TabletToolTipState::Up => {
2469 tool.tip_up(event.time_msec());
2470 }
2471 }
2472 }
2473 }
2474
2475 fn on_tablet_tool_proximity<I: InputBackend>(&mut self, event: I::TabletToolProximityEvent)
2476 where
2477 I::Device: 'static, // Needed for downcasting.
2478 {
2479 let Some(pos) = self.compute_tablet_position(&event) else {
2480 return;
2481 };
2482
2483 let under = self.niri.contents_under(pos);
2484
2485 let tablet_seat = self.niri.seat.tablet_seat();
2486 let display_handle = self.niri.display_handle.clone();
2487 let tool = tablet_seat.add_tool::<Self>(self, &display_handle, &event.tool());
2488 let tablet = tablet_seat.get_tablet(&TabletDescriptor::from(&event.device()));
2489 if let Some(tablet) = tablet {
2490 match event.state() {
2491 ProximityState::In => {
2492 if let Some(under) = under.surface {
2493 tool.proximity_in(
2494 pos,
2495 under,
2496 &tablet,
2497 SERIAL_COUNTER.next_serial(),
2498 event.time_msec(),
2499 );
2500 }
2501 self.niri.pointer_hidden = false;
2502 self.niri.tablet_cursor_location = Some(pos);
2503 }
2504 ProximityState::Out => {
2505 tool.proximity_out(event.time_msec());
2506
2507 // Move the mouse pointer here to avoid discontinuity.
2508 //
2509 // Plus, Wayland SDL2 currently warps the pointer into some weird
2510 // location on proximity out, so this should help it a little.
2511 if let Some(pos) = self.niri.tablet_cursor_location {
2512 self.move_cursor(pos);
2513 }
2514
2515 self.niri.pointer_hidden = false;
2516 self.niri.tablet_cursor_location = None;
2517 }
2518 }
2519
2520 // FIXME: granular.
2521 self.niri.queue_redraw_all();
2522 }
2523 }
2524
2525 fn on_tablet_tool_button<I: InputBackend>(&mut self, event: I::TabletToolButtonEvent) {
2526 let tool = self.niri.seat.tablet_seat().get_tool(&event.tool());
2527
2528 if let Some(tool) = tool {
2529 tool.button(
2530 event.button(),
2531 event.button_state(),
2532 SERIAL_COUNTER.next_serial(),
2533 event.time_msec(),
2534 );
2535 }
2536 }
2537
2538 fn on_gesture_swipe_begin<I: InputBackend>(&mut self, event: I::GestureSwipeBeginEvent) {
2539 if event.fingers() == 3 {
2540 self.niri.gesture_swipe_3f_cumulative = Some((0., 0.));
2541
2542 // We handled this event.
2543 return;
2544 }
2545
2546 let serial = SERIAL_COUNTER.next_serial();
2547 let pointer = self.niri.seat.get_pointer().unwrap();
2548
2549 if self.update_pointer_contents() {
2550 pointer.frame(self);
2551 }
2552
2553 pointer.gesture_swipe_begin(
2554 self,
2555 &GestureSwipeBeginEvent {
2556 serial,
2557 time: event.time_msec(),
2558 fingers: event.fingers(),
2559 },
2560 );
2561 }
2562
2563 fn on_gesture_swipe_update<I: InputBackend + 'static>(
2564 &mut self,
2565 event: I::GestureSwipeUpdateEvent,
2566 ) where
2567 I::Device: 'static,
2568 {
2569 let mut delta_x = event.delta_x();
2570 let mut delta_y = event.delta_y();
2571
2572 if let Some(libinput_event) =
2573 (&event as &dyn Any).downcast_ref::<input::event::gesture::GestureSwipeUpdateEvent>()
2574 {
2575 delta_x = libinput_event.dx_unaccelerated();
2576 delta_y = libinput_event.dy_unaccelerated();
2577 }
2578
2579 let device = event.device();
2580 if let Some(device) = (&device as &dyn Any).downcast_ref::<input::Device>() {
2581 if device.config_scroll_natural_scroll_enabled() {
2582 delta_x = -delta_x;
2583 delta_y = -delta_y;
2584 }
2585 }
2586
2587 if let Some((cx, cy)) = &mut self.niri.gesture_swipe_3f_cumulative {
2588 *cx += delta_x;
2589 *cy += delta_y;
2590
2591 // Check if the gesture moved far enough to decide. Threshold copied from GNOME Shell.
2592 let (cx, cy) = (*cx, *cy);
2593 if cx * cx + cy * cy >= 16. * 16. {
2594 self.niri.gesture_swipe_3f_cumulative = None;
2595
2596 if let Some(output) = self.niri.output_under_cursor() {
2597 if cx.abs() > cy.abs() {
2598 self.niri.layout.view_offset_gesture_begin(&output, true);
2599 } else {
2600 self.niri
2601 .layout
2602 .workspace_switch_gesture_begin(&output, true);
2603 }
2604 }
2605 }
2606 }
2607
2608 let timestamp = Duration::from_micros(event.time());
2609
2610 let mut handled = false;
2611 let res = self
2612 .niri
2613 .layout
2614 .workspace_switch_gesture_update(delta_y, timestamp, true);
2615 if let Some(output) = res {
2616 if let Some(output) = output {
2617 self.niri.queue_redraw(&output);
2618 }
2619 handled = true;
2620 }
2621
2622 let res = self
2623 .niri
2624 .layout
2625 .view_offset_gesture_update(delta_x, timestamp, true);
2626 if let Some(output) = res {
2627 if let Some(output) = output {
2628 self.niri.queue_redraw(&output);
2629 }
2630 handled = true;
2631 }
2632
2633 if handled {
2634 // We handled this event.
2635 return;
2636 }
2637
2638 let pointer = self.niri.seat.get_pointer().unwrap();
2639
2640 if self.update_pointer_contents() {
2641 pointer.frame(self);
2642 }
2643
2644 pointer.gesture_swipe_update(
2645 self,
2646 &GestureSwipeUpdateEvent {
2647 time: event.time_msec(),
2648 delta: event.delta(),
2649 },
2650 );
2651 }
2652
2653 fn on_gesture_swipe_end<I: InputBackend>(&mut self, event: I::GestureSwipeEndEvent) {
2654 self.niri.gesture_swipe_3f_cumulative = None;
2655
2656 let mut handled = false;
2657 let res = self
2658 .niri
2659 .layout
2660 .workspace_switch_gesture_end(event.cancelled(), Some(true));
2661 if let Some(output) = res {
2662 self.niri.queue_redraw(&output);
2663 handled = true;
2664 }
2665
2666 let res = self
2667 .niri
2668 .layout
2669 .view_offset_gesture_end(event.cancelled(), Some(true));
2670 if let Some(output) = res {
2671 self.niri.queue_redraw(&output);
2672 handled = true;
2673 }
2674
2675 if handled {
2676 // We handled this event.
2677 return;
2678 }
2679
2680 let serial = SERIAL_COUNTER.next_serial();
2681 let pointer = self.niri.seat.get_pointer().unwrap();
2682
2683 if self.update_pointer_contents() {
2684 pointer.frame(self);
2685 }
2686
2687 pointer.gesture_swipe_end(
2688 self,
2689 &GestureSwipeEndEvent {
2690 serial,
2691 time: event.time_msec(),
2692 cancelled: event.cancelled(),
2693 },
2694 );
2695 }
2696
2697 fn on_gesture_pinch_begin<I: InputBackend>(&mut self, event: I::GesturePinchBeginEvent) {
2698 let serial = SERIAL_COUNTER.next_serial();
2699 let pointer = self.niri.seat.get_pointer().unwrap();
2700
2701 if self.update_pointer_contents() {
2702 pointer.frame(self);
2703 }
2704
2705 pointer.gesture_pinch_begin(
2706 self,
2707 &GesturePinchBeginEvent {
2708 serial,
2709 time: event.time_msec(),
2710 fingers: event.fingers(),
2711 },
2712 );
2713 }
2714
2715 fn on_gesture_pinch_update<I: InputBackend>(&mut self, event: I::GesturePinchUpdateEvent) {
2716 let pointer = self.niri.seat.get_pointer().unwrap();
2717
2718 if self.update_pointer_contents() {
2719 pointer.frame(self);
2720 }
2721
2722 pointer.gesture_pinch_update(
2723 self,
2724 &GesturePinchUpdateEvent {
2725 time: event.time_msec(),
2726 delta: event.delta(),
2727 scale: event.scale(),
2728 rotation: event.rotation(),
2729 },
2730 );
2731 }
2732
2733 fn on_gesture_pinch_end<I: InputBackend>(&mut self, event: I::GesturePinchEndEvent) {
2734 let serial = SERIAL_COUNTER.next_serial();
2735 let pointer = self.niri.seat.get_pointer().unwrap();
2736
2737 if self.update_pointer_contents() {
2738 pointer.frame(self);
2739 }
2740
2741 pointer.gesture_pinch_end(
2742 self,
2743 &GesturePinchEndEvent {
2744 serial,
2745 time: event.time_msec(),
2746 cancelled: event.cancelled(),
2747 },
2748 );
2749 }
2750
2751 fn on_gesture_hold_begin<I: InputBackend>(&mut self, event: I::GestureHoldBeginEvent) {
2752 let serial = SERIAL_COUNTER.next_serial();
2753 let pointer = self.niri.seat.get_pointer().unwrap();
2754
2755 if self.update_pointer_contents() {
2756 pointer.frame(self);
2757 }
2758
2759 pointer.gesture_hold_begin(
2760 self,
2761 &GestureHoldBeginEvent {
2762 serial,
2763 time: event.time_msec(),
2764 fingers: event.fingers(),
2765 },
2766 );
2767 }
2768
2769 fn on_gesture_hold_end<I: InputBackend>(&mut self, event: I::GestureHoldEndEvent) {
2770 let serial = SERIAL_COUNTER.next_serial();
2771 let pointer = self.niri.seat.get_pointer().unwrap();
2772
2773 if self.update_pointer_contents() {
2774 pointer.frame(self);
2775 }
2776
2777 pointer.gesture_hold_end(
2778 self,
2779 &GestureHoldEndEvent {
2780 serial,
2781 time: event.time_msec(),
2782 cancelled: event.cancelled(),
2783 },
2784 );
2785 }
2786
2787 fn compute_absolute_location<I: InputBackend>(
2788 &self,
2789 evt: &impl AbsolutePositionEvent<I>,
2790 fallback_output: Option<&Output>,
2791 ) -> Option<Point<f64, Logical>> {
2792 let output = evt.device().output(self);
2793 let output = output.as_ref().or(fallback_output)?;
2794 let output_geo = self.niri.global_space.output_geometry(output).unwrap();
2795 let transform = output.current_transform();
2796 let size = transform.invert().transform_size(output_geo.size);
2797 Some(
2798 transform.transform_point_in(evt.position_transformed(size), &size.to_f64())
2799 + output_geo.loc.to_f64(),
2800 )
2801 }
2802
2803 /// Computes the cursor position for the touch event.
2804 ///
2805 /// This function handles the touch output mapping, as well as coordinate transform
2806 fn compute_touch_location<I: InputBackend>(
2807 &self,
2808 evt: &impl AbsolutePositionEvent<I>,
2809 ) -> Option<Point<f64, Logical>> {
2810 self.compute_absolute_location(evt, self.niri.output_for_touch())
2811 }
2812
2813 fn on_touch_down<I: InputBackend>(&mut self, evt: I::TouchDownEvent) {
2814 let Some(handle) = self.niri.seat.get_touch() else {
2815 return;
2816 };
2817 let Some(touch_location) = self.compute_touch_location(&evt) else {
2818 return;
2819 };
2820
2821 let serial = SERIAL_COUNTER.next_serial();
2822
2823 let under = self.niri.contents_under(touch_location);
2824
2825 if !handle.is_grabbed() {
2826 if let Some((window, _)) = under.window {
2827 self.niri.layout.activate_window(&window);
2828
2829 // Check if we need to start an interactive move.
2830 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
2831 let mod_down = match self.backend.mod_key() {
2832 CompositorMod::Super => mods.logo,
2833 CompositorMod::Alt => mods.alt,
2834 };
2835 if mod_down {
2836 let (output, pos_within_output) =
2837 self.niri.output_under(touch_location).unwrap();
2838 let output = output.clone();
2839
2840 if self.niri.layout.interactive_move_begin(
2841 window.clone(),
2842 &output,
2843 pos_within_output,
2844 ) {
2845 let start_data = TouchGrabStartData {
2846 focus: None,
2847 slot: evt.slot(),
2848 location: touch_location,
2849 };
2850 let grab = TouchMoveGrab::new(start_data, window.clone());
2851 handle.set_grab(self, grab, serial);
2852 }
2853 }
2854
2855 // FIXME: granular.
2856 self.niri.queue_redraw_all();
2857 } else if let Some(output) = under.output {
2858 self.niri.layout.activate_output(&output);
2859
2860 // FIXME: granular.
2861 self.niri.queue_redraw_all();
2862 }
2863 self.niri.focus_layer_surface_if_on_demand(under.layer);
2864 };
2865
2866 handle.down(
2867 self,
2868 under.surface,
2869 &DownEvent {
2870 slot: evt.slot(),
2871 location: touch_location,
2872 serial,
2873 time: evt.time_msec(),
2874 },
2875 );
2876
2877 // We're using touch, hide the pointer.
2878 self.niri.pointer_hidden = true;
2879 }
2880 fn on_touch_up<I: InputBackend>(&mut self, evt: I::TouchUpEvent) {
2881 let Some(handle) = self.niri.seat.get_touch() else {
2882 return;
2883 };
2884 let serial = SERIAL_COUNTER.next_serial();
2885 handle.up(
2886 self,
2887 &UpEvent {
2888 slot: evt.slot(),
2889 serial,
2890 time: evt.time_msec(),
2891 },
2892 )
2893 }
2894 fn on_touch_motion<I: InputBackend>(&mut self, evt: I::TouchMotionEvent) {
2895 let Some(handle) = self.niri.seat.get_touch() else {
2896 return;
2897 };
2898 let Some(touch_location) = self.compute_touch_location(&evt) else {
2899 return;
2900 };
2901 let under = self.niri.contents_under(touch_location);
2902 handle.motion(
2903 self,
2904 under.surface,
2905 &TouchMotionEvent {
2906 slot: evt.slot(),
2907 location: touch_location,
2908 time: evt.time_msec(),
2909 },
2910 );
2911 }
2912 fn on_touch_frame<I: InputBackend>(&mut self, _evt: I::TouchFrameEvent) {
2913 let Some(handle) = self.niri.seat.get_touch() else {
2914 return;
2915 };
2916 handle.frame(self);
2917 }
2918 fn on_touch_cancel<I: InputBackend>(&mut self, _evt: I::TouchCancelEvent) {
2919 let Some(handle) = self.niri.seat.get_touch() else {
2920 return;
2921 };
2922 handle.cancel(self);
2923 }
2924
2925 fn on_switch_toggle<I: InputBackend>(&mut self, evt: I::SwitchToggleEvent) {
2926 let Some(switch) = evt.switch() else {
2927 return;
2928 };
2929
2930 if switch == Switch::Lid {
2931 let is_closed = evt.state() == SwitchState::On;
2932 debug!("lid switch {}", if is_closed { "closed" } else { "opened" });
2933 self.niri.is_lid_closed = is_closed;
2934 self.backend.on_output_config_changed(&mut self.niri);
2935 }
2936
2937 let action = {
2938 let bindings = &self.niri.config.borrow().switch_events;
2939 find_configured_switch_action(bindings, switch, evt.state())
2940 };
2941
2942 if let Some(action) = action {
2943 self.do_action(action, true);
2944 }
2945 }
2946}
2947
2948/// Check whether the key should be intercepted and mark intercepted
2949/// pressed keys as `suppressed`, thus preventing `releases` corresponding
2950/// to them from being delivered.
2951#[allow(clippy::too_many_arguments)]
2952fn should_intercept_key(
2953 suppressed_keys: &mut HashSet<Keycode>,
2954 bindings: &Binds,
2955 comp_mod: CompositorMod,
2956 key_code: Keycode,
2957 modified: Keysym,
2958 raw: Option<Keysym>,
2959 pressed: bool,
2960 mods: ModifiersState,
2961 screenshot_ui: &ScreenshotUi,
2962 disable_power_key_handling: bool,
2963 is_inhibiting_shortcuts: bool,
2964) -> FilterResult<Option<Bind>> {
2965 // Actions are only triggered on presses, release of the key
2966 // shouldn't try to intercept anything unless we have marked
2967 // the key to suppress.
2968 if !pressed && !suppressed_keys.contains(&key_code) {
2969 return FilterResult::Forward;
2970 }
2971
2972 let mut final_bind = find_bind(
2973 bindings,
2974 comp_mod,
2975 modified,
2976 raw,
2977 mods,
2978 disable_power_key_handling,
2979 );
2980
2981 // Allow only a subset of compositor actions while the screenshot UI is open, since the user
2982 // cannot see the screen.
2983 if screenshot_ui.is_open() {
2984 let mut use_screenshot_ui_action = true;
2985
2986 if let Some(bind) = &final_bind {
2987 if allowed_during_screenshot(&bind.action) {
2988 use_screenshot_ui_action = false;
2989 }
2990 }
2991
2992 if use_screenshot_ui_action {
2993 if let Some(raw) = raw {
2994 final_bind = screenshot_ui.action(raw, mods).map(|action| Bind {
2995 key: Key {
2996 trigger: Trigger::Keysym(raw),
2997 // Not entirely correct but it doesn't matter in how we currently use it.
2998 modifiers: Modifiers::empty(),
2999 },
3000 action,
3001 repeat: true,
3002 cooldown: None,
3003 allow_when_locked: false,
3004 // The screenshot UI owns the focus anyway, so this doesn't really matter.
3005 // But logically, nothing can inhibit its actions. Only opening it can be
3006 // inhibited.
3007 allow_inhibiting: false,
3008 });
3009 }
3010 }
3011 }
3012
3013 match (final_bind, pressed) {
3014 (Some(bind), true) => {
3015 if is_inhibiting_shortcuts && bind.allow_inhibiting {
3016 FilterResult::Forward
3017 } else {
3018 suppressed_keys.insert(key_code);
3019 FilterResult::Intercept(Some(bind))
3020 }
3021 }
3022 (_, false) => {
3023 // By this point, we know that the key was suppressed on press. Even if we're inhibiting
3024 // shortcuts, we should still suppress the release.
3025 // But we don't need to check for shortcuts inhibition here, because
3026 // if it was inhibited on press (forwarded to the client), it wouldn't be suppressed,
3027 // so the release would already have been forwarded at the start of this function.
3028 suppressed_keys.remove(&key_code);
3029 FilterResult::Intercept(None)
3030 }
3031 (None, true) => FilterResult::Forward,
3032 }
3033}
3034
3035fn find_bind(
3036 bindings: &Binds,
3037 comp_mod: CompositorMod,
3038 modified: Keysym,
3039 raw: Option<Keysym>,
3040 mods: ModifiersState,
3041 disable_power_key_handling: bool,
3042) -> Option<Bind> {
3043 use keysyms::*;
3044
3045 // Handle hardcoded binds.
3046 #[allow(non_upper_case_globals)] // wat
3047 let hardcoded_action = match modified.raw() {
3048 modified @ KEY_XF86Switch_VT_1..=KEY_XF86Switch_VT_12 => {
3049 let vt = (modified - KEY_XF86Switch_VT_1 + 1) as i32;
3050 Some(Action::ChangeVt(vt))
3051 }
3052 KEY_XF86PowerOff if !disable_power_key_handling => Some(Action::Suspend),
3053 _ => None,
3054 };
3055
3056 if let Some(action) = hardcoded_action {
3057 return Some(Bind {
3058 key: Key {
3059 // Not entirely correct but it doesn't matter in how we currently use it.
3060 trigger: Trigger::Keysym(modified),
3061 modifiers: Modifiers::empty(),
3062 },
3063 action,
3064 repeat: true,
3065 cooldown: None,
3066 allow_when_locked: false,
3067 // In a worst-case scenario, the user has no way to unlock the compositor and a
3068 // misbehaving client has a keyboard shortcuts inhibitor, "jailing" the user.
3069 // The user must always be able to change VTs to recover from such a situation.
3070 // It also makes no sense to inhibit the default power key handling.
3071 // Hardcoded binds must never be inhibited.
3072 allow_inhibiting: false,
3073 });
3074 }
3075
3076 let trigger = Trigger::Keysym(raw?);
3077 find_configured_bind(bindings, comp_mod, trigger, mods)
3078}
3079
3080fn find_configured_bind(
3081 bindings: &Binds,
3082 comp_mod: CompositorMod,
3083 trigger: Trigger,
3084 mods: ModifiersState,
3085) -> Option<Bind> {
3086 // Handle configured binds.
3087 let mut modifiers = modifiers_from_state(mods);
3088
3089 let (mod_down, comp_mod) = match comp_mod {
3090 CompositorMod::Super => (mods.logo, Modifiers::SUPER),
3091 CompositorMod::Alt => (mods.alt, Modifiers::ALT),
3092 };
3093 if mod_down {
3094 modifiers |= Modifiers::COMPOSITOR;
3095 }
3096
3097 for bind in &bindings.0 {
3098 if bind.key.trigger != trigger {
3099 continue;
3100 }
3101
3102 let mut bind_modifiers = bind.key.modifiers;
3103 if bind_modifiers.contains(Modifiers::COMPOSITOR) {
3104 bind_modifiers |= comp_mod;
3105 } else if bind_modifiers.contains(comp_mod) {
3106 bind_modifiers |= Modifiers::COMPOSITOR;
3107 }
3108
3109 if bind_modifiers == modifiers {
3110 return Some(bind.clone());
3111 }
3112 }
3113
3114 None
3115}
3116
3117fn find_configured_switch_action(
3118 bindings: &SwitchBinds,
3119 switch: Switch,
3120 state: SwitchState,
3121) -> Option<Action> {
3122 let switch_action = match (switch, state) {
3123 (Switch::Lid, SwitchState::Off) => &bindings.lid_open,
3124 (Switch::Lid, SwitchState::On) => &bindings.lid_close,
3125 (Switch::TabletMode, SwitchState::Off) => &bindings.tablet_mode_off,
3126 (Switch::TabletMode, SwitchState::On) => &bindings.tablet_mode_on,
3127 _ => unreachable!(),
3128 };
3129 switch_action
3130 .as_ref()
3131 .map(|switch_action| Action::Spawn(switch_action.spawn.clone()))
3132}
3133
3134fn modifiers_from_state(mods: ModifiersState) -> Modifiers {
3135 let mut modifiers = Modifiers::empty();
3136 if mods.ctrl {
3137 modifiers |= Modifiers::CTRL;
3138 }
3139 if mods.shift {
3140 modifiers |= Modifiers::SHIFT;
3141 }
3142 if mods.alt {
3143 modifiers |= Modifiers::ALT;
3144 }
3145 if mods.logo {
3146 modifiers |= Modifiers::SUPER;
3147 }
3148 if mods.iso_level3_shift {
3149 modifiers |= Modifiers::ISO_LEVEL3_SHIFT;
3150 }
3151 if mods.iso_level5_shift {
3152 modifiers |= Modifiers::ISO_LEVEL5_SHIFT;
3153 }
3154 modifiers
3155}
3156
3157fn should_activate_monitors<I: InputBackend>(event: &InputEvent<I>) -> bool {
3158 match event {
3159 InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true,
3160 InputEvent::PointerButton { event } if event.state() == ButtonState::Pressed => true,
3161 InputEvent::PointerMotion { .. }
3162 | InputEvent::PointerMotionAbsolute { .. }
3163 | InputEvent::PointerAxis { .. }
3164 | InputEvent::GestureSwipeBegin { .. }
3165 | InputEvent::GesturePinchBegin { .. }
3166 | InputEvent::GestureHoldBegin { .. }
3167 | InputEvent::TouchDown { .. }
3168 | InputEvent::TouchMotion { .. }
3169 | InputEvent::TabletToolAxis { .. }
3170 | InputEvent::TabletToolProximity { .. }
3171 | InputEvent::TabletToolTip { .. }
3172 | InputEvent::TabletToolButton { .. } => true,
3173 // Ignore events like device additions and removals, key releases, gesture ends.
3174 _ => false,
3175 }
3176}
3177
3178fn should_hide_hotkey_overlay<I: InputBackend>(event: &InputEvent<I>) -> bool {
3179 match event {
3180 InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true,
3181 InputEvent::PointerButton { event } if event.state() == ButtonState::Pressed => true,
3182 InputEvent::PointerAxis { .. }
3183 | InputEvent::GestureSwipeBegin { .. }
3184 | InputEvent::GesturePinchBegin { .. }
3185 | InputEvent::TouchDown { .. }
3186 | InputEvent::TouchMotion { .. }
3187 | InputEvent::TabletToolTip { .. }
3188 | InputEvent::TabletToolButton { .. } => true,
3189 _ => false,
3190 }
3191}
3192
3193fn should_hide_exit_confirm_dialog<I: InputBackend>(event: &InputEvent<I>) -> bool {
3194 match event {
3195 InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true,
3196 InputEvent::PointerButton { event } if event.state() == ButtonState::Pressed => true,
3197 InputEvent::PointerAxis { .. }
3198 | InputEvent::GestureSwipeBegin { .. }
3199 | InputEvent::GesturePinchBegin { .. }
3200 | InputEvent::TouchDown { .. }
3201 | InputEvent::TouchMotion { .. }
3202 | InputEvent::TabletToolTip { .. }
3203 | InputEvent::TabletToolButton { .. } => true,
3204 _ => false,
3205 }
3206}
3207
3208fn should_notify_activity<I: InputBackend>(event: &InputEvent<I>) -> bool {
3209 !matches!(
3210 event,
3211 InputEvent::DeviceAdded { .. } | InputEvent::DeviceRemoved { .. }
3212 )
3213}
3214
3215fn should_reset_pointer_inactivity_timer<I: InputBackend>(event: &InputEvent<I>) -> bool {
3216 matches!(
3217 event,
3218 InputEvent::PointerAxis { .. }
3219 | InputEvent::PointerButton { .. }
3220 | InputEvent::PointerMotion { .. }
3221 | InputEvent::PointerMotionAbsolute { .. }
3222 | InputEvent::TabletToolAxis { .. }
3223 | InputEvent::TabletToolButton { .. }
3224 | InputEvent::TabletToolProximity { .. }
3225 | InputEvent::TabletToolTip { .. }
3226 )
3227}
3228
3229fn allowed_when_locked(action: &Action) -> bool {
3230 matches!(
3231 action,
3232 Action::Quit(_)
3233 | Action::ChangeVt(_)
3234 | Action::Suspend
3235 | Action::PowerOffMonitors
3236 | Action::PowerOnMonitors
3237 | Action::SwitchLayout(_)
3238 | Action::ToggleKeyboardShortcutsInhibit
3239 )
3240}
3241
3242fn allowed_during_screenshot(action: &Action) -> bool {
3243 matches!(
3244 action,
3245 Action::Quit(_)
3246 | Action::ChangeVt(_)
3247 | Action::Suspend
3248 | Action::PowerOffMonitors
3249 | Action::PowerOnMonitors
3250 )
3251}
3252
3253pub fn apply_libinput_settings(config: &niri_config::Input, device: &mut input::Device) {
3254 // According to Mutter code, this setting is specific to touchpads.
3255 let is_touchpad = device.config_tap_finger_count() > 0;
3256 if is_touchpad {
3257 let c = &config.touchpad;
3258 let _ = device.config_send_events_set_mode(if c.off {
3259 input::SendEventsMode::DISABLED
3260 } else if c.disabled_on_external_mouse {
3261 input::SendEventsMode::DISABLED_ON_EXTERNAL_MOUSE
3262 } else {
3263 input::SendEventsMode::ENABLED
3264 });
3265 let _ = device.config_tap_set_enabled(c.tap);
3266 let _ = device.config_dwt_set_enabled(c.dwt);
3267 let _ = device.config_dwtp_set_enabled(c.dwtp);
3268 let _ = device.config_tap_set_drag_lock_enabled(c.drag_lock);
3269 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
3270 let _ = device.config_accel_set_speed(c.accel_speed);
3271 let _ = device.config_left_handed_set(c.left_handed);
3272 let _ = device.config_middle_emulation_set_enabled(c.middle_emulation);
3273
3274 if let Some(accel_profile) = c.accel_profile {
3275 let _ = device.config_accel_set_profile(accel_profile.into());
3276 } else if let Some(default) = device.config_accel_default_profile() {
3277 let _ = device.config_accel_set_profile(default);
3278 }
3279
3280 if let Some(method) = c.scroll_method {
3281 let _ = device.config_scroll_set_method(method.into());
3282
3283 if method == niri_config::ScrollMethod::OnButtonDown {
3284 if let Some(button) = c.scroll_button {
3285 let _ = device.config_scroll_set_button(button);
3286 }
3287 }
3288 } else if let Some(default) = device.config_scroll_default_method() {
3289 let _ = device.config_scroll_set_method(default);
3290
3291 if default == input::ScrollMethod::OnButtonDown {
3292 if let Some(button) = c.scroll_button {
3293 let _ = device.config_scroll_set_button(button);
3294 }
3295 }
3296 }
3297
3298 if let Some(tap_button_map) = c.tap_button_map {
3299 let _ = device.config_tap_set_button_map(tap_button_map.into());
3300 } else if let Some(default) = device.config_tap_default_button_map() {
3301 let _ = device.config_tap_set_button_map(default);
3302 }
3303
3304 if let Some(method) = c.click_method {
3305 let _ = device.config_click_set_method(method.into());
3306 } else if let Some(default) = device.config_click_default_method() {
3307 let _ = device.config_click_set_method(default);
3308 }
3309 }
3310
3311 // This is how Mutter tells apart mice.
3312 let mut is_trackball = false;
3313 let mut is_trackpoint = false;
3314 if let Some(udev_device) = unsafe { device.udev_device() } {
3315 if udev_device.property_value("ID_INPUT_TRACKBALL").is_some() {
3316 is_trackball = true;
3317 }
3318 if udev_device
3319 .property_value("ID_INPUT_POINTINGSTICK")
3320 .is_some()
3321 {
3322 is_trackpoint = true;
3323 }
3324 }
3325
3326 let is_mouse = device.has_capability(input::DeviceCapability::Pointer)
3327 && !is_touchpad
3328 && !is_trackball
3329 && !is_trackpoint;
3330 if is_mouse {
3331 let c = &config.mouse;
3332 let _ = device.config_send_events_set_mode(if c.off {
3333 input::SendEventsMode::DISABLED
3334 } else {
3335 input::SendEventsMode::ENABLED
3336 });
3337 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
3338 let _ = device.config_accel_set_speed(c.accel_speed);
3339 let _ = device.config_left_handed_set(c.left_handed);
3340 let _ = device.config_middle_emulation_set_enabled(c.middle_emulation);
3341
3342 if let Some(accel_profile) = c.accel_profile {
3343 let _ = device.config_accel_set_profile(accel_profile.into());
3344 } else if let Some(default) = device.config_accel_default_profile() {
3345 let _ = device.config_accel_set_profile(default);
3346 }
3347
3348 if let Some(method) = c.scroll_method {
3349 let _ = device.config_scroll_set_method(method.into());
3350
3351 if method == niri_config::ScrollMethod::OnButtonDown {
3352 if let Some(button) = c.scroll_button {
3353 let _ = device.config_scroll_set_button(button);
3354 }
3355 }
3356 } else if let Some(default) = device.config_scroll_default_method() {
3357 let _ = device.config_scroll_set_method(default);
3358
3359 if default == input::ScrollMethod::OnButtonDown {
3360 if let Some(button) = c.scroll_button {
3361 let _ = device.config_scroll_set_button(button);
3362 }
3363 }
3364 }
3365 }
3366
3367 if is_trackball {
3368 let c = &config.trackball;
3369 let _ = device.config_send_events_set_mode(if c.off {
3370 input::SendEventsMode::DISABLED
3371 } else {
3372 input::SendEventsMode::ENABLED
3373 });
3374 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
3375 let _ = device.config_accel_set_speed(c.accel_speed);
3376 let _ = device.config_middle_emulation_set_enabled(c.middle_emulation);
3377 let _ = device.config_left_handed_set(c.left_handed);
3378
3379 if let Some(accel_profile) = c.accel_profile {
3380 let _ = device.config_accel_set_profile(accel_profile.into());
3381 } else if let Some(default) = device.config_accel_default_profile() {
3382 let _ = device.config_accel_set_profile(default);
3383 }
3384
3385 if let Some(method) = c.scroll_method {
3386 let _ = device.config_scroll_set_method(method.into());
3387
3388 if method == niri_config::ScrollMethod::OnButtonDown {
3389 if let Some(button) = c.scroll_button {
3390 let _ = device.config_scroll_set_button(button);
3391 }
3392 }
3393 } else if let Some(default) = device.config_scroll_default_method() {
3394 let _ = device.config_scroll_set_method(default);
3395
3396 if default == input::ScrollMethod::OnButtonDown {
3397 if let Some(button) = c.scroll_button {
3398 let _ = device.config_scroll_set_button(button);
3399 }
3400 }
3401 }
3402 }
3403
3404 if is_trackpoint {
3405 let c = &config.trackpoint;
3406 let _ = device.config_send_events_set_mode(if c.off {
3407 input::SendEventsMode::DISABLED
3408 } else {
3409 input::SendEventsMode::ENABLED
3410 });
3411 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
3412 let _ = device.config_accel_set_speed(c.accel_speed);
3413 let _ = device.config_middle_emulation_set_enabled(c.middle_emulation);
3414
3415 if let Some(accel_profile) = c.accel_profile {
3416 let _ = device.config_accel_set_profile(accel_profile.into());
3417 } else if let Some(default) = device.config_accel_default_profile() {
3418 let _ = device.config_accel_set_profile(default);
3419 }
3420
3421 if let Some(method) = c.scroll_method {
3422 let _ = device.config_scroll_set_method(method.into());
3423
3424 if method == niri_config::ScrollMethod::OnButtonDown {
3425 if let Some(button) = c.scroll_button {
3426 let _ = device.config_scroll_set_button(button);
3427 }
3428 }
3429 } else if let Some(default) = device.config_scroll_default_method() {
3430 let _ = device.config_scroll_set_method(default);
3431
3432 if default == input::ScrollMethod::OnButtonDown {
3433 if let Some(button) = c.scroll_button {
3434 let _ = device.config_scroll_set_button(button);
3435 }
3436 }
3437 }
3438 }
3439
3440 let is_tablet = device.has_capability(input::DeviceCapability::TabletTool);
3441 if is_tablet {
3442 let c = &config.tablet;
3443 let _ = device.config_send_events_set_mode(if c.off {
3444 input::SendEventsMode::DISABLED
3445 } else {
3446 input::SendEventsMode::ENABLED
3447 });
3448 let _ = device.config_left_handed_set(c.left_handed);
3449 }
3450}
3451
3452pub fn mods_with_binds(
3453 comp_mod: CompositorMod,
3454 binds: &Binds,
3455 triggers: &[Trigger],
3456) -> HashSet<Modifiers> {
3457 let comp_mod = match comp_mod {
3458 CompositorMod::Super => Modifiers::SUPER,
3459 CompositorMod::Alt => Modifiers::ALT,
3460 };
3461
3462 let mut rv = HashSet::new();
3463 for bind in &binds.0 {
3464 if !triggers.iter().any(|trigger| bind.key.trigger == *trigger) {
3465 continue;
3466 }
3467
3468 let mut mods = bind.key.modifiers;
3469 if mods.contains(Modifiers::COMPOSITOR) {
3470 mods.remove(Modifiers::COMPOSITOR);
3471 mods.insert(comp_mod);
3472 }
3473
3474 rv.insert(mods);
3475 }
3476
3477 rv
3478}
3479
3480pub fn mods_with_mouse_binds(comp_mod: CompositorMod, binds: &Binds) -> HashSet<Modifiers> {
3481 mods_with_binds(
3482 comp_mod,
3483 binds,
3484 &[
3485 Trigger::MouseLeft,
3486 Trigger::MouseRight,
3487 Trigger::MouseMiddle,
3488 Trigger::MouseBack,
3489 Trigger::MouseForward,
3490 ],
3491 )
3492}
3493
3494pub fn mods_with_wheel_binds(comp_mod: CompositorMod, binds: &Binds) -> HashSet<Modifiers> {
3495 mods_with_binds(
3496 comp_mod,
3497 binds,
3498 &[
3499 Trigger::WheelScrollUp,
3500 Trigger::WheelScrollDown,
3501 Trigger::WheelScrollLeft,
3502 Trigger::WheelScrollRight,
3503 ],
3504 )
3505}
3506
3507pub fn mods_with_finger_scroll_binds(comp_mod: CompositorMod, binds: &Binds) -> HashSet<Modifiers> {
3508 mods_with_binds(
3509 comp_mod,
3510 binds,
3511 &[
3512 Trigger::TouchpadScrollUp,
3513 Trigger::TouchpadScrollDown,
3514 Trigger::TouchpadScrollLeft,
3515 Trigger::TouchpadScrollRight,
3516 ],
3517 )
3518}
3519
3520#[cfg(test)]
3521mod tests {
3522 use std::cell::Cell;
3523
3524 use super::*;
3525 use crate::animation::Clock;
3526
3527 #[test]
3528 fn bindings_suppress_keys() {
3529 let close_keysym = Keysym::q;
3530 let bindings = Binds(vec![Bind {
3531 key: Key {
3532 trigger: Trigger::Keysym(close_keysym),
3533 modifiers: Modifiers::COMPOSITOR | Modifiers::CTRL,
3534 },
3535 action: Action::CloseWindow,
3536 repeat: true,
3537 cooldown: None,
3538 allow_when_locked: false,
3539 allow_inhibiting: true,
3540 }]);
3541
3542 let comp_mod = CompositorMod::Super;
3543 let mut suppressed_keys = HashSet::new();
3544
3545 let screenshot_ui = ScreenshotUi::new(Clock::default(), Default::default());
3546 let disable_power_key_handling = false;
3547 let is_inhibiting_shortcuts = Cell::new(false);
3548
3549 // The key_code we pick is arbitrary, the only thing
3550 // that matters is that they are different between cases.
3551
3552 let close_key_code = Keycode::from(close_keysym.raw() + 8u32);
3553 let close_key_event = |suppr: &mut HashSet<Keycode>, mods: ModifiersState, pressed| {
3554 should_intercept_key(
3555 suppr,
3556 &bindings,
3557 comp_mod,
3558 close_key_code,
3559 close_keysym,
3560 Some(close_keysym),
3561 pressed,
3562 mods,
3563 &screenshot_ui,
3564 disable_power_key_handling,
3565 is_inhibiting_shortcuts.get(),
3566 )
3567 };
3568
3569 // Key event with the code which can't trigger any action.
3570 let none_key_event = |suppr: &mut HashSet<Keycode>, mods: ModifiersState, pressed| {
3571 should_intercept_key(
3572 suppr,
3573 &bindings,
3574 comp_mod,
3575 Keycode::from(Keysym::l.raw() + 8),
3576 Keysym::l,
3577 Some(Keysym::l),
3578 pressed,
3579 mods,
3580 &screenshot_ui,
3581 disable_power_key_handling,
3582 is_inhibiting_shortcuts.get(),
3583 )
3584 };
3585
3586 let mut mods = ModifiersState {
3587 logo: true,
3588 ctrl: true,
3589 ..Default::default()
3590 };
3591
3592 // Action press/release.
3593
3594 let filter = close_key_event(&mut suppressed_keys, mods, true);
3595 assert!(matches!(
3596 filter,
3597 FilterResult::Intercept(Some(Bind {
3598 action: Action::CloseWindow,
3599 ..
3600 }))
3601 ));
3602 assert!(suppressed_keys.contains(&close_key_code));
3603
3604 let filter = close_key_event(&mut suppressed_keys, mods, false);
3605 assert!(matches!(filter, FilterResult::Intercept(None)));
3606 assert!(suppressed_keys.is_empty());
3607
3608 // Remove mod to make it for a binding.
3609
3610 mods.shift = true;
3611 let filter = close_key_event(&mut suppressed_keys, mods, true);
3612 assert!(matches!(filter, FilterResult::Forward));
3613
3614 mods.shift = false;
3615 let filter = close_key_event(&mut suppressed_keys, mods, false);
3616 assert!(matches!(filter, FilterResult::Forward));
3617
3618 // Just none press/release.
3619
3620 let filter = none_key_event(&mut suppressed_keys, mods, true);
3621 assert!(matches!(filter, FilterResult::Forward));
3622
3623 let filter = none_key_event(&mut suppressed_keys, mods, false);
3624 assert!(matches!(filter, FilterResult::Forward));
3625
3626 // Press action, press arbitrary, release action, release arbitrary.
3627
3628 let filter = close_key_event(&mut suppressed_keys, mods, true);
3629 assert!(matches!(
3630 filter,
3631 FilterResult::Intercept(Some(Bind {
3632 action: Action::CloseWindow,
3633 ..
3634 }))
3635 ));
3636
3637 let filter = none_key_event(&mut suppressed_keys, mods, true);
3638 assert!(matches!(filter, FilterResult::Forward));
3639
3640 let filter = close_key_event(&mut suppressed_keys, mods, false);
3641 assert!(matches!(filter, FilterResult::Intercept(None)));
3642
3643 let filter = none_key_event(&mut suppressed_keys, mods, false);
3644 assert!(matches!(filter, FilterResult::Forward));
3645
3646 // Trigger and remove all mods.
3647
3648 let filter = close_key_event(&mut suppressed_keys, mods, true);
3649 assert!(matches!(
3650 filter,
3651 FilterResult::Intercept(Some(Bind {
3652 action: Action::CloseWindow,
3653 ..
3654 }))
3655 ));
3656
3657 mods = Default::default();
3658 let filter = close_key_event(&mut suppressed_keys, mods, false);
3659 assert!(matches!(filter, FilterResult::Intercept(None)));
3660
3661 // Ensure that no keys are being suppressed.
3662 assert!(suppressed_keys.is_empty());
3663
3664 // Now test shortcut inhibiting.
3665
3666 // With inhibited shortcuts, we don't intercept our shortcut.
3667 is_inhibiting_shortcuts.set(true);
3668
3669 mods = ModifiersState {
3670 logo: true,
3671 ctrl: true,
3672 ..Default::default()
3673 };
3674
3675 let filter = close_key_event(&mut suppressed_keys, mods, true);
3676 assert!(matches!(filter, FilterResult::Forward));
3677 assert!(suppressed_keys.is_empty());
3678
3679 let filter = close_key_event(&mut suppressed_keys, mods, false);
3680 assert!(matches!(filter, FilterResult::Forward));
3681 assert!(suppressed_keys.is_empty());
3682
3683 // Toggle it off after pressing the shortcut.
3684 let filter = close_key_event(&mut suppressed_keys, mods, true);
3685 assert!(matches!(filter, FilterResult::Forward));
3686 assert!(suppressed_keys.is_empty());
3687
3688 is_inhibiting_shortcuts.set(false);
3689
3690 let filter = close_key_event(&mut suppressed_keys, mods, false);
3691 assert!(matches!(filter, FilterResult::Forward));
3692 assert!(suppressed_keys.is_empty());
3693
3694 // Toggle it on after pressing the shortcut.
3695 let filter = close_key_event(&mut suppressed_keys, mods, true);
3696 assert!(matches!(
3697 filter,
3698 FilterResult::Intercept(Some(Bind {
3699 action: Action::CloseWindow,
3700 ..
3701 }))
3702 ));
3703 assert!(suppressed_keys.contains(&close_key_code));
3704
3705 is_inhibiting_shortcuts.set(true);
3706
3707 let filter = close_key_event(&mut suppressed_keys, mods, false);
3708 assert!(matches!(filter, FilterResult::Intercept(None)));
3709 assert!(suppressed_keys.is_empty());
3710 }
3711
3712 #[test]
3713 fn comp_mod_handling() {
3714 let bindings = Binds(vec![
3715 Bind {
3716 key: Key {
3717 trigger: Trigger::Keysym(Keysym::q),
3718 modifiers: Modifiers::COMPOSITOR,
3719 },
3720 action: Action::CloseWindow,
3721 repeat: true,
3722 cooldown: None,
3723 allow_when_locked: false,
3724 allow_inhibiting: true,
3725 },
3726 Bind {
3727 key: Key {
3728 trigger: Trigger::Keysym(Keysym::h),
3729 modifiers: Modifiers::SUPER,
3730 },
3731 action: Action::FocusColumnLeft,
3732 repeat: true,
3733 cooldown: None,
3734 allow_when_locked: false,
3735 allow_inhibiting: true,
3736 },
3737 Bind {
3738 key: Key {
3739 trigger: Trigger::Keysym(Keysym::j),
3740 modifiers: Modifiers::empty(),
3741 },
3742 action: Action::FocusWindowDown,
3743 repeat: true,
3744 cooldown: None,
3745 allow_when_locked: false,
3746 allow_inhibiting: true,
3747 },
3748 Bind {
3749 key: Key {
3750 trigger: Trigger::Keysym(Keysym::k),
3751 modifiers: Modifiers::COMPOSITOR | Modifiers::SUPER,
3752 },
3753 action: Action::FocusWindowUp,
3754 repeat: true,
3755 cooldown: None,
3756 allow_when_locked: false,
3757 allow_inhibiting: true,
3758 },
3759 Bind {
3760 key: Key {
3761 trigger: Trigger::Keysym(Keysym::l),
3762 modifiers: Modifiers::SUPER | Modifiers::ALT,
3763 },
3764 action: Action::FocusColumnRight,
3765 repeat: true,
3766 cooldown: None,
3767 allow_when_locked: false,
3768 allow_inhibiting: true,
3769 },
3770 ]);
3771
3772 assert_eq!(
3773 find_configured_bind(
3774 &bindings,
3775 CompositorMod::Super,
3776 Trigger::Keysym(Keysym::q),
3777 ModifiersState {
3778 logo: true,
3779 ..Default::default()
3780 }
3781 )
3782 .as_ref(),
3783 Some(&bindings.0[0])
3784 );
3785 assert_eq!(
3786 find_configured_bind(
3787 &bindings,
3788 CompositorMod::Super,
3789 Trigger::Keysym(Keysym::q),
3790 ModifiersState::default(),
3791 ),
3792 None,
3793 );
3794
3795 assert_eq!(
3796 find_configured_bind(
3797 &bindings,
3798 CompositorMod::Super,
3799 Trigger::Keysym(Keysym::h),
3800 ModifiersState {
3801 logo: true,
3802 ..Default::default()
3803 }
3804 )
3805 .as_ref(),
3806 Some(&bindings.0[1])
3807 );
3808 assert_eq!(
3809 find_configured_bind(
3810 &bindings,
3811 CompositorMod::Super,
3812 Trigger::Keysym(Keysym::h),
3813 ModifiersState::default(),
3814 ),
3815 None,
3816 );
3817
3818 assert_eq!(
3819 find_configured_bind(
3820 &bindings,
3821 CompositorMod::Super,
3822 Trigger::Keysym(Keysym::j),
3823 ModifiersState {
3824 logo: true,
3825 ..Default::default()
3826 }
3827 ),
3828 None,
3829 );
3830 assert_eq!(
3831 find_configured_bind(
3832 &bindings,
3833 CompositorMod::Super,
3834 Trigger::Keysym(Keysym::j),
3835 ModifiersState::default(),
3836 )
3837 .as_ref(),
3838 Some(&bindings.0[2])
3839 );
3840
3841 assert_eq!(
3842 find_configured_bind(
3843 &bindings,
3844 CompositorMod::Super,
3845 Trigger::Keysym(Keysym::k),
3846 ModifiersState {
3847 logo: true,
3848 ..Default::default()
3849 }
3850 )
3851 .as_ref(),
3852 Some(&bindings.0[3])
3853 );
3854 assert_eq!(
3855 find_configured_bind(
3856 &bindings,
3857 CompositorMod::Super,
3858 Trigger::Keysym(Keysym::k),
3859 ModifiersState::default(),
3860 ),
3861 None,
3862 );
3863
3864 assert_eq!(
3865 find_configured_bind(
3866 &bindings,
3867 CompositorMod::Super,
3868 Trigger::Keysym(Keysym::l),
3869 ModifiersState {
3870 logo: true,
3871 alt: true,
3872 ..Default::default()
3873 }
3874 )
3875 .as_ref(),
3876 Some(&bindings.0[4])
3877 );
3878 assert_eq!(
3879 find_configured_bind(
3880 &bindings,
3881 CompositorMod::Super,
3882 Trigger::Keysym(Keysym::l),
3883 ModifiersState {
3884 logo: true,
3885 ..Default::default()
3886 },
3887 ),
3888 None,
3889 );
3890 }
3891}