use std::any::Any; use std::cmp::min; use std::collections::hash_map::Entry; use std::collections::HashSet; use std::time::Duration; use calloop::timer::{TimeoutAction, Timer}; use input::event::gesture::GestureEventCoordinates as _; use niri_config::{Action, Bind, Binds, Key, Modifiers, SwitchBinds, Trigger}; use niri_ipc::LayoutSwitchTarget; use smithay::backend::input::{ AbsolutePositionEvent, Axis, AxisSource, ButtonState, Device, DeviceCapability, Event, GestureBeginEvent, GestureEndEvent, GesturePinchUpdateEvent as _, GestureSwipeUpdateEvent as _, InputBackend, InputEvent, KeyState, KeyboardKeyEvent, Keycode, MouseButton, PointerAxisEvent, PointerButtonEvent, PointerMotionEvent, ProximityState, Switch, SwitchState, SwitchToggleEvent, TabletToolButtonEvent, TabletToolEvent, TabletToolProximityEvent, TabletToolTipEvent, TabletToolTipState, TouchEvent, }; use smithay::backend::libinput::LibinputInputBackend; use smithay::input::keyboard::{keysyms, FilterResult, Keysym, ModifiersState}; use smithay::input::pointer::{ AxisFrame, ButtonEvent, CursorIcon, CursorImageStatus, Focus, GestureHoldBeginEvent, GestureHoldEndEvent, GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent, GestureSwipeBeginEvent, GestureSwipeEndEvent, GestureSwipeUpdateEvent, GrabStartData as PointerGrabStartData, MotionEvent, RelativeMotionEvent, }; use smithay::input::touch::{ DownEvent, GrabStartData as TouchGrabStartData, MotionEvent as TouchMotionEvent, UpEvent, }; use smithay::input::SeatHandler; use smithay::utils::{Logical, Point, Rectangle, Transform, SERIAL_COUNTER}; use smithay::wayland::pointer_constraints::{with_pointer_constraint, PointerConstraint}; use smithay::wayland::tablet_manager::{TabletDescriptor, TabletSeatTrait}; use touch_move_grab::TouchMoveGrab; use self::move_grab::MoveGrab; use self::resize_grab::ResizeGrab; use self::spatial_movement_grab::SpatialMovementGrab; use crate::niri::State; use crate::ui::screenshot_ui::ScreenshotUi; use crate::utils::spawning::spawn; use crate::utils::{center, get_monotonic_time, ResizeEdge}; pub mod move_grab; pub mod resize_grab; pub mod scroll_tracker; pub mod spatial_movement_grab; pub mod swipe_tracker; pub mod touch_move_grab; pub mod touch_resize_grab; pub const DOUBLE_CLICK_TIME: Duration = Duration::from_millis(400); #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CompositorMod { Super, Alt, } #[derive(Debug, Clone, Copy, PartialEq)] pub struct TabletData { pub aspect_ratio: f64, } pub enum PointerOrTouchStartData { Pointer(PointerGrabStartData), Touch(TouchGrabStartData), } impl PointerOrTouchStartData { pub fn location(&self) -> Point { match self { PointerOrTouchStartData::Pointer(x) => x.location, PointerOrTouchStartData::Touch(x) => x.location, } } } impl State { pub fn process_input_event(&mut self, event: InputEvent) where I::Device: 'static, // Needed for downcasting. { let _span = tracy_client::span!("process_input_event"); // A bit of a hack, but animation end runs some logic (i.e. workspace clean-up) and it // doesn't always trigger due to damage, etc. So run it here right before it might prove // important. Besides, animations affect the input, so it's best to have up-to-date values // here. self.niri.layout.advance_animations(get_monotonic_time()); if self.niri.monitors_active { // Notify the idle-notifier of activity. if should_notify_activity(&event) { let _span = tracy_client::span!("IdleNotifierState::notify_activity"); self.niri .idle_notifier_state .notify_activity(&self.niri.seat); } } else { // Power on monitors if they were off. if should_activate_monitors(&event) { self.niri.activate_monitors(&mut self.backend); // Notify the idle-notifier of activity only if we're also powering on the // monitors. self.niri .idle_notifier_state .notify_activity(&self.niri.seat); } } if should_reset_pointer_inactivity_timer(&event) { self.niri.reset_pointer_inactivity_timer(); } let hide_hotkey_overlay = self.niri.hotkey_overlay.is_open() && should_hide_hotkey_overlay(&event); let hide_exit_confirm_dialog = self .niri .exit_confirm_dialog .as_ref() .map_or(false, |d| d.is_open()) && should_hide_exit_confirm_dialog(&event); use InputEvent::*; match event { DeviceAdded { device } => self.on_device_added(device), DeviceRemoved { device } => self.on_device_removed(device), Keyboard { event } => self.on_keyboard::(event), PointerMotion { event } => self.on_pointer_motion::(event), PointerMotionAbsolute { event } => self.on_pointer_motion_absolute::(event), PointerButton { event } => self.on_pointer_button::(event), PointerAxis { event } => self.on_pointer_axis::(event), TabletToolAxis { event } => self.on_tablet_tool_axis::(event), TabletToolTip { event } => self.on_tablet_tool_tip::(event), TabletToolProximity { event } => self.on_tablet_tool_proximity::(event), TabletToolButton { event } => self.on_tablet_tool_button::(event), GestureSwipeBegin { event } => self.on_gesture_swipe_begin::(event), GestureSwipeUpdate { event } => self.on_gesture_swipe_update::(event), GestureSwipeEnd { event } => self.on_gesture_swipe_end::(event), GesturePinchBegin { event } => self.on_gesture_pinch_begin::(event), GesturePinchUpdate { event } => self.on_gesture_pinch_update::(event), GesturePinchEnd { event } => self.on_gesture_pinch_end::(event), GestureHoldBegin { event } => self.on_gesture_hold_begin::(event), GestureHoldEnd { event } => self.on_gesture_hold_end::(event), TouchDown { event } => self.on_touch_down::(event), TouchMotion { event } => self.on_touch_motion::(event), TouchUp { event } => self.on_touch_up::(event), TouchCancel { event } => self.on_touch_cancel::(event), TouchFrame { event } => self.on_touch_frame::(event), SwitchToggle { event } => self.on_switch_toggle::(event), Special(_) => (), } // Do this last so that screenshot still gets it. // FIXME: do this in a less cursed fashion somehow. if hide_hotkey_overlay && self.niri.hotkey_overlay.hide() { self.niri.queue_redraw_all(); } if let Some(dialog) = &mut self.niri.exit_confirm_dialog { if hide_exit_confirm_dialog && dialog.hide() { self.niri.queue_redraw_all(); } } } pub fn process_libinput_event(&mut self, event: &mut InputEvent) { let _span = tracy_client::span!("process_libinput_event"); match event { InputEvent::DeviceAdded { device } => { self.niri.devices.insert(device.clone()); if device.has_capability(input::DeviceCapability::TabletTool) { match device.size() { Some((w, h)) => { let aspect_ratio = w / h; let data = TabletData { aspect_ratio }; self.niri.tablets.insert(device.clone(), data); } None => { warn!("tablet tool device has no size"); } } } if device.has_capability(input::DeviceCapability::Keyboard) { if let Some(led_state) = self .niri .seat .get_keyboard() .map(|keyboard| keyboard.led_state()) { device.led_update(led_state.into()); } } if device.has_capability(input::DeviceCapability::Touch) { self.niri.touch.insert(device.clone()); } apply_libinput_settings(&self.niri.config.borrow().input, device); } InputEvent::DeviceRemoved { device } => { self.niri.touch.remove(device); self.niri.tablets.remove(device); self.niri.devices.remove(device); } _ => (), } } fn on_device_added(&mut self, device: impl Device) { if device.has_capability(DeviceCapability::TabletTool) { let tablet_seat = self.niri.seat.tablet_seat(); let desc = TabletDescriptor::from(&device); tablet_seat.add_tablet::(&self.niri.display_handle, &desc); } if device.has_capability(DeviceCapability::Touch) && self.niri.seat.get_touch().is_none() { self.niri.seat.add_touch(); } } fn on_device_removed(&mut self, device: impl Device) { if device.has_capability(DeviceCapability::TabletTool) { let tablet_seat = self.niri.seat.tablet_seat(); let desc = TabletDescriptor::from(&device); tablet_seat.remove_tablet(&desc); // If there are no tablets in seat we can remove all tools if tablet_seat.count_tablets() == 0 { tablet_seat.clear_tools(); } } if device.has_capability(DeviceCapability::Touch) && self.niri.touch.is_empty() { self.niri.seat.remove_touch(); } } /// Computes the rectangle that covers all outputs in global space. fn global_bounding_rectangle(&self) -> Option> { self.niri.global_space.outputs().fold( None, |acc: Option>, output| { self.niri .global_space .output_geometry(output) .map(|geo| acc.map(|acc| acc.merge(geo)).unwrap_or(geo)) }, ) } /// Computes the cursor position for the tablet event. /// /// This function handles the tablet output mapping, as well as coordinate clamping and aspect /// ratio correction. fn compute_tablet_position( &self, event: &(impl Event + TabletToolEvent), ) -> Option> where I::Device: 'static, { let (target_geo, keep_ratio, px, transform) = if let Some(output) = self.niri.output_for_tablet() { ( self.niri.global_space.output_geometry(output).unwrap(), true, 1. / output.current_scale().fractional_scale(), output.current_transform(), ) } else { let geo = self.global_bounding_rectangle()?; // FIXME: this 1 px size should ideally somehow be computed for the rightmost output // corresponding to the position on the right when clamping. let output = self.niri.global_space.outputs().next().unwrap(); let scale = output.current_scale().fractional_scale(); // Do not keep ratio for the unified mode as this is what OpenTabletDriver expects. (geo, false, 1. / scale, Transform::Normal) }; let mut pos = { let size = transform.invert().transform_size(target_geo.size); transform.transform_point_in(event.position_transformed(size), &size.to_f64()) }; if keep_ratio { pos.x /= target_geo.size.w as f64; pos.y /= target_geo.size.h as f64; let device = event.device(); if let Some(device) = (&device as &dyn Any).downcast_ref::() { if let Some(data) = self.niri.tablets.get(device) { // This code does the same thing as mutter with "keep aspect ratio" enabled. let size = transform.invert().transform_size(target_geo.size); let output_aspect_ratio = size.w as f64 / size.h as f64; let ratio = data.aspect_ratio / output_aspect_ratio; if ratio > 1. { pos.x *= ratio; } else { pos.y /= ratio; } } }; pos.x *= target_geo.size.w as f64; pos.y *= target_geo.size.h as f64; } pos.x = pos.x.clamp(0.0, target_geo.size.w as f64 - px); pos.y = pos.y.clamp(0.0, target_geo.size.h as f64 - px); Some(pos + target_geo.loc.to_f64()) } fn on_keyboard(&mut self, event: I::KeyboardKeyEvent) { let comp_mod = self.backend.mod_key(); let serial = SERIAL_COUNTER.next_serial(); let time = Event::time_msec(&event); let pressed = event.state() == KeyState::Pressed; // Stop bind key repeat on any release. This won't work 100% correctly in cases like: // 1. Press Mod // 2. Press Left (repeat starts) // 3. Press PgDown (new repeat starts) // 4. Release Left (PgDown repeat stops) // But it's good enough for now. // FIXME: handle this properly. if !pressed { if let Some(token) = self.niri.bind_repeat_timer.take() { self.niri.event_loop.remove(token); } } if pressed { self.hide_cursor_if_needed(); } let Some(Some(bind)) = self.niri.seat.get_keyboard().unwrap().input( self, event.key_code(), event.state(), serial, time, |this, mods, keysym| { let bindings = &this.niri.config.borrow().binds; let key_code = event.key_code(); let modified = keysym.modified_sym(); let raw = keysym.raw_latin_sym_or_raw_current_sym(); if let Some(dialog) = &this.niri.exit_confirm_dialog { if dialog.is_open() && pressed && raw == Some(Keysym::Return) { info!("quitting after confirming exit dialog"); this.niri.stop_signal.stop(); } } should_intercept_key( &mut this.niri.suppressed_keys, bindings, comp_mod, key_code, modified, raw, pressed, *mods, &this.niri.screenshot_ui, this.niri.config.borrow().input.disable_power_key_handling, ) }, ) else { return; }; if !pressed { return; } self.handle_bind(bind.clone()); self.start_key_repeat(bind); } fn start_key_repeat(&mut self, bind: Bind) { if !bind.repeat { return; } // Stop the previous key repeat if any. if let Some(token) = self.niri.bind_repeat_timer.take() { self.niri.event_loop.remove(token); } let config = self.niri.config.borrow(); let config = &config.input.keyboard; let repeat_rate = config.repeat_rate; if repeat_rate == 0 { return; } let repeat_duration = Duration::from_secs_f64(1. / f64::from(repeat_rate)); let repeat_timer = Timer::from_duration(Duration::from_millis(u64::from(config.repeat_delay))); let token = self .niri .event_loop .insert_source(repeat_timer, move |_, _, state| { state.handle_bind(bind.clone()); TimeoutAction::ToDuration(repeat_duration) }) .unwrap(); self.niri.bind_repeat_timer = Some(token); } fn hide_cursor_if_needed(&mut self) { if !self.niri.config.borrow().cursor.hide_when_typing { return; } // niri keeps this set only while actively using a tablet, which means the cursor position // is likely to change almost immediately, causing pointer_hidden to just flicker back and // forth. if self.niri.tablet_cursor_location.is_some() { return; } self.niri.pointer_hidden = true; self.niri.queue_redraw_all(); } pub fn handle_bind(&mut self, bind: Bind) { let Some(cooldown) = bind.cooldown else { self.do_action(bind.action, bind.allow_when_locked); return; }; // Check this first so that it doesn't trigger the cooldown. if self.niri.is_locked() && !(bind.allow_when_locked || allowed_when_locked(&bind.action)) { return; } match self.niri.bind_cooldown_timers.entry(bind.key) { // The bind is on cooldown. Entry::Occupied(_) => (), Entry::Vacant(entry) => { let timer = Timer::from_duration(cooldown); let token = self .niri .event_loop .insert_source(timer, move |_, _, state| { if state.niri.bind_cooldown_timers.remove(&bind.key).is_none() { error!("bind cooldown timer entry disappeared"); } TimeoutAction::Drop }) .unwrap(); entry.insert(token); self.do_action(bind.action, bind.allow_when_locked); } } } pub fn do_action(&mut self, action: Action, allow_when_locked: bool) { if self.niri.is_locked() && !(allow_when_locked || allowed_when_locked(&action)) { return; } if let Some(touch) = self.niri.seat.get_touch() { touch.cancel(self); } match action { Action::Quit(skip_confirmation) => { if !skip_confirmation { if let Some(dialog) = &mut self.niri.exit_confirm_dialog { if dialog.show() { self.niri.queue_redraw_all(); } return; } } info!("quitting as requested"); self.niri.stop_signal.stop() } Action::ChangeVt(vt) => { self.backend.change_vt(vt); // Changing VT may not deliver the key releases, so clear the state. self.niri.suppressed_keys.clear(); } Action::Suspend => { self.backend.suspend(); // Suspend may not deliver the key releases, so clear the state. self.niri.suppressed_keys.clear(); } Action::PowerOffMonitors => { self.niri.deactivate_monitors(&mut self.backend); } Action::PowerOnMonitors => { self.niri.activate_monitors(&mut self.backend); } Action::ToggleDebugTint => { self.backend.toggle_debug_tint(); self.niri.queue_redraw_all(); } Action::DebugToggleOpaqueRegions => { self.niri.debug_draw_opaque_regions = !self.niri.debug_draw_opaque_regions; self.niri.queue_redraw_all(); } Action::DebugToggleDamage => { self.niri.debug_toggle_damage(); } Action::Spawn(command) => { spawn(command); } Action::DoScreenTransition(delay_ms) => { self.backend.with_primary_renderer(|renderer| { self.niri.do_screen_transition(renderer, delay_ms); }); } Action::ScreenshotScreen => { let active = self.niri.layout.active_output().cloned(); if let Some(active) = active { self.backend.with_primary_renderer(|renderer| { if let Err(err) = self.niri.screenshot(renderer, &active) { warn!("error taking screenshot: {err:?}"); } }); } } Action::ConfirmScreenshot => { self.backend.with_primary_renderer(|renderer| { match self.niri.screenshot_ui.capture(renderer) { Ok((size, pixels)) => { if let Err(err) = self.niri.save_screenshot(size, pixels) { warn!("error saving screenshot: {err:?}"); } } Err(err) => { warn!("error capturing screenshot: {err:?}"); } } }); self.niri.screenshot_ui.close(); self.niri .cursor_manager .set_cursor_image(CursorImageStatus::default_named()); self.niri.queue_redraw_all(); } Action::CancelScreenshot => { self.niri.screenshot_ui.close(); self.niri .cursor_manager .set_cursor_image(CursorImageStatus::default_named()); self.niri.queue_redraw_all(); } Action::ScreenshotTogglePointer => { self.niri.screenshot_ui.toggle_pointer(); self.niri.queue_redraw_all(); } Action::Screenshot => { self.open_screenshot_ui(); } Action::ScreenshotWindow => { let active = self.niri.layout.active_window(); if let Some((mapped, output)) = active { self.backend.with_primary_renderer(|renderer| { if let Err(err) = self.niri.screenshot_window(renderer, output, mapped) { warn!("error taking screenshot: {err:?}"); } }); } } Action::ScreenshotWindowById(id) => { let mut windows = self.niri.layout.windows(); let window = windows.find(|(_, m)| m.id().get() == id); if let Some((Some(monitor), mapped)) = window { let output = monitor.output(); self.backend.with_primary_renderer(|renderer| { if let Err(err) = self.niri.screenshot_window(renderer, output, mapped) { warn!("error taking screenshot: {err:?}"); } }); } } Action::CloseWindow => { if let Some(mapped) = self.niri.layout.focus() { mapped.toplevel().send_close(); } } Action::CloseWindowById(id) => { let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id); if let Some((_, mapped)) = window { mapped.toplevel().send_close(); } } Action::FullscreenWindow => { let focus = self.niri.layout.focus().map(|m| m.window.clone()); if let Some(window) = focus { self.niri.layout.toggle_fullscreen(&window); // FIXME: granular self.niri.queue_redraw_all(); } } Action::FullscreenWindowById(id) => { let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id); let window = window.map(|(_, m)| m.window.clone()); if let Some(window) = window { self.niri.layout.toggle_fullscreen(&window); // FIXME: granular self.niri.queue_redraw_all(); } } Action::FocusWindow(id) => { let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id); let window = window.map(|(_, m)| m.window.clone()); if let Some(window) = window { let active_output = self.niri.layout.active_output().cloned(); self.niri.layout.activate_window(&window); let new_active = self.niri.layout.active_output().cloned(); #[allow(clippy::collapsible_if)] if new_active != active_output { if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&new_active.unwrap()); } } else { self.maybe_warp_cursor_to_focus(); } // FIXME: granular self.niri.queue_redraw_all(); } } Action::SwitchLayout(action) => { let keyboard = &self.niri.seat.get_keyboard().unwrap(); keyboard.with_xkb_state(self, |mut state| match action { LayoutSwitchTarget::Next => state.cycle_next_layout(), LayoutSwitchTarget::Prev => state.cycle_prev_layout(), }); } Action::MoveColumnLeft => { self.niri.layout.move_left(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::MoveColumnRight => { self.niri.layout.move_right(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::MoveColumnToFirst => { self.niri.layout.move_column_to_first(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::MoveColumnToLast => { self.niri.layout.move_column_to_last(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::MoveColumnLeftOrToMonitorLeft => { if let Some(output) = self.niri.output_left() { if self.niri.layout.move_column_left_or_to_output(&output) && !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } else { self.maybe_warp_cursor_to_focus(); } } else { self.niri.layout.move_left(); self.maybe_warp_cursor_to_focus(); } // FIXME: granular self.niri.queue_redraw_all(); } Action::MoveColumnRightOrToMonitorRight => { if let Some(output) = self.niri.output_right() { if self.niri.layout.move_column_right_or_to_output(&output) && !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } else { self.maybe_warp_cursor_to_focus(); } } else { self.niri.layout.move_right(); self.maybe_warp_cursor_to_focus(); } // FIXME: granular self.niri.queue_redraw_all(); } Action::MoveWindowDown => { self.niri.layout.move_down(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::MoveWindowUp => { self.niri.layout.move_up(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::MoveWindowDownOrToWorkspaceDown => { self.niri.layout.move_down_or_to_workspace_down(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::MoveWindowUpOrToWorkspaceUp => { self.niri.layout.move_up_or_to_workspace_up(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::ConsumeOrExpelWindowLeft => { self.niri.layout.consume_or_expel_window_left(None); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::ConsumeOrExpelWindowLeftById(id) => { let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id); let window = window.map(|(_, m)| m.window.clone()); if let Some(window) = window { self.niri.layout.consume_or_expel_window_left(Some(&window)); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } } Action::ConsumeOrExpelWindowRight => { self.niri.layout.consume_or_expel_window_right(None); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::ConsumeOrExpelWindowRightById(id) => { let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id); let window = window.map(|(_, m)| m.window.clone()); if let Some(window) = window { self.niri .layout .consume_or_expel_window_right(Some(&window)); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } } Action::FocusColumnLeft => { self.niri.layout.focus_left(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::FocusColumnRight => { self.niri.layout.focus_right(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::FocusColumnFirst => { self.niri.layout.focus_column_first(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::FocusColumnLast => { self.niri.layout.focus_column_last(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::FocusColumnRightOrFirst => { self.niri.layout.focus_column_right_or_first(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::FocusColumnLeftOrLast => { self.niri.layout.focus_column_left_or_last(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::FocusWindowOrMonitorUp => { if let Some(output) = self.niri.output_up() { if self.niri.layout.focus_window_up_or_output(&output) && !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } else { self.maybe_warp_cursor_to_focus(); } } else { self.niri.layout.focus_up(); self.maybe_warp_cursor_to_focus(); } // FIXME: granular self.niri.queue_redraw_all(); } Action::FocusWindowOrMonitorDown => { if let Some(output) = self.niri.output_down() { if self.niri.layout.focus_window_down_or_output(&output) && !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } else { self.maybe_warp_cursor_to_focus(); } } else { self.niri.layout.focus_down(); self.maybe_warp_cursor_to_focus(); } // FIXME: granular self.niri.queue_redraw_all(); } Action::FocusColumnOrMonitorLeft => { if let Some(output) = self.niri.output_left() { if self.niri.layout.focus_column_left_or_output(&output) && !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } else { self.maybe_warp_cursor_to_focus(); } } else { self.niri.layout.focus_left(); self.maybe_warp_cursor_to_focus(); } // FIXME: granular self.niri.queue_redraw_all(); } Action::FocusColumnOrMonitorRight => { if let Some(output) = self.niri.output_right() { if self.niri.layout.focus_column_right_or_output(&output) && !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } else { self.maybe_warp_cursor_to_focus(); } } else { self.niri.layout.focus_right(); self.maybe_warp_cursor_to_focus(); } // FIXME: granular self.niri.queue_redraw_all(); } Action::FocusWindowDown => { self.niri.layout.focus_down(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::FocusWindowUp => { self.niri.layout.focus_up(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::FocusWindowDownOrColumnLeft => { self.niri.layout.focus_down_or_left(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::FocusWindowDownOrColumnRight => { self.niri.layout.focus_down_or_right(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::FocusWindowUpOrColumnLeft => { self.niri.layout.focus_up_or_left(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::FocusWindowUpOrColumnRight => { self.niri.layout.focus_up_or_right(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::FocusWindowOrWorkspaceDown => { self.niri.layout.focus_window_or_workspace_down(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::FocusWindowOrWorkspaceUp => { self.niri.layout.focus_window_or_workspace_up(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::MoveWindowToWorkspaceDown => { self.niri.layout.move_to_workspace_down(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::MoveWindowToWorkspaceUp => { self.niri.layout.move_to_workspace_up(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::MoveWindowToWorkspace(reference) => { if let Some((mut output, index)) = self.niri.find_output_and_workspace_index(reference) { // The source output is always the active output, so if the target output is // also the active output, we don't need to use move_to_output(). if let Some(active) = self.niri.layout.active_output() { if output.as_ref() == Some(active) { output = None; } } if let Some(output) = output { self.niri.layout.move_to_output(None, &output, Some(index)); if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } else { self.niri.layout.move_to_workspace(None, index); self.maybe_warp_cursor_to_focus(); } // FIXME: granular self.niri.queue_redraw_all(); } } Action::MoveWindowToWorkspaceById { window_id: id, reference, } => { let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id); let window = window.map(|(_, m)| m.window.clone()); if let Some(window) = window { if let Some((output, index)) = self.niri.find_output_and_workspace_index(reference) { let target_was_active = self .niri .layout .active_output() .map_or(false, |active| output.as_ref() == Some(active)); if let Some(output) = output { self.niri .layout .move_to_output(Some(&window), &output, Some(index)); // If the active output changed (window was moved and focused). #[allow(clippy::collapsible_if)] if !target_was_active && self.niri.layout.active_output() == Some(&output) { if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } } else { self.niri.layout.move_to_workspace(Some(&window), index); // If we focused the target window. let new_active_win = self.niri.layout.active_window(); if new_active_win.map_or(false, |(win, _)| win.window == window) { self.maybe_warp_cursor_to_focus(); } } // FIXME: granular self.niri.queue_redraw_all(); } } } Action::MoveColumnToWorkspaceDown => { self.niri.layout.move_column_to_workspace_down(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::MoveColumnToWorkspaceUp => { self.niri.layout.move_column_to_workspace_up(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::MoveColumnToWorkspace(reference) => { if let Some((mut output, index)) = self.niri.find_output_and_workspace_index(reference) { if let Some(active) = self.niri.layout.active_output() { if output.as_ref() == Some(active) { output = None; } } if let Some(output) = output { self.niri .layout .move_column_to_workspace_on_output(&output, index); if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } else { self.niri.layout.move_column_to_workspace(index); self.maybe_warp_cursor_to_focus(); } // FIXME: granular self.niri.queue_redraw_all(); } } Action::FocusWorkspaceDown => { self.niri.layout.switch_workspace_down(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::FocusWorkspaceUp => { self.niri.layout.switch_workspace_up(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::FocusWorkspace(reference) => { if let Some((mut output, index)) = self.niri.find_output_and_workspace_index(reference) { if let Some(active) = self.niri.layout.active_output() { if output.as_ref() == Some(active) { output = None; } } if let Some(output) = output { self.niri.layout.focus_output(&output); self.niri.layout.switch_workspace(index); if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } else { let config = &self.niri.config; if config.borrow().input.workspace_auto_back_and_forth { self.niri.layout.switch_workspace_auto_back_and_forth(index); } else { self.niri.layout.switch_workspace(index); } self.maybe_warp_cursor_to_focus(); } // FIXME: granular self.niri.queue_redraw_all(); } } Action::FocusWorkspacePrevious => { self.niri.layout.switch_workspace_previous(); // FIXME: granular self.niri.queue_redraw_all(); } Action::MoveWorkspaceDown => { self.niri.layout.move_workspace_down(); // FIXME: granular self.niri.queue_redraw_all(); } Action::MoveWorkspaceUp => { self.niri.layout.move_workspace_up(); // FIXME: granular self.niri.queue_redraw_all(); } Action::ConsumeWindowIntoColumn => { self.niri.layout.consume_into_column(); // This does not cause immediate focus or window size change, so warping mouse to // focus won't do anything here. // FIXME: granular self.niri.queue_redraw_all(); } Action::ExpelWindowFromColumn => { self.niri.layout.expel_from_column(); self.maybe_warp_cursor_to_focus(); // FIXME: granular self.niri.queue_redraw_all(); } Action::SwitchPresetColumnWidth => { self.niri.layout.toggle_width(); } Action::SwitchPresetWindowHeight => { self.niri.layout.toggle_window_height(None); } Action::SwitchPresetWindowHeightById(id) => { let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id); let window = window.map(|(_, m)| m.window.clone()); if let Some(window) = window { self.niri.layout.toggle_window_height(Some(&window)); } } Action::CenterColumn => { self.niri.layout.center_column(); // FIXME: granular self.niri.queue_redraw_all(); } Action::MaximizeColumn => { self.niri.layout.toggle_full_width(); } Action::FocusMonitorLeft => { if let Some(output) = self.niri.output_left() { self.niri.layout.focus_output(&output); if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } } Action::FocusMonitorRight => { if let Some(output) = self.niri.output_right() { self.niri.layout.focus_output(&output); if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } } Action::FocusMonitorDown => { if let Some(output) = self.niri.output_down() { self.niri.layout.focus_output(&output); if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } } Action::FocusMonitorUp => { if let Some(output) = self.niri.output_up() { self.niri.layout.focus_output(&output); if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } } Action::MoveWindowToMonitorLeft => { if let Some(output) = self.niri.output_left() { self.niri.layout.move_to_output(None, &output, None); self.niri.layout.focus_output(&output); if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } } Action::MoveWindowToMonitorRight => { if let Some(output) = self.niri.output_right() { self.niri.layout.move_to_output(None, &output, None); self.niri.layout.focus_output(&output); if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } } Action::MoveWindowToMonitorDown => { if let Some(output) = self.niri.output_down() { self.niri.layout.move_to_output(None, &output, None); self.niri.layout.focus_output(&output); if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } } Action::MoveWindowToMonitorUp => { if let Some(output) = self.niri.output_up() { self.niri.layout.move_to_output(None, &output, None); self.niri.layout.focus_output(&output); if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } } Action::MoveColumnToMonitorLeft => { if let Some(output) = self.niri.output_left() { self.niri.layout.move_column_to_output(&output); self.niri.layout.focus_output(&output); if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } } Action::MoveColumnToMonitorRight => { if let Some(output) = self.niri.output_right() { self.niri.layout.move_column_to_output(&output); self.niri.layout.focus_output(&output); if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } } Action::MoveColumnToMonitorDown => { if let Some(output) = self.niri.output_down() { self.niri.layout.move_column_to_output(&output); self.niri.layout.focus_output(&output); if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } } Action::MoveColumnToMonitorUp => { if let Some(output) = self.niri.output_up() { self.niri.layout.move_column_to_output(&output); self.niri.layout.focus_output(&output); if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } } Action::SetColumnWidth(change) => { self.niri.layout.set_column_width(change); } Action::SetWindowHeight(change) => { self.niri.layout.set_window_height(None, change); } Action::SetWindowHeightById { id, change } => { let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id); let window = window.map(|(_, m)| m.window.clone()); if let Some(window) = window { self.niri.layout.set_window_height(Some(&window), change); } } Action::ResetWindowHeight => { self.niri.layout.reset_window_height(None); } Action::ResetWindowHeightById(id) => { let window = self.niri.layout.windows().find(|(_, m)| m.id().get() == id); let window = window.map(|(_, m)| m.window.clone()); if let Some(window) = window { self.niri.layout.reset_window_height(Some(&window)); } } Action::ShowHotkeyOverlay => { if self.niri.hotkey_overlay.show() { self.niri.queue_redraw_all(); } } Action::MoveWorkspaceToMonitorLeft => { if let Some(output) = self.niri.output_left() { self.niri.layout.move_workspace_to_output(&output); if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } } Action::MoveWorkspaceToMonitorRight => { if let Some(output) = self.niri.output_right() { self.niri.layout.move_workspace_to_output(&output); if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } } Action::MoveWorkspaceToMonitorDown => { if let Some(output) = self.niri.output_down() { self.niri.layout.move_workspace_to_output(&output); if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } } Action::MoveWorkspaceToMonitorUp => { if let Some(output) = self.niri.output_up() { self.niri.layout.move_workspace_to_output(&output); if !self.maybe_warp_cursor_to_focus_centered() { self.move_cursor_to_output(&output); } } } } } fn on_pointer_motion(&mut self, event: I::PointerMotionEvent) { // We need an output to be able to move the pointer. if self.niri.global_space.outputs().next().is_none() { return; } let serial = SERIAL_COUNTER.next_serial(); let pointer = self.niri.seat.get_pointer().unwrap(); let pos = pointer.current_location(); // We have an output, so we can compute the new location and focus. let mut new_pos = pos + event.delta(); // We received an event for the regular pointer, so show it now. self.niri.pointer_hidden = false; self.niri.tablet_cursor_location = None; // Check if we have an active pointer constraint. // // FIXME: ideally this should use the pointer focus with up-to-date global location. let mut pointer_confined = None; if let Some(under) = &self.niri.pointer_contents.surface { // No need to check if the pointer focus surface matches, because here we're checking // for an already-active constraint, and the constraint is deactivated when the focused // surface changes. let pos_within_surface = pos - under.1; let mut pointer_locked = false; with_pointer_constraint(&under.0, &pointer, |constraint| { let Some(constraint) = constraint else { return }; if !constraint.is_active() { return; } // Constraint does not apply if not within region. if let Some(region) = constraint.region() { if !region.contains(pos_within_surface.to_i32_round()) { return; } } match &*constraint { PointerConstraint::Locked(_locked) => { pointer_locked = true; } PointerConstraint::Confined(confine) => { pointer_confined = Some((under.clone(), confine.region().cloned())); } } }); // If the pointer is locked, only send relative motion. if pointer_locked { pointer.relative_motion( self, Some(under.clone()), &RelativeMotionEvent { delta: event.delta(), delta_unaccel: event.delta_unaccel(), utime: event.time(), }, ); pointer.frame(self); // I guess a redraw to hide the tablet cursor could be nice? Doesn't matter too // much here I think. return; } } if self .niri .global_space .output_under(new_pos) .next() .is_none() { // We ended up outside the outputs and need to clip the movement. if let Some(output) = self.niri.global_space.output_under(pos).next() { // The pointer was previously on some output. Clip the movement against its // boundaries. let geom = self.niri.global_space.output_geometry(output).unwrap(); new_pos.x = new_pos .x .clamp(geom.loc.x as f64, (geom.loc.x + geom.size.w - 1) as f64); new_pos.y = new_pos .y .clamp(geom.loc.y as f64, (geom.loc.y + geom.size.h - 1) as f64); } else { // The pointer was not on any output in the first place. Find one for it. // Let's do the simple thing and just put it on the first output. let output = self.niri.global_space.outputs().next().unwrap(); let geom = self.niri.global_space.output_geometry(output).unwrap(); new_pos = center(geom).to_f64(); } } if let Some(output) = self.niri.screenshot_ui.selection_output() { let geom = self.niri.global_space.output_geometry(output).unwrap(); let mut point = (new_pos - geom.loc.to_f64()) .to_physical(output.current_scale().fractional_scale()) .to_i32_round::(); let size = output.current_mode().unwrap().size; let transform = output.current_transform(); let size = transform.transform_size(size); point.x = point.x.clamp(0, size.w - 1); point.y = point.y.clamp(0, size.h - 1); self.niri.screenshot_ui.pointer_motion(point); } let under = self.niri.contents_under(new_pos); // Handle confined pointer. if let Some((focus_surface, region)) = pointer_confined { let mut prevent = false; // Prevent the pointer from leaving the focused surface. if Some(&focus_surface.0) != under.surface.as_ref().map(|(s, _)| s) { prevent = true; } // Prevent the pointer from leaving the confine region, if any. if let Some(region) = region { let new_pos_within_surface = new_pos - focus_surface.1; if !region.contains(new_pos_within_surface.to_i32_round()) { prevent = true; } } if prevent { pointer.relative_motion( self, Some(focus_surface), &RelativeMotionEvent { delta: event.delta(), delta_unaccel: event.delta_unaccel(), utime: event.time(), }, ); pointer.frame(self); return; } } self.niri.handle_focus_follows_mouse(&under); self.niri.pointer_contents.clone_from(&under); pointer.motion( self, under.surface.clone(), &MotionEvent { location: new_pos, serial, time: event.time_msec(), }, ); pointer.relative_motion( self, under.surface, &RelativeMotionEvent { delta: event.delta(), delta_unaccel: event.delta_unaccel(), utime: event.time(), }, ); pointer.frame(self); // Activate a new confinement if necessary. self.niri.maybe_activate_pointer_constraint(); // Redraw to update the cursor position. // FIXME: redraw only outputs overlapping the cursor. self.niri.queue_redraw_all(); } fn on_pointer_motion_absolute( &mut self, event: I::PointerMotionAbsoluteEvent, ) { let Some(output_geo) = self.global_bounding_rectangle() else { return; }; let pos = event.position_transformed(output_geo.size) + output_geo.loc.to_f64(); let serial = SERIAL_COUNTER.next_serial(); let pointer = self.niri.seat.get_pointer().unwrap(); if let Some(output) = self.niri.screenshot_ui.selection_output() { let geom = self.niri.global_space.output_geometry(output).unwrap(); let mut point = (pos - geom.loc.to_f64()) .to_physical(output.current_scale().fractional_scale()) .to_i32_round::(); let size = output.current_mode().unwrap().size; let transform = output.current_transform(); let size = transform.transform_size(size); point.x = point.x.clamp(0, size.w - 1); point.y = point.y.clamp(0, size.h - 1); self.niri.screenshot_ui.pointer_motion(point); } let under = self.niri.contents_under(pos); self.niri.handle_focus_follows_mouse(&under); self.niri.pointer_contents.clone_from(&under); pointer.motion( self, under.surface, &MotionEvent { location: pos, serial, time: event.time_msec(), }, ); pointer.frame(self); self.niri.maybe_activate_pointer_constraint(); // We moved the pointer, show it. self.niri.pointer_hidden = false; // We moved the regular pointer, so show it now. self.niri.tablet_cursor_location = None; // Redraw to update the cursor position. // FIXME: redraw only outputs overlapping the cursor. self.niri.queue_redraw_all(); } fn on_pointer_button(&mut self, event: I::PointerButtonEvent) { let pointer = self.niri.seat.get_pointer().unwrap(); let serial = SERIAL_COUNTER.next_serial(); let button = event.button_code(); let button_state = event.state(); if ButtonState::Pressed == button_state { // We received an event for the regular pointer, so show it now. self.niri.pointer_hidden = false; self.niri.tablet_cursor_location = None; if let Some(mapped) = self.niri.window_under_cursor() { let window = mapped.window.clone(); // Check if we need to start an interactive move. if event.button() == Some(MouseButton::Left) && !pointer.is_grabbed() { let mods = self.niri.seat.get_keyboard().unwrap().modifier_state(); let mod_down = match self.backend.mod_key() { CompositorMod::Super => mods.logo, CompositorMod::Alt => mods.alt, }; if mod_down { let location = pointer.current_location(); let (output, pos_within_output) = self.niri.output_under(location).unwrap(); let output = output.clone(); self.niri.layout.activate_window(&window); if self.niri.layout.interactive_move_begin( window.clone(), &output, pos_within_output, ) { let start_data = PointerGrabStartData { focus: None, button: event.button_code(), location, }; let grab = MoveGrab::new(start_data, window.clone()); pointer.set_grab(self, grab, serial, Focus::Clear); self.niri .cursor_manager .set_cursor_image(CursorImageStatus::Named(CursorIcon::Move)); } } } // Check if we need to start an interactive resize. else if event.button() == Some(MouseButton::Right) && !pointer.is_grabbed() { let mods = self.niri.seat.get_keyboard().unwrap().modifier_state(); let mod_down = match self.backend.mod_key() { CompositorMod::Super => mods.logo, CompositorMod::Alt => mods.alt, }; if mod_down { let location = pointer.current_location(); let (output, pos_within_output) = self.niri.output_under(location).unwrap(); let edges = self .niri .layout .resize_edges_under(output, pos_within_output) .unwrap(); if !edges.is_empty() { // See if we got a double resize-click gesture. // FIXME: deduplicate with resize_request in xdg-shell somehow. let time = get_monotonic_time(); let last_cell = mapped.last_interactive_resize_start(); let last = last_cell.get(); last_cell.set(Some((time, edges))); if let Some((last_time, last_edges)) = last { if time.saturating_sub(last_time) <= DOUBLE_CLICK_TIME { // Allow quick resize after a triple click. last_cell.set(None); let intersection = edges.intersection(last_edges); if intersection.intersects(ResizeEdge::LEFT_RIGHT) { // FIXME: don't activate once we can pass specific windows // to actions. self.niri.layout.activate_window(&window); self.niri.layout.toggle_full_width(); } if intersection.intersects(ResizeEdge::TOP_BOTTOM) { self.niri.layout.activate_window(&window); self.niri.layout.reset_window_height(Some(&window)); } // FIXME: granular. self.niri.queue_redraw_all(); return; } } self.niri.layout.activate_window(&window); if self .niri .layout .interactive_resize_begin(window.clone(), edges) { let start_data = PointerGrabStartData { focus: None, button: event.button_code(), location, }; let grab = ResizeGrab::new(start_data, window.clone()); pointer.set_grab(self, grab, serial, Focus::Clear); self.niri.cursor_manager.set_cursor_image( CursorImageStatus::Named(edges.cursor_icon()), ); } } } } self.niri.layout.activate_window(&window); // FIXME: granular. self.niri.queue_redraw_all(); } else if let Some(output) = self.niri.output_under_cursor() { self.niri.layout.activate_output(&output); // FIXME: granular. self.niri.queue_redraw_all(); } if event.button() == Some(MouseButton::Middle) && !pointer.is_grabbed() { let mods = self.niri.seat.get_keyboard().unwrap().modifier_state(); let mod_down = match self.backend.mod_key() { CompositorMod::Super => mods.logo, CompositorMod::Alt => mods.alt, }; if mod_down { if let Some(output) = self.niri.output_under_cursor() { let location = pointer.current_location(); let start_data = PointerGrabStartData { focus: None, button: event.button_code(), location, }; let grab = SpatialMovementGrab::new(start_data, output); pointer.set_grab(self, grab, serial, Focus::Clear); self.niri .cursor_manager .set_cursor_image(CursorImageStatus::Named(CursorIcon::AllScroll)); } } } }; self.update_pointer_contents(); if ButtonState::Pressed == button_state { let layer_under = self.niri.pointer_contents.layer.clone(); self.niri.focus_layer_surface_if_on_demand(layer_under); } if let Some(button) = event.button() { let pos = pointer.current_location(); if let Some((output, _)) = self.niri.output_under(pos) { let output = output.clone(); let geom = self.niri.global_space.output_geometry(&output).unwrap(); let mut point = (pos - geom.loc.to_f64()) .to_physical(output.current_scale().fractional_scale()) .to_i32_round(); let size = output.current_mode().unwrap().size; let transform = output.current_transform(); let size = transform.transform_size(size); point.x = min(size.w - 1, point.x); point.y = min(size.h - 1, point.y); if self .niri .screenshot_ui .pointer_button(output, point, button, button_state) { self.niri.queue_redraw_all(); } } } pointer.button( self, &ButtonEvent { button, state: button_state, serial, time: event.time_msec(), }, ); pointer.frame(self); } fn on_pointer_axis(&mut self, event: I::PointerAxisEvent) { let source = event.source(); // We received an event for the regular pointer, so show it now. This is also needed for // update_pointer_contents() below to return the real contents, necessary for the pointer // axis event to reach the window. self.niri.pointer_hidden = false; self.niri.tablet_cursor_location = None; let horizontal_amount_v120 = event.amount_v120(Axis::Horizontal); let vertical_amount_v120 = event.amount_v120(Axis::Vertical); // Handle wheel scroll bindings. if source == AxisSource::Wheel { // If we have a scroll bind with current modifiers, then accumulate and don't pass to // Wayland. If there's no bind, reset the accumulator. let mods = self.niri.seat.get_keyboard().unwrap().modifier_state(); let modifiers = modifiers_from_state(mods); if self.niri.mods_with_wheel_binds.contains(&modifiers) { let comp_mod = self.backend.mod_key(); let horizontal = horizontal_amount_v120.unwrap_or(0.); let ticks = self.niri.horizontal_wheel_tracker.accumulate(horizontal); if ticks != 0 { let config = self.niri.config.borrow(); let bindings = &config.binds; let bind_left = find_configured_bind(bindings, comp_mod, Trigger::WheelScrollLeft, mods); let bind_right = find_configured_bind(bindings, comp_mod, Trigger::WheelScrollRight, mods); drop(config); if let Some(right) = bind_right { for _ in 0..ticks { self.handle_bind(right.clone()); } } if let Some(left) = bind_left { for _ in ticks..0 { self.handle_bind(left.clone()); } } } let vertical = vertical_amount_v120.unwrap_or(0.); let ticks = self.niri.vertical_wheel_tracker.accumulate(vertical); if ticks != 0 { let config = self.niri.config.borrow(); let bindings = &config.binds; let bind_up = find_configured_bind(bindings, comp_mod, Trigger::WheelScrollUp, mods); let bind_down = find_configured_bind(bindings, comp_mod, Trigger::WheelScrollDown, mods); drop(config); if let Some(down) = bind_down { for _ in 0..ticks { self.handle_bind(down.clone()); } } if let Some(up) = bind_up { for _ in ticks..0 { self.handle_bind(up.clone()); } } } return; } else { self.niri.horizontal_wheel_tracker.reset(); self.niri.vertical_wheel_tracker.reset(); } } let horizontal_amount = event.amount(Axis::Horizontal); let vertical_amount = event.amount(Axis::Vertical); // Handle touchpad scroll bindings. if source == AxisSource::Finger { let mods = self.niri.seat.get_keyboard().unwrap().modifier_state(); let modifiers = modifiers_from_state(mods); if self.niri.mods_with_finger_scroll_binds.contains(&modifiers) { let comp_mod = self.backend.mod_key(); let horizontal = horizontal_amount.unwrap_or(0.); let ticks = self .niri .horizontal_finger_scroll_tracker .accumulate(horizontal); if ticks != 0 { let config = self.niri.config.borrow(); let bindings = &config.binds; let bind_left = find_configured_bind(bindings, comp_mod, Trigger::TouchpadScrollLeft, mods); let bind_right = find_configured_bind( bindings, comp_mod, Trigger::TouchpadScrollRight, mods, ); drop(config); if let Some(right) = bind_right { for _ in 0..ticks { self.handle_bind(right.clone()); } } if let Some(left) = bind_left { for _ in ticks..0 { self.handle_bind(left.clone()); } } } let vertical = vertical_amount.unwrap_or(0.); let ticks = self .niri .vertical_finger_scroll_tracker .accumulate(vertical); if ticks != 0 { let config = self.niri.config.borrow(); let bindings = &config.binds; let bind_up = find_configured_bind(bindings, comp_mod, Trigger::TouchpadScrollUp, mods); let bind_down = find_configured_bind(bindings, comp_mod, Trigger::TouchpadScrollDown, mods); drop(config); if let Some(down) = bind_down { for _ in 0..ticks { self.handle_bind(down.clone()); } } if let Some(up) = bind_up { for _ in ticks..0 { self.handle_bind(up.clone()); } } } return; } else { self.niri.horizontal_finger_scroll_tracker.reset(); self.niri.vertical_finger_scroll_tracker.reset(); } } let scroll_factor = match source { AxisSource::Wheel => self.niri.config.borrow().input.mouse.scroll_factor, AxisSource::Finger => self.niri.config.borrow().input.touchpad.scroll_factor, _ => None, }; let scroll_factor = scroll_factor.map(|x| x.0).unwrap_or(1.); let horizontal_amount = horizontal_amount.unwrap_or_else(|| { // Winit backend, discrete scrolling. horizontal_amount_v120.unwrap_or(0.0) / 120. * 15. }) * scroll_factor; let vertical_amount = vertical_amount.unwrap_or_else(|| { // Winit backend, discrete scrolling. vertical_amount_v120.unwrap_or(0.0) / 120. * 15. }) * scroll_factor; let horizontal_amount_v120 = horizontal_amount_v120.map(|x| x * scroll_factor); let vertical_amount_v120 = vertical_amount_v120.map(|x| x * scroll_factor); let mut frame = AxisFrame::new(event.time_msec()).source(source); if horizontal_amount != 0.0 { frame = frame .relative_direction(Axis::Horizontal, event.relative_direction(Axis::Horizontal)); frame = frame.value(Axis::Horizontal, horizontal_amount); if let Some(v120) = horizontal_amount_v120 { frame = frame.v120(Axis::Horizontal, v120 as i32); } } if vertical_amount != 0.0 { frame = frame.relative_direction(Axis::Vertical, event.relative_direction(Axis::Vertical)); frame = frame.value(Axis::Vertical, vertical_amount); if let Some(v120) = vertical_amount_v120 { frame = frame.v120(Axis::Vertical, v120 as i32); } } if source == AxisSource::Finger { if event.amount(Axis::Horizontal) == Some(0.0) { frame = frame.stop(Axis::Horizontal); } if event.amount(Axis::Vertical) == Some(0.0) { frame = frame.stop(Axis::Vertical); } } self.update_pointer_contents(); let pointer = &self.niri.seat.get_pointer().unwrap(); pointer.axis(self, frame); pointer.frame(self); } fn on_tablet_tool_axis(&mut self, event: I::TabletToolAxisEvent) where I::Device: 'static, // Needed for downcasting. { let Some(pos) = self.compute_tablet_position(&event) else { return; }; let under = self.niri.contents_under(pos); let tablet_seat = self.niri.seat.tablet_seat(); let tablet = tablet_seat.get_tablet(&TabletDescriptor::from(&event.device())); let tool = tablet_seat.get_tool(&event.tool()); if let (Some(tablet), Some(tool)) = (tablet, tool) { if event.pressure_has_changed() { tool.pressure(event.pressure()); } if event.distance_has_changed() { tool.distance(event.distance()); } if event.tilt_has_changed() { tool.tilt(event.tilt()); } if event.slider_has_changed() { tool.slider_position(event.slider_position()); } if event.rotation_has_changed() { tool.rotation(event.rotation()); } if event.wheel_has_changed() { tool.wheel(event.wheel_delta(), event.wheel_delta_discrete()); } tool.motion( pos, under.surface, &tablet, SERIAL_COUNTER.next_serial(), event.time_msec(), ); self.niri.pointer_hidden = false; self.niri.tablet_cursor_location = Some(pos); } // Redraw to update the cursor position. // FIXME: redraw only outputs overlapping the cursor. self.niri.queue_redraw_all(); } fn on_tablet_tool_tip(&mut self, event: I::TabletToolTipEvent) { let tool = self.niri.seat.tablet_seat().get_tool(&event.tool()); if let Some(tool) = tool { match event.tip_state() { TabletToolTipState::Down => { let serial = SERIAL_COUNTER.next_serial(); tool.tip_down(serial, event.time_msec()); if let Some(pos) = self.niri.tablet_cursor_location { let under = self.niri.contents_under(pos); if let Some(window) = under.window { self.niri.layout.activate_window(&window); // FIXME: granular. self.niri.queue_redraw_all(); } else if let Some(output) = under.output { self.niri.layout.activate_output(&output); // FIXME: granular. self.niri.queue_redraw_all(); } self.niri.focus_layer_surface_if_on_demand(under.layer); } } TabletToolTipState::Up => { tool.tip_up(event.time_msec()); } } } } fn on_tablet_tool_proximity(&mut self, event: I::TabletToolProximityEvent) where I::Device: 'static, // Needed for downcasting. { let Some(pos) = self.compute_tablet_position(&event) else { return; }; let under = self.niri.contents_under(pos); let tablet_seat = self.niri.seat.tablet_seat(); let display_handle = self.niri.display_handle.clone(); let tool = tablet_seat.add_tool::(self, &display_handle, &event.tool()); let tablet = tablet_seat.get_tablet(&TabletDescriptor::from(&event.device())); if let Some(tablet) = tablet { match event.state() { ProximityState::In => { if let Some(under) = under.surface { tool.proximity_in( pos, under, &tablet, SERIAL_COUNTER.next_serial(), event.time_msec(), ); } self.niri.pointer_hidden = false; self.niri.tablet_cursor_location = Some(pos); } ProximityState::Out => { tool.proximity_out(event.time_msec()); // Move the mouse pointer here to avoid discontinuity. // // Plus, Wayland SDL2 currently warps the pointer into some weird // location on proximity out, so this should help it a little. if let Some(pos) = self.niri.tablet_cursor_location { self.move_cursor(pos); } self.niri.pointer_hidden = false; self.niri.tablet_cursor_location = None; } } // FIXME: granular. self.niri.queue_redraw_all(); } } fn on_tablet_tool_button(&mut self, event: I::TabletToolButtonEvent) { let tool = self.niri.seat.tablet_seat().get_tool(&event.tool()); if let Some(tool) = tool { tool.button( event.button(), event.button_state(), SERIAL_COUNTER.next_serial(), event.time_msec(), ); } } fn on_gesture_swipe_begin(&mut self, event: I::GestureSwipeBeginEvent) { if event.fingers() == 3 { self.niri.gesture_swipe_3f_cumulative = Some((0., 0.)); // We handled this event. return; } let serial = SERIAL_COUNTER.next_serial(); let pointer = self.niri.seat.get_pointer().unwrap(); if self.update_pointer_contents() { pointer.frame(self); } pointer.gesture_swipe_begin( self, &GestureSwipeBeginEvent { serial, time: event.time_msec(), fingers: event.fingers(), }, ); } fn on_gesture_swipe_update( &mut self, event: I::GestureSwipeUpdateEvent, ) where I::Device: 'static, { let mut delta_x = event.delta_x(); let mut delta_y = event.delta_y(); if let Some(libinput_event) = (&event as &dyn Any).downcast_ref::() { delta_x = libinput_event.dx_unaccelerated(); delta_y = libinput_event.dy_unaccelerated(); } let device = event.device(); if let Some(device) = (&device as &dyn Any).downcast_ref::() { if device.config_scroll_natural_scroll_enabled() { delta_x = -delta_x; delta_y = -delta_y; } } if let Some((cx, cy)) = &mut self.niri.gesture_swipe_3f_cumulative { *cx += delta_x; *cy += delta_y; // Check if the gesture moved far enough to decide. Threshold copied from GNOME Shell. let (cx, cy) = (*cx, *cy); if cx * cx + cy * cy >= 16. * 16. { self.niri.gesture_swipe_3f_cumulative = None; if let Some(output) = self.niri.output_under_cursor() { if cx.abs() > cy.abs() { self.niri.layout.view_offset_gesture_begin(&output, true); } else { self.niri .layout .workspace_switch_gesture_begin(&output, true); } } } } let timestamp = Duration::from_micros(event.time()); let mut handled = false; let res = self .niri .layout .workspace_switch_gesture_update(delta_y, timestamp, true); if let Some(output) = res { if let Some(output) = output { self.niri.queue_redraw(&output); } handled = true; } let res = self .niri .layout .view_offset_gesture_update(delta_x, timestamp, true); if let Some(output) = res { if let Some(output) = output { self.niri.queue_redraw(&output); } handled = true; } if handled { // We handled this event. return; } let pointer = self.niri.seat.get_pointer().unwrap(); if self.update_pointer_contents() { pointer.frame(self); } pointer.gesture_swipe_update( self, &GestureSwipeUpdateEvent { time: event.time_msec(), delta: event.delta(), }, ); } fn on_gesture_swipe_end(&mut self, event: I::GestureSwipeEndEvent) { self.niri.gesture_swipe_3f_cumulative = None; let mut handled = false; let res = self .niri .layout .workspace_switch_gesture_end(event.cancelled(), Some(true)); if let Some(output) = res { self.niri.queue_redraw(&output); handled = true; } let res = self .niri .layout .view_offset_gesture_end(event.cancelled(), Some(true)); if let Some(output) = res { self.niri.queue_redraw(&output); handled = true; } if handled { // We handled this event. return; } let serial = SERIAL_COUNTER.next_serial(); let pointer = self.niri.seat.get_pointer().unwrap(); if self.update_pointer_contents() { pointer.frame(self); } pointer.gesture_swipe_end( self, &GestureSwipeEndEvent { serial, time: event.time_msec(), cancelled: event.cancelled(), }, ); } fn on_gesture_pinch_begin(&mut self, event: I::GesturePinchBeginEvent) { let serial = SERIAL_COUNTER.next_serial(); let pointer = self.niri.seat.get_pointer().unwrap(); if self.update_pointer_contents() { pointer.frame(self); } pointer.gesture_pinch_begin( self, &GesturePinchBeginEvent { serial, time: event.time_msec(), fingers: event.fingers(), }, ); } fn on_gesture_pinch_update(&mut self, event: I::GesturePinchUpdateEvent) { let pointer = self.niri.seat.get_pointer().unwrap(); if self.update_pointer_contents() { pointer.frame(self); } pointer.gesture_pinch_update( self, &GesturePinchUpdateEvent { time: event.time_msec(), delta: event.delta(), scale: event.scale(), rotation: event.rotation(), }, ); } fn on_gesture_pinch_end(&mut self, event: I::GesturePinchEndEvent) { let serial = SERIAL_COUNTER.next_serial(); let pointer = self.niri.seat.get_pointer().unwrap(); if self.update_pointer_contents() { pointer.frame(self); } pointer.gesture_pinch_end( self, &GesturePinchEndEvent { serial, time: event.time_msec(), cancelled: event.cancelled(), }, ); } fn on_gesture_hold_begin(&mut self, event: I::GestureHoldBeginEvent) { let serial = SERIAL_COUNTER.next_serial(); let pointer = self.niri.seat.get_pointer().unwrap(); if self.update_pointer_contents() { pointer.frame(self); } pointer.gesture_hold_begin( self, &GestureHoldBeginEvent { serial, time: event.time_msec(), fingers: event.fingers(), }, ); } fn on_gesture_hold_end(&mut self, event: I::GestureHoldEndEvent) { let serial = SERIAL_COUNTER.next_serial(); let pointer = self.niri.seat.get_pointer().unwrap(); if self.update_pointer_contents() { pointer.frame(self); } pointer.gesture_hold_end( self, &GestureHoldEndEvent { serial, time: event.time_msec(), cancelled: event.cancelled(), }, ); } /// Computes the cursor position for the touch event. /// /// This function handles the touch output mapping, as well as coordinate transform fn compute_touch_location>( &self, evt: &E, ) -> Option> { let output = self.niri.output_for_touch()?; let output_geo = self.niri.global_space.output_geometry(output).unwrap(); let transform = output.current_transform(); let size = transform.invert().transform_size(output_geo.size); Some( transform.transform_point_in(evt.position_transformed(size), &size.to_f64()) + output_geo.loc.to_f64(), ) } fn on_touch_down(&mut self, evt: I::TouchDownEvent) { let Some(handle) = self.niri.seat.get_touch() else { return; }; let Some(touch_location) = self.compute_touch_location(&evt) else { return; }; let serial = SERIAL_COUNTER.next_serial(); let under = self.niri.contents_under(touch_location); if !handle.is_grabbed() { if let Some(window) = under.window { self.niri.layout.activate_window(&window); // Check if we need to start an interactive move. let mods = self.niri.seat.get_keyboard().unwrap().modifier_state(); let mod_down = match self.backend.mod_key() { CompositorMod::Super => mods.logo, CompositorMod::Alt => mods.alt, }; if mod_down { let (output, pos_within_output) = self.niri.output_under(touch_location).unwrap(); let output = output.clone(); if self.niri.layout.interactive_move_begin( window.clone(), &output, pos_within_output, ) { let start_data = TouchGrabStartData { focus: None, slot: evt.slot(), location: touch_location, }; let grab = TouchMoveGrab::new(start_data, window.clone()); handle.set_grab(self, grab, serial); } } // FIXME: granular. self.niri.queue_redraw_all(); } else if let Some(output) = under.output { self.niri.layout.activate_output(&output); // FIXME: granular. self.niri.queue_redraw_all(); } self.niri.focus_layer_surface_if_on_demand(under.layer); }; handle.down( self, under.surface, &DownEvent { slot: evt.slot(), location: touch_location, serial, time: evt.time_msec(), }, ); // We're using touch, hide the pointer. self.niri.pointer_hidden = true; } fn on_touch_up(&mut self, evt: I::TouchUpEvent) { let Some(handle) = self.niri.seat.get_touch() else { return; }; let serial = SERIAL_COUNTER.next_serial(); handle.up( self, &UpEvent { slot: evt.slot(), serial, time: evt.time_msec(), }, ) } fn on_touch_motion(&mut self, evt: I::TouchMotionEvent) { let Some(handle) = self.niri.seat.get_touch() else { return; }; let Some(touch_location) = self.compute_touch_location(&evt) else { return; }; let under = self.niri.contents_under(touch_location); handle.motion( self, under.surface, &TouchMotionEvent { slot: evt.slot(), location: touch_location, time: evt.time_msec(), }, ); } fn on_touch_frame(&mut self, _evt: I::TouchFrameEvent) { let Some(handle) = self.niri.seat.get_touch() else { return; }; handle.frame(self); } fn on_touch_cancel(&mut self, _evt: I::TouchCancelEvent) { let Some(handle) = self.niri.seat.get_touch() else { return; }; handle.cancel(self); } fn on_switch_toggle(&mut self, evt: I::SwitchToggleEvent) { let Some(switch) = evt.switch() else { return; }; if switch == Switch::Lid { let is_closed = evt.state() == SwitchState::On; debug!("lid switch {}", if is_closed { "closed" } else { "opened" }); self.niri.is_lid_closed = is_closed; self.backend.on_output_config_changed(&mut self.niri); } let action = { let bindings = &self.niri.config.borrow().switch_events; find_configured_switch_action(bindings, switch, evt.state()) }; if let Some(action) = action { self.do_action(action, true); } } } /// Check whether the key should be intercepted and mark intercepted /// pressed keys as `suppressed`, thus preventing `releases` corresponding /// to them from being delivered. #[allow(clippy::too_many_arguments)] fn should_intercept_key( suppressed_keys: &mut HashSet, bindings: &Binds, comp_mod: CompositorMod, key_code: Keycode, modified: Keysym, raw: Option, pressed: bool, mods: ModifiersState, screenshot_ui: &ScreenshotUi, disable_power_key_handling: bool, ) -> FilterResult> { // Actions are only triggered on presses, release of the key // shouldn't try to intercept anything unless we have marked // the key to suppress. if !pressed && !suppressed_keys.contains(&key_code) { return FilterResult::Forward; } let mut final_bind = find_bind( bindings, comp_mod, modified, raw, mods, disable_power_key_handling, ); // Allow only a subset of compositor actions while the screenshot UI is open, since the user // cannot see the screen. if screenshot_ui.is_open() { let mut use_screenshot_ui_action = true; if let Some(bind) = &final_bind { if allowed_during_screenshot(&bind.action) { use_screenshot_ui_action = false; } } if use_screenshot_ui_action { if let Some(raw) = raw { final_bind = screenshot_ui.action(raw, mods).map(|action| Bind { key: Key { trigger: Trigger::Keysym(raw), // Not entirely correct but it doesn't matter in how we currently use it. modifiers: Modifiers::empty(), }, action, repeat: true, cooldown: None, allow_when_locked: false, }); } } } match (final_bind, pressed) { (Some(bind), true) => { suppressed_keys.insert(key_code); FilterResult::Intercept(Some(bind)) } (_, false) => { suppressed_keys.remove(&key_code); FilterResult::Intercept(None) } (None, true) => FilterResult::Forward, } } fn find_bind( bindings: &Binds, comp_mod: CompositorMod, modified: Keysym, raw: Option, mods: ModifiersState, disable_power_key_handling: bool, ) -> Option { use keysyms::*; // Handle hardcoded binds. #[allow(non_upper_case_globals)] // wat let hardcoded_action = match modified.raw() { modified @ KEY_XF86Switch_VT_1..=KEY_XF86Switch_VT_12 => { let vt = (modified - KEY_XF86Switch_VT_1 + 1) as i32; Some(Action::ChangeVt(vt)) } KEY_XF86PowerOff if !disable_power_key_handling => Some(Action::Suspend), _ => None, }; if let Some(action) = hardcoded_action { return Some(Bind { key: Key { // Not entirely correct but it doesn't matter in how we currently use it. trigger: Trigger::Keysym(modified), modifiers: Modifiers::empty(), }, action, repeat: true, cooldown: None, allow_when_locked: false, }); } let trigger = Trigger::Keysym(raw?); find_configured_bind(bindings, comp_mod, trigger, mods) } fn find_configured_bind( bindings: &Binds, comp_mod: CompositorMod, trigger: Trigger, mods: ModifiersState, ) -> Option { // Handle configured binds. let mut modifiers = modifiers_from_state(mods); let (mod_down, comp_mod) = match comp_mod { CompositorMod::Super => (mods.logo, Modifiers::SUPER), CompositorMod::Alt => (mods.alt, Modifiers::ALT), }; if mod_down { modifiers |= Modifiers::COMPOSITOR; } for bind in &bindings.0 { if bind.key.trigger != trigger { continue; } let mut bind_modifiers = bind.key.modifiers; if bind_modifiers.contains(Modifiers::COMPOSITOR) { bind_modifiers |= comp_mod; } else if bind_modifiers.contains(comp_mod) { bind_modifiers |= Modifiers::COMPOSITOR; } if bind_modifiers == modifiers { return Some(bind.clone()); } } None } fn find_configured_switch_action( bindings: &SwitchBinds, switch: Switch, state: SwitchState, ) -> Option { let switch_action = match (switch, state) { (Switch::Lid, SwitchState::Off) => &bindings.lid_open, (Switch::Lid, SwitchState::On) => &bindings.lid_close, (Switch::TabletMode, SwitchState::Off) => &bindings.tablet_mode_off, (Switch::TabletMode, SwitchState::On) => &bindings.tablet_mode_on, _ => unreachable!(), }; switch_action .as_ref() .map(|switch_action| Action::Spawn(switch_action.spawn.clone())) } fn modifiers_from_state(mods: ModifiersState) -> Modifiers { let mut modifiers = Modifiers::empty(); if mods.ctrl { modifiers |= Modifiers::CTRL; } if mods.shift { modifiers |= Modifiers::SHIFT; } if mods.alt { modifiers |= Modifiers::ALT; } if mods.logo { modifiers |= Modifiers::SUPER; } if mods.iso_level3_shift { modifiers |= Modifiers::ISO_LEVEL3_SHIFT; } if mods.iso_level5_shift { modifiers |= Modifiers::ISO_LEVEL5_SHIFT; } modifiers } fn should_activate_monitors(event: &InputEvent) -> bool { match event { InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true, InputEvent::PointerButton { event } if event.state() == ButtonState::Pressed => true, InputEvent::PointerMotion { .. } | InputEvent::PointerMotionAbsolute { .. } | InputEvent::PointerAxis { .. } | InputEvent::GestureSwipeBegin { .. } | InputEvent::GesturePinchBegin { .. } | InputEvent::GestureHoldBegin { .. } | InputEvent::TouchDown { .. } | InputEvent::TouchMotion { .. } | InputEvent::TabletToolAxis { .. } | InputEvent::TabletToolProximity { .. } | InputEvent::TabletToolTip { .. } | InputEvent::TabletToolButton { .. } => true, // Ignore events like device additions and removals, key releases, gesture ends. _ => false, } } fn should_hide_hotkey_overlay(event: &InputEvent) -> bool { match event { InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true, InputEvent::PointerButton { event } if event.state() == ButtonState::Pressed => true, InputEvent::PointerAxis { .. } | InputEvent::GestureSwipeBegin { .. } | InputEvent::GesturePinchBegin { .. } | InputEvent::TouchDown { .. } | InputEvent::TouchMotion { .. } | InputEvent::TabletToolTip { .. } | InputEvent::TabletToolButton { .. } => true, _ => false, } } fn should_hide_exit_confirm_dialog(event: &InputEvent) -> bool { match event { InputEvent::Keyboard { event } if event.state() == KeyState::Pressed => true, InputEvent::PointerButton { event } if event.state() == ButtonState::Pressed => true, InputEvent::PointerAxis { .. } | InputEvent::GestureSwipeBegin { .. } | InputEvent::GesturePinchBegin { .. } | InputEvent::TouchDown { .. } | InputEvent::TouchMotion { .. } | InputEvent::TabletToolTip { .. } | InputEvent::TabletToolButton { .. } => true, _ => false, } } fn should_notify_activity(event: &InputEvent) -> bool { !matches!( event, InputEvent::DeviceAdded { .. } | InputEvent::DeviceRemoved { .. } ) } fn should_reset_pointer_inactivity_timer(event: &InputEvent) -> bool { matches!( event, InputEvent::PointerAxis { .. } | InputEvent::PointerButton { .. } | InputEvent::PointerMotion { .. } | InputEvent::PointerMotionAbsolute { .. } | InputEvent::TabletToolAxis { .. } | InputEvent::TabletToolButton { .. } | InputEvent::TabletToolProximity { .. } | InputEvent::TabletToolTip { .. } ) } fn allowed_when_locked(action: &Action) -> bool { matches!( action, Action::Quit(_) | Action::ChangeVt(_) | Action::Suspend | Action::PowerOffMonitors | Action::PowerOnMonitors | Action::SwitchLayout(_) ) } fn allowed_during_screenshot(action: &Action) -> bool { matches!( action, Action::Quit(_) | Action::ChangeVt(_) | Action::Suspend | Action::PowerOffMonitors | Action::PowerOnMonitors ) } pub fn apply_libinput_settings(config: &niri_config::Input, device: &mut input::Device) { // According to Mutter code, this setting is specific to touchpads. let is_touchpad = device.config_tap_finger_count() > 0; if is_touchpad { let c = &config.touchpad; let _ = device.config_send_events_set_mode(if c.off { input::SendEventsMode::DISABLED } else if c.disabled_on_external_mouse { input::SendEventsMode::DISABLED_ON_EXTERNAL_MOUSE } else { input::SendEventsMode::ENABLED }); let _ = device.config_tap_set_enabled(c.tap); let _ = device.config_dwt_set_enabled(c.dwt); let _ = device.config_dwtp_set_enabled(c.dwtp); let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll); let _ = device.config_accel_set_speed(c.accel_speed); let _ = device.config_left_handed_set(c.left_handed); let _ = device.config_middle_emulation_set_enabled(c.middle_emulation); if let Some(accel_profile) = c.accel_profile { let _ = device.config_accel_set_profile(accel_profile.into()); } else if let Some(default) = device.config_accel_default_profile() { let _ = device.config_accel_set_profile(default); } if let Some(method) = c.scroll_method { let _ = device.config_scroll_set_method(method.into()); if method == niri_config::ScrollMethod::OnButtonDown { if let Some(button) = c.scroll_button { let _ = device.config_scroll_set_button(button); } } } else if let Some(default) = device.config_scroll_default_method() { let _ = device.config_scroll_set_method(default); if default == input::ScrollMethod::OnButtonDown { if let Some(button) = c.scroll_button { let _ = device.config_scroll_set_button(button); } } } if let Some(tap_button_map) = c.tap_button_map { let _ = device.config_tap_set_button_map(tap_button_map.into()); } else if let Some(default) = device.config_tap_default_button_map() { let _ = device.config_tap_set_button_map(default); } if let Some(method) = c.click_method { let _ = device.config_click_set_method(method.into()); } else if let Some(default) = device.config_click_default_method() { let _ = device.config_click_set_method(default); } } // This is how Mutter tells apart mice. let mut is_trackball = false; let mut is_trackpoint = false; if let Some(udev_device) = unsafe { device.udev_device() } { if udev_device.property_value("ID_INPUT_TRACKBALL").is_some() { is_trackball = true; } if udev_device .property_value("ID_INPUT_POINTINGSTICK") .is_some() { is_trackpoint = true; } } let is_mouse = device.has_capability(input::DeviceCapability::Pointer) && !is_touchpad && !is_trackball && !is_trackpoint; if is_mouse { let c = &config.mouse; let _ = device.config_send_events_set_mode(if c.off { input::SendEventsMode::DISABLED } else { input::SendEventsMode::ENABLED }); let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll); let _ = device.config_accel_set_speed(c.accel_speed); let _ = device.config_left_handed_set(c.left_handed); let _ = device.config_middle_emulation_set_enabled(c.middle_emulation); if let Some(accel_profile) = c.accel_profile { let _ = device.config_accel_set_profile(accel_profile.into()); } else if let Some(default) = device.config_accel_default_profile() { let _ = device.config_accel_set_profile(default); } if let Some(method) = c.scroll_method { let _ = device.config_scroll_set_method(method.into()); if method == niri_config::ScrollMethod::OnButtonDown { if let Some(button) = c.scroll_button { let _ = device.config_scroll_set_button(button); } } } else if let Some(default) = device.config_scroll_default_method() { let _ = device.config_scroll_set_method(default); if default == input::ScrollMethod::OnButtonDown { if let Some(button) = c.scroll_button { let _ = device.config_scroll_set_button(button); } } } } if is_trackball { let c = &config.trackball; let _ = device.config_send_events_set_mode(if c.off { input::SendEventsMode::DISABLED } else { input::SendEventsMode::ENABLED }); let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll); let _ = device.config_accel_set_speed(c.accel_speed); let _ = device.config_middle_emulation_set_enabled(c.middle_emulation); let _ = device.config_left_handed_set(c.left_handed); if let Some(accel_profile) = c.accel_profile { let _ = device.config_accel_set_profile(accel_profile.into()); } else if let Some(default) = device.config_accel_default_profile() { let _ = device.config_accel_set_profile(default); } if let Some(method) = c.scroll_method { let _ = device.config_scroll_set_method(method.into()); if method == niri_config::ScrollMethod::OnButtonDown { if let Some(button) = c.scroll_button { let _ = device.config_scroll_set_button(button); } } } else if let Some(default) = device.config_scroll_default_method() { let _ = device.config_scroll_set_method(default); if default == input::ScrollMethod::OnButtonDown { if let Some(button) = c.scroll_button { let _ = device.config_scroll_set_button(button); } } } } if is_trackpoint { let c = &config.trackpoint; let _ = device.config_send_events_set_mode(if c.off { input::SendEventsMode::DISABLED } else { input::SendEventsMode::ENABLED }); let _ = device.config_scroll_set_natural_scroll_enabled(c.natural_scroll); let _ = device.config_accel_set_speed(c.accel_speed); let _ = device.config_middle_emulation_set_enabled(c.middle_emulation); if let Some(accel_profile) = c.accel_profile { let _ = device.config_accel_set_profile(accel_profile.into()); } else if let Some(default) = device.config_accel_default_profile() { let _ = device.config_accel_set_profile(default); } if let Some(method) = c.scroll_method { let _ = device.config_scroll_set_method(method.into()); if method == niri_config::ScrollMethod::OnButtonDown { if let Some(button) = c.scroll_button { let _ = device.config_scroll_set_button(button); } } } else if let Some(default) = device.config_scroll_default_method() { let _ = device.config_scroll_set_method(default); if default == input::ScrollMethod::OnButtonDown { if let Some(button) = c.scroll_button { let _ = device.config_scroll_set_button(button); } } } } let is_tablet = device.has_capability(input::DeviceCapability::TabletTool); if is_tablet { let c = &config.tablet; let _ = device.config_send_events_set_mode(if c.off { input::SendEventsMode::DISABLED } else { input::SendEventsMode::ENABLED }); let _ = device.config_left_handed_set(c.left_handed); } } pub fn mods_with_binds( comp_mod: CompositorMod, binds: &Binds, triggers: &[Trigger], ) -> HashSet { let comp_mod = match comp_mod { CompositorMod::Super => Modifiers::SUPER, CompositorMod::Alt => Modifiers::ALT, }; let mut rv = HashSet::new(); for bind in &binds.0 { if !triggers.iter().any(|trigger| bind.key.trigger == *trigger) { continue; } let mut mods = bind.key.modifiers; if mods.contains(Modifiers::COMPOSITOR) { mods.remove(Modifiers::COMPOSITOR); mods.insert(comp_mod); } rv.insert(mods); } rv } pub fn mods_with_wheel_binds(comp_mod: CompositorMod, binds: &Binds) -> HashSet { mods_with_binds( comp_mod, binds, &[ Trigger::WheelScrollUp, Trigger::WheelScrollDown, Trigger::WheelScrollLeft, Trigger::WheelScrollRight, ], ) } pub fn mods_with_finger_scroll_binds(comp_mod: CompositorMod, binds: &Binds) -> HashSet { mods_with_binds( comp_mod, binds, &[ Trigger::TouchpadScrollUp, Trigger::TouchpadScrollDown, Trigger::TouchpadScrollLeft, Trigger::TouchpadScrollRight, ], ) } #[cfg(test)] mod tests { use super::*; #[test] fn bindings_suppress_keys() { let close_keysym = Keysym::q; let bindings = Binds(vec![Bind { key: Key { trigger: Trigger::Keysym(close_keysym), modifiers: Modifiers::COMPOSITOR | Modifiers::CTRL, }, action: Action::CloseWindow, repeat: true, cooldown: None, allow_when_locked: false, }]); let comp_mod = CompositorMod::Super; let mut suppressed_keys = HashSet::new(); let screenshot_ui = ScreenshotUi::new(Default::default()); let disable_power_key_handling = false; // The key_code we pick is arbitrary, the only thing // that matters is that they are different between cases. let close_key_code = Keycode::from(close_keysym.raw() + 8u32); let close_key_event = |suppr: &mut HashSet, mods: ModifiersState, pressed| { should_intercept_key( suppr, &bindings, comp_mod, close_key_code, close_keysym, Some(close_keysym), pressed, mods, &screenshot_ui, disable_power_key_handling, ) }; // Key event with the code which can't trigger any action. let none_key_event = |suppr: &mut HashSet, mods: ModifiersState, pressed| { should_intercept_key( suppr, &bindings, comp_mod, Keycode::from(Keysym::l.raw() + 8), Keysym::l, Some(Keysym::l), pressed, mods, &screenshot_ui, disable_power_key_handling, ) }; let mut mods = ModifiersState { logo: true, ctrl: true, ..Default::default() }; // Action press/release. let filter = close_key_event(&mut suppressed_keys, mods, true); assert!(matches!( filter, FilterResult::Intercept(Some(Bind { action: Action::CloseWindow, .. })) )); assert!(suppressed_keys.contains(&close_key_code)); let filter = close_key_event(&mut suppressed_keys, mods, false); assert!(matches!(filter, FilterResult::Intercept(None))); assert!(suppressed_keys.is_empty()); // Remove mod to make it for a binding. mods.shift = true; let filter = close_key_event(&mut suppressed_keys, mods, true); assert!(matches!(filter, FilterResult::Forward)); mods.shift = false; let filter = close_key_event(&mut suppressed_keys, mods, false); assert!(matches!(filter, FilterResult::Forward)); // Just none press/release. let filter = none_key_event(&mut suppressed_keys, mods, true); assert!(matches!(filter, FilterResult::Forward)); let filter = none_key_event(&mut suppressed_keys, mods, false); assert!(matches!(filter, FilterResult::Forward)); // Press action, press arbitrary, release action, release arbitrary. let filter = close_key_event(&mut suppressed_keys, mods, true); assert!(matches!( filter, FilterResult::Intercept(Some(Bind { action: Action::CloseWindow, .. })) )); let filter = none_key_event(&mut suppressed_keys, mods, true); assert!(matches!(filter, FilterResult::Forward)); let filter = close_key_event(&mut suppressed_keys, mods, false); assert!(matches!(filter, FilterResult::Intercept(None))); let filter = none_key_event(&mut suppressed_keys, mods, false); assert!(matches!(filter, FilterResult::Forward)); // Trigger and remove all mods. let filter = close_key_event(&mut suppressed_keys, mods, true); assert!(matches!( filter, FilterResult::Intercept(Some(Bind { action: Action::CloseWindow, .. })) )); mods = Default::default(); let filter = close_key_event(&mut suppressed_keys, mods, false); assert!(matches!(filter, FilterResult::Intercept(None))); // Ensure that no keys are being suppressed. assert!(suppressed_keys.is_empty()); } #[test] fn comp_mod_handling() { let bindings = Binds(vec![ Bind { key: Key { trigger: Trigger::Keysym(Keysym::q), modifiers: Modifiers::COMPOSITOR, }, action: Action::CloseWindow, repeat: true, cooldown: None, allow_when_locked: false, }, Bind { key: Key { trigger: Trigger::Keysym(Keysym::h), modifiers: Modifiers::SUPER, }, action: Action::FocusColumnLeft, repeat: true, cooldown: None, allow_when_locked: false, }, Bind { key: Key { trigger: Trigger::Keysym(Keysym::j), modifiers: Modifiers::empty(), }, action: Action::FocusWindowDown, repeat: true, cooldown: None, allow_when_locked: false, }, Bind { key: Key { trigger: Trigger::Keysym(Keysym::k), modifiers: Modifiers::COMPOSITOR | Modifiers::SUPER, }, action: Action::FocusWindowUp, repeat: true, cooldown: None, allow_when_locked: false, }, Bind { key: Key { trigger: Trigger::Keysym(Keysym::l), modifiers: Modifiers::SUPER | Modifiers::ALT, }, action: Action::FocusColumnRight, repeat: true, cooldown: None, allow_when_locked: false, }, ]); assert_eq!( find_configured_bind( &bindings, CompositorMod::Super, Trigger::Keysym(Keysym::q), ModifiersState { logo: true, ..Default::default() } ) .as_ref(), Some(&bindings.0[0]) ); assert_eq!( find_configured_bind( &bindings, CompositorMod::Super, Trigger::Keysym(Keysym::q), ModifiersState::default(), ), None, ); assert_eq!( find_configured_bind( &bindings, CompositorMod::Super, Trigger::Keysym(Keysym::h), ModifiersState { logo: true, ..Default::default() } ) .as_ref(), Some(&bindings.0[1]) ); assert_eq!( find_configured_bind( &bindings, CompositorMod::Super, Trigger::Keysym(Keysym::h), ModifiersState::default(), ), None, ); assert_eq!( find_configured_bind( &bindings, CompositorMod::Super, Trigger::Keysym(Keysym::j), ModifiersState { logo: true, ..Default::default() } ), None, ); assert_eq!( find_configured_bind( &bindings, CompositorMod::Super, Trigger::Keysym(Keysym::j), ModifiersState::default(), ) .as_ref(), Some(&bindings.0[2]) ); assert_eq!( find_configured_bind( &bindings, CompositorMod::Super, Trigger::Keysym(Keysym::k), ModifiersState { logo: true, ..Default::default() } ) .as_ref(), Some(&bindings.0[3]) ); assert_eq!( find_configured_bind( &bindings, CompositorMod::Super, Trigger::Keysym(Keysym::k), ModifiersState::default(), ), None, ); assert_eq!( find_configured_bind( &bindings, CompositorMod::Super, Trigger::Keysym(Keysym::l), ModifiersState { logo: true, alt: true, ..Default::default() } ) .as_ref(), Some(&bindings.0[4]) ); assert_eq!( find_configured_bind( &bindings, CompositorMod::Super, Trigger::Keysym(Keysym::l), ModifiersState { logo: true, ..Default::default() }, ), None, ); } }