forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBfa2baceMaximilian Huber1 year ago1550 commits

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