forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB4eddcefIvan Molodetskikh1 year ago1772 commits

mod.rs3843 lines, 145.7 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::FocusWindowPrevious => {
685 if let Some(window) = self.niri.previously_focused_window.clone() {
686 self.focus_window(&window);
687 }
688 }
689 Action::SwitchLayout(action) => {
690 let keyboard = &self.niri.seat.get_keyboard().unwrap();
691 keyboard.with_xkb_state(self, |mut state| match action {
692 LayoutSwitchTarget::Next => state.cycle_next_layout(),
693 LayoutSwitchTarget::Prev => state.cycle_prev_layout(),
694 LayoutSwitchTarget::Index(layout) => {
695 let num_layouts = state.xkb().lock().unwrap().layouts().count();
696 if usize::from(layout) >= num_layouts {
697 warn!("requested layout doesn't exist")
698 } else {
699 state.set_layout(Layout(layout.into()))
700 }
701 }
702 });
703 }
704 Action::MoveColumnLeft => {
705 self.niri.layout.move_left();
706 self.maybe_warp_cursor_to_focus();
707 // FIXME: granular
708 self.niri.queue_redraw_all();
709 }
710 Action::MoveColumnRight => {
711 self.niri.layout.move_right();
712 self.maybe_warp_cursor_to_focus();
713 // FIXME: granular
714 self.niri.queue_redraw_all();
715 }
716 Action::MoveColumnToFirst => {
717 self.niri.layout.move_column_to_first();
718 self.maybe_warp_cursor_to_focus();
719 // FIXME: granular
720 self.niri.queue_redraw_all();
721 }
722 Action::MoveColumnToLast => {
723 self.niri.layout.move_column_to_last();
724 self.maybe_warp_cursor_to_focus();
725 // FIXME: granular
726 self.niri.queue_redraw_all();
727 }
728 Action::MoveColumnLeftOrToMonitorLeft => {
729 if let Some(output) = self.niri.output_left() {
730 if self.niri.layout.move_column_left_or_to_output(&output)
731 && !self.maybe_warp_cursor_to_focus_centered()
732 {
733 self.move_cursor_to_output(&output);
734 } else {
735 self.maybe_warp_cursor_to_focus();
736 }
737 } else {
738 self.niri.layout.move_left();
739 self.maybe_warp_cursor_to_focus();
740 }
741
742 // FIXME: granular
743 self.niri.queue_redraw_all();
744 }
745 Action::MoveColumnRightOrToMonitorRight => {
746 if let Some(output) = self.niri.output_right() {
747 if self.niri.layout.move_column_right_or_to_output(&output)
748 && !self.maybe_warp_cursor_to_focus_centered()
749 {
750 self.move_cursor_to_output(&output);
751 } else {
752 self.maybe_warp_cursor_to_focus();
753 }
754 } else {
755 self.niri.layout.move_right();
756 self.maybe_warp_cursor_to_focus();
757 }
758
759 // FIXME: granular
760 self.niri.queue_redraw_all();
761 }
762 Action::MoveWindowDown => {
763 self.niri.layout.move_down();
764 self.maybe_warp_cursor_to_focus();
765 // FIXME: granular
766 self.niri.queue_redraw_all();
767 }
768 Action::MoveWindowUp => {
769 self.niri.layout.move_up();
770 self.maybe_warp_cursor_to_focus();
771 // FIXME: granular
772 self.niri.queue_redraw_all();
773 }
774 Action::MoveWindowDownOrToWorkspaceDown => {
775 self.niri.layout.move_down_or_to_workspace_down();
776 self.maybe_warp_cursor_to_focus();
777 // FIXME: granular
778 self.niri.queue_redraw_all();
779 }
780 Action::MoveWindowUpOrToWorkspaceUp => {
781 self.niri.layout.move_up_or_to_workspace_up();
782 self.maybe_warp_cursor_to_focus();
783 // FIXME: granular
784 self.niri.queue_redraw_all();
785 }
786 Action::ConsumeOrExpelWindowLeft => {
787 self.niri.layout.consume_or_expel_window_left(None);
788 self.maybe_warp_cursor_to_focus();
789 // FIXME: granular
790 self.niri.queue_redraw_all();
791 }
792 Action::ConsumeOrExpelWindowLeftById(id) => {
793 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
794 let window = window.map(|(_, m)| m.window.clone());
795 if let Some(window) = window {
796 self.niri.layout.consume_or_expel_window_left(Some(&window));
797 self.maybe_warp_cursor_to_focus();
798 // FIXME: granular
799 self.niri.queue_redraw_all();
800 }
801 }
802 Action::ConsumeOrExpelWindowRight => {
803 self.niri.layout.consume_or_expel_window_right(None);
804 self.maybe_warp_cursor_to_focus();
805 // FIXME: granular
806 self.niri.queue_redraw_all();
807 }
808 Action::ConsumeOrExpelWindowRightById(id) => {
809 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
810 let window = window.map(|(_, m)| m.window.clone());
811 if let Some(window) = window {
812 self.niri
813 .layout
814 .consume_or_expel_window_right(Some(&window));
815 self.maybe_warp_cursor_to_focus();
816 // FIXME: granular
817 self.niri.queue_redraw_all();
818 }
819 }
820 Action::FocusColumnLeft => {
821 self.niri.layout.focus_left();
822 self.maybe_warp_cursor_to_focus();
823 self.niri.layer_shell_on_demand_focus = None;
824 // FIXME: granular
825 self.niri.queue_redraw_all();
826 }
827 Action::FocusColumnRight => {
828 self.niri.layout.focus_right();
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::FocusColumnFirst => {
835 self.niri.layout.focus_column_first();
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::FocusColumnLast => {
842 self.niri.layout.focus_column_last();
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::FocusColumnRightOrFirst => {
849 self.niri.layout.focus_column_right_or_first();
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::FocusColumnLeftOrLast => {
856 self.niri.layout.focus_column_left_or_last();
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::FocusWindowOrMonitorUp => {
863 if let Some(output) = self.niri.output_up() {
864 if self.niri.layout.focus_window_up_or_output(&output)
865 && !self.maybe_warp_cursor_to_focus_centered()
866 {
867 self.move_cursor_to_output(&output);
868 } else {
869 self.maybe_warp_cursor_to_focus();
870 }
871 } else {
872 self.niri.layout.focus_up();
873 self.maybe_warp_cursor_to_focus();
874 }
875 self.niri.layer_shell_on_demand_focus = None;
876
877 // FIXME: granular
878 self.niri.queue_redraw_all();
879 }
880 Action::FocusWindowOrMonitorDown => {
881 if let Some(output) = self.niri.output_down() {
882 if self.niri.layout.focus_window_down_or_output(&output)
883 && !self.maybe_warp_cursor_to_focus_centered()
884 {
885 self.move_cursor_to_output(&output);
886 } else {
887 self.maybe_warp_cursor_to_focus();
888 }
889 } else {
890 self.niri.layout.focus_down();
891 self.maybe_warp_cursor_to_focus();
892 }
893 self.niri.layer_shell_on_demand_focus = None;
894
895 // FIXME: granular
896 self.niri.queue_redraw_all();
897 }
898 Action::FocusColumnOrMonitorLeft => {
899 if let Some(output) = self.niri.output_left() {
900 if self.niri.layout.focus_column_left_or_output(&output)
901 && !self.maybe_warp_cursor_to_focus_centered()
902 {
903 self.move_cursor_to_output(&output);
904 } else {
905 self.maybe_warp_cursor_to_focus();
906 }
907 } else {
908 self.niri.layout.focus_left();
909 self.maybe_warp_cursor_to_focus();
910 }
911 self.niri.layer_shell_on_demand_focus = None;
912
913 // FIXME: granular
914 self.niri.queue_redraw_all();
915 }
916 Action::FocusColumnOrMonitorRight => {
917 if let Some(output) = self.niri.output_right() {
918 if self.niri.layout.focus_column_right_or_output(&output)
919 && !self.maybe_warp_cursor_to_focus_centered()
920 {
921 self.move_cursor_to_output(&output);
922 } else {
923 self.maybe_warp_cursor_to_focus();
924 }
925 } else {
926 self.niri.layout.focus_right();
927 self.maybe_warp_cursor_to_focus();
928 }
929 self.niri.layer_shell_on_demand_focus = None;
930
931 // FIXME: granular
932 self.niri.queue_redraw_all();
933 }
934 Action::FocusWindowDown => {
935 self.niri.layout.focus_down();
936 self.maybe_warp_cursor_to_focus();
937 self.niri.layer_shell_on_demand_focus = None;
938 // FIXME: granular
939 self.niri.queue_redraw_all();
940 }
941 Action::FocusWindowUp => {
942 self.niri.layout.focus_up();
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::FocusWindowDownOrColumnLeft => {
949 self.niri.layout.focus_down_or_left();
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::FocusWindowDownOrColumnRight => {
956 self.niri.layout.focus_down_or_right();
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::FocusWindowUpOrColumnLeft => {
963 self.niri.layout.focus_up_or_left();
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::FocusWindowUpOrColumnRight => {
970 self.niri.layout.focus_up_or_right();
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::FocusWindowOrWorkspaceDown => {
977 self.niri.layout.focus_window_or_workspace_down();
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::FocusWindowOrWorkspaceUp => {
984 self.niri.layout.focus_window_or_workspace_up();
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::MoveWindowToWorkspaceDown => {
991 self.niri.layout.move_to_workspace_down();
992 self.maybe_warp_cursor_to_focus();
993 // FIXME: granular
994 self.niri.queue_redraw_all();
995 }
996 Action::MoveWindowToWorkspaceUp => {
997 self.niri.layout.move_to_workspace_up();
998 self.maybe_warp_cursor_to_focus();
999 // FIXME: granular
1000 self.niri.queue_redraw_all();
1001 }
1002 Action::MoveWindowToWorkspace(reference) => {
1003 if let Some((mut output, index)) =
1004 self.niri.find_output_and_workspace_index(reference)
1005 {
1006 // The source output is always the active output, so if the target output is
1007 // also the active output, we don't need to use move_to_output().
1008 if let Some(active) = self.niri.layout.active_output() {
1009 if output.as_ref() == Some(active) {
1010 output = None;
1011 }
1012 }
1013
1014 if let Some(output) = output {
1015 self.niri.layout.move_to_output(None, &output, Some(index));
1016
1017 if !self.maybe_warp_cursor_to_focus_centered() {
1018 self.move_cursor_to_output(&output);
1019 }
1020 } else {
1021 self.niri.layout.move_to_workspace(None, index);
1022 self.maybe_warp_cursor_to_focus();
1023 }
1024
1025 // FIXME: granular
1026 self.niri.queue_redraw_all();
1027 }
1028 }
1029 Action::MoveWindowToWorkspaceById {
1030 window_id: id,
1031 reference,
1032 } => {
1033 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1034 let window = window.map(|(_, m)| m.window.clone());
1035 if let Some(window) = window {
1036 if let Some((output, index)) =
1037 self.niri.find_output_and_workspace_index(reference)
1038 {
1039 let target_was_active = self
1040 .niri
1041 .layout
1042 .active_output()
1043 .is_some_and(|active| output.as_ref() == Some(active));
1044
1045 if let Some(output) = output {
1046 self.niri
1047 .layout
1048 .move_to_output(Some(&window), &output, Some(index));
1049
1050 // If the active output changed (window was moved and focused).
1051 #[allow(clippy::collapsible_if)]
1052 if !target_was_active
1053 && self.niri.layout.active_output() == Some(&output)
1054 {
1055 if !self.maybe_warp_cursor_to_focus_centered() {
1056 self.move_cursor_to_output(&output);
1057 }
1058 }
1059 } else {
1060 self.niri.layout.move_to_workspace(Some(&window), index);
1061
1062 // If we focused the target window.
1063 let new_focus = self.niri.layout.focus();
1064 if new_focus.is_some_and(|win| win.window == window) {
1065 self.maybe_warp_cursor_to_focus();
1066 }
1067 }
1068
1069 // FIXME: granular
1070 self.niri.queue_redraw_all();
1071 }
1072 }
1073 }
1074 Action::MoveColumnToWorkspaceDown => {
1075 self.niri.layout.move_column_to_workspace_down();
1076 self.maybe_warp_cursor_to_focus();
1077 // FIXME: granular
1078 self.niri.queue_redraw_all();
1079 }
1080 Action::MoveColumnToWorkspaceUp => {
1081 self.niri.layout.move_column_to_workspace_up();
1082 self.maybe_warp_cursor_to_focus();
1083 // FIXME: granular
1084 self.niri.queue_redraw_all();
1085 }
1086 Action::MoveColumnToWorkspace(reference) => {
1087 if let Some((mut output, index)) =
1088 self.niri.find_output_and_workspace_index(reference)
1089 {
1090 if let Some(active) = self.niri.layout.active_output() {
1091 if output.as_ref() == Some(active) {
1092 output = None;
1093 }
1094 }
1095
1096 if let Some(output) = output {
1097 self.niri
1098 .layout
1099 .move_column_to_workspace_on_output(&output, index);
1100 if !self.maybe_warp_cursor_to_focus_centered() {
1101 self.move_cursor_to_output(&output);
1102 }
1103 } else {
1104 self.niri.layout.move_column_to_workspace(index);
1105 self.maybe_warp_cursor_to_focus();
1106 }
1107
1108 // FIXME: granular
1109 self.niri.queue_redraw_all();
1110 }
1111 }
1112 Action::FocusWorkspaceDown => {
1113 self.niri.layout.switch_workspace_down();
1114 self.maybe_warp_cursor_to_focus();
1115 self.niri.layer_shell_on_demand_focus = None;
1116 // FIXME: granular
1117 self.niri.queue_redraw_all();
1118 }
1119 Action::FocusWorkspaceUp => {
1120 self.niri.layout.switch_workspace_up();
1121 self.maybe_warp_cursor_to_focus();
1122 self.niri.layer_shell_on_demand_focus = None;
1123 // FIXME: granular
1124 self.niri.queue_redraw_all();
1125 }
1126 Action::FocusWorkspace(reference) => {
1127 if let Some((mut output, index)) =
1128 self.niri.find_output_and_workspace_index(reference)
1129 {
1130 if let Some(active) = self.niri.layout.active_output() {
1131 if output.as_ref() == Some(active) {
1132 output = None;
1133 }
1134 }
1135
1136 if let Some(output) = output {
1137 self.niri.layout.focus_output(&output);
1138 self.niri.layout.switch_workspace(index);
1139 if !self.maybe_warp_cursor_to_focus_centered() {
1140 self.move_cursor_to_output(&output);
1141 }
1142 } else {
1143 let config = &self.niri.config;
1144 if config.borrow().input.workspace_auto_back_and_forth {
1145 self.niri.layout.switch_workspace_auto_back_and_forth(index);
1146 } else {
1147 self.niri.layout.switch_workspace(index);
1148 }
1149 self.maybe_warp_cursor_to_focus();
1150 }
1151 self.niri.layer_shell_on_demand_focus = None;
1152
1153 // FIXME: granular
1154 self.niri.queue_redraw_all();
1155 }
1156 }
1157 Action::FocusWorkspacePrevious => {
1158 self.niri.layout.switch_workspace_previous();
1159 self.maybe_warp_cursor_to_focus();
1160 self.niri.layer_shell_on_demand_focus = None;
1161 // FIXME: granular
1162 self.niri.queue_redraw_all();
1163 }
1164 Action::MoveWorkspaceDown => {
1165 self.niri.layout.move_workspace_down();
1166 // FIXME: granular
1167 self.niri.queue_redraw_all();
1168 }
1169 Action::MoveWorkspaceUp => {
1170 self.niri.layout.move_workspace_up();
1171 // FIXME: granular
1172 self.niri.queue_redraw_all();
1173 }
1174 Action::MoveWorkspaceToIndex(new_idx) => {
1175 self.niri.layout.move_workspace_to_idx(None, new_idx);
1176 // FIXME: granular
1177 self.niri.queue_redraw_all();
1178 }
1179 Action::MoveWorkspaceToIndexByRef { new_idx, reference } => {
1180 if let Some(res) = self.niri.find_output_and_workspace_index(reference) {
1181 self.niri.layout.move_workspace_to_idx(Some(res), new_idx);
1182 // FIXME: granular
1183 self.niri.queue_redraw_all();
1184 }
1185 }
1186 Action::SetWorkspaceName(name) => {
1187 self.niri.layout.set_workspace_name(name, None);
1188 }
1189 Action::SetWorkspaceNameByRef { name, reference } => {
1190 self.niri.layout.set_workspace_name(name, Some(reference));
1191 }
1192 Action::UnsetWorkspaceName => {
1193 self.niri.layout.unset_workspace_name(None);
1194 }
1195 Action::UnsetWorkSpaceNameByRef(reference) => {
1196 self.niri.layout.unset_workspace_name(Some(reference));
1197 }
1198 Action::ConsumeWindowIntoColumn => {
1199 self.niri.layout.consume_into_column();
1200 // This does not cause immediate focus or window size change, so warping mouse to
1201 // focus won't do anything here.
1202 // FIXME: granular
1203 self.niri.queue_redraw_all();
1204 }
1205 Action::ExpelWindowFromColumn => {
1206 self.niri.layout.expel_from_column();
1207 self.maybe_warp_cursor_to_focus();
1208 // FIXME: granular
1209 self.niri.queue_redraw_all();
1210 }
1211 Action::SwapWindowRight => {
1212 self.niri
1213 .layout
1214 .swap_window_in_direction(ScrollDirection::Right);
1215 self.maybe_warp_cursor_to_focus();
1216 // FIXME: granular
1217 self.niri.queue_redraw_all();
1218 }
1219 Action::SwapWindowLeft => {
1220 self.niri
1221 .layout
1222 .swap_window_in_direction(ScrollDirection::Left);
1223 self.maybe_warp_cursor_to_focus();
1224 // FIXME: granular
1225 self.niri.queue_redraw_all();
1226 }
1227 Action::SwitchPresetColumnWidth => {
1228 self.niri.layout.toggle_width();
1229 }
1230 Action::SwitchPresetWindowWidth => {
1231 self.niri.layout.toggle_window_width(None);
1232 }
1233 Action::SwitchPresetWindowWidthById(id) => {
1234 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1235 let window = window.map(|(_, m)| m.window.clone());
1236 if let Some(window) = window {
1237 self.niri.layout.toggle_window_width(Some(&window));
1238 }
1239 }
1240 Action::SwitchPresetWindowHeight => {
1241 self.niri.layout.toggle_window_height(None);
1242 }
1243 Action::SwitchPresetWindowHeightById(id) => {
1244 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1245 let window = window.map(|(_, m)| m.window.clone());
1246 if let Some(window) = window {
1247 self.niri.layout.toggle_window_height(Some(&window));
1248 }
1249 }
1250 Action::CenterColumn => {
1251 self.niri.layout.center_column();
1252 // FIXME: granular
1253 self.niri.queue_redraw_all();
1254 }
1255 Action::CenterWindow => {
1256 self.niri.layout.center_window(None);
1257 // FIXME: granular
1258 self.niri.queue_redraw_all();
1259 }
1260 Action::CenterWindowById(id) => {
1261 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1262 let window = window.map(|(_, m)| m.window.clone());
1263 if let Some(window) = window {
1264 self.niri.layout.center_window(Some(&window));
1265 // FIXME: granular
1266 self.niri.queue_redraw_all();
1267 }
1268 }
1269 Action::MaximizeColumn => {
1270 self.niri.layout.toggle_full_width();
1271 }
1272 Action::FocusMonitorLeft => {
1273 if let Some(output) = self.niri.output_left() {
1274 self.niri.layout.focus_output(&output);
1275 if !self.maybe_warp_cursor_to_focus_centered() {
1276 self.move_cursor_to_output(&output);
1277 }
1278 self.niri.layer_shell_on_demand_focus = None;
1279 }
1280 }
1281 Action::FocusMonitorRight => {
1282 if let Some(output) = self.niri.output_right() {
1283 self.niri.layout.focus_output(&output);
1284 if !self.maybe_warp_cursor_to_focus_centered() {
1285 self.move_cursor_to_output(&output);
1286 }
1287 self.niri.layer_shell_on_demand_focus = None;
1288 }
1289 }
1290 Action::FocusMonitorDown => {
1291 if let Some(output) = self.niri.output_down() {
1292 self.niri.layout.focus_output(&output);
1293 if !self.maybe_warp_cursor_to_focus_centered() {
1294 self.move_cursor_to_output(&output);
1295 }
1296 self.niri.layer_shell_on_demand_focus = None;
1297 }
1298 }
1299 Action::FocusMonitorUp => {
1300 if let Some(output) = self.niri.output_up() {
1301 self.niri.layout.focus_output(&output);
1302 if !self.maybe_warp_cursor_to_focus_centered() {
1303 self.move_cursor_to_output(&output);
1304 }
1305 self.niri.layer_shell_on_demand_focus = None;
1306 }
1307 }
1308 Action::FocusMonitorPrevious => {
1309 if let Some(output) = self.niri.output_previous() {
1310 self.niri.layout.focus_output(&output);
1311 if !self.maybe_warp_cursor_to_focus_centered() {
1312 self.move_cursor_to_output(&output);
1313 }
1314 self.niri.layer_shell_on_demand_focus = None;
1315 }
1316 }
1317 Action::FocusMonitorNext => {
1318 if let Some(output) = self.niri.output_next() {
1319 self.niri.layout.focus_output(&output);
1320 if !self.maybe_warp_cursor_to_focus_centered() {
1321 self.move_cursor_to_output(&output);
1322 }
1323 self.niri.layer_shell_on_demand_focus = None;
1324 }
1325 }
1326 Action::MoveWindowToMonitorLeft => {
1327 if let Some(output) = self.niri.output_left() {
1328 self.niri.layout.move_to_output(None, &output, None);
1329 self.niri.layout.focus_output(&output);
1330 if !self.maybe_warp_cursor_to_focus_centered() {
1331 self.move_cursor_to_output(&output);
1332 }
1333 }
1334 }
1335 Action::MoveWindowToMonitorRight => {
1336 if let Some(output) = self.niri.output_right() {
1337 self.niri.layout.move_to_output(None, &output, None);
1338 self.niri.layout.focus_output(&output);
1339 if !self.maybe_warp_cursor_to_focus_centered() {
1340 self.move_cursor_to_output(&output);
1341 }
1342 }
1343 }
1344 Action::MoveWindowToMonitorDown => {
1345 if let Some(output) = self.niri.output_down() {
1346 self.niri.layout.move_to_output(None, &output, None);
1347 self.niri.layout.focus_output(&output);
1348 if !self.maybe_warp_cursor_to_focus_centered() {
1349 self.move_cursor_to_output(&output);
1350 }
1351 }
1352 }
1353 Action::MoveWindowToMonitorUp => {
1354 if let Some(output) = self.niri.output_up() {
1355 self.niri.layout.move_to_output(None, &output, None);
1356 self.niri.layout.focus_output(&output);
1357 if !self.maybe_warp_cursor_to_focus_centered() {
1358 self.move_cursor_to_output(&output);
1359 }
1360 }
1361 }
1362 Action::MoveWindowToMonitorPrevious => {
1363 if let Some(output) = self.niri.output_previous() {
1364 self.niri.layout.move_to_output(None, &output, None);
1365 self.niri.layout.focus_output(&output);
1366 if !self.maybe_warp_cursor_to_focus_centered() {
1367 self.move_cursor_to_output(&output);
1368 }
1369 }
1370 }
1371 Action::MoveWindowToMonitorNext => {
1372 if let Some(output) = self.niri.output_next() {
1373 self.niri.layout.move_to_output(None, &output, None);
1374 self.niri.layout.focus_output(&output);
1375 if !self.maybe_warp_cursor_to_focus_centered() {
1376 self.move_cursor_to_output(&output);
1377 }
1378 }
1379 }
1380 Action::MoveColumnToMonitorLeft => {
1381 if let Some(output) = self.niri.output_left() {
1382 self.niri.layout.move_column_to_output(&output);
1383 self.niri.layout.focus_output(&output);
1384 if !self.maybe_warp_cursor_to_focus_centered() {
1385 self.move_cursor_to_output(&output);
1386 }
1387 }
1388 }
1389 Action::MoveColumnToMonitorRight => {
1390 if let Some(output) = self.niri.output_right() {
1391 self.niri.layout.move_column_to_output(&output);
1392 self.niri.layout.focus_output(&output);
1393 if !self.maybe_warp_cursor_to_focus_centered() {
1394 self.move_cursor_to_output(&output);
1395 }
1396 }
1397 }
1398 Action::MoveColumnToMonitorDown => {
1399 if let Some(output) = self.niri.output_down() {
1400 self.niri.layout.move_column_to_output(&output);
1401 self.niri.layout.focus_output(&output);
1402 if !self.maybe_warp_cursor_to_focus_centered() {
1403 self.move_cursor_to_output(&output);
1404 }
1405 }
1406 }
1407 Action::MoveColumnToMonitorUp => {
1408 if let Some(output) = self.niri.output_up() {
1409 self.niri.layout.move_column_to_output(&output);
1410 self.niri.layout.focus_output(&output);
1411 if !self.maybe_warp_cursor_to_focus_centered() {
1412 self.move_cursor_to_output(&output);
1413 }
1414 }
1415 }
1416 Action::MoveColumnToMonitorPrevious => {
1417 if let Some(output) = self.niri.output_previous() {
1418 self.niri.layout.move_column_to_output(&output);
1419 self.niri.layout.focus_output(&output);
1420 if !self.maybe_warp_cursor_to_focus_centered() {
1421 self.move_cursor_to_output(&output);
1422 }
1423 }
1424 }
1425 Action::MoveColumnToMonitorNext => {
1426 if let Some(output) = self.niri.output_next() {
1427 self.niri.layout.move_column_to_output(&output);
1428 self.niri.layout.focus_output(&output);
1429 if !self.maybe_warp_cursor_to_focus_centered() {
1430 self.move_cursor_to_output(&output);
1431 }
1432 }
1433 }
1434 Action::SetColumnWidth(change) => {
1435 self.niri.layout.set_column_width(change);
1436 }
1437 Action::SetWindowWidth(change) => {
1438 self.niri.layout.set_window_width(None, change);
1439 }
1440 Action::SetWindowWidthById { id, change } => {
1441 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1442 let window = window.map(|(_, m)| m.window.clone());
1443 if let Some(window) = window {
1444 self.niri.layout.set_window_width(Some(&window), change);
1445 }
1446 }
1447 Action::SetWindowHeight(change) => {
1448 self.niri.layout.set_window_height(None, change);
1449 }
1450 Action::SetWindowHeightById { id, change } => {
1451 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1452 let window = window.map(|(_, m)| m.window.clone());
1453 if let Some(window) = window {
1454 self.niri.layout.set_window_height(Some(&window), change);
1455 }
1456 }
1457 Action::ResetWindowHeight => {
1458 self.niri.layout.reset_window_height(None);
1459 }
1460 Action::ResetWindowHeightById(id) => {
1461 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1462 let window = window.map(|(_, m)| m.window.clone());
1463 if let Some(window) = window {
1464 self.niri.layout.reset_window_height(Some(&window));
1465 }
1466 }
1467 Action::ShowHotkeyOverlay => {
1468 if self.niri.hotkey_overlay.show() {
1469 self.niri.queue_redraw_all();
1470 }
1471 }
1472 Action::MoveWorkspaceToMonitorLeft => {
1473 if let Some(output) = self.niri.output_left() {
1474 self.niri.layout.move_workspace_to_output(&output);
1475 if !self.maybe_warp_cursor_to_focus_centered() {
1476 self.move_cursor_to_output(&output);
1477 }
1478 }
1479 }
1480 Action::MoveWorkspaceToMonitorRight => {
1481 if let Some(output) = self.niri.output_right() {
1482 self.niri.layout.move_workspace_to_output(&output);
1483 if !self.maybe_warp_cursor_to_focus_centered() {
1484 self.move_cursor_to_output(&output);
1485 }
1486 }
1487 }
1488 Action::MoveWorkspaceToMonitorDown => {
1489 if let Some(output) = self.niri.output_down() {
1490 self.niri.layout.move_workspace_to_output(&output);
1491 if !self.maybe_warp_cursor_to_focus_centered() {
1492 self.move_cursor_to_output(&output);
1493 }
1494 }
1495 }
1496 Action::MoveWorkspaceToMonitorUp => {
1497 if let Some(output) = self.niri.output_up() {
1498 self.niri.layout.move_workspace_to_output(&output);
1499 if !self.maybe_warp_cursor_to_focus_centered() {
1500 self.move_cursor_to_output(&output);
1501 }
1502 }
1503 }
1504 Action::MoveWorkspaceToMonitorPrevious => {
1505 if let Some(output) = self.niri.output_previous() {
1506 self.niri.layout.move_workspace_to_output(&output);
1507 if !self.maybe_warp_cursor_to_focus_centered() {
1508 self.move_cursor_to_output(&output);
1509 }
1510 }
1511 }
1512 Action::MoveWorkspaceToMonitorNext => {
1513 if let Some(output) = self.niri.output_next() {
1514 self.niri.layout.move_workspace_to_output(&output);
1515 if !self.maybe_warp_cursor_to_focus_centered() {
1516 self.move_cursor_to_output(&output);
1517 }
1518 }
1519 }
1520 Action::MoveWorkspaceToMonitor(new_output) => {
1521 if let Some(new_output) = self.niri.output_by_name_match(&new_output).cloned() {
1522 if self.niri.layout.move_workspace_to_output(&new_output)
1523 && !self.maybe_warp_cursor_to_focus_centered()
1524 {
1525 self.move_cursor_to_output(&new_output);
1526 }
1527 }
1528 }
1529 Action::MoveWorkspaceToMonitorByRef {
1530 output_name,
1531 reference,
1532 } => {
1533 if let Some((output, old_idx)) =
1534 self.niri.find_output_and_workspace_index(reference)
1535 {
1536 if let Some(new_output) = self.niri.output_by_name_match(&output_name).cloned()
1537 {
1538 if self.niri.layout.move_workspace_to_output_by_id(
1539 old_idx,
1540 output,
1541 new_output.clone(),
1542 ) {
1543 // Cursor warp already calls `queue_redraw_all`
1544 if !self.maybe_warp_cursor_to_focus_centered() {
1545 self.move_cursor_to_output(&new_output);
1546 }
1547 }
1548 }
1549 }
1550 }
1551 Action::ToggleWindowFloating => {
1552 self.niri.layout.toggle_window_floating(None);
1553 // FIXME: granular
1554 self.niri.queue_redraw_all();
1555 }
1556 Action::ToggleWindowFloatingById(id) => {
1557 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1558 let window = window.map(|(_, m)| m.window.clone());
1559 if let Some(window) = window {
1560 self.niri.layout.toggle_window_floating(Some(&window));
1561 // FIXME: granular
1562 self.niri.queue_redraw_all();
1563 }
1564 }
1565 Action::MoveWindowToFloating => {
1566 self.niri.layout.set_window_floating(None, true);
1567 // FIXME: granular
1568 self.niri.queue_redraw_all();
1569 }
1570 Action::MoveWindowToFloatingById(id) => {
1571 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1572 let window = window.map(|(_, m)| m.window.clone());
1573 if let Some(window) = window {
1574 self.niri.layout.set_window_floating(Some(&window), true);
1575 // FIXME: granular
1576 self.niri.queue_redraw_all();
1577 }
1578 }
1579 Action::MoveWindowToTiling => {
1580 self.niri.layout.set_window_floating(None, false);
1581 // FIXME: granular
1582 self.niri.queue_redraw_all();
1583 }
1584 Action::MoveWindowToTilingById(id) => {
1585 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1586 let window = window.map(|(_, m)| m.window.clone());
1587 if let Some(window) = window {
1588 self.niri.layout.set_window_floating(Some(&window), false);
1589 // FIXME: granular
1590 self.niri.queue_redraw_all();
1591 }
1592 }
1593 Action::FocusFloating => {
1594 self.niri.layout.focus_floating();
1595 self.maybe_warp_cursor_to_focus();
1596 // FIXME: granular
1597 self.niri.queue_redraw_all();
1598 }
1599 Action::FocusTiling => {
1600 self.niri.layout.focus_tiling();
1601 self.maybe_warp_cursor_to_focus();
1602 // FIXME: granular
1603 self.niri.queue_redraw_all();
1604 }
1605 Action::SwitchFocusBetweenFloatingAndTiling => {
1606 self.niri.layout.switch_focus_floating_tiling();
1607 self.maybe_warp_cursor_to_focus();
1608 // FIXME: granular
1609 self.niri.queue_redraw_all();
1610 }
1611 Action::MoveFloatingWindowById { id, x, y } => {
1612 let window = if let Some(id) = id {
1613 let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id);
1614 let window = window.map(|(_, m)| m.window.clone());
1615 if window.is_none() {
1616 return;
1617 }
1618 window
1619 } else {
1620 None
1621 };
1622
1623 self.niri
1624 .layout
1625 .move_floating_window(window.as_ref(), x, y, true);
1626 // FIXME: granular
1627 self.niri.queue_redraw_all();
1628 }
1629 Action::ToggleWindowRuleOpacity => {
1630 let active_window = self
1631 .niri
1632 .layout
1633 .active_workspace_mut()
1634 .and_then(|ws| ws.active_window_mut());
1635 if let Some(window) = active_window {
1636 if window.rules().opacity.is_some_and(|o| o != 1.) {
1637 window.toggle_ignore_opacity_window_rule();
1638 // FIXME: granular
1639 self.niri.queue_redraw_all();
1640 }
1641 }
1642 }
1643 Action::ToggleWindowRuleOpacityById(id) => {
1644 let window = self
1645 .niri
1646 .layout
1647 .workspaces_mut()
1648 .find_map(|ws| ws.windows_mut().find(|w| w.id().get() == id));
1649 if let Some(window) = window {
1650 if window.rules().opacity.is_some_and(|o| o != 1.) {
1651 window.toggle_ignore_opacity_window_rule();
1652 // FIXME: granular
1653 self.niri.queue_redraw_all();
1654 }
1655 }
1656 }
1657 }
1658 }
1659
1660 fn on_pointer_motion<I: InputBackend>(&mut self, event: I::PointerMotionEvent) {
1661 // We need an output to be able to move the pointer.
1662 if self.niri.global_space.outputs().next().is_none() {
1663 return;
1664 }
1665
1666 let serial = SERIAL_COUNTER.next_serial();
1667
1668 let pointer = self.niri.seat.get_pointer().unwrap();
1669
1670 let pos = pointer.current_location();
1671
1672 // We have an output, so we can compute the new location and focus.
1673 let mut new_pos = pos + event.delta();
1674
1675 // We received an event for the regular pointer, so show it now.
1676 self.niri.pointer_hidden = false;
1677 self.niri.tablet_cursor_location = None;
1678
1679 // Check if we have an active pointer constraint.
1680 //
1681 // FIXME: ideally this should use the pointer focus with up-to-date global location.
1682 let mut pointer_confined = None;
1683 if let Some(under) = &self.niri.pointer_contents.surface {
1684 // No need to check if the pointer focus surface matches, because here we're checking
1685 // for an already-active constraint, and the constraint is deactivated when the focused
1686 // surface changes.
1687 let pos_within_surface = pos - under.1;
1688
1689 let mut pointer_locked = false;
1690 with_pointer_constraint(&under.0, &pointer, |constraint| {
1691 let Some(constraint) = constraint else { return };
1692 if !constraint.is_active() {
1693 return;
1694 }
1695
1696 // Constraint does not apply if not within region.
1697 if let Some(region) = constraint.region() {
1698 if !region.contains(pos_within_surface.to_i32_round()) {
1699 return;
1700 }
1701 }
1702
1703 match &*constraint {
1704 PointerConstraint::Locked(_locked) => {
1705 pointer_locked = true;
1706 }
1707 PointerConstraint::Confined(confine) => {
1708 pointer_confined = Some((under.clone(), confine.region().cloned()));
1709 }
1710 }
1711 });
1712
1713 // If the pointer is locked, only send relative motion.
1714 if pointer_locked {
1715 pointer.relative_motion(
1716 self,
1717 Some(under.clone()),
1718 &RelativeMotionEvent {
1719 delta: event.delta(),
1720 delta_unaccel: event.delta_unaccel(),
1721 utime: event.time(),
1722 },
1723 );
1724
1725 pointer.frame(self);
1726
1727 // I guess a redraw to hide the tablet cursor could be nice? Doesn't matter too
1728 // much here I think.
1729 return;
1730 }
1731 }
1732
1733 if self
1734 .niri
1735 .global_space
1736 .output_under(new_pos)
1737 .next()
1738 .is_none()
1739 {
1740 // We ended up outside the outputs and need to clip the movement.
1741 if let Some(output) = self.niri.global_space.output_under(pos).next() {
1742 // The pointer was previously on some output. Clip the movement against its
1743 // boundaries.
1744 let geom = self.niri.global_space.output_geometry(output).unwrap();
1745 new_pos.x = new_pos
1746 .x
1747 .clamp(geom.loc.x as f64, (geom.loc.x + geom.size.w - 1) as f64);
1748 new_pos.y = new_pos
1749 .y
1750 .clamp(geom.loc.y as f64, (geom.loc.y + geom.size.h - 1) as f64);
1751 } else {
1752 // The pointer was not on any output in the first place. Find one for it.
1753 // Let's do the simple thing and just put it on the first output.
1754 let output = self.niri.global_space.outputs().next().unwrap();
1755 let geom = self.niri.global_space.output_geometry(output).unwrap();
1756 new_pos = center(geom).to_f64();
1757 }
1758 }
1759
1760 if let Some(output) = self.niri.screenshot_ui.selection_output() {
1761 let geom = self.niri.global_space.output_geometry(output).unwrap();
1762 let mut point = (new_pos - geom.loc.to_f64())
1763 .to_physical(output.current_scale().fractional_scale())
1764 .to_i32_round::<i32>();
1765
1766 let size = output.current_mode().unwrap().size;
1767 let transform = output.current_transform();
1768 let size = transform.transform_size(size);
1769 point.x = point.x.clamp(0, size.w - 1);
1770 point.y = point.y.clamp(0, size.h - 1);
1771
1772 self.niri.screenshot_ui.pointer_motion(point);
1773 }
1774
1775 let under = self.niri.contents_under(new_pos);
1776
1777 // Handle confined pointer.
1778 if let Some((focus_surface, region)) = pointer_confined {
1779 let mut prevent = false;
1780
1781 // Prevent the pointer from leaving the focused surface.
1782 if Some(&focus_surface.0) != under.surface.as_ref().map(|(s, _)| s) {
1783 prevent = true;
1784 }
1785
1786 // Prevent the pointer from leaving the confine region, if any.
1787 if let Some(region) = region {
1788 let new_pos_within_surface = new_pos - focus_surface.1;
1789 if !region.contains(new_pos_within_surface.to_i32_round()) {
1790 prevent = true;
1791 }
1792 }
1793
1794 if prevent {
1795 pointer.relative_motion(
1796 self,
1797 Some(focus_surface),
1798 &RelativeMotionEvent {
1799 delta: event.delta(),
1800 delta_unaccel: event.delta_unaccel(),
1801 utime: event.time(),
1802 },
1803 );
1804
1805 pointer.frame(self);
1806
1807 return;
1808 }
1809 }
1810
1811 self.niri.handle_focus_follows_mouse(&under);
1812
1813 self.niri.pointer_contents.clone_from(&under);
1814
1815 pointer.motion(
1816 self,
1817 under.surface.clone(),
1818 &MotionEvent {
1819 location: new_pos,
1820 serial,
1821 time: event.time_msec(),
1822 },
1823 );
1824
1825 pointer.relative_motion(
1826 self,
1827 under.surface,
1828 &RelativeMotionEvent {
1829 delta: event.delta(),
1830 delta_unaccel: event.delta_unaccel(),
1831 utime: event.time(),
1832 },
1833 );
1834
1835 pointer.frame(self);
1836
1837 // Activate a new confinement if necessary.
1838 self.niri.maybe_activate_pointer_constraint();
1839
1840 // Redraw to update the cursor position.
1841 // FIXME: redraw only outputs overlapping the cursor.
1842 self.niri.queue_redraw_all();
1843 }
1844
1845 fn on_pointer_motion_absolute<I: InputBackend>(
1846 &mut self,
1847 event: I::PointerMotionAbsoluteEvent,
1848 ) {
1849 let Some(pos) = self.compute_absolute_location(&event, None).or_else(|| {
1850 self.global_bounding_rectangle().map(|output_geo| {
1851 event.position_transformed(output_geo.size) + output_geo.loc.to_f64()
1852 })
1853 }) else {
1854 return;
1855 };
1856
1857 let serial = SERIAL_COUNTER.next_serial();
1858
1859 let pointer = self.niri.seat.get_pointer().unwrap();
1860
1861 if let Some(output) = self.niri.screenshot_ui.selection_output() {
1862 let geom = self.niri.global_space.output_geometry(output).unwrap();
1863 let mut point = (pos - geom.loc.to_f64())
1864 .to_physical(output.current_scale().fractional_scale())
1865 .to_i32_round::<i32>();
1866
1867 let size = output.current_mode().unwrap().size;
1868 let transform = output.current_transform();
1869 let size = transform.transform_size(size);
1870 point.x = point.x.clamp(0, size.w - 1);
1871 point.y = point.y.clamp(0, size.h - 1);
1872
1873 self.niri.screenshot_ui.pointer_motion(point);
1874 }
1875
1876 let under = self.niri.contents_under(pos);
1877
1878 self.niri.handle_focus_follows_mouse(&under);
1879
1880 self.niri.pointer_contents.clone_from(&under);
1881
1882 pointer.motion(
1883 self,
1884 under.surface,
1885 &MotionEvent {
1886 location: pos,
1887 serial,
1888 time: event.time_msec(),
1889 },
1890 );
1891
1892 pointer.frame(self);
1893
1894 self.niri.maybe_activate_pointer_constraint();
1895
1896 // We moved the pointer, show it.
1897 self.niri.pointer_hidden = false;
1898
1899 // We moved the regular pointer, so show it now.
1900 self.niri.tablet_cursor_location = None;
1901
1902 // Redraw to update the cursor position.
1903 // FIXME: redraw only outputs overlapping the cursor.
1904 self.niri.queue_redraw_all();
1905 }
1906
1907 fn on_pointer_button<I: InputBackend>(&mut self, event: I::PointerButtonEvent) {
1908 let pointer = self.niri.seat.get_pointer().unwrap();
1909
1910 let serial = SERIAL_COUNTER.next_serial();
1911
1912 let button = event.button();
1913
1914 let button_code = event.button_code();
1915
1916 let button_state = event.state();
1917
1918 // Ignore release events for mouse clicks that triggered a bind.
1919 if self.niri.suppressed_buttons.remove(&button_code) {
1920 return;
1921 }
1922
1923 if ButtonState::Pressed == button_state {
1924 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
1925 let modifiers = modifiers_from_state(mods);
1926
1927 if self.niri.mods_with_mouse_binds.contains(&modifiers) {
1928 let comp_mod = self.backend.mod_key();
1929
1930 if let Some(bind) = match button {
1931 Some(MouseButton::Left) => Some(Trigger::MouseLeft),
1932 Some(MouseButton::Right) => Some(Trigger::MouseRight),
1933 Some(MouseButton::Middle) => Some(Trigger::MouseMiddle),
1934 Some(MouseButton::Back) => Some(Trigger::MouseBack),
1935 Some(MouseButton::Forward) => Some(Trigger::MouseForward),
1936 _ => None,
1937 }
1938 .and_then(|trigger| {
1939 let config = self.niri.config.borrow();
1940 let bindings = &config.binds;
1941 find_configured_bind(bindings, comp_mod, trigger, mods)
1942 }) {
1943 self.niri.suppressed_buttons.insert(button_code);
1944 self.handle_bind(bind.clone());
1945 return;
1946 };
1947 }
1948
1949 // We received an event for the regular pointer, so show it now.
1950 self.niri.pointer_hidden = false;
1951 self.niri.tablet_cursor_location = None;
1952
1953 if let Some(mapped) = self.niri.window_under_cursor() {
1954 let window = mapped.window.clone();
1955
1956 // Check if we need to start an interactive move.
1957 if button == Some(MouseButton::Left) && !pointer.is_grabbed() {
1958 let mod_down = match self.backend.mod_key() {
1959 CompositorMod::Super => mods.logo,
1960 CompositorMod::Alt => mods.alt,
1961 };
1962 if mod_down {
1963 let location = pointer.current_location();
1964 let (output, pos_within_output) = self.niri.output_under(location).unwrap();
1965 let output = output.clone();
1966
1967 self.niri.layout.activate_window(&window);
1968
1969 if self.niri.layout.interactive_move_begin(
1970 window.clone(),
1971 &output,
1972 pos_within_output,
1973 ) {
1974 let start_data = PointerGrabStartData {
1975 focus: None,
1976 button: button_code,
1977 location,
1978 };
1979 let grab = MoveGrab::new(start_data, window.clone());
1980 pointer.set_grab(self, grab, serial, Focus::Clear);
1981 self.niri
1982 .cursor_manager
1983 .set_cursor_image(CursorImageStatus::Named(CursorIcon::Move));
1984 }
1985 }
1986 }
1987 // Check if we need to start an interactive resize.
1988 else if button == Some(MouseButton::Right) && !pointer.is_grabbed() {
1989 let mod_down = match self.backend.mod_key() {
1990 CompositorMod::Super => mods.logo,
1991 CompositorMod::Alt => mods.alt,
1992 };
1993 if mod_down {
1994 let location = pointer.current_location();
1995 let (output, pos_within_output) = self.niri.output_under(location).unwrap();
1996 let edges = self
1997 .niri
1998 .layout
1999 .resize_edges_under(output, pos_within_output)
2000 .unwrap();
2001
2002 if !edges.is_empty() {
2003 // See if we got a double resize-click gesture.
2004 // FIXME: deduplicate with resize_request in xdg-shell somehow.
2005 let time = get_monotonic_time();
2006 let last_cell = mapped.last_interactive_resize_start();
2007 let mut last = last_cell.get();
2008 last_cell.set(Some((time, edges)));
2009
2010 // Floating windows don't have either of the double-resize-click
2011 // gestures, so just allow it to resize.
2012 if mapped.is_floating() {
2013 last = None;
2014 last_cell.set(None);
2015 }
2016
2017 if let Some((last_time, last_edges)) = last {
2018 if time.saturating_sub(last_time) <= DOUBLE_CLICK_TIME {
2019 // Allow quick resize after a triple click.
2020 last_cell.set(None);
2021
2022 let intersection = edges.intersection(last_edges);
2023 if intersection.intersects(ResizeEdge::LEFT_RIGHT) {
2024 // FIXME: don't activate once we can pass specific windows
2025 // to actions.
2026 self.niri.layout.activate_window(&window);
2027 self.niri.layout.toggle_full_width();
2028 }
2029 if intersection.intersects(ResizeEdge::TOP_BOTTOM) {
2030 self.niri.layout.activate_window(&window);
2031 self.niri.layout.reset_window_height(Some(&window));
2032 }
2033 // FIXME: granular.
2034 self.niri.queue_redraw_all();
2035 return;
2036 }
2037 }
2038
2039 self.niri.layout.activate_window(&window);
2040
2041 if self
2042 .niri
2043 .layout
2044 .interactive_resize_begin(window.clone(), edges)
2045 {
2046 let start_data = PointerGrabStartData {
2047 focus: None,
2048 button: button_code,
2049 location,
2050 };
2051 let grab = ResizeGrab::new(start_data, window.clone());
2052 pointer.set_grab(self, grab, serial, Focus::Clear);
2053 self.niri.cursor_manager.set_cursor_image(
2054 CursorImageStatus::Named(edges.cursor_icon()),
2055 );
2056 }
2057 }
2058 }
2059 }
2060
2061 self.niri.layout.activate_window(&window);
2062
2063 // FIXME: granular.
2064 self.niri.queue_redraw_all();
2065 } else if let Some(output) = self.niri.output_under_cursor() {
2066 self.niri.layout.activate_output(&output);
2067
2068 // FIXME: granular.
2069 self.niri.queue_redraw_all();
2070 }
2071
2072 if button == Some(MouseButton::Middle) && !pointer.is_grabbed() {
2073 let mod_down = match self.backend.mod_key() {
2074 CompositorMod::Super => mods.logo,
2075 CompositorMod::Alt => mods.alt,
2076 };
2077 if mod_down {
2078 if let Some(output) = self.niri.output_under_cursor() {
2079 let location = pointer.current_location();
2080 let start_data = PointerGrabStartData {
2081 focus: None,
2082 button: button_code,
2083 location,
2084 };
2085 let grab = SpatialMovementGrab::new(start_data, output);
2086 pointer.set_grab(self, grab, serial, Focus::Clear);
2087 self.niri
2088 .cursor_manager
2089 .set_cursor_image(CursorImageStatus::Named(CursorIcon::AllScroll));
2090 }
2091 }
2092 }
2093 };
2094
2095 self.update_pointer_contents();
2096
2097 if ButtonState::Pressed == button_state {
2098 let layer_under = self.niri.pointer_contents.layer.clone();
2099 self.niri.focus_layer_surface_if_on_demand(layer_under);
2100 }
2101
2102 if let Some(button) = button {
2103 let pos = pointer.current_location();
2104 if let Some((output, _)) = self.niri.output_under(pos) {
2105 let output = output.clone();
2106 let geom = self.niri.global_space.output_geometry(&output).unwrap();
2107 let mut point = (pos - geom.loc.to_f64())
2108 .to_physical(output.current_scale().fractional_scale())
2109 .to_i32_round();
2110
2111 let size = output.current_mode().unwrap().size;
2112 let transform = output.current_transform();
2113 let size = transform.transform_size(size);
2114 point.x = min(size.w - 1, point.x);
2115 point.y = min(size.h - 1, point.y);
2116
2117 if self
2118 .niri
2119 .screenshot_ui
2120 .pointer_button(output, point, button, button_state)
2121 {
2122 self.niri.queue_redraw_all();
2123 }
2124 }
2125 }
2126
2127 pointer.button(
2128 self,
2129 &ButtonEvent {
2130 button: button_code,
2131 state: button_state,
2132 serial,
2133 time: event.time_msec(),
2134 },
2135 );
2136 pointer.frame(self);
2137 }
2138
2139 fn on_pointer_axis<I: InputBackend>(&mut self, event: I::PointerAxisEvent) {
2140 let pointer = &self.niri.seat.get_pointer().unwrap();
2141
2142 let source = event.source();
2143
2144 // We received an event for the regular pointer, so show it now. This is also needed for
2145 // update_pointer_contents() below to return the real contents, necessary for the pointer
2146 // axis event to reach the window.
2147 self.niri.pointer_hidden = false;
2148 self.niri.tablet_cursor_location = None;
2149
2150 let horizontal_amount_v120 = event.amount_v120(Axis::Horizontal);
2151 let vertical_amount_v120 = event.amount_v120(Axis::Vertical);
2152
2153 // Handle wheel scroll bindings.
2154 if source == AxisSource::Wheel {
2155 // If we have a scroll bind with current modifiers, then accumulate and don't pass to
2156 // Wayland. If there's no bind, reset the accumulator.
2157 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
2158 let modifiers = modifiers_from_state(mods);
2159 if self.niri.mods_with_wheel_binds.contains(&modifiers) {
2160 let comp_mod = self.backend.mod_key();
2161
2162 let horizontal = horizontal_amount_v120.unwrap_or(0.);
2163 let ticks = self.niri.horizontal_wheel_tracker.accumulate(horizontal);
2164 if ticks != 0 {
2165 let config = self.niri.config.borrow();
2166 let bindings = &config.binds;
2167 let bind_left =
2168 find_configured_bind(bindings, comp_mod, Trigger::WheelScrollLeft, mods);
2169 let bind_right =
2170 find_configured_bind(bindings, comp_mod, Trigger::WheelScrollRight, mods);
2171 drop(config);
2172
2173 if let Some(right) = bind_right {
2174 for _ in 0..ticks {
2175 self.handle_bind(right.clone());
2176 }
2177 }
2178 if let Some(left) = bind_left {
2179 for _ in ticks..0 {
2180 self.handle_bind(left.clone());
2181 }
2182 }
2183 }
2184
2185 let vertical = vertical_amount_v120.unwrap_or(0.);
2186 let ticks = self.niri.vertical_wheel_tracker.accumulate(vertical);
2187 if ticks != 0 {
2188 let config = self.niri.config.borrow();
2189 let bindings = &config.binds;
2190 let bind_up =
2191 find_configured_bind(bindings, comp_mod, Trigger::WheelScrollUp, mods);
2192 let bind_down =
2193 find_configured_bind(bindings, comp_mod, Trigger::WheelScrollDown, mods);
2194 drop(config);
2195
2196 if let Some(down) = bind_down {
2197 for _ in 0..ticks {
2198 self.handle_bind(down.clone());
2199 }
2200 }
2201 if let Some(up) = bind_up {
2202 for _ in ticks..0 {
2203 self.handle_bind(up.clone());
2204 }
2205 }
2206 }
2207
2208 return;
2209 } else {
2210 self.niri.horizontal_wheel_tracker.reset();
2211 self.niri.vertical_wheel_tracker.reset();
2212 }
2213 }
2214
2215 let horizontal_amount = event.amount(Axis::Horizontal);
2216 let vertical_amount = event.amount(Axis::Vertical);
2217
2218 // Handle touchpad scroll bindings.
2219 if source == AxisSource::Finger {
2220 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
2221 let modifiers = modifiers_from_state(mods);
2222 if self.niri.mods_with_finger_scroll_binds.contains(&modifiers) {
2223 let comp_mod = self.backend.mod_key();
2224
2225 let horizontal = horizontal_amount.unwrap_or(0.);
2226 let ticks = self
2227 .niri
2228 .horizontal_finger_scroll_tracker
2229 .accumulate(horizontal);
2230 if ticks != 0 {
2231 let config = self.niri.config.borrow();
2232 let bindings = &config.binds;
2233 let bind_left =
2234 find_configured_bind(bindings, comp_mod, Trigger::TouchpadScrollLeft, mods);
2235 let bind_right = find_configured_bind(
2236 bindings,
2237 comp_mod,
2238 Trigger::TouchpadScrollRight,
2239 mods,
2240 );
2241 drop(config);
2242
2243 if let Some(right) = bind_right {
2244 for _ in 0..ticks {
2245 self.handle_bind(right.clone());
2246 }
2247 }
2248 if let Some(left) = bind_left {
2249 for _ in ticks..0 {
2250 self.handle_bind(left.clone());
2251 }
2252 }
2253 }
2254
2255 let vertical = vertical_amount.unwrap_or(0.);
2256 let ticks = self
2257 .niri
2258 .vertical_finger_scroll_tracker
2259 .accumulate(vertical);
2260 if ticks != 0 {
2261 let config = self.niri.config.borrow();
2262 let bindings = &config.binds;
2263 let bind_up =
2264 find_configured_bind(bindings, comp_mod, Trigger::TouchpadScrollUp, mods);
2265 let bind_down =
2266 find_configured_bind(bindings, comp_mod, Trigger::TouchpadScrollDown, mods);
2267 drop(config);
2268
2269 if let Some(down) = bind_down {
2270 for _ in 0..ticks {
2271 self.handle_bind(down.clone());
2272 }
2273 }
2274 if let Some(up) = bind_up {
2275 for _ in ticks..0 {
2276 self.handle_bind(up.clone());
2277 }
2278 }
2279 }
2280
2281 return;
2282 } else {
2283 self.niri.horizontal_finger_scroll_tracker.reset();
2284 self.niri.vertical_finger_scroll_tracker.reset();
2285 }
2286 }
2287
2288 self.update_pointer_contents();
2289
2290 let scroll_factor = match source {
2291 AxisSource::Wheel => self.niri.config.borrow().input.mouse.scroll_factor,
2292 AxisSource::Finger => self.niri.config.borrow().input.touchpad.scroll_factor,
2293 _ => None,
2294 };
2295 let window_scroll_factor = pointer
2296 .current_focus()
2297 .map(|focused| self.niri.find_root_shell_surface(&focused))
2298 .and_then(|root| self.niri.layout.find_window_and_output(&root).unzip().0)
2299 .and_then(|window| window.rules().scroll_factor);
2300 let scroll_factor =
2301 scroll_factor.map(|x| x.0).unwrap_or(1.) * window_scroll_factor.unwrap_or(1.);
2302
2303 let horizontal_amount = horizontal_amount.unwrap_or_else(|| {
2304 // Winit backend, discrete scrolling.
2305 horizontal_amount_v120.unwrap_or(0.0) / 120. * 15.
2306 }) * scroll_factor;
2307 let vertical_amount = vertical_amount.unwrap_or_else(|| {
2308 // Winit backend, discrete scrolling.
2309 vertical_amount_v120.unwrap_or(0.0) / 120. * 15.
2310 }) * scroll_factor;
2311
2312 let horizontal_amount_v120 = horizontal_amount_v120.map(|x| x * scroll_factor);
2313 let vertical_amount_v120 = vertical_amount_v120.map(|x| x * scroll_factor);
2314
2315 let mut frame = AxisFrame::new(event.time_msec()).source(source);
2316 if horizontal_amount != 0.0 {
2317 frame = frame
2318 .relative_direction(Axis::Horizontal, event.relative_direction(Axis::Horizontal));
2319 frame = frame.value(Axis::Horizontal, horizontal_amount);
2320 if let Some(v120) = horizontal_amount_v120 {
2321 frame = frame.v120(Axis::Horizontal, v120 as i32);
2322 }
2323 }
2324 if vertical_amount != 0.0 {
2325 frame =
2326 frame.relative_direction(Axis::Vertical, event.relative_direction(Axis::Vertical));
2327 frame = frame.value(Axis::Vertical, vertical_amount);
2328 if let Some(v120) = vertical_amount_v120 {
2329 frame = frame.v120(Axis::Vertical, v120 as i32);
2330 }
2331 }
2332
2333 if source == AxisSource::Finger {
2334 if event.amount(Axis::Horizontal) == Some(0.0) {
2335 frame = frame.stop(Axis::Horizontal);
2336 }
2337 if event.amount(Axis::Vertical) == Some(0.0) {
2338 frame = frame.stop(Axis::Vertical);
2339 }
2340 }
2341
2342 pointer.axis(self, frame);
2343 pointer.frame(self);
2344 }
2345
2346 fn on_tablet_tool_axis<I: InputBackend>(&mut self, event: I::TabletToolAxisEvent)
2347 where
2348 I::Device: 'static, // Needed for downcasting.
2349 {
2350 let Some(pos) = self.compute_tablet_position(&event) else {
2351 return;
2352 };
2353
2354 let under = self.niri.contents_under(pos);
2355
2356 let tablet_seat = self.niri.seat.tablet_seat();
2357 let tablet = tablet_seat.get_tablet(&TabletDescriptor::from(&event.device()));
2358 let tool = tablet_seat.get_tool(&event.tool());
2359 if let (Some(tablet), Some(tool)) = (tablet, tool) {
2360 if event.pressure_has_changed() {
2361 tool.pressure(event.pressure());
2362 }
2363 if event.distance_has_changed() {
2364 tool.distance(event.distance());
2365 }
2366 if event.tilt_has_changed() {
2367 tool.tilt(event.tilt());
2368 }
2369 if event.slider_has_changed() {
2370 tool.slider_position(event.slider_position());
2371 }
2372 if event.rotation_has_changed() {
2373 tool.rotation(event.rotation());
2374 }
2375 if event.wheel_has_changed() {
2376 tool.wheel(event.wheel_delta(), event.wheel_delta_discrete());
2377 }
2378
2379 tool.motion(
2380 pos,
2381 under.surface,
2382 &tablet,
2383 SERIAL_COUNTER.next_serial(),
2384 event.time_msec(),
2385 );
2386
2387 self.niri.pointer_hidden = false;
2388 self.niri.tablet_cursor_location = Some(pos);
2389 }
2390
2391 // Redraw to update the cursor position.
2392 // FIXME: redraw only outputs overlapping the cursor.
2393 self.niri.queue_redraw_all();
2394 }
2395
2396 fn on_tablet_tool_tip<I: InputBackend>(&mut self, event: I::TabletToolTipEvent) {
2397 let tool = self.niri.seat.tablet_seat().get_tool(&event.tool());
2398
2399 if let Some(tool) = tool {
2400 match event.tip_state() {
2401 TabletToolTipState::Down => {
2402 let serial = SERIAL_COUNTER.next_serial();
2403 tool.tip_down(serial, event.time_msec());
2404
2405 if let Some(pos) = self.niri.tablet_cursor_location {
2406 let under = self.niri.contents_under(pos);
2407 if let Some(window) = under.window {
2408 self.niri.layout.activate_window(&window);
2409
2410 // FIXME: granular.
2411 self.niri.queue_redraw_all();
2412 } else if let Some(output) = under.output {
2413 self.niri.layout.activate_output(&output);
2414
2415 // FIXME: granular.
2416 self.niri.queue_redraw_all();
2417 }
2418 self.niri.focus_layer_surface_if_on_demand(under.layer);
2419 }
2420 }
2421 TabletToolTipState::Up => {
2422 tool.tip_up(event.time_msec());
2423 }
2424 }
2425 }
2426 }
2427
2428 fn on_tablet_tool_proximity<I: InputBackend>(&mut self, event: I::TabletToolProximityEvent)
2429 where
2430 I::Device: 'static, // Needed for downcasting.
2431 {
2432 let Some(pos) = self.compute_tablet_position(&event) else {
2433 return;
2434 };
2435
2436 let under = self.niri.contents_under(pos);
2437
2438 let tablet_seat = self.niri.seat.tablet_seat();
2439 let display_handle = self.niri.display_handle.clone();
2440 let tool = tablet_seat.add_tool::<Self>(self, &display_handle, &event.tool());
2441 let tablet = tablet_seat.get_tablet(&TabletDescriptor::from(&event.device()));
2442 if let Some(tablet) = tablet {
2443 match event.state() {
2444 ProximityState::In => {
2445 if let Some(under) = under.surface {
2446 tool.proximity_in(
2447 pos,
2448 under,
2449 &tablet,
2450 SERIAL_COUNTER.next_serial(),
2451 event.time_msec(),
2452 );
2453 }
2454 self.niri.pointer_hidden = false;
2455 self.niri.tablet_cursor_location = Some(pos);
2456 }
2457 ProximityState::Out => {
2458 tool.proximity_out(event.time_msec());
2459
2460 // Move the mouse pointer here to avoid discontinuity.
2461 //
2462 // Plus, Wayland SDL2 currently warps the pointer into some weird
2463 // location on proximity out, so this should help it a little.
2464 if let Some(pos) = self.niri.tablet_cursor_location {
2465 self.move_cursor(pos);
2466 }
2467
2468 self.niri.pointer_hidden = false;
2469 self.niri.tablet_cursor_location = None;
2470 }
2471 }
2472
2473 // FIXME: granular.
2474 self.niri.queue_redraw_all();
2475 }
2476 }
2477
2478 fn on_tablet_tool_button<I: InputBackend>(&mut self, event: I::TabletToolButtonEvent) {
2479 let tool = self.niri.seat.tablet_seat().get_tool(&event.tool());
2480
2481 if let Some(tool) = tool {
2482 tool.button(
2483 event.button(),
2484 event.button_state(),
2485 SERIAL_COUNTER.next_serial(),
2486 event.time_msec(),
2487 );
2488 }
2489 }
2490
2491 fn on_gesture_swipe_begin<I: InputBackend>(&mut self, event: I::GestureSwipeBeginEvent) {
2492 if event.fingers() == 3 {
2493 self.niri.gesture_swipe_3f_cumulative = Some((0., 0.));
2494
2495 // We handled this event.
2496 return;
2497 }
2498
2499 let serial = SERIAL_COUNTER.next_serial();
2500 let pointer = self.niri.seat.get_pointer().unwrap();
2501
2502 if self.update_pointer_contents() {
2503 pointer.frame(self);
2504 }
2505
2506 pointer.gesture_swipe_begin(
2507 self,
2508 &GestureSwipeBeginEvent {
2509 serial,
2510 time: event.time_msec(),
2511 fingers: event.fingers(),
2512 },
2513 );
2514 }
2515
2516 fn on_gesture_swipe_update<I: InputBackend + 'static>(
2517 &mut self,
2518 event: I::GestureSwipeUpdateEvent,
2519 ) where
2520 I::Device: 'static,
2521 {
2522 let mut delta_x = event.delta_x();
2523 let mut delta_y = event.delta_y();
2524
2525 if let Some(libinput_event) =
2526 (&event as &dyn Any).downcast_ref::<input::event::gesture::GestureSwipeUpdateEvent>()
2527 {
2528 delta_x = libinput_event.dx_unaccelerated();
2529 delta_y = libinput_event.dy_unaccelerated();
2530 }
2531
2532 let device = event.device();
2533 if let Some(device) = (&device as &dyn Any).downcast_ref::<input::Device>() {
2534 if device.config_scroll_natural_scroll_enabled() {
2535 delta_x = -delta_x;
2536 delta_y = -delta_y;
2537 }
2538 }
2539
2540 if let Some((cx, cy)) = &mut self.niri.gesture_swipe_3f_cumulative {
2541 *cx += delta_x;
2542 *cy += delta_y;
2543
2544 // Check if the gesture moved far enough to decide. Threshold copied from GNOME Shell.
2545 let (cx, cy) = (*cx, *cy);
2546 if cx * cx + cy * cy >= 16. * 16. {
2547 self.niri.gesture_swipe_3f_cumulative = None;
2548
2549 if let Some(output) = self.niri.output_under_cursor() {
2550 if cx.abs() > cy.abs() {
2551 self.niri.layout.view_offset_gesture_begin(&output, true);
2552 } else {
2553 self.niri
2554 .layout
2555 .workspace_switch_gesture_begin(&output, true);
2556 }
2557 }
2558 }
2559 }
2560
2561 let timestamp = Duration::from_micros(event.time());
2562
2563 let mut handled = false;
2564 let res = self
2565 .niri
2566 .layout
2567 .workspace_switch_gesture_update(delta_y, timestamp, true);
2568 if let Some(output) = res {
2569 if let Some(output) = output {
2570 self.niri.queue_redraw(&output);
2571 }
2572 handled = true;
2573 }
2574
2575 let res = self
2576 .niri
2577 .layout
2578 .view_offset_gesture_update(delta_x, timestamp, true);
2579 if let Some(output) = res {
2580 if let Some(output) = output {
2581 self.niri.queue_redraw(&output);
2582 }
2583 handled = true;
2584 }
2585
2586 if handled {
2587 // We handled this event.
2588 return;
2589 }
2590
2591 let pointer = self.niri.seat.get_pointer().unwrap();
2592
2593 if self.update_pointer_contents() {
2594 pointer.frame(self);
2595 }
2596
2597 pointer.gesture_swipe_update(
2598 self,
2599 &GestureSwipeUpdateEvent {
2600 time: event.time_msec(),
2601 delta: event.delta(),
2602 },
2603 );
2604 }
2605
2606 fn on_gesture_swipe_end<I: InputBackend>(&mut self, event: I::GestureSwipeEndEvent) {
2607 self.niri.gesture_swipe_3f_cumulative = None;
2608
2609 let mut handled = false;
2610 let res = self
2611 .niri
2612 .layout
2613 .workspace_switch_gesture_end(event.cancelled(), Some(true));
2614 if let Some(output) = res {
2615 self.niri.queue_redraw(&output);
2616 handled = true;
2617 }
2618
2619 let res = self
2620 .niri
2621 .layout
2622 .view_offset_gesture_end(event.cancelled(), Some(true));
2623 if let Some(output) = res {
2624 self.niri.queue_redraw(&output);
2625 handled = true;
2626 }
2627
2628 if handled {
2629 // We handled this event.
2630 return;
2631 }
2632
2633 let serial = SERIAL_COUNTER.next_serial();
2634 let pointer = self.niri.seat.get_pointer().unwrap();
2635
2636 if self.update_pointer_contents() {
2637 pointer.frame(self);
2638 }
2639
2640 pointer.gesture_swipe_end(
2641 self,
2642 &GestureSwipeEndEvent {
2643 serial,
2644 time: event.time_msec(),
2645 cancelled: event.cancelled(),
2646 },
2647 );
2648 }
2649
2650 fn on_gesture_pinch_begin<I: InputBackend>(&mut self, event: I::GesturePinchBeginEvent) {
2651 let serial = SERIAL_COUNTER.next_serial();
2652 let pointer = self.niri.seat.get_pointer().unwrap();
2653
2654 if self.update_pointer_contents() {
2655 pointer.frame(self);
2656 }
2657
2658 pointer.gesture_pinch_begin(
2659 self,
2660 &GesturePinchBeginEvent {
2661 serial,
2662 time: event.time_msec(),
2663 fingers: event.fingers(),
2664 },
2665 );
2666 }
2667
2668 fn on_gesture_pinch_update<I: InputBackend>(&mut self, event: I::GesturePinchUpdateEvent) {
2669 let pointer = self.niri.seat.get_pointer().unwrap();
2670
2671 if self.update_pointer_contents() {
2672 pointer.frame(self);
2673 }
2674
2675 pointer.gesture_pinch_update(
2676 self,
2677 &GesturePinchUpdateEvent {
2678 time: event.time_msec(),
2679 delta: event.delta(),
2680 scale: event.scale(),
2681 rotation: event.rotation(),
2682 },
2683 );
2684 }
2685
2686 fn on_gesture_pinch_end<I: InputBackend>(&mut self, event: I::GesturePinchEndEvent) {
2687 let serial = SERIAL_COUNTER.next_serial();
2688 let pointer = self.niri.seat.get_pointer().unwrap();
2689
2690 if self.update_pointer_contents() {
2691 pointer.frame(self);
2692 }
2693
2694 pointer.gesture_pinch_end(
2695 self,
2696 &GesturePinchEndEvent {
2697 serial,
2698 time: event.time_msec(),
2699 cancelled: event.cancelled(),
2700 },
2701 );
2702 }
2703
2704 fn on_gesture_hold_begin<I: InputBackend>(&mut self, event: I::GestureHoldBeginEvent) {
2705 let serial = SERIAL_COUNTER.next_serial();
2706 let pointer = self.niri.seat.get_pointer().unwrap();
2707
2708 if self.update_pointer_contents() {
2709 pointer.frame(self);
2710 }
2711
2712 pointer.gesture_hold_begin(
2713 self,
2714 &GestureHoldBeginEvent {
2715 serial,
2716 time: event.time_msec(),
2717 fingers: event.fingers(),
2718 },
2719 );
2720 }
2721
2722 fn on_gesture_hold_end<I: InputBackend>(&mut self, event: I::GestureHoldEndEvent) {
2723 let serial = SERIAL_COUNTER.next_serial();
2724 let pointer = self.niri.seat.get_pointer().unwrap();
2725
2726 if self.update_pointer_contents() {
2727 pointer.frame(self);
2728 }
2729
2730 pointer.gesture_hold_end(
2731 self,
2732 &GestureHoldEndEvent {
2733 serial,
2734 time: event.time_msec(),
2735 cancelled: event.cancelled(),
2736 },
2737 );
2738 }
2739
2740 fn compute_absolute_location<I: InputBackend>(
2741 &self,
2742 evt: &impl AbsolutePositionEvent<I>,
2743 fallback_output: Option<&Output>,
2744 ) -> Option<Point<f64, Logical>> {
2745 let output = evt.device().output(self);
2746 let output = output.as_ref().or(fallback_output)?;
2747 let output_geo = self.niri.global_space.output_geometry(output).unwrap();
2748 let transform = output.current_transform();
2749 let size = transform.invert().transform_size(output_geo.size);
2750 Some(
2751 transform.transform_point_in(evt.position_transformed(size), &size.to_f64())
2752 + output_geo.loc.to_f64(),
2753 )
2754 }
2755
2756 /// Computes the cursor position for the touch event.
2757 ///
2758 /// This function handles the touch output mapping, as well as coordinate transform
2759 fn compute_touch_location<I: InputBackend>(
2760 &self,
2761 evt: &impl AbsolutePositionEvent<I>,
2762 ) -> Option<Point<f64, Logical>> {
2763 self.compute_absolute_location(evt, self.niri.output_for_touch())
2764 }
2765
2766 fn on_touch_down<I: InputBackend>(&mut self, evt: I::TouchDownEvent) {
2767 let Some(handle) = self.niri.seat.get_touch() else {
2768 return;
2769 };
2770 let Some(touch_location) = self.compute_touch_location(&evt) else {
2771 return;
2772 };
2773
2774 let serial = SERIAL_COUNTER.next_serial();
2775
2776 let under = self.niri.contents_under(touch_location);
2777
2778 if !handle.is_grabbed() {
2779 if let Some(window) = under.window {
2780 self.niri.layout.activate_window(&window);
2781
2782 // Check if we need to start an interactive move.
2783 let mods = self.niri.seat.get_keyboard().unwrap().modifier_state();
2784 let mod_down = match self.backend.mod_key() {
2785 CompositorMod::Super => mods.logo,
2786 CompositorMod::Alt => mods.alt,
2787 };
2788 if mod_down {
2789 let (output, pos_within_output) =
2790 self.niri.output_under(touch_location).unwrap();
2791 let output = output.clone();
2792
2793 if self.niri.layout.interactive_move_begin(
2794 window.clone(),
2795 &output,
2796 pos_within_output,
2797 ) {
2798 let start_data = TouchGrabStartData {
2799 focus: None,
2800 slot: evt.slot(),
2801 location: touch_location,
2802 };
2803 let grab = TouchMoveGrab::new(start_data, window.clone());
2804 handle.set_grab(self, grab, serial);
2805 }
2806 }
2807
2808 // FIXME: granular.
2809 self.niri.queue_redraw_all();
2810 } else if let Some(output) = under.output {
2811 self.niri.layout.activate_output(&output);
2812
2813 // FIXME: granular.
2814 self.niri.queue_redraw_all();
2815 }
2816 self.niri.focus_layer_surface_if_on_demand(under.layer);
2817 };
2818
2819 handle.down(
2820 self,
2821 under.surface,
2822 &DownEvent {
2823 slot: evt.slot(),
2824 location: touch_location,
2825 serial,
2826 time: evt.time_msec(),
2827 },
2828 );
2829
2830 // We're using touch, hide the pointer.
2831 self.niri.pointer_hidden = true;
2832 }
2833 fn on_touch_up<I: InputBackend>(&mut self, evt: I::TouchUpEvent) {
2834 let Some(handle) = self.niri.seat.get_touch() else {
2835 return;
2836 };
2837 let serial = SERIAL_COUNTER.next_serial();
2838 handle.up(
2839 self,
2840 &UpEvent {
2841 slot: evt.slot(),
2842 serial,
2843 time: evt.time_msec(),
2844 },
2845 )
2846 }
2847 fn on_touch_motion<I: InputBackend>(&mut self, evt: I::TouchMotionEvent) {
2848 let Some(handle) = self.niri.seat.get_touch() else {
2849 return;
2850 };
2851 let Some(touch_location) = self.compute_touch_location(&evt) else {
2852 return;
2853 };
2854 let under = self.niri.contents_under(touch_location);
2855 handle.motion(
2856 self,
2857 under.surface,
2858 &TouchMotionEvent {
2859 slot: evt.slot(),
2860 location: touch_location,
2861 time: evt.time_msec(),
2862 },
2863 );
2864 }
2865 fn on_touch_frame<I: InputBackend>(&mut self, _evt: I::TouchFrameEvent) {
2866 let Some(handle) = self.niri.seat.get_touch() else {
2867 return;
2868 };
2869 handle.frame(self);
2870 }
2871 fn on_touch_cancel<I: InputBackend>(&mut self, _evt: I::TouchCancelEvent) {
2872 let Some(handle) = self.niri.seat.get_touch() else {
2873 return;
2874 };
2875 handle.cancel(self);
2876 }
2877
2878 fn on_switch_toggle<I: InputBackend>(&mut self, evt: I::SwitchToggleEvent) {
2879 let Some(switch) = evt.switch() else {
2880 return;
2881 };
2882
2883 if switch == Switch::Lid {
2884 let is_closed = evt.state() == SwitchState::On;
2885 debug!("lid switch {}", if is_closed { "closed" } else { "opened" });
2886 self.niri.is_lid_closed = is_closed;
2887 self.backend.on_output_config_changed(&mut self.niri);
2888 }
2889
2890 let action = {
2891 let bindings = &self.niri.config.borrow().switch_events;
2892 find_configured_switch_action(bindings, switch, evt.state())
2893 };
2894
2895 if let Some(action) = action {
2896 self.do_action(action, true);
2897 }
2898 }
2899}
2900
2901/// Check whether the key should be intercepted and mark intercepted
2902/// pressed keys as `suppressed`, thus preventing `releases` corresponding
2903/// to them from being delivered.
2904#[allow(clippy::too_many_arguments)]
2905fn should_intercept_key(
2906 suppressed_keys: &mut HashSet<Keycode>,
2907 bindings: &Binds,
2908 comp_mod: CompositorMod,
2909 key_code: Keycode,
2910 modified: Keysym,
2911 raw: Option<Keysym>,
2912 pressed: bool,
2913 mods: ModifiersState,
2914 screenshot_ui: &ScreenshotUi,
2915 disable_power_key_handling: bool,
2916 is_inhibiting_shortcuts: bool,
2917) -> FilterResult<Option<Bind>> {
2918 // Actions are only triggered on presses, release of the key
2919 // shouldn't try to intercept anything unless we have marked
2920 // the key to suppress.
2921 if !pressed && !suppressed_keys.contains(&key_code) {
2922 return FilterResult::Forward;
2923 }
2924
2925 let mut final_bind = find_bind(
2926 bindings,
2927 comp_mod,
2928 modified,
2929 raw,
2930 mods,
2931 disable_power_key_handling,
2932 );
2933
2934 // Allow only a subset of compositor actions while the screenshot UI is open, since the user
2935 // cannot see the screen.
2936 if screenshot_ui.is_open() {
2937 let mut use_screenshot_ui_action = true;
2938
2939 if let Some(bind) = &final_bind {
2940 if allowed_during_screenshot(&bind.action) {
2941 use_screenshot_ui_action = false;
2942 }
2943 }
2944
2945 if use_screenshot_ui_action {
2946 if let Some(raw) = raw {
2947 final_bind = screenshot_ui.action(raw, mods).map(|action| Bind {
2948 key: Key {
2949 trigger: Trigger::Keysym(raw),
2950 // Not entirely correct but it doesn't matter in how we currently use it.
2951 modifiers: Modifiers::empty(),
2952 },
2953 action,
2954 repeat: true,
2955 cooldown: None,
2956 allow_when_locked: false,
2957 // The screenshot UI owns the focus anyway, so this doesn't really matter.
2958 // But logically, nothing can inhibit its actions. Only opening it can be
2959 // inhibited.
2960 allow_inhibiting: false,
2961 });
2962 }
2963 }
2964 }
2965
2966 match (final_bind, pressed) {
2967 (Some(bind), true) => {
2968 if is_inhibiting_shortcuts && bind.allow_inhibiting {
2969 FilterResult::Forward
2970 } else {
2971 suppressed_keys.insert(key_code);
2972 FilterResult::Intercept(Some(bind))
2973 }
2974 }
2975 (_, false) => {
2976 // By this point, we know that the key was suppressed on press. Even if we're inhibiting
2977 // shortcuts, we should still suppress the release.
2978 // But we don't need to check for shortcuts inhibition here, because
2979 // if it was inhibited on press (forwarded to the client), it wouldn't be suppressed,
2980 // so the release would already have been forwarded at the start of this function.
2981 suppressed_keys.remove(&key_code);
2982 FilterResult::Intercept(None)
2983 }
2984 (None, true) => FilterResult::Forward,
2985 }
2986}
2987
2988fn find_bind(
2989 bindings: &Binds,
2990 comp_mod: CompositorMod,
2991 modified: Keysym,
2992 raw: Option<Keysym>,
2993 mods: ModifiersState,
2994 disable_power_key_handling: bool,
2995) -> Option<Bind> {
2996 use keysyms::*;
2997
2998 // Handle hardcoded binds.
2999 #[allow(non_upper_case_globals)] // wat
3000 let hardcoded_action = match modified.raw() {
3001 modified @ KEY_XF86Switch_VT_1..=KEY_XF86Switch_VT_12 => {
3002 let vt = (modified - KEY_XF86Switch_VT_1 + 1) as i32;
3003 Some(Action::ChangeVt(vt))
3004 }
3005 KEY_XF86PowerOff if !disable_power_key_handling => Some(Action::Suspend),
3006 _ => None,
3007 };
3008
3009 if let Some(action) = hardcoded_action {
3010 return Some(Bind {
3011 key: Key {
3012 // Not entirely correct but it doesn't matter in how we currently use it.
3013 trigger: Trigger::Keysym(modified),
3014 modifiers: Modifiers::empty(),
3015 },
3016 action,
3017 repeat: true,
3018 cooldown: None,
3019 allow_when_locked: false,
3020 // In a worst-case scenario, the user has no way to unlock the compositor and a
3021 // misbehaving client has a keyboard shortcuts inhibitor, "jailing" the user.
3022 // The user must always be able to change VTs to recover from such a situation.
3023 // It also makes no sense to inhibit the default power key handling.
3024 // Hardcoded binds must never be inhibited.
3025 allow_inhibiting: false,
3026 });
3027 }
3028
3029 let trigger = Trigger::Keysym(raw?);
3030 find_configured_bind(bindings, comp_mod, trigger, mods)
3031}
3032
3033fn find_configured_bind(
3034 bindings: &Binds,
3035 comp_mod: CompositorMod,
3036 trigger: Trigger,
3037 mods: ModifiersState,
3038) -> Option<Bind> {
3039 // Handle configured binds.
3040 let mut modifiers = modifiers_from_state(mods);
3041
3042 let (mod_down, comp_mod) = match comp_mod {
3043 CompositorMod::Super => (mods.logo, Modifiers::SUPER),
3044 CompositorMod::Alt => (mods.alt, Modifiers::ALT),
3045 };
3046 if mod_down {
3047 modifiers |= Modifiers::COMPOSITOR;
3048 }
3049
3050 for bind in &bindings.0 {
3051 if bind.key.trigger != trigger {
3052 continue;
3053 }
3054
3055 let mut bind_modifiers = bind.key.modifiers;
3056 if bind_modifiers.contains(Modifiers::COMPOSITOR) {
3057 bind_modifiers |= comp_mod;
3058 } else if bind_modifiers.contains(comp_mod) {
3059 bind_modifiers |= Modifiers::COMPOSITOR;
3060 }
3061
3062 if bind_modifiers == modifiers {
3063 return Some(bind.clone());
3064 }
3065 }
3066
3067 None
3068}
3069
3070fn find_configured_switch_action(
3071 bindings: &SwitchBinds,
3072 switch: Switch,
3073 state: SwitchState,
3074) -> Option<Action> {
3075 let switch_action = match (switch, state) {
3076 (Switch::Lid, SwitchState::Off) => &bindings.lid_open,
3077 (Switch::Lid, SwitchState::On) => &bindings.lid_close,
3078 (Switch::TabletMode, SwitchState::Off) => &bindings.tablet_mode_off,
3079 (Switch::TabletMode, SwitchState::On) => &bindings.tablet_mode_on,
3080 _ => unreachable!(),
3081 };
3082 switch_action
3083 .as_ref()
3084 .map(|switch_action| Action::Spawn(switch_action.spawn.clone()))
3085}
3086
3087fn modifiers_from_state(mods: ModifiersState) -> Modifiers {
3088 let mut modifiers = Modifiers::empty();
3089 if mods.ctrl {
3090 modifiers |= Modifiers::CTRL;
3091 }
3092 if mods.shift {
3093 modifiers |= Modifiers::SHIFT;
3094 }
3095 if mods.alt {
3096 modifiers |= Modifiers::ALT;
3097 }
3098 if mods.logo {
3099 modifiers |= Modifiers::SUPER;
3100 }
3101 if mods.iso_level3_shift {
3102 modifiers |= Modifiers::ISO_LEVEL3_SHIFT;
3103 }
3104 if mods.iso_level5_shift {
3105 modifiers |= Modifiers::ISO_LEVEL5_SHIFT;
3106 }
3107 modifiers
3108}
3109
3110fn should_activate_monitors<I: InputBackend>(event: &InputEvent<I>) -> bool {
3111 match event {
3112 InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true,
3113 InputEvent::PointerButton { event } if event.state() == ButtonState::Pressed => true,
3114 InputEvent::PointerMotion { .. }
3115 | InputEvent::PointerMotionAbsolute { .. }
3116 | InputEvent::PointerAxis { .. }
3117 | InputEvent::GestureSwipeBegin { .. }
3118 | InputEvent::GesturePinchBegin { .. }
3119 | InputEvent::GestureHoldBegin { .. }
3120 | InputEvent::TouchDown { .. }
3121 | InputEvent::TouchMotion { .. }
3122 | InputEvent::TabletToolAxis { .. }
3123 | InputEvent::TabletToolProximity { .. }
3124 | InputEvent::TabletToolTip { .. }
3125 | InputEvent::TabletToolButton { .. } => true,
3126 // Ignore events like device additions and removals, key releases, gesture ends.
3127 _ => false,
3128 }
3129}
3130
3131fn should_hide_hotkey_overlay<I: InputBackend>(event: &InputEvent<I>) -> bool {
3132 match event {
3133 InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true,
3134 InputEvent::PointerButton { event } if event.state() == ButtonState::Pressed => true,
3135 InputEvent::PointerAxis { .. }
3136 | InputEvent::GestureSwipeBegin { .. }
3137 | InputEvent::GesturePinchBegin { .. }
3138 | InputEvent::TouchDown { .. }
3139 | InputEvent::TouchMotion { .. }
3140 | InputEvent::TabletToolTip { .. }
3141 | InputEvent::TabletToolButton { .. } => true,
3142 _ => false,
3143 }
3144}
3145
3146fn should_hide_exit_confirm_dialog<I: InputBackend>(event: &InputEvent<I>) -> bool {
3147 match event {
3148 InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true,
3149 InputEvent::PointerButton { event } if event.state() == ButtonState::Pressed => true,
3150 InputEvent::PointerAxis { .. }
3151 | InputEvent::GestureSwipeBegin { .. }
3152 | InputEvent::GesturePinchBegin { .. }
3153 | InputEvent::TouchDown { .. }
3154 | InputEvent::TouchMotion { .. }
3155 | InputEvent::TabletToolTip { .. }
3156 | InputEvent::TabletToolButton { .. } => true,
3157 _ => false,
3158 }
3159}
3160
3161fn should_notify_activity<I: InputBackend>(event: &InputEvent<I>) -> bool {
3162 !matches!(
3163 event,
3164 InputEvent::DeviceAdded { .. } | InputEvent::DeviceRemoved { .. }
3165 )
3166}
3167
3168fn should_reset_pointer_inactivity_timer<I: InputBackend>(event: &InputEvent<I>) -> bool {
3169 matches!(
3170 event,
3171 InputEvent::PointerAxis { .. }
3172 | InputEvent::PointerButton { .. }
3173 | InputEvent::PointerMotion { .. }
3174 | InputEvent::PointerMotionAbsolute { .. }
3175 | InputEvent::TabletToolAxis { .. }
3176 | InputEvent::TabletToolButton { .. }
3177 | InputEvent::TabletToolProximity { .. }
3178 | InputEvent::TabletToolTip { .. }
3179 )
3180}
3181
3182fn allowed_when_locked(action: &Action) -> bool {
3183 matches!(
3184 action,
3185 Action::Quit(_)
3186 | Action::ChangeVt(_)
3187 | Action::Suspend
3188 | Action::PowerOffMonitors
3189 | Action::PowerOnMonitors
3190 | Action::SwitchLayout(_)
3191 | Action::ToggleKeyboardShortcutsInhibit
3192 )
3193}
3194
3195fn allowed_during_screenshot(action: &Action) -> bool {
3196 matches!(
3197 action,
3198 Action::Quit(_)
3199 | Action::ChangeVt(_)
3200 | Action::Suspend
3201 | Action::PowerOffMonitors
3202 | Action::PowerOnMonitors
3203 )
3204}
3205
3206pub fn apply_libinput_settings(config: &niri_config::Input, device: &mut input::Device) {
3207 // According to Mutter code, this setting is specific to touchpads.
3208 let is_touchpad = device.config_tap_finger_count() > 0;
3209 if is_touchpad {
3210 let c = &config.touchpad;
3211 let _ = device.config_send_events_set_mode(if c.off {
3212 input::SendEventsMode::DISABLED
3213 } else if c.disabled_on_external_mouse {
3214 input::SendEventsMode::DISABLED_ON_EXTERNAL_MOUSE
3215 } else {
3216 input::SendEventsMode::ENABLED
3217 });
3218 let _ = device.config_tap_set_enabled(c.tap);
3219 let _ = device.config_dwt_set_enabled(c.dwt);
3220 let _ = device.config_dwtp_set_enabled(c.dwtp);
3221 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
3222 let _ = device.config_accel_set_speed(c.accel_speed);
3223 let _ = device.config_left_handed_set(c.left_handed);
3224 let _ = device.config_middle_emulation_set_enabled(c.middle_emulation);
3225
3226 if let Some(accel_profile) = c.accel_profile {
3227 let _ = device.config_accel_set_profile(accel_profile.into());
3228 } else if let Some(default) = device.config_accel_default_profile() {
3229 let _ = device.config_accel_set_profile(default);
3230 }
3231
3232 if let Some(method) = c.scroll_method {
3233 let _ = device.config_scroll_set_method(method.into());
3234
3235 if method == niri_config::ScrollMethod::OnButtonDown {
3236 if let Some(button) = c.scroll_button {
3237 let _ = device.config_scroll_set_button(button);
3238 }
3239 }
3240 } else if let Some(default) = device.config_scroll_default_method() {
3241 let _ = device.config_scroll_set_method(default);
3242
3243 if default == input::ScrollMethod::OnButtonDown {
3244 if let Some(button) = c.scroll_button {
3245 let _ = device.config_scroll_set_button(button);
3246 }
3247 }
3248 }
3249
3250 if let Some(tap_button_map) = c.tap_button_map {
3251 let _ = device.config_tap_set_button_map(tap_button_map.into());
3252 } else if let Some(default) = device.config_tap_default_button_map() {
3253 let _ = device.config_tap_set_button_map(default);
3254 }
3255
3256 if let Some(method) = c.click_method {
3257 let _ = device.config_click_set_method(method.into());
3258 } else if let Some(default) = device.config_click_default_method() {
3259 let _ = device.config_click_set_method(default);
3260 }
3261 }
3262
3263 // This is how Mutter tells apart mice.
3264 let mut is_trackball = false;
3265 let mut is_trackpoint = false;
3266 if let Some(udev_device) = unsafe { device.udev_device() } {
3267 if udev_device.property_value("ID_INPUT_TRACKBALL").is_some() {
3268 is_trackball = true;
3269 }
3270 if udev_device
3271 .property_value("ID_INPUT_POINTINGSTICK")
3272 .is_some()
3273 {
3274 is_trackpoint = true;
3275 }
3276 }
3277
3278 let is_mouse = device.has_capability(input::DeviceCapability::Pointer)
3279 && !is_touchpad
3280 && !is_trackball
3281 && !is_trackpoint;
3282 if is_mouse {
3283 let c = &config.mouse;
3284 let _ = device.config_send_events_set_mode(if c.off {
3285 input::SendEventsMode::DISABLED
3286 } else {
3287 input::SendEventsMode::ENABLED
3288 });
3289 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
3290 let _ = device.config_accel_set_speed(c.accel_speed);
3291 let _ = device.config_left_handed_set(c.left_handed);
3292 let _ = device.config_middle_emulation_set_enabled(c.middle_emulation);
3293
3294 if let Some(accel_profile) = c.accel_profile {
3295 let _ = device.config_accel_set_profile(accel_profile.into());
3296 } else if let Some(default) = device.config_accel_default_profile() {
3297 let _ = device.config_accel_set_profile(default);
3298 }
3299
3300 if let Some(method) = c.scroll_method {
3301 let _ = device.config_scroll_set_method(method.into());
3302
3303 if method == niri_config::ScrollMethod::OnButtonDown {
3304 if let Some(button) = c.scroll_button {
3305 let _ = device.config_scroll_set_button(button);
3306 }
3307 }
3308 } else if let Some(default) = device.config_scroll_default_method() {
3309 let _ = device.config_scroll_set_method(default);
3310
3311 if default == input::ScrollMethod::OnButtonDown {
3312 if let Some(button) = c.scroll_button {
3313 let _ = device.config_scroll_set_button(button);
3314 }
3315 }
3316 }
3317 }
3318
3319 if is_trackball {
3320 let c = &config.trackball;
3321 let _ = device.config_send_events_set_mode(if c.off {
3322 input::SendEventsMode::DISABLED
3323 } else {
3324 input::SendEventsMode::ENABLED
3325 });
3326 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
3327 let _ = device.config_accel_set_speed(c.accel_speed);
3328 let _ = device.config_middle_emulation_set_enabled(c.middle_emulation);
3329 let _ = device.config_left_handed_set(c.left_handed);
3330
3331 if let Some(accel_profile) = c.accel_profile {
3332 let _ = device.config_accel_set_profile(accel_profile.into());
3333 } else if let Some(default) = device.config_accel_default_profile() {
3334 let _ = device.config_accel_set_profile(default);
3335 }
3336
3337 if let Some(method) = c.scroll_method {
3338 let _ = device.config_scroll_set_method(method.into());
3339
3340 if method == niri_config::ScrollMethod::OnButtonDown {
3341 if let Some(button) = c.scroll_button {
3342 let _ = device.config_scroll_set_button(button);
3343 }
3344 }
3345 } else if let Some(default) = device.config_scroll_default_method() {
3346 let _ = device.config_scroll_set_method(default);
3347
3348 if default == input::ScrollMethod::OnButtonDown {
3349 if let Some(button) = c.scroll_button {
3350 let _ = device.config_scroll_set_button(button);
3351 }
3352 }
3353 }
3354 }
3355
3356 if is_trackpoint {
3357 let c = &config.trackpoint;
3358 let _ = device.config_send_events_set_mode(if c.off {
3359 input::SendEventsMode::DISABLED
3360 } else {
3361 input::SendEventsMode::ENABLED
3362 });
3363 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
3364 let _ = device.config_accel_set_speed(c.accel_speed);
3365 let _ = device.config_middle_emulation_set_enabled(c.middle_emulation);
3366
3367 if let Some(accel_profile) = c.accel_profile {
3368 let _ = device.config_accel_set_profile(accel_profile.into());
3369 } else if let Some(default) = device.config_accel_default_profile() {
3370 let _ = device.config_accel_set_profile(default);
3371 }
3372
3373 if let Some(method) = c.scroll_method {
3374 let _ = device.config_scroll_set_method(method.into());
3375
3376 if method == niri_config::ScrollMethod::OnButtonDown {
3377 if let Some(button) = c.scroll_button {
3378 let _ = device.config_scroll_set_button(button);
3379 }
3380 }
3381 } else if let Some(default) = device.config_scroll_default_method() {
3382 let _ = device.config_scroll_set_method(default);
3383
3384 if default == input::ScrollMethod::OnButtonDown {
3385 if let Some(button) = c.scroll_button {
3386 let _ = device.config_scroll_set_button(button);
3387 }
3388 }
3389 }
3390 }
3391
3392 let is_tablet = device.has_capability(input::DeviceCapability::TabletTool);
3393 if is_tablet {
3394 let c = &config.tablet;
3395 let _ = device.config_send_events_set_mode(if c.off {
3396 input::SendEventsMode::DISABLED
3397 } else {
3398 input::SendEventsMode::ENABLED
3399 });
3400 let _ = device.config_left_handed_set(c.left_handed);
3401 }
3402}
3403
3404pub fn mods_with_binds(
3405 comp_mod: CompositorMod,
3406 binds: &Binds,
3407 triggers: &[Trigger],
3408) -> HashSet<Modifiers> {
3409 let comp_mod = match comp_mod {
3410 CompositorMod::Super => Modifiers::SUPER,
3411 CompositorMod::Alt => Modifiers::ALT,
3412 };
3413
3414 let mut rv = HashSet::new();
3415 for bind in &binds.0 {
3416 if !triggers.iter().any(|trigger| bind.key.trigger == *trigger) {
3417 continue;
3418 }
3419
3420 let mut mods = bind.key.modifiers;
3421 if mods.contains(Modifiers::COMPOSITOR) {
3422 mods.remove(Modifiers::COMPOSITOR);
3423 mods.insert(comp_mod);
3424 }
3425
3426 rv.insert(mods);
3427 }
3428
3429 rv
3430}
3431
3432pub fn mods_with_mouse_binds(comp_mod: CompositorMod, binds: &Binds) -> HashSet<Modifiers> {
3433 mods_with_binds(
3434 comp_mod,
3435 binds,
3436 &[
3437 Trigger::MouseLeft,
3438 Trigger::MouseRight,
3439 Trigger::MouseMiddle,
3440 Trigger::MouseBack,
3441 Trigger::MouseForward,
3442 ],
3443 )
3444}
3445
3446pub fn mods_with_wheel_binds(comp_mod: CompositorMod, binds: &Binds) -> HashSet<Modifiers> {
3447 mods_with_binds(
3448 comp_mod,
3449 binds,
3450 &[
3451 Trigger::WheelScrollUp,
3452 Trigger::WheelScrollDown,
3453 Trigger::WheelScrollLeft,
3454 Trigger::WheelScrollRight,
3455 ],
3456 )
3457}
3458
3459pub fn mods_with_finger_scroll_binds(comp_mod: CompositorMod, binds: &Binds) -> HashSet<Modifiers> {
3460 mods_with_binds(
3461 comp_mod,
3462 binds,
3463 &[
3464 Trigger::TouchpadScrollUp,
3465 Trigger::TouchpadScrollDown,
3466 Trigger::TouchpadScrollLeft,
3467 Trigger::TouchpadScrollRight,
3468 ],
3469 )
3470}
3471
3472#[cfg(test)]
3473mod tests {
3474 use std::cell::Cell;
3475
3476 use super::*;
3477 use crate::animation::Clock;
3478
3479 #[test]
3480 fn bindings_suppress_keys() {
3481 let close_keysym = Keysym::q;
3482 let bindings = Binds(vec![Bind {
3483 key: Key {
3484 trigger: Trigger::Keysym(close_keysym),
3485 modifiers: Modifiers::COMPOSITOR | Modifiers::CTRL,
3486 },
3487 action: Action::CloseWindow,
3488 repeat: true,
3489 cooldown: None,
3490 allow_when_locked: false,
3491 allow_inhibiting: true,
3492 }]);
3493
3494 let comp_mod = CompositorMod::Super;
3495 let mut suppressed_keys = HashSet::new();
3496
3497 let screenshot_ui = ScreenshotUi::new(Clock::default(), Default::default());
3498 let disable_power_key_handling = false;
3499 let is_inhibiting_shortcuts = Cell::new(false);
3500
3501 // The key_code we pick is arbitrary, the only thing
3502 // that matters is that they are different between cases.
3503
3504 let close_key_code = Keycode::from(close_keysym.raw() + 8u32);
3505 let close_key_event = |suppr: &mut HashSet<Keycode>, mods: ModifiersState, pressed| {
3506 should_intercept_key(
3507 suppr,
3508 &bindings,
3509 comp_mod,
3510 close_key_code,
3511 close_keysym,
3512 Some(close_keysym),
3513 pressed,
3514 mods,
3515 &screenshot_ui,
3516 disable_power_key_handling,
3517 is_inhibiting_shortcuts.get(),
3518 )
3519 };
3520
3521 // Key event with the code which can't trigger any action.
3522 let none_key_event = |suppr: &mut HashSet<Keycode>, mods: ModifiersState, pressed| {
3523 should_intercept_key(
3524 suppr,
3525 &bindings,
3526 comp_mod,
3527 Keycode::from(Keysym::l.raw() + 8),
3528 Keysym::l,
3529 Some(Keysym::l),
3530 pressed,
3531 mods,
3532 &screenshot_ui,
3533 disable_power_key_handling,
3534 is_inhibiting_shortcuts.get(),
3535 )
3536 };
3537
3538 let mut mods = ModifiersState {
3539 logo: true,
3540 ctrl: true,
3541 ..Default::default()
3542 };
3543
3544 // Action press/release.
3545
3546 let filter = close_key_event(&mut suppressed_keys, mods, true);
3547 assert!(matches!(
3548 filter,
3549 FilterResult::Intercept(Some(Bind {
3550 action: Action::CloseWindow,
3551 ..
3552 }))
3553 ));
3554 assert!(suppressed_keys.contains(&close_key_code));
3555
3556 let filter = close_key_event(&mut suppressed_keys, mods, false);
3557 assert!(matches!(filter, FilterResult::Intercept(None)));
3558 assert!(suppressed_keys.is_empty());
3559
3560 // Remove mod to make it for a binding.
3561
3562 mods.shift = true;
3563 let filter = close_key_event(&mut suppressed_keys, mods, true);
3564 assert!(matches!(filter, FilterResult::Forward));
3565
3566 mods.shift = false;
3567 let filter = close_key_event(&mut suppressed_keys, mods, false);
3568 assert!(matches!(filter, FilterResult::Forward));
3569
3570 // Just none press/release.
3571
3572 let filter = none_key_event(&mut suppressed_keys, mods, true);
3573 assert!(matches!(filter, FilterResult::Forward));
3574
3575 let filter = none_key_event(&mut suppressed_keys, mods, false);
3576 assert!(matches!(filter, FilterResult::Forward));
3577
3578 // Press action, press arbitrary, release action, release arbitrary.
3579
3580 let filter = close_key_event(&mut suppressed_keys, mods, true);
3581 assert!(matches!(
3582 filter,
3583 FilterResult::Intercept(Some(Bind {
3584 action: Action::CloseWindow,
3585 ..
3586 }))
3587 ));
3588
3589 let filter = none_key_event(&mut suppressed_keys, mods, true);
3590 assert!(matches!(filter, FilterResult::Forward));
3591
3592 let filter = close_key_event(&mut suppressed_keys, mods, false);
3593 assert!(matches!(filter, FilterResult::Intercept(None)));
3594
3595 let filter = none_key_event(&mut suppressed_keys, mods, false);
3596 assert!(matches!(filter, FilterResult::Forward));
3597
3598 // Trigger and remove all mods.
3599
3600 let filter = close_key_event(&mut suppressed_keys, mods, true);
3601 assert!(matches!(
3602 filter,
3603 FilterResult::Intercept(Some(Bind {
3604 action: Action::CloseWindow,
3605 ..
3606 }))
3607 ));
3608
3609 mods = Default::default();
3610 let filter = close_key_event(&mut suppressed_keys, mods, false);
3611 assert!(matches!(filter, FilterResult::Intercept(None)));
3612
3613 // Ensure that no keys are being suppressed.
3614 assert!(suppressed_keys.is_empty());
3615
3616 // Now test shortcut inhibiting.
3617
3618 // With inhibited shortcuts, we don't intercept our shortcut.
3619 is_inhibiting_shortcuts.set(true);
3620
3621 mods = ModifiersState {
3622 logo: true,
3623 ctrl: true,
3624 ..Default::default()
3625 };
3626
3627 let filter = close_key_event(&mut suppressed_keys, mods, true);
3628 assert!(matches!(filter, FilterResult::Forward));
3629 assert!(suppressed_keys.is_empty());
3630
3631 let filter = close_key_event(&mut suppressed_keys, mods, false);
3632 assert!(matches!(filter, FilterResult::Forward));
3633 assert!(suppressed_keys.is_empty());
3634
3635 // Toggle it off after pressing the shortcut.
3636 let filter = close_key_event(&mut suppressed_keys, mods, true);
3637 assert!(matches!(filter, FilterResult::Forward));
3638 assert!(suppressed_keys.is_empty());
3639
3640 is_inhibiting_shortcuts.set(false);
3641
3642 let filter = close_key_event(&mut suppressed_keys, mods, false);
3643 assert!(matches!(filter, FilterResult::Forward));
3644 assert!(suppressed_keys.is_empty());
3645
3646 // Toggle it on after pressing the shortcut.
3647 let filter = close_key_event(&mut suppressed_keys, mods, true);
3648 assert!(matches!(
3649 filter,
3650 FilterResult::Intercept(Some(Bind {
3651 action: Action::CloseWindow,
3652 ..
3653 }))
3654 ));
3655 assert!(suppressed_keys.contains(&close_key_code));
3656
3657 is_inhibiting_shortcuts.set(true);
3658
3659 let filter = close_key_event(&mut suppressed_keys, mods, false);
3660 assert!(matches!(filter, FilterResult::Intercept(None)));
3661 assert!(suppressed_keys.is_empty());
3662 }
3663
3664 #[test]
3665 fn comp_mod_handling() {
3666 let bindings = Binds(vec![
3667 Bind {
3668 key: Key {
3669 trigger: Trigger::Keysym(Keysym::q),
3670 modifiers: Modifiers::COMPOSITOR,
3671 },
3672 action: Action::CloseWindow,
3673 repeat: true,
3674 cooldown: None,
3675 allow_when_locked: false,
3676 allow_inhibiting: true,
3677 },
3678 Bind {
3679 key: Key {
3680 trigger: Trigger::Keysym(Keysym::h),
3681 modifiers: Modifiers::SUPER,
3682 },
3683 action: Action::FocusColumnLeft,
3684 repeat: true,
3685 cooldown: None,
3686 allow_when_locked: false,
3687 allow_inhibiting: true,
3688 },
3689 Bind {
3690 key: Key {
3691 trigger: Trigger::Keysym(Keysym::j),
3692 modifiers: Modifiers::empty(),
3693 },
3694 action: Action::FocusWindowDown,
3695 repeat: true,
3696 cooldown: None,
3697 allow_when_locked: false,
3698 allow_inhibiting: true,
3699 },
3700 Bind {
3701 key: Key {
3702 trigger: Trigger::Keysym(Keysym::k),
3703 modifiers: Modifiers::COMPOSITOR | Modifiers::SUPER,
3704 },
3705 action: Action::FocusWindowUp,
3706 repeat: true,
3707 cooldown: None,
3708 allow_when_locked: false,
3709 allow_inhibiting: true,
3710 },
3711 Bind {
3712 key: Key {
3713 trigger: Trigger::Keysym(Keysym::l),
3714 modifiers: Modifiers::SUPER | Modifiers::ALT,
3715 },
3716 action: Action::FocusColumnRight,
3717 repeat: true,
3718 cooldown: None,
3719 allow_when_locked: false,
3720 allow_inhibiting: true,
3721 },
3722 ]);
3723
3724 assert_eq!(
3725 find_configured_bind(
3726 &bindings,
3727 CompositorMod::Super,
3728 Trigger::Keysym(Keysym::q),
3729 ModifiersState {
3730 logo: true,
3731 ..Default::default()
3732 }
3733 )
3734 .as_ref(),
3735 Some(&bindings.0[0])
3736 );
3737 assert_eq!(
3738 find_configured_bind(
3739 &bindings,
3740 CompositorMod::Super,
3741 Trigger::Keysym(Keysym::q),
3742 ModifiersState::default(),
3743 ),
3744 None,
3745 );
3746
3747 assert_eq!(
3748 find_configured_bind(
3749 &bindings,
3750 CompositorMod::Super,
3751 Trigger::Keysym(Keysym::h),
3752 ModifiersState {
3753 logo: true,
3754 ..Default::default()
3755 }
3756 )
3757 .as_ref(),
3758 Some(&bindings.0[1])
3759 );
3760 assert_eq!(
3761 find_configured_bind(
3762 &bindings,
3763 CompositorMod::Super,
3764 Trigger::Keysym(Keysym::h),
3765 ModifiersState::default(),
3766 ),
3767 None,
3768 );
3769
3770 assert_eq!(
3771 find_configured_bind(
3772 &bindings,
3773 CompositorMod::Super,
3774 Trigger::Keysym(Keysym::j),
3775 ModifiersState {
3776 logo: true,
3777 ..Default::default()
3778 }
3779 ),
3780 None,
3781 );
3782 assert_eq!(
3783 find_configured_bind(
3784 &bindings,
3785 CompositorMod::Super,
3786 Trigger::Keysym(Keysym::j),
3787 ModifiersState::default(),
3788 )
3789 .as_ref(),
3790 Some(&bindings.0[2])
3791 );
3792
3793 assert_eq!(
3794 find_configured_bind(
3795 &bindings,
3796 CompositorMod::Super,
3797 Trigger::Keysym(Keysym::k),
3798 ModifiersState {
3799 logo: true,
3800 ..Default::default()
3801 }
3802 )
3803 .as_ref(),
3804 Some(&bindings.0[3])
3805 );
3806 assert_eq!(
3807 find_configured_bind(
3808 &bindings,
3809 CompositorMod::Super,
3810 Trigger::Keysym(Keysym::k),
3811 ModifiersState::default(),
3812 ),
3813 None,
3814 );
3815
3816 assert_eq!(
3817 find_configured_bind(
3818 &bindings,
3819 CompositorMod::Super,
3820 Trigger::Keysym(Keysym::l),
3821 ModifiersState {
3822 logo: true,
3823 alt: true,
3824 ..Default::default()
3825 }
3826 )
3827 .as_ref(),
3828 Some(&bindings.0[4])
3829 );
3830 assert_eq!(
3831 find_configured_bind(
3832 &bindings,
3833 CompositorMod::Super,
3834 Trigger::Keysym(Keysym::l),
3835 ModifiersState {
3836 logo: true,
3837 ..Default::default()
3838 },
3839 ),
3840 None,
3841 );
3842 }
3843}