forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB1599a01Ivan Molodetskikh3 years ago398 commits

input.rs1197 lines, 47.4 KiBHistoryRawDownload
1use std::collections::HashSet;
2
3use smithay::backend::input::{
4 AbsolutePositionEvent, Axis, AxisSource, ButtonState, Device, DeviceCapability, Event,
5 GestureBeginEvent, GestureEndEvent, GesturePinchUpdateEvent as _, GestureSwipeUpdateEvent as _,
6 InputBackend, InputEvent, KeyState, KeyboardKeyEvent, PointerAxisEvent, PointerButtonEvent,
7 PointerMotionEvent, ProximityState, TabletToolButtonEvent, TabletToolEvent,
8 TabletToolProximityEvent, TabletToolTipEvent, TabletToolTipState,
9};
10use smithay::backend::libinput::LibinputInputBackend;
11use smithay::input::keyboard::{keysyms, FilterResult, Keysym, ModifiersState};
12use smithay::input::pointer::{
13 AxisFrame, ButtonEvent, CursorImageStatus, GestureHoldBeginEvent, GestureHoldEndEvent,
14 GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent, GestureSwipeBeginEvent,
15 GestureSwipeEndEvent, GestureSwipeUpdateEvent, MotionEvent, RelativeMotionEvent,
16};
17use smithay::utils::SERIAL_COUNTER;
18use smithay::wayland::tablet_manager::{TabletDescriptor, TabletSeatTrait};
19
20use crate::config::{Action, Binds, LayoutAction, Modifiers};
21use crate::niri::State;
22use crate::screenshot_ui::ScreenshotUi;
23use crate::utils::{center, get_monotonic_time, spawn};
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum CompositorMod {
27 Super,
28 Alt,
29}
30
31impl State {
32 pub fn process_input_event<I: InputBackend>(&mut self, event: InputEvent<I>) {
33 let _span = tracy_client::span!("process_input_event");
34
35 // A bit of a hack, but animation end runs some logic (i.e. workspace clean-up) and it
36 // doesn't always trigger due to damage, etc. So run it here right before it might prove
37 // important. Besides, animations affect the input, so it's best to have up-to-date values
38 // here.
39 self.niri.layout.advance_animations(get_monotonic_time());
40
41 // Power on monitors if they were off.
42 if should_activate_monitors(&event) {
43 self.niri.activate_monitors(&self.backend);
44 }
45
46 let comp_mod = self.backend.mod_key();
47
48 match event {
49 InputEvent::Keyboard { event, .. } => {
50 let serial = SERIAL_COUNTER.next_serial();
51 let time = Event::time_msec(&event);
52 let pressed = event.state() == KeyState::Pressed;
53
54 let Some(Some(action)) = self.niri.seat.get_keyboard().unwrap().input(
55 self,
56 event.key_code(),
57 event.state(),
58 serial,
59 time,
60 |this, mods, keysym| {
61 let bindings = &this.niri.config.borrow().binds;
62 let key_code = event.key_code();
63 let modified = keysym.modified_sym();
64 let raw = keysym.raw_latin_sym_or_raw_current_sym();
65 should_intercept_key(
66 &mut this.niri.suppressed_keys,
67 bindings,
68 comp_mod,
69 key_code,
70 modified,
71 raw,
72 pressed,
73 *mods,
74 &this.niri.screenshot_ui,
75 )
76 },
77 ) else {
78 return;
79 };
80
81 // Filter actions when the key is released or the session is locked.
82 if !pressed {
83 return;
84 }
85
86 if self.niri.is_locked()
87 && !matches!(
88 action,
89 Action::Quit
90 | Action::ChangeVt(_)
91 | Action::Suspend
92 | Action::PowerOffMonitors
93 | Action::SwitchLayout(_)
94 )
95 {
96 return;
97 }
98
99 match action {
100 Action::Quit => {
101 info!("quitting because quit bind was pressed");
102 self.niri.stop_signal.stop()
103 }
104 Action::ChangeVt(vt) => {
105 self.backend.change_vt(vt);
106 // Changing `VT` may not deliver the key releases, so clear the state.
107 self.niri.suppressed_keys.clear();
108 }
109 Action::Suspend => {
110 self.backend.suspend();
111 // Suspend may not deliver the key releases, so clear the state.
112 self.niri.suppressed_keys.clear();
113 }
114 Action::PowerOffMonitors => {
115 self.niri.deactivate_monitors(&self.backend);
116 }
117 Action::ToggleDebugTint => {
118 self.backend.toggle_debug_tint();
119 }
120 Action::Spawn(command) => {
121 spawn(command);
122 }
123 Action::ScreenshotScreen => {
124 let active = self.niri.layout.active_output().cloned();
125 if let Some(active) = active {
126 if let Some(renderer) = self.backend.renderer() {
127 if let Err(err) = self.niri.screenshot(renderer, &active) {
128 warn!("error taking screenshot: {err:?}");
129 }
130 }
131 }
132 }
133 Action::ConfirmScreenshot => {
134 if let Some(renderer) = self.backend.renderer() {
135 match self.niri.screenshot_ui.capture(renderer) {
136 Ok((size, pixels)) => {
137 if let Err(err) = self.niri.save_screenshot(size, pixels) {
138 warn!("error saving screenshot: {err:?}");
139 }
140 }
141 Err(err) => {
142 warn!("error capturing screenshot: {err:?}");
143 }
144 }
145 }
146
147 self.niri.screenshot_ui.close();
148 self.niri
149 .cursor_manager
150 .set_cursor_image(CursorImageStatus::default_named());
151 self.niri.queue_redraw_all();
152 }
153 Action::CancelScreenshot => {
154 self.niri.screenshot_ui.close();
155 self.niri
156 .cursor_manager
157 .set_cursor_image(CursorImageStatus::default_named());
158 self.niri.queue_redraw_all();
159 }
160 Action::Screenshot => {
161 if let Some(renderer) = self.backend.renderer() {
162 self.niri.open_screenshot_ui(renderer);
163 }
164 }
165 Action::ScreenshotWindow => {
166 let active = self.niri.layout.active_window();
167 if let Some((window, output)) = active {
168 if let Some(renderer) = self.backend.renderer() {
169 if let Err(err) =
170 self.niri.screenshot_window(renderer, &output, &window)
171 {
172 warn!("error taking screenshot: {err:?}");
173 }
174 }
175 }
176 }
177 Action::CloseWindow => {
178 if let Some(window) = self.niri.layout.focus() {
179 window.toplevel().send_close();
180 }
181 }
182 Action::FullscreenWindow => {
183 let focus = self.niri.layout.focus().cloned();
184 if let Some(window) = focus {
185 self.niri.layout.toggle_fullscreen(&window);
186 }
187 }
188 Action::SwitchLayout(action) => {
189 self.niri
190 .seat
191 .get_keyboard()
192 .unwrap()
193 .with_xkb_state(self, |mut state| match action {
194 LayoutAction::Next => state.cycle_next_layout(),
195 LayoutAction::Prev => state.cycle_prev_layout(),
196 });
197 }
198 Action::MoveColumnLeft => {
199 self.niri.layout.move_left();
200 // FIXME: granular
201 self.niri.queue_redraw_all();
202 }
203 Action::MoveColumnRight => {
204 self.niri.layout.move_right();
205 // FIXME: granular
206 self.niri.queue_redraw_all();
207 }
208 Action::MoveWindowDown => {
209 self.niri.layout.move_down();
210 // FIXME: granular
211 self.niri.queue_redraw_all();
212 }
213 Action::MoveWindowUp => {
214 self.niri.layout.move_up();
215 // FIXME: granular
216 self.niri.queue_redraw_all();
217 }
218 Action::FocusColumnLeft => {
219 self.niri.layout.focus_left();
220 }
221 Action::FocusColumnRight => {
222 self.niri.layout.focus_right();
223 }
224 Action::FocusWindowDown => {
225 self.niri.layout.focus_down();
226 }
227 Action::FocusWindowUp => {
228 self.niri.layout.focus_up();
229 }
230 Action::MoveWindowToWorkspaceDown => {
231 self.niri.layout.move_to_workspace_down();
232 // FIXME: granular
233 self.niri.queue_redraw_all();
234 }
235 Action::MoveWindowToWorkspaceUp => {
236 self.niri.layout.move_to_workspace_up();
237 // FIXME: granular
238 self.niri.queue_redraw_all();
239 }
240 Action::MoveWindowToWorkspace(idx) => {
241 let idx = idx.saturating_sub(1) as usize;
242 self.niri.layout.move_to_workspace(idx);
243 // FIXME: granular
244 self.niri.queue_redraw_all();
245 }
246 Action::FocusWorkspaceDown => {
247 self.niri.layout.switch_workspace_down();
248 // FIXME: granular
249 self.niri.queue_redraw_all();
250 }
251 Action::FocusWorkspaceUp => {
252 self.niri.layout.switch_workspace_up();
253 // FIXME: granular
254 self.niri.queue_redraw_all();
255 }
256 Action::FocusWorkspace(idx) => {
257 let idx = idx.saturating_sub(1) as usize;
258 self.niri.layout.switch_workspace(idx);
259 // FIXME: granular
260 self.niri.queue_redraw_all();
261 }
262 Action::MoveWorkspaceDown => {
263 self.niri.layout.move_workspace_down();
264 // FIXME: granular
265 self.niri.queue_redraw_all();
266 }
267 Action::MoveWorkspaceUp => {
268 self.niri.layout.move_workspace_up();
269 // FIXME: granular
270 self.niri.queue_redraw_all();
271 }
272 Action::ConsumeWindowIntoColumn => {
273 self.niri.layout.consume_into_column();
274 // FIXME: granular
275 self.niri.queue_redraw_all();
276 }
277 Action::ExpelWindowFromColumn => {
278 self.niri.layout.expel_from_column();
279 // FIXME: granular
280 self.niri.queue_redraw_all();
281 }
282 Action::SwitchPresetColumnWidth => {
283 self.niri.layout.toggle_width();
284 }
285 Action::CenterColumn => {
286 self.niri.layout.center_column();
287 // FIXME: granular
288 self.niri.queue_redraw_all();
289 }
290 Action::MaximizeColumn => {
291 self.niri.layout.toggle_full_width();
292 }
293 Action::FocusMonitorLeft => {
294 if let Some(output) = self.niri.output_left() {
295 self.niri.layout.focus_output(&output);
296 self.move_cursor_to_output(&output);
297 }
298 }
299 Action::FocusMonitorRight => {
300 if let Some(output) = self.niri.output_right() {
301 self.niri.layout.focus_output(&output);
302 self.move_cursor_to_output(&output);
303 }
304 }
305 Action::FocusMonitorDown => {
306 if let Some(output) = self.niri.output_down() {
307 self.niri.layout.focus_output(&output);
308 self.move_cursor_to_output(&output);
309 }
310 }
311 Action::FocusMonitorUp => {
312 if let Some(output) = self.niri.output_up() {
313 self.niri.layout.focus_output(&output);
314 self.move_cursor_to_output(&output);
315 }
316 }
317 Action::MoveWindowToMonitorLeft => {
318 if let Some(output) = self.niri.output_left() {
319 self.niri.layout.move_to_output(&output);
320 self.move_cursor_to_output(&output);
321 }
322 }
323 Action::MoveWindowToMonitorRight => {
324 if let Some(output) = self.niri.output_right() {
325 self.niri.layout.move_to_output(&output);
326 self.move_cursor_to_output(&output);
327 }
328 }
329 Action::MoveWindowToMonitorDown => {
330 if let Some(output) = self.niri.output_down() {
331 self.niri.layout.move_to_output(&output);
332 self.move_cursor_to_output(&output);
333 }
334 }
335 Action::MoveWindowToMonitorUp => {
336 if let Some(output) = self.niri.output_up() {
337 self.niri.layout.move_to_output(&output);
338 self.move_cursor_to_output(&output);
339 }
340 }
341 Action::SetColumnWidth(change) => {
342 self.niri.layout.set_column_width(change);
343 }
344 Action::SetWindowHeight(change) => {
345 self.niri.layout.set_window_height(change);
346 }
347 }
348 }
349 InputEvent::PointerMotion { event, .. } => {
350 // We need an output to be able to move the pointer.
351 if self.niri.global_space.outputs().next().is_none() {
352 return;
353 }
354
355 let serial = SERIAL_COUNTER.next_serial();
356
357 let pointer = self.niri.seat.get_pointer().unwrap();
358
359 let pos = pointer.current_location();
360
361 // We have an output, so we can compute the new location and focus.
362 let mut new_pos = pos + event.delta();
363
364 if self
365 .niri
366 .global_space
367 .output_under(new_pos)
368 .next()
369 .is_none()
370 {
371 // We ended up outside the outputs and need to clip the movement.
372 if let Some(output) = self.niri.global_space.output_under(pos).next() {
373 // The pointer was previously on some output. Clip the movement against its
374 // boundaries.
375 let geom = self.niri.global_space.output_geometry(output).unwrap();
376 new_pos.x = new_pos
377 .x
378 .clamp(geom.loc.x as f64, (geom.loc.x + geom.size.w - 1) as f64);
379 new_pos.y = new_pos
380 .y
381 .clamp(geom.loc.y as f64, (geom.loc.y + geom.size.h - 1) as f64);
382 } else {
383 // The pointer was not on any output in the first place. Find one for it.
384 // Let's do the simple thing and just put it on the first output.
385 let output = self.niri.global_space.outputs().next().unwrap();
386 let geom = self.niri.global_space.output_geometry(output).unwrap();
387 new_pos = center(geom).to_f64();
388 }
389 }
390
391 if let Some(output) = self.niri.screenshot_ui.selection_output() {
392 let geom = self.niri.global_space.output_geometry(output).unwrap();
393 let mut point = new_pos;
394 point.x = point
395 .x
396 .clamp(geom.loc.x as f64, (geom.loc.x + geom.size.w - 1) as f64);
397 point.y = point
398 .y
399 .clamp(geom.loc.y as f64, (geom.loc.y + geom.size.h - 1) as f64);
400 let point = (point - geom.loc.to_f64())
401 .to_physical(output.current_scale().fractional_scale())
402 .to_i32_round();
403 self.niri.screenshot_ui.pointer_motion(point);
404 }
405
406 let under = self.niri.surface_under_and_global_space(new_pos);
407 self.niri.pointer_focus = under.clone();
408 let under = under.map(|u| u.surface);
409
410 pointer.motion(
411 self,
412 under.clone(),
413 &MotionEvent {
414 location: new_pos,
415 serial,
416 time: event.time_msec(),
417 },
418 );
419
420 pointer.relative_motion(
421 self,
422 under,
423 &RelativeMotionEvent {
424 delta: event.delta(),
425 delta_unaccel: event.delta_unaccel(),
426 utime: event.time(),
427 },
428 );
429
430 pointer.frame(self);
431
432 // Redraw to update the cursor position.
433 // FIXME: redraw only outputs overlapping the cursor.
434 self.niri.queue_redraw_all();
435 }
436 InputEvent::PointerMotionAbsolute { event, .. } => {
437 let Some(output) = self.niri.global_space.outputs().next() else {
438 return;
439 };
440
441 let output_geo = self.niri.global_space.output_geometry(output).unwrap();
442
443 let pos = event.position_transformed(output_geo.size) + output_geo.loc.to_f64();
444
445 let serial = SERIAL_COUNTER.next_serial();
446
447 let pointer = self.niri.seat.get_pointer().unwrap();
448
449 if let Some(output) = self.niri.screenshot_ui.selection_output() {
450 let geom = self.niri.global_space.output_geometry(output).unwrap();
451 let mut point = pos;
452 point.x = point
453 .x
454 .clamp(geom.loc.x as f64, (geom.loc.x + geom.size.w - 1) as f64);
455 point.y = point
456 .y
457 .clamp(geom.loc.y as f64, (geom.loc.y + geom.size.h - 1) as f64);
458 let point = (point - geom.loc.to_f64())
459 .to_physical(output.current_scale().fractional_scale())
460 .to_i32_round();
461 self.niri.screenshot_ui.pointer_motion(point);
462 }
463
464 let under = self.niri.surface_under_and_global_space(pos);
465 self.niri.pointer_focus = under.clone();
466 let under = under.map(|u| u.surface);
467
468 pointer.motion(
469 self,
470 under,
471 &MotionEvent {
472 location: pos,
473 serial,
474 time: event.time_msec(),
475 },
476 );
477
478 pointer.frame(self);
479
480 // Redraw to update the cursor position.
481 // FIXME: redraw only outputs overlapping the cursor.
482 self.niri.queue_redraw_all();
483 }
484 InputEvent::PointerButton { event, .. } => {
485 let pointer = self.niri.seat.get_pointer().unwrap();
486
487 let serial = SERIAL_COUNTER.next_serial();
488
489 let button = event.button_code();
490
491 let button_state = event.state();
492
493 if ButtonState::Pressed == button_state && !pointer.is_grabbed() {
494 if let Some(window) = self.niri.window_under_cursor() {
495 let window = window.clone();
496 self.niri.layout.activate_window(&window);
497 } else if let Some(output) = self.niri.output_under_cursor() {
498 self.niri.layout.activate_output(&output);
499 }
500 };
501
502 self.update_pointer_focus();
503
504 if let Some(button) = event.button() {
505 let pos = pointer.current_location();
506 if let Some((output, _)) = self.niri.output_under(pos) {
507 let output = output.clone();
508 let geom = self.niri.global_space.output_geometry(&output).unwrap();
509 let mut point = pos;
510 // Re-clamp as pointer can be within 0.5 from the limit which will round up
511 // to a wrong value.
512 point.x = point
513 .x
514 .clamp(geom.loc.x as f64, (geom.loc.x + geom.size.w - 1) as f64);
515 point.y = point
516 .y
517 .clamp(geom.loc.y as f64, (geom.loc.y + geom.size.h - 1) as f64);
518 let point = (point - geom.loc.to_f64())
519 .to_physical(output.current_scale().fractional_scale())
520 .to_i32_round();
521 if self.niri.screenshot_ui.pointer_button(
522 output,
523 point,
524 button,
525 button_state,
526 ) {
527 self.niri.queue_redraw_all();
528 }
529 }
530 }
531
532 pointer.button(
533 self,
534 &ButtonEvent {
535 button,
536 state: button_state,
537 serial,
538 time: event.time_msec(),
539 },
540 );
541 pointer.frame(self);
542 }
543 InputEvent::PointerAxis { event, .. } => {
544 let source = event.source();
545
546 let horizontal_amount = event.amount(Axis::Horizontal).unwrap_or_else(|| {
547 event.amount_discrete(Axis::Horizontal).unwrap_or(0.0) * 3.0
548 });
549 let vertical_amount = event
550 .amount(Axis::Vertical)
551 .unwrap_or_else(|| event.amount_discrete(Axis::Vertical).unwrap_or(0.0) * 3.0);
552 let horizontal_amount_discrete = event.amount_discrete(Axis::Horizontal);
553 let vertical_amount_discrete = event.amount_discrete(Axis::Vertical);
554
555 let mut frame = AxisFrame::new(event.time_msec()).source(source);
556 if horizontal_amount != 0.0 {
557 frame = frame.value(Axis::Horizontal, horizontal_amount);
558 if let Some(discrete) = horizontal_amount_discrete {
559 frame = frame.discrete(Axis::Horizontal, discrete as i32);
560 }
561 }
562 if vertical_amount != 0.0 {
563 frame = frame.value(Axis::Vertical, vertical_amount);
564 if let Some(discrete) = vertical_amount_discrete {
565 frame = frame.discrete(Axis::Vertical, discrete as i32);
566 }
567 }
568
569 if source == AxisSource::Finger {
570 if event.amount(Axis::Horizontal) == Some(0.0) {
571 frame = frame.stop(Axis::Horizontal);
572 }
573 if event.amount(Axis::Vertical) == Some(0.0) {
574 frame = frame.stop(Axis::Vertical);
575 }
576 }
577
578 self.update_pointer_focus();
579
580 let pointer = &self.niri.seat.get_pointer().unwrap();
581 pointer.axis(self, frame);
582 pointer.frame(self);
583 }
584 InputEvent::TabletToolAxis { event, .. } => {
585 let Some(output) = self.niri.output_for_tablet() else {
586 return;
587 };
588
589 let output_geo = self.niri.global_space.output_geometry(output).unwrap();
590
591 let pos = event.position_transformed(output_geo.size) + output_geo.loc.to_f64();
592
593 let serial = SERIAL_COUNTER.next_serial();
594
595 let pointer = self.niri.seat.get_pointer().unwrap();
596
597 let under = self.niri.surface_under_and_global_space(pos);
598 self.niri.pointer_focus = under.clone();
599 let under = under.map(|u| u.surface);
600
601 pointer.motion(
602 self,
603 under.clone(),
604 &MotionEvent {
605 location: pos,
606 serial,
607 time: event.time_msec(),
608 },
609 );
610 pointer.frame(self);
611
612 let tablet_seat = self.niri.seat.tablet_seat();
613 let tablet = tablet_seat.get_tablet(&TabletDescriptor::from(&event.device()));
614 let tool = tablet_seat.get_tool(&event.tool());
615 if let (Some(tablet), Some(tool)) = (tablet, tool) {
616 if event.pressure_has_changed() {
617 tool.pressure(event.pressure());
618 }
619 if event.distance_has_changed() {
620 tool.distance(event.distance());
621 }
622 if event.tilt_has_changed() {
623 tool.tilt(event.tilt());
624 }
625 if event.slider_has_changed() {
626 tool.slider_position(event.slider_position());
627 }
628 if event.rotation_has_changed() {
629 tool.rotation(event.rotation());
630 }
631 if event.wheel_has_changed() {
632 tool.wheel(event.wheel_delta(), event.wheel_delta_discrete());
633 }
634
635 tool.motion(
636 pos,
637 under,
638 &tablet,
639 SERIAL_COUNTER.next_serial(),
640 event.time_msec(),
641 );
642 }
643
644 // Redraw to update the cursor position.
645 // FIXME: redraw only outputs overlapping the cursor.
646 self.niri.queue_redraw_all();
647 }
648 InputEvent::TabletToolTip { event, .. } => {
649 let tool = self.niri.seat.tablet_seat().get_tool(&event.tool());
650
651 if let Some(tool) = tool {
652 match event.tip_state() {
653 TabletToolTipState::Down => {
654 let serial = SERIAL_COUNTER.next_serial();
655 tool.tip_down(serial, event.time_msec());
656
657 let pointer = self.niri.seat.get_pointer().unwrap();
658 if !pointer.is_grabbed() {
659 if let Some(window) = self.niri.window_under_cursor() {
660 let window = window.clone();
661 self.niri.layout.activate_window(&window);
662 } else if let Some(output) = self.niri.output_under_cursor() {
663 self.niri.layout.activate_output(&output);
664 }
665 };
666 }
667 TabletToolTipState::Up => {
668 tool.tip_up(event.time_msec());
669 }
670 }
671 }
672 }
673 InputEvent::TabletToolProximity { event, .. } => {
674 let Some(output) = self.niri.output_for_tablet() else {
675 return;
676 };
677
678 let output_geo = self.niri.global_space.output_geometry(output).unwrap();
679
680 let pos = event.position_transformed(output_geo.size) + output_geo.loc.to_f64();
681
682 let serial = SERIAL_COUNTER.next_serial();
683
684 let pointer = self.niri.seat.get_pointer().unwrap();
685
686 let under = self.niri.surface_under_and_global_space(pos);
687 self.niri.pointer_focus = under.clone();
688 let under = under.map(|u| u.surface);
689
690 pointer.motion(
691 self,
692 under.clone(),
693 &MotionEvent {
694 location: pos,
695 serial,
696 time: event.time_msec(),
697 },
698 );
699 pointer.frame(self);
700
701 let tablet_seat = self.niri.seat.tablet_seat();
702 let tool = tablet_seat.add_tool::<Self>(&self.niri.display_handle, &event.tool());
703 let tablet = tablet_seat.get_tablet(&TabletDescriptor::from(&event.device()));
704 if let (Some(under), Some(tablet)) = (under, tablet) {
705 match event.state() {
706 ProximityState::In => tool.proximity_in(
707 pos,
708 under,
709 &tablet,
710 SERIAL_COUNTER.next_serial(),
711 event.time_msec(),
712 ),
713 ProximityState::Out => tool.proximity_out(event.time_msec()),
714 }
715 }
716 }
717 InputEvent::TabletToolButton { event, .. } => {
718 let tool = self.niri.seat.tablet_seat().get_tool(&event.tool());
719
720 if let Some(tool) = tool {
721 tool.button(
722 event.button(),
723 event.button_state(),
724 SERIAL_COUNTER.next_serial(),
725 event.time_msec(),
726 );
727 }
728 }
729 InputEvent::DeviceAdded { device } => {
730 if device.has_capability(DeviceCapability::TabletTool) {
731 self.niri.seat.tablet_seat().add_tablet::<Self>(
732 &self.niri.display_handle,
733 &TabletDescriptor::from(&device),
734 );
735 }
736 }
737 InputEvent::DeviceRemoved { device } => {
738 if device.has_capability(DeviceCapability::TabletTool) {
739 let tablet_seat = self.niri.seat.tablet_seat();
740
741 tablet_seat.remove_tablet(&TabletDescriptor::from(&device));
742
743 // If there are no tablets in seat we can remove all tools
744 if tablet_seat.count_tablets() == 0 {
745 tablet_seat.clear_tools();
746 }
747 }
748 }
749 InputEvent::GestureSwipeBegin { event } => {
750 if event.fingers() == 3 {
751 if let Some(output) = self.niri.output_under_cursor() {
752 self.niri.layout.workspace_switch_gesture_begin(&output);
753
754 // FIXME: granular. This one is awkward because this can cancel a gesture on
755 // multiple other outputs in theory.
756 self.niri.queue_redraw_all();
757 }
758
759 // We handled this event.
760 return;
761 }
762
763 let serial = SERIAL_COUNTER.next_serial();
764 let pointer = self.niri.seat.get_pointer().unwrap();
765
766 if self.update_pointer_focus() {
767 pointer.frame(self);
768 }
769
770 pointer.gesture_swipe_begin(
771 self,
772 &GestureSwipeBeginEvent {
773 serial,
774 time: event.time_msec(),
775 fingers: event.fingers(),
776 },
777 );
778 }
779 InputEvent::GestureSwipeUpdate { event } => {
780 let res = self
781 .niri
782 .layout
783 .workspace_switch_gesture_update(event.delta_y());
784 if let Some(output) = res {
785 if let Some(output) = output {
786 self.niri.queue_redraw(output);
787 }
788
789 // We handled this event.
790 return;
791 }
792
793 let pointer = self.niri.seat.get_pointer().unwrap();
794
795 if self.update_pointer_focus() {
796 pointer.frame(self);
797 }
798
799 pointer.gesture_swipe_update(
800 self,
801 &GestureSwipeUpdateEvent {
802 time: event.time_msec(),
803 delta: event.delta(),
804 },
805 );
806 }
807 InputEvent::GestureSwipeEnd { event } => {
808 let res = self
809 .niri
810 .layout
811 .workspace_switch_gesture_end(event.cancelled());
812 if let Some(output) = res {
813 self.niri.queue_redraw(output);
814
815 // We handled this event.
816 return;
817 }
818
819 let serial = SERIAL_COUNTER.next_serial();
820 let pointer = self.niri.seat.get_pointer().unwrap();
821
822 if self.update_pointer_focus() {
823 pointer.frame(self);
824 }
825
826 pointer.gesture_swipe_end(
827 self,
828 &GestureSwipeEndEvent {
829 serial,
830 time: event.time_msec(),
831 cancelled: event.cancelled(),
832 },
833 );
834 }
835 InputEvent::GesturePinchBegin { event } => {
836 let serial = SERIAL_COUNTER.next_serial();
837 let pointer = self.niri.seat.get_pointer().unwrap();
838
839 if self.update_pointer_focus() {
840 pointer.frame(self);
841 }
842
843 pointer.gesture_pinch_begin(
844 self,
845 &GesturePinchBeginEvent {
846 serial,
847 time: event.time_msec(),
848 fingers: event.fingers(),
849 },
850 );
851 }
852 InputEvent::GesturePinchUpdate { event } => {
853 let pointer = self.niri.seat.get_pointer().unwrap();
854
855 if self.update_pointer_focus() {
856 pointer.frame(self);
857 }
858
859 pointer.gesture_pinch_update(
860 self,
861 &GesturePinchUpdateEvent {
862 time: event.time_msec(),
863 delta: event.delta(),
864 scale: event.scale(),
865 rotation: event.rotation(),
866 },
867 );
868 }
869 InputEvent::GesturePinchEnd { event } => {
870 let serial = SERIAL_COUNTER.next_serial();
871 let pointer = self.niri.seat.get_pointer().unwrap();
872
873 if self.update_pointer_focus() {
874 pointer.frame(self);
875 }
876
877 pointer.gesture_pinch_end(
878 self,
879 &GesturePinchEndEvent {
880 serial,
881 time: event.time_msec(),
882 cancelled: event.cancelled(),
883 },
884 );
885 }
886 InputEvent::GestureHoldBegin { event } => {
887 let serial = SERIAL_COUNTER.next_serial();
888 let pointer = self.niri.seat.get_pointer().unwrap();
889
890 if self.update_pointer_focus() {
891 pointer.frame(self);
892 }
893
894 pointer.gesture_hold_begin(
895 self,
896 &GestureHoldBeginEvent {
897 serial,
898 time: event.time_msec(),
899 fingers: event.fingers(),
900 },
901 );
902 }
903 InputEvent::GestureHoldEnd { event } => {
904 let serial = SERIAL_COUNTER.next_serial();
905 let pointer = self.niri.seat.get_pointer().unwrap();
906
907 if self.update_pointer_focus() {
908 pointer.frame(self);
909 }
910
911 pointer.gesture_hold_end(
912 self,
913 &GestureHoldEndEvent {
914 serial,
915 time: event.time_msec(),
916 cancelled: event.cancelled(),
917 },
918 );
919 }
920 InputEvent::TouchDown { .. } => (),
921 InputEvent::TouchMotion { .. } => (),
922 InputEvent::TouchUp { .. } => (),
923 InputEvent::TouchCancel { .. } => (),
924 InputEvent::TouchFrame { .. } => (),
925 InputEvent::Special(_) => (),
926 }
927 }
928
929 pub fn process_libinput_event(&mut self, event: &mut InputEvent<LibinputInputBackend>) {
930 if let InputEvent::DeviceAdded { device } = event {
931 // According to Mutter code, this setting is specific to touchpads.
932 let is_touchpad = device.config_tap_finger_count() > 0;
933 if is_touchpad {
934 let c = &self.niri.config.borrow().input.touchpad;
935 let _ = device.config_tap_set_enabled(c.tap);
936 let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll);
937 let _ = device.config_accel_set_speed(c.accel_speed);
938 }
939 }
940 }
941}
942
943/// Check whether the key should be intercepted and mark intercepted
944/// pressed keys as `suppressed`, thus preventing `releases` corresponding
945/// to them from being delivered.
946#[allow(clippy::too_many_arguments)]
947fn should_intercept_key(
948 suppressed_keys: &mut HashSet<u32>,
949 bindings: &Binds,
950 comp_mod: CompositorMod,
951 key_code: u32,
952 modified: Keysym,
953 raw: Option<Keysym>,
954 pressed: bool,
955 mods: ModifiersState,
956 screenshot_ui: &ScreenshotUi,
957) -> FilterResult<Option<Action>> {
958 // Actions are only triggered on presses, release of the key
959 // shouldn't try to intercept anything unless we have marked
960 // the key to suppress.
961 if !pressed && !suppressed_keys.contains(&key_code) {
962 return FilterResult::Forward;
963 }
964
965 let mut final_action = action(bindings, comp_mod, modified, raw, mods);
966 if screenshot_ui.is_open()
967 // Allow only a subset of compositor actions while the screenshot UI is open,
968 // since the user cannot see the screen.
969 && !matches!(
970 final_action,
971 Some(Action::Quit | Action::ChangeVt(_) | Action::Suspend | Action::PowerOffMonitors)
972 )
973 {
974 // Otherwise, use the screenshot UI action.
975 final_action = screenshot_ui.action(raw, mods);
976 }
977
978 match (final_action, pressed) {
979 (Some(action), true) => {
980 suppressed_keys.insert(key_code);
981 FilterResult::Intercept(Some(action))
982 }
983 (_, false) => {
984 suppressed_keys.remove(&key_code);
985 FilterResult::Intercept(None)
986 }
987 (None, true) => FilterResult::Forward,
988 }
989}
990
991fn action(
992 bindings: &Binds,
993 comp_mod: CompositorMod,
994 modified: Keysym,
995 raw: Option<Keysym>,
996 mods: ModifiersState,
997) -> Option<Action> {
998 use keysyms::*;
999
1000 // Handle hardcoded binds.
1001 #[allow(non_upper_case_globals)] // wat
1002 match modified.raw() {
1003 modified @ KEY_XF86Switch_VT_1..=KEY_XF86Switch_VT_12 => {
1004 let vt = (modified - KEY_XF86Switch_VT_1 + 1) as i32;
1005 return Some(Action::ChangeVt(vt));
1006 }
1007 KEY_XF86PowerOff => return Some(Action::Suspend),
1008 _ => (),
1009 }
1010
1011 // Handle configured binds.
1012 let mut modifiers = Modifiers::empty();
1013 if mods.ctrl {
1014 modifiers |= Modifiers::CTRL;
1015 }
1016 if mods.shift {
1017 modifiers |= Modifiers::SHIFT;
1018 }
1019 if mods.alt {
1020 modifiers |= Modifiers::ALT;
1021 }
1022 if mods.logo {
1023 modifiers |= Modifiers::SUPER;
1024 }
1025
1026 let (mod_down, mut comp_mod) = match comp_mod {
1027 CompositorMod::Super => (mods.logo, Modifiers::SUPER),
1028 CompositorMod::Alt => (mods.alt, Modifiers::ALT),
1029 };
1030 if mod_down {
1031 modifiers |= Modifiers::COMPOSITOR;
1032 } else {
1033 comp_mod = Modifiers::empty();
1034 }
1035
1036 let Some(raw) = raw else {
1037 return None;
1038 };
1039
1040 for bind in &bindings.0 {
1041 if bind.key.keysym != raw {
1042 continue;
1043 }
1044
1045 if bind.key.modifiers | comp_mod == modifiers {
1046 return bind.actions.first().cloned();
1047 }
1048 }
1049
1050 None
1051}
1052
1053fn should_activate_monitors<I: InputBackend>(event: &InputEvent<I>) -> bool {
1054 match event {
1055 InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true,
1056 InputEvent::PointerMotion { .. }
1057 | InputEvent::PointerMotionAbsolute { .. }
1058 | InputEvent::PointerButton { .. }
1059 | InputEvent::PointerAxis { .. }
1060 | InputEvent::GestureSwipeBegin { .. }
1061 | InputEvent::GesturePinchBegin { .. }
1062 | InputEvent::GestureHoldBegin { .. }
1063 | InputEvent::TouchDown { .. }
1064 | InputEvent::TouchMotion { .. }
1065 | InputEvent::TabletToolAxis { .. }
1066 | InputEvent::TabletToolProximity { .. }
1067 | InputEvent::TabletToolTip { .. }
1068 | InputEvent::TabletToolButton { .. } => true,
1069 // Ignore events like device additions and removals, key releases, gesture ends.
1070 _ => false,
1071 }
1072}
1073
1074#[cfg(test)]
1075mod tests {
1076 use super::*;
1077 use crate::config::{Action, Bind, Binds, Key, Modifiers};
1078
1079 #[test]
1080 fn bindings_suppress_keys() {
1081 let close_keysym = Keysym::q;
1082 let bindings = Binds(vec![Bind {
1083 key: Key {
1084 keysym: close_keysym,
1085 modifiers: Modifiers::COMPOSITOR | Modifiers::CTRL,
1086 },
1087 actions: vec![Action::CloseWindow],
1088 }]);
1089
1090 let comp_mod = CompositorMod::Super;
1091 let mut suppressed_keys = HashSet::new();
1092
1093 let screenshot_ui = ScreenshotUi::new();
1094
1095 // The key_code we pick is arbitrary, the only thing
1096 // that matters is that they are different between cases.
1097
1098 let close_key_code = close_keysym.into();
1099 let close_key_event = |suppr: &mut HashSet<u32>, mods: ModifiersState, pressed| {
1100 should_intercept_key(
1101 suppr,
1102 &bindings,
1103 comp_mod,
1104 close_key_code,
1105 close_keysym,
1106 Some(close_keysym),
1107 pressed,
1108 mods,
1109 &screenshot_ui,
1110 )
1111 };
1112
1113 // Key event with the code which can't trigger any action.
1114 let none_key_event = |suppr: &mut HashSet<u32>, mods: ModifiersState, pressed| {
1115 should_intercept_key(
1116 suppr,
1117 &bindings,
1118 comp_mod,
1119 Keysym::l.into(),
1120 Keysym::l,
1121 Some(Keysym::l),
1122 pressed,
1123 mods,
1124 &screenshot_ui,
1125 )
1126 };
1127
1128 let mut mods = ModifiersState {
1129 logo: true,
1130 ctrl: true,
1131 ..Default::default()
1132 };
1133
1134 // Action press/release.
1135
1136 let filter = close_key_event(&mut suppressed_keys, mods, true);
1137 assert!(matches!(
1138 filter,
1139 FilterResult::Intercept(Some(Action::CloseWindow))
1140 ));
1141 assert!(suppressed_keys.contains(&close_key_code));
1142
1143 let filter = close_key_event(&mut suppressed_keys, mods, false);
1144 assert!(matches!(filter, FilterResult::Intercept(None)));
1145 assert!(suppressed_keys.is_empty());
1146
1147 // Remove mod to make it for a binding.
1148
1149 mods.shift = true;
1150 let filter = close_key_event(&mut suppressed_keys, mods, true);
1151 assert!(matches!(filter, FilterResult::Forward));
1152
1153 mods.shift = false;
1154 let filter = close_key_event(&mut suppressed_keys, mods, false);
1155 assert!(matches!(filter, FilterResult::Forward));
1156
1157 // Just none press/release.
1158
1159 let filter = none_key_event(&mut suppressed_keys, mods, true);
1160 assert!(matches!(filter, FilterResult::Forward));
1161
1162 let filter = none_key_event(&mut suppressed_keys, mods, false);
1163 assert!(matches!(filter, FilterResult::Forward));
1164
1165 // Press action, press arbitrary, release action, release arbitrary.
1166
1167 let filter = close_key_event(&mut suppressed_keys, mods, true);
1168 assert!(matches!(
1169 filter,
1170 FilterResult::Intercept(Some(Action::CloseWindow))
1171 ));
1172
1173 let filter = none_key_event(&mut suppressed_keys, mods, true);
1174 assert!(matches!(filter, FilterResult::Forward));
1175
1176 let filter = close_key_event(&mut suppressed_keys, mods, false);
1177 assert!(matches!(filter, FilterResult::Intercept(None)));
1178
1179 let filter = none_key_event(&mut suppressed_keys, mods, false);
1180 assert!(matches!(filter, FilterResult::Forward));
1181
1182 // Trigger and remove all mods.
1183
1184 let filter = close_key_event(&mut suppressed_keys, mods, true);
1185 assert!(matches!(
1186 filter,
1187 FilterResult::Intercept(Some(Action::CloseWindow))
1188 ));
1189
1190 mods = Default::default();
1191 let filter = close_key_event(&mut suppressed_keys, mods, false);
1192 assert!(matches!(filter, FilterResult::Intercept(None)));
1193
1194 // Ensure that no keys are being suppressed.
1195 assert!(suppressed_keys.is_empty());
1196 }
1197}