forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB289ae36Ivan Molodetskikh2 years ago1428 commits

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