diff --git a/niri-config/src/binds.rs b/niri-config/src/binds.rs index 3525a84f..4a715f68 100644 --- a/niri-config/src/binds.rs +++ b/niri-config/src/binds.rs @@ -22,7 +22,7 @@ pub struct Binds(pub Vec); #[derive(Debug, Clone, PartialEq)] pub struct Bind { pub key: Key, - pub action: Action, + pub action: BoundAction, pub repeat: bool, pub cooldown: Option, pub allow_when_locked: bool, @@ -30,6 +30,45 @@ pub struct Bind { pub hotkey_overlay_title: Option>, } +#[derive(Debug, Clone, PartialEq)] +pub enum BoundAction { + Press(Action), + Release(Action), + Both { press: Action, release: Action }, +} + +impl Bind { + pub fn has_press(&self) -> bool { + matches!( + self.action, + BoundAction::Press(_) | BoundAction::Both { .. } + ) + } + + pub fn has_release(&self) -> bool { + matches!( + self.action, + BoundAction::Release(_) | BoundAction::Both { .. } + ) + } + + pub fn press_action(&self) -> Option<&Action> { + match &self.action { + BoundAction::Press(action) => Some(action), + BoundAction::Both { press, .. } => Some(press), + BoundAction::Release(_) => None, + } + } + + pub fn release_action(&self) -> Option<&Action> { + match &self.action { + BoundAction::Release(action) => Some(action), + BoundAction::Both { release, .. } => Some(release), + BoundAction::Press(_) => None, + } + } +} + #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)] pub struct Key { pub trigger: Trigger, @@ -921,16 +960,19 @@ where .parse::() .map_err(|e| DecodeError::conversion(&node.node_name, e.wrap_err("invalid keybind")))?; - let mut repeat = true; + let mut repeat = None; + let mut repeat_node = None; let mut cooldown = None; let mut allow_when_locked = false; let mut allow_when_locked_node = None; let mut allow_inhibiting = true; let mut hotkey_overlay_title = None; + for (name, val) in &node.properties { match &***name { "repeat" => { - repeat = knuffel::traits::DecodeScalar::decode(val, ctx)?; + repeat = Some(knuffel::traits::DecodeScalar::decode(val, ctx)?); + repeat_node = Some(name); } "cooldown-ms" => { cooldown = Some(Duration::from_millis( @@ -957,14 +999,12 @@ where } } - let mut children = node.children(); - // If the action is invalid but the key is fine, we still want to return something. // That way, the parent can handle the existence of duplicate keybinds, // even if their contents are not valid. let dummy = Self { key, - action: Action::Spawn(vec![]), + action: BoundAction::Press(Action::Spawn(vec![])), repeat: true, cooldown: None, allow_when_locked: false, @@ -972,54 +1012,182 @@ where hotkey_overlay_title: None, }; - if let Some(child) = children.next() { - for unwanted_child in children { - ctx.emit_error(DecodeError::unexpected( - unwanted_child, - "node", - "only one action is allowed per keybind", - )); - } + // direct_action is an action node that is not wrapped in a press or release section + let mut direct_action: Option = None; + let mut press_action: Option = None; + let mut release_action: Option = None; + + let decode_action = |ctx: &mut knuffel::decode::Context, + child: &knuffel::ast::SpannedNode| { match Action::decode_node(child, ctx) { - Ok(action) => { - if !matches!(action, Action::Spawn(_) | Action::SpawnSh(_)) { - if let Some(node) = allow_when_locked_node { - ctx.emit_error(DecodeError::unexpected( - node, - "property", - "allow-when-locked can only be set on spawn binds", - )); - } - } + Ok(action) => Some(action), + Err(e) => { + ctx.emit_error(e); + None + } + } + }; - // The toggle-inhibit action must always be uninhibitable. - // Otherwise, it would be impossible to trigger it. - if matches!(action, Action::ToggleKeyboardShortcutsInhibit) { - allow_inhibiting = false; - } + for child in node.children() { + let child_name = &*child.node_name; + let child_name: &str = child_name.as_ref(); + + if child_name == "press" || child_name == "release" { + let is_press = child_name == "press"; + let slot = if is_press { + &mut press_action + } else { + &mut release_action + }; + + if slot.is_some() { + ctx.emit_error(DecodeError::unexpected( + &child.node_name, + "section", + format!("duplicate `{child_name}` section"), + )); + continue; + } - Ok(Self { - key, - action, - repeat, - cooldown, - allow_when_locked, - allow_inhibiting, - hotkey_overlay_title, - }) + if direct_action.is_some() { + ctx.emit_error(DecodeError::unexpected( + &child.node_name, + "section", + "cannot mix direct actions with press/release sections", + )); + continue; } - Err(e) => { - ctx.emit_error(e); - Ok(dummy) + + // The action is the section's single child node. + let mut children = child.children(); + let Some(action_child) = children.next() else { + ctx.emit_error(DecodeError::missing( + child, + format!("expected an action for this {child_name} section"), + )); + continue; + }; + + for unwanted_child in children { + ctx.emit_error(DecodeError::unexpected( + unwanted_child, + "node", + "only one action is allowed per keybind", + )); + } + + *slot = decode_action(ctx, action_child); + } else { + if direct_action.is_some() { + ctx.emit_error(DecodeError::unexpected( + &child.node_name, + "node", + "only one action is allowed per keybind", + )); + continue; + } + + if press_action.is_some() || release_action.is_some() { + ctx.emit_error(DecodeError::unexpected( + &child.node_name, + "node", + "cannot mix direct actions with press/release sections", + )); + continue; } + + direct_action = decode_action(ctx, child); } - } else { - ctx.emit_error(DecodeError::missing( + } + + let press_action = press_action.or(direct_action); + + if release_action.is_some() + && matches!( + key.trigger, + Trigger::WheelScrollDown + | Trigger::WheelScrollUp + | Trigger::WheelScrollLeft + | Trigger::WheelScrollRight + | Trigger::TouchpadScrollDown + | Trigger::TouchpadScrollUp + | Trigger::TouchpadScrollLeft + | Trigger::TouchpadScrollRight + ) + { + ctx.emit_error(DecodeError::unexpected( node, - "expected an action for this keybind", + "bind", + "release sections are not supported for scroll binds", )); - Ok(dummy) + release_action = None; + } + + if let Some(node) = repeat_node { + if repeat == Some(true) && press_action.is_none() && release_action.is_some() { + ctx.emit_error(DecodeError::unexpected( + node, + "property", + "release-only binds cannot repeat", + )); + } + } + + if let Some(node) = allow_when_locked_node { + for action in press_action.iter().chain(release_action.iter()) { + if !matches!(action, Action::Spawn(_) | Action::SpawnSh(_)) { + ctx.emit_error(DecodeError::unexpected( + node, + "property", + "allow-when-locked can only be set on spawn binds", + )); + } + } + } + + // The toggle-inhibit action must always be uninhibitable. + // Otherwise, it would be impossible to trigger it. + if matches!(press_action, Some(Action::ToggleKeyboardShortcutsInhibit)) + || matches!(release_action, Some(Action::ToggleKeyboardShortcutsInhibit)) + { + allow_inhibiting = false; } + + let repeat = match repeat { + Some(value) => value, + None => release_action.is_none(), + }; + + let action = match (press_action, release_action) { + (Some(press), Some(release)) => BoundAction::Both { press, release }, + (Some(press), None) => BoundAction::Press(press), + (None, Some(release)) => BoundAction::Release(release), + (None, None) => { + // If a press or release section was present, an error about its missing or + // invalid action was already emitted above. + let has_section = node.children().any(|child| { + let name = child.node_name.as_ref(); + name == "press" || name == "release" + }); + if !has_section { + ctx.emit_error(DecodeError::missing( + node, + "expected an action for this keybind", + )); + } + return Ok(dummy); + } + }; + + Ok(Self { + key, + action, + repeat, + cooldown, + allow_when_locked, + allow_inhibiting, + hotkey_overlay_title, + }) } } diff --git a/niri-config/src/lib.rs b/niri-config/src/lib.rs index 6066ebc7..40eccb55 100644 --- a/niri-config/src/lib.rs +++ b/niri-config/src/lib.rs @@ -950,6 +950,12 @@ mod tests { Mod+Shift+E allow-inhibiting=false { quit skip-confirmation=true; } Mod+WheelScrollDown cooldown-ms=150 { focus-workspace-down; } Super+Alt+S allow-when-locked=true { spawn-sh "pkill orca || exec orca"; } + Mod { + release { toggle-overview; } + } + Shift+Mod { + release { toggle-window-floating; } + } } switch-events { @@ -2006,7 +2012,9 @@ mod tests { COMPOSITOR, ), }, - action: ToggleKeyboardShortcutsInhibit, + action: Press( + ToggleKeyboardShortcutsInhibit, + ), repeat: true, cooldown: None, allow_when_locked: false, @@ -2026,7 +2034,9 @@ mod tests { SHIFT | COMPOSITOR, ), }, - action: ToggleKeyboardShortcutsInhibit, + action: Press( + ToggleKeyboardShortcutsInhibit, + ), repeat: true, cooldown: None, allow_when_locked: false, @@ -2042,10 +2052,12 @@ mod tests { COMPOSITOR, ), }, - action: Spawn( - [ - "alacritty", - ], + action: Press( + Spawn( + [ + "alacritty", + ], + ), ), repeat: true, cooldown: None, @@ -2062,7 +2074,9 @@ mod tests { COMPOSITOR, ), }, - action: CloseWindow, + action: Press( + CloseWindow, + ), repeat: true, cooldown: None, allow_when_locked: false, @@ -2080,7 +2094,9 @@ mod tests { SHIFT | COMPOSITOR, ), }, - action: FocusMonitorLeft, + action: Press( + FocusMonitorLeft, + ), repeat: true, cooldown: None, allow_when_locked: false, @@ -2096,8 +2112,10 @@ mod tests { SHIFT | COMPOSITOR, ), }, - action: FocusMonitor( - "eDP-1", + action: Press( + FocusMonitor( + "eDP-1", + ), ), repeat: true, cooldown: None, @@ -2114,7 +2132,9 @@ mod tests { CTRL | SHIFT | COMPOSITOR, ), }, - action: MoveWindowToMonitorRight, + action: Press( + MoveWindowToMonitorRight, + ), repeat: true, cooldown: None, allow_when_locked: false, @@ -2130,8 +2150,10 @@ mod tests { CTRL | ALT | COMPOSITOR, ), }, - action: MoveWindowToMonitor( - "eDP-1", + action: Press( + MoveWindowToMonitor( + "eDP-1", + ), ), repeat: true, cooldown: None, @@ -2148,8 +2170,10 @@ mod tests { CTRL | ALT | COMPOSITOR, ), }, - action: MoveColumnToMonitor( - "DP-1", + action: Press( + MoveColumnToMonitor( + "DP-1", + ), ), repeat: true, cooldown: None, @@ -2166,7 +2190,9 @@ mod tests { COMPOSITOR, ), }, - action: ConsumeWindowIntoColumn, + action: Press( + ConsumeWindowIntoColumn, + ), repeat: true, cooldown: None, allow_when_locked: false, @@ -2182,9 +2208,11 @@ mod tests { COMPOSITOR, ), }, - action: FocusWorkspace( - Index( - 1, + action: Press( + FocusWorkspace( + Index( + 1, + ), ), ), repeat: true, @@ -2202,9 +2230,11 @@ mod tests { SHIFT | COMPOSITOR, ), }, - action: FocusWorkspace( - Name( - "workspace-1", + action: Press( + FocusWorkspace( + Name( + "workspace-1", + ), ), ), repeat: true, @@ -2222,8 +2252,10 @@ mod tests { SHIFT | COMPOSITOR, ), }, - action: Quit( - true, + action: Press( + Quit( + true, + ), ), repeat: true, cooldown: None, @@ -2238,7 +2270,9 @@ mod tests { COMPOSITOR, ), }, - action: FocusWorkspaceDown, + action: Press( + FocusWorkspaceDown, + ), repeat: true, cooldown: Some( 150ms, @@ -2256,8 +2290,10 @@ mod tests { ALT | SUPER, ), }, - action: SpawnSh( - "pkill orca || exec orca", + action: Press( + SpawnSh( + "pkill orca || exec orca", + ), ), repeat: true, cooldown: None, @@ -2265,6 +2301,38 @@ mod tests { allow_inhibiting: true, hotkey_overlay_title: None, }, + Bind { + key: Key { + trigger: CompositorMod, + modifiers: Modifiers( + COMPOSITOR, + ), + }, + action: Release( + ToggleOverview, + ), + repeat: false, + cooldown: None, + allow_when_locked: false, + allow_inhibiting: true, + hotkey_overlay_title: None, + }, + Bind { + key: Key { + trigger: CompositorMod, + modifiers: Modifiers( + SHIFT | COMPOSITOR, + ), + }, + action: Release( + ToggleWindowFloating, + ), + repeat: false, + cooldown: None, + allow_when_locked: false, + allow_inhibiting: true, + hotkey_overlay_title: None, + }, ], ), switch_events: SwitchBinds { @@ -2378,13 +2446,15 @@ mod tests { ALT, ), }, - action: MruAdvance { - direction: Forward, - scope: None, - filter: Some( - All, - ), - }, + action: Press( + MruAdvance { + direction: Forward, + scope: None, + filter: Some( + All, + ), + }, + ), repeat: true, cooldown: None, allow_when_locked: false, @@ -2400,13 +2470,15 @@ mod tests { ALT, ), }, - action: MruAdvance { - direction: Forward, - scope: None, - filter: Some( - AppId, - ), - }, + action: Press( + MruAdvance { + direction: Forward, + scope: None, + filter: Some( + AppId, + ), + }, + ), repeat: true, cooldown: None, allow_when_locked: false, @@ -2422,15 +2494,17 @@ mod tests { SUPER, ), }, - action: MruAdvance { - direction: Forward, - scope: Some( - Output, - ), - filter: Some( - All, - ), - }, + action: Press( + MruAdvance { + direction: Forward, + scope: Some( + Output, + ), + filter: Some( + All, + ), + }, + ), repeat: true, cooldown: None, allow_when_locked: false, diff --git a/niri-config/src/recent_windows.rs b/niri-config/src/recent_windows.rs index ba0710cc..958a325f 100644 --- a/niri-config/src/recent_windows.rs +++ b/niri-config/src/recent_windows.rs @@ -2,7 +2,7 @@ use knuffel::errors::DecodeError; use smithay::input::keyboard::Keysym; use crate::utils::{expect_only_children, MergeWith}; -use crate::{Action, Bind, Color, FloatOrInt, Key, Modifiers, Trigger}; +use crate::{Action, Bind, BoundAction, Color, FloatOrInt, Key, Modifiers, Trigger}; #[derive(Debug, PartialEq)] pub struct RecentWindows { @@ -146,7 +146,7 @@ impl From for Bind { fn from(x: MruBind) -> Self { Self { key: x.key, - action: Action::from(x.action), + action: BoundAction::Press(Action::from(x.action)), repeat: true, cooldown: None, allow_when_locked: false, diff --git a/src/backend/tty.rs b/src/backend/tty.rs index c30ca6ba..3629a15f 100644 --- a/src/backend/tty.rs +++ b/src/backend/tty.rs @@ -618,6 +618,14 @@ impl Tty { SessionEvent::PauseSession => { debug!("pausing session"); + // We won't receive key or button releases for whatever is held down while the + // session is paused, so forget about all of it. + // + // Slightly cursed to do from an idle... But we don't have State here conveniently, + // and it should be fine to delay this until the loop callback. + niri.event_loop + .insert_idle(|state| state.release_held_inputs()); + self.libinput.suspend(); for device in self.devices.values_mut() { diff --git a/src/input/mod.rs b/src/input/mod.rs index 8129ec69..e8ea269a 100644 --- a/src/input/mod.rs +++ b/src/input/mod.rs @@ -1,12 +1,14 @@ use std::any::Any; use std::collections::hash_map::Entry; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::time::Duration; use calloop::timer::{TimeoutAction, Timer}; +use calloop::RegistrationToken; use input::event::gesture::GestureEventCoordinates as _; use niri_config::{ - Action, Bind, Binds, Config, Key, ModKey, Modifiers, MruDirection, SwitchBinds, Trigger, + is_keysym_modifier, Action, Bind, Binds, BoundAction, Config, Key, ModKey, Modifiers, + MruDirection, SwitchBinds, Trigger, }; use niri_ipc::LayoutSwitchTarget; use smithay::backend::input::{ @@ -50,7 +52,7 @@ use self::spatial_movement_grab::SpatialMovementGrab; use crate::dbus::freedesktop_a11y::KbMonBlock; use crate::layout::scrolling::ScrollDirection; use crate::layout::{ActivateWindow, LayoutElement as _}; -use crate::niri::{CastTarget, PointerVisibility, State}; +use crate::niri::{CastTarget, Niri, PointerVisibility, State}; use crate::ui::mru::{WindowMru, WindowMruUi}; use crate::ui::screenshot_ui::ScreenshotUi; use crate::utils::spawning::{spawn, spawn_sh}; @@ -137,6 +139,8 @@ impl AnyStartData { enum ShouldInterceptResult { /// Forward the event to the focused client. Forward, + /// Forward the event to the focused client, and handle the given bind. + ForwardAndHandle(Bind), /// Do not forward the event, and handle the given bind. InterceptAndHandle(Bind), /// Do not forward the event, and do nothing else. @@ -492,6 +496,13 @@ impl State { // The accessibility modifier first press must not change XKB state, so we return // early here. if block == KbMonBlock::ModifierFirstPress { + // A pending release action recorded for the key must still run. + if !pressed { + if let Some(bind) = self.niri.pending_release_binds.remove(&event.key_code()) { + self.niri.suppressed_keys.remove(&event.key_code()); + self.handle_bind(bind, false); + } + } return; } block @@ -533,8 +544,13 @@ impl State { // modifiers without accidentally leaking them to wl_keyboard.enter. So for now // let's forward modifier releases to the clients here to deal with the most // common case. - if !pressed - && matches!( + if !pressed { + // The accessibility handler consumes the release. + // So, make sure to run any pending release actions. + let bind = this.niri.pending_release_binds.remove(&key_code); + this.niri.suppressed_keys.remove(&key_code); + + let forward = matches!( modified, Keysym::Shift_L | Keysym::Shift_R @@ -544,12 +560,11 @@ impl State { | Keysym::Super_R | Keysym::Alt_L | Keysym::Alt_R - ) - { - return ShouldInterceptResult::Forward; - } else { - return ShouldInterceptResult::InterceptOnly; + ); + return bind_intercept_result(bind, forward); } + + return ShouldInterceptResult::InterceptOnly; } if this.niri.exit_confirm_dialog.is_open() && pressed { @@ -568,11 +583,13 @@ impl State { if this.niri.window_mru_ui.is_open() && !pressed && modifiers.is_empty() { this.do_action(Action::MruConfirm, false); - if this.niri.suppressed_keys.remove(&key_code) { - return ShouldInterceptResult::InterceptOnly; - } else { - return ShouldInterceptResult::Forward; - } + // A pending release action recorded for the key must still run if it + // closed the MRU instead of going through the regular bind lookup. + return released_key_intercept_result( + &mut this.niri.suppressed_keys, + &mut this.niri.pending_release_binds, + key_code, + ); } if pressed && raw == Some(Keysym::Escape) { @@ -592,6 +609,11 @@ impl State { this.niri.screenshot_ui.set_space_down(pressed); } + if pressed { + this.niri.cancel_interrupted_release_binds(); + } + + let is_locked = this.niri.is_locked(); let res = { let config = this.niri.config.borrow(); let bindings = @@ -599,6 +621,8 @@ impl State { should_intercept_key( &mut this.niri.suppressed_keys, + &mut this.niri.pending_release_binds, + &this.niri.bind_cooldown_timers, bindings, mod_key, key_code, @@ -609,6 +633,7 @@ impl State { &this.niri.screenshot_ui, this.niri.config.borrow().input.disable_power_key_handling, is_inhibiting_shortcuts, + is_locked, ) }; @@ -633,8 +658,9 @@ impl State { return; }; - match result { - ShouldInterceptResult::Forward => { + // Forward the event to the client, unless the key was intercepted. + match &result { + ShouldInterceptResult::Forward | ShouldInterceptResult::ForwardAndHandle(_) => { keyboard.input_forward( self, event.key_code(), @@ -644,13 +670,23 @@ impl State { mods_changed, ); } - ShouldInterceptResult::InterceptAndHandle(bind) => { + ShouldInterceptResult::InterceptAndHandle(_) | ShouldInterceptResult::InterceptOnly => { + if mods_changed { + keyboard.advertise_modifier_state(self); + } + } + } + + // Handle the bind, if the result came with one. + match result { + ShouldInterceptResult::ForwardAndHandle(bind) + | ShouldInterceptResult::InterceptAndHandle(bind) => { + self.handle_bind(bind.clone(), pressed); if pressed { - self.handle_bind(bind.clone()); self.start_key_repeat(bind); } } - ShouldInterceptResult::InterceptOnly => {} + ShouldInterceptResult::Forward | ShouldInterceptResult::InterceptOnly => {} } } @@ -680,7 +716,7 @@ impl State { .niri .event_loop .insert_source(repeat_timer, move |_, _, state| { - state.handle_bind(bind.clone()); + state.handle_bind(bind.clone(), true); TimeoutAction::ToDuration(repeat_duration) }) .unwrap(); @@ -710,37 +746,75 @@ impl State { 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); + pub fn handle_bind(&mut self, bind: Bind, pressed: bool) { + let action = if pressed { + bind.press_action() + } else { + bind.release_action() + }; + let Some(action) = action.cloned() else { return; }; + let allowed_when_locked = bind_allowed_when_locked(&bind, pressed); + let allowed_during_screenshot = bind_allowed_during_screenshot(&bind, pressed); + // 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)) { + if self.niri.is_locked() && !allowed_when_locked { 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); + // The bind lookup already substitutes the screenshot UI's own + // actions for presses, so only releases need to be filtered here. + if !pressed && self.niri.screenshot_ui.is_open() && !allowed_during_screenshot { + return; + } - self.do_action(bind.action, bind.allow_when_locked); + // Check to see if we are under a cooldown. + // We apply the cooldown to the press action for press-only and press/release. + // We apply the cooldown to the release action for release-only. + if pressed == bind.has_press() { + if let Some(cooldown) = bind.cooldown { + match self.niri.bind_cooldown_timers.entry(bind.key) { + // The bind is on cooldown, so don't run its action. + Entry::Occupied(_) => return, + 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(action, allowed_when_locked); + } + + /// Forgets all held inputs, running the release actions of anything that was still held. + pub fn release_held_inputs(&mut self) { + let mut binds = Vec::new(); + binds.extend( + self.niri + .pending_release_binds + .drain() + .map(|(_, bind)| bind), + ); + + // Forget the rest of the input state: the releases will never arrive. + self.niri.clear_input_state(); + + for bind in binds { + self.handle_bind(bind, false); + } } pub fn do_action(&mut self, action: Action, allow_when_locked: bool) { @@ -763,26 +837,18 @@ impl State { 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(); + // Changing VT may not deliver the key releases, so treat the held binds as + // released while the session is still usable. + self.release_held_inputs(); - // Stop ongoing key repeat if any. - if let Some(token) = self.niri.bind_repeat_timer.take() { - self.niri.event_loop.remove(token); - } + self.backend.change_vt(vt); } Action::Suspend => { - self.backend.suspend(); + // Suspend may not deliver the key releases, so treat the held binds as + // released before suspending. + self.release_held_inputs(); - // Suspend may not deliver the key releases, so clear the state. - self.niri.suppressed_keys.clear(); - - // Stop ongoing key repeat if any. - if let Some(token) = self.niri.bind_repeat_timer.take() { - self.niri.event_loop.remove(token); - } + self.backend.suspend(); } Action::PowerOffMonitors => { self.niri.deactivate_monitors(&mut self.backend); @@ -2869,16 +2935,17 @@ impl State { let mod_key = self.backend.mod_key(&self.niri.config.borrow()); - // Ignore release events for mouse clicks that triggered a bind. - if self.niri.suppressed_buttons.remove(&button_code) { - return; - } - let mods = self.niri.seat.get_keyboard().unwrap().modifier_state(); let modifiers = modifiers_from_state(mods); let mod_down = modifiers.contains(mod_key.to_modifiers()); + if self.niri.suppressed_buttons.remove(&button_code) { + return; + } + if ButtonState::Pressed == button_state { + self.niri.cancel_interrupted_release_binds(); + let mut is_mru_open = false; if let Some(mru_output) = self.niri.window_mru_ui.output() { is_mru_open = true; @@ -2917,12 +2984,14 @@ impl State { find_configured_bind(bindings, mod_key, trigger, mods) }) .filter(|bind| { - !self.niri.screenshot_ui.is_open() || allowed_during_screenshot(&bind.action) + !self.niri.screenshot_ui.is_open() || bind_allowed_during_screenshot(bind, true) }) { self.niri.suppressed_buttons.insert(button_code); - self.handle_bind(bind.clone()); + if bind.has_press() { + self.handle_bind(bind.clone(), true); + } return; - }; + } } // We received an event for the regular pointer, so show it now. @@ -3187,6 +3256,8 @@ impl State { } fn on_pointer_axis(&mut self, event: I::PointerAxisEvent) { + self.niri.cancel_interrupted_release_binds(); + let pointer = &self.niri.seat.get_pointer().unwrap(); let source = event.source(); @@ -3249,7 +3320,7 @@ impl State { trigger: Trigger::WheelScrollLeft, modifiers: Modifiers::empty(), }, - action: Action::FocusColumnLeftUnderMouse, + action: BoundAction::Press(Action::FocusColumnLeftUnderMouse), repeat: true, cooldown: None, allow_when_locked: false, @@ -3261,7 +3332,7 @@ impl State { trigger: Trigger::WheelScrollRight, modifiers: Modifiers::empty(), }, - action: Action::FocusColumnRightUnderMouse, + action: BoundAction::Press(Action::FocusColumnRightUnderMouse), repeat: true, cooldown: None, allow_when_locked: false, @@ -3281,7 +3352,7 @@ impl State { ) .filter(|bind| { !self.niri.screenshot_ui.is_open() - || allowed_during_screenshot(&bind.action) + || bind_allowed_during_screenshot(bind, true) }); let bind_right = find_configured_bind( bindings, @@ -3291,19 +3362,19 @@ impl State { ) .filter(|bind| { !self.niri.screenshot_ui.is_open() - || allowed_during_screenshot(&bind.action) + || bind_allowed_during_screenshot(bind, true) }); (bind_left, bind_right) }; if let Some(right) = bind_right { for _ in 0..ticks { - self.handle_bind(right.clone()); + self.handle_bind(right.clone(), true); } } if let Some(left) = bind_left { for _ in ticks..0 { - self.handle_bind(left.clone()); + self.handle_bind(left.clone(), true); } } } @@ -3329,7 +3400,7 @@ impl State { trigger: Trigger::WheelScrollUp, modifiers: Modifiers::empty(), }, - action: Action::FocusWorkspaceUpUnderMouse, + action: BoundAction::Press(Action::FocusWorkspaceUpUnderMouse), repeat: true, cooldown: Some(Duration::from_millis(50)), allow_when_locked: false, @@ -3341,7 +3412,7 @@ impl State { trigger: Trigger::WheelScrollDown, modifiers: Modifiers::empty(), }, - action: Action::FocusWorkspaceDownUnderMouse, + action: BoundAction::Press(Action::FocusWorkspaceDownUnderMouse), repeat: true, cooldown: Some(Duration::from_millis(50)), allow_when_locked: false, @@ -3355,7 +3426,7 @@ impl State { trigger: Trigger::WheelScrollUp, modifiers: Modifiers::empty(), }, - action: Action::FocusColumnLeftUnderMouse, + action: BoundAction::Press(Action::FocusColumnLeftUnderMouse), repeat: true, cooldown: Some(Duration::from_millis(50)), allow_when_locked: false, @@ -3367,7 +3438,7 @@ impl State { trigger: Trigger::WheelScrollDown, modifiers: Modifiers::empty(), }, - action: Action::FocusColumnRightUnderMouse, + action: BoundAction::Press(Action::FocusColumnRightUnderMouse), repeat: true, cooldown: Some(Duration::from_millis(50)), allow_when_locked: false, @@ -3387,25 +3458,25 @@ impl State { ) .filter(|bind| { !self.niri.screenshot_ui.is_open() - || allowed_during_screenshot(&bind.action) + || bind_allowed_during_screenshot(bind, true) }); let bind_down = find_configured_bind(bindings, mod_key, Trigger::WheelScrollDown, mods) .filter(|bind| { !self.niri.screenshot_ui.is_open() - || allowed_during_screenshot(&bind.action) + || bind_allowed_during_screenshot(bind, true) }); (bind_up, bind_down) }; if let Some(down) = bind_down { for _ in 0..ticks { - self.handle_bind(down.clone()); + self.handle_bind(down.clone(), true); } } if let Some(up) = bind_up { for _ in ticks..0 { - self.handle_bind(up.clone()); + self.handle_bind(up.clone(), true); } } } @@ -3539,24 +3610,24 @@ impl State { ) .filter(|bind| { !self.niri.screenshot_ui.is_open() - || allowed_during_screenshot(&bind.action) + || bind_allowed_during_screenshot(bind, true) }); let bind_right = find_configured_bind(bindings, mod_key, Trigger::TouchpadScrollRight, mods) .filter(|bind| { !self.niri.screenshot_ui.is_open() - || allowed_during_screenshot(&bind.action) + || bind_allowed_during_screenshot(bind, true) }); drop(config); if let Some(right) = bind_right { for _ in 0..ticks { - self.handle_bind(right.clone()); + self.handle_bind(right.clone(), true); } } if let Some(left) = bind_left { for _ in ticks..0 { - self.handle_bind(left.clone()); + self.handle_bind(left.clone(), true); } } } @@ -3577,24 +3648,24 @@ impl State { ) .filter(|bind| { !self.niri.screenshot_ui.is_open() - || allowed_during_screenshot(&bind.action) + || bind_allowed_during_screenshot(bind, true) }); let bind_down = find_configured_bind(bindings, mod_key, Trigger::TouchpadScrollDown, mods) .filter(|bind| { !self.niri.screenshot_ui.is_open() - || allowed_during_screenshot(&bind.action) + || bind_allowed_during_screenshot(bind, true) }); drop(config); if let Some(down) = bind_down { for _ in 0..ticks { - self.handle_bind(down.clone()); + self.handle_bind(down.clone(), true); } } if let Some(up) = bind_up { for _ in ticks..0 { - self.handle_bind(up.clone()); + self.handle_bind(up.clone(), true); } } } @@ -3771,6 +3842,8 @@ impl State { match tip_state { TabletToolTipState::Down => { + self.niri.cancel_interrupted_release_binds(); + if let Some(pos) = self.niri.tablet_cursor_location { let under = self.niri.contents_under(pos); @@ -3986,10 +4059,9 @@ impl State { if let Some(tool) = tool { let button = event.button(); + let button_state = event.button_state(); - if self.niri.suppressed_buttons.remove(&button) { - return; - } + let mod_key = self.backend.mod_key(&self.niri.config.borrow()); let trigger = match button { BTN_STYLUS => Some(Trigger::TabletStylusButton1), @@ -3998,9 +4070,17 @@ impl State { _ => None, }; + if self.niri.suppressed_buttons.remove(&button) { + return; + } + + if button_state == ButtonState::Pressed { + self.niri.cancel_interrupted_release_binds(); + } + + // Handle press binds. if let Some(trigger) = trigger { - if event.button_state() == ButtonState::Pressed { - let mod_key = self.backend.mod_key(&self.niri.config.borrow()); + if button_state == ButtonState::Pressed { let mods = self.niri.seat.get_keyboard().unwrap().modifier_state(); let modifiers = modifiers_from_state(mods); @@ -4012,11 +4092,13 @@ impl State { } .filter(|bind| { !self.niri.screenshot_ui.is_open() - || allowed_during_screenshot(&bind.action) + || bind_allowed_during_screenshot(bind, true) }); if let Some(bind) = bind { self.niri.suppressed_buttons.insert(button); - self.handle_bind(bind.clone()); + if bind.has_press() { + self.handle_bind(bind.clone(), true); + } return; } } @@ -4030,7 +4112,7 @@ impl State { &tablet::tool::ButtonEvent { serial: SERIAL_COUNTER.next_serial(), button, - state: event.button_state(), + state: button_state, time, }, ); @@ -4040,6 +4122,8 @@ impl State { } fn on_gesture_swipe_begin(&mut self, event: I::GestureSwipeBeginEvent) { + self.niri.cancel_interrupted_release_binds(); + if self.niri.window_mru_ui.is_open() || self.niri.screenshot_ui.is_open() { // Don't start swipe gestures while in the compositor UI. return; @@ -4243,6 +4327,8 @@ impl State { } fn on_gesture_pinch_begin(&mut self, event: I::GesturePinchBeginEvent) { + self.niri.cancel_interrupted_release_binds(); + let serial = SERIAL_COUNTER.next_serial(); let pointer = self.niri.seat.get_pointer().unwrap(); @@ -4314,6 +4400,8 @@ impl State { } fn on_gesture_hold_begin(&mut self, event: I::GestureHoldBeginEvent) { + self.niri.cancel_interrupted_release_binds(); + let serial = SERIAL_COUNTER.next_serial(); let pointer = self.niri.seat.get_pointer().unwrap(); @@ -4385,6 +4473,8 @@ impl State { }; let slot = evt.slot(); + self.niri.cancel_interrupted_release_binds(); + let serial = SERIAL_COUNTER.next_serial(); let under = self.niri.contents_under(pos); @@ -4617,12 +4707,59 @@ impl State { } } -/// Check whether the key should be intercepted and mark intercepted -/// pressed keys as `suppressed`, thus preventing `releases` corresponding -/// to them from being delivered. +impl Niri { + fn cancel_interrupted_release_binds(&mut self) { + retain_press_binds(&mut self.pending_release_binds); + } +} + +fn retain_press_binds(binds: &mut HashMap) { + binds.retain(|_, bind| bind.has_press()); +} + +fn released_key_intercept_result( + suppressed_keys: &mut HashSet, + pending_release_binds: &mut HashMap, + key_code: Keycode, +) -> ShouldInterceptResult { + let bind = pending_release_binds.remove(&key_code); + let suppressed = suppressed_keys.remove(&key_code); + + bind_intercept_result(bind, !suppressed) +} + +fn bind_intercept_result(bind: Option, forward: bool) -> ShouldInterceptResult { + match (bind, forward) { + (Some(bind), true) => ShouldInterceptResult::ForwardAndHandle(bind), + (Some(bind), false) => ShouldInterceptResult::InterceptAndHandle(bind), + (None, true) => ShouldInterceptResult::Forward, + (None, false) => ShouldInterceptResult::InterceptOnly, + } +} + +fn is_bind_on_cooldown(bind: &Bind, cooldown_timers: &HashMap) -> bool { + bind.cooldown.is_some() && cooldown_timers.contains_key(&bind.key) +} + +/// Checks whether the key should be intercepted, and tracks the presses of intercepted keys. +/// +/// An intercepted key press is recorded in `suppressed_keys`, which prevents its release from +/// being forwarded to clients. If the matching bind has a release action, the bind is also +/// recorded in `pending_release_binds`, so that its release action triggers when the key is +/// released, regardless of the modifiers held at that point. +/// +/// A release action only triggers if the bind's modifiers matched when the key was pressed. +/// +/// A release-only bind is cancelled by other input before this runs; see +/// `cancel_interrupted_release_binds()`. A bind with a press action always runs its release action. +/// +/// A bind whose press action is rate-limited by its cooldown is skipped entirely: +/// No action runs, and no release action is recorded. #[allow(clippy::too_many_arguments)] fn should_intercept_key<'a>( suppressed_keys: &mut HashSet, + pending_release_binds: &mut HashMap, + cooldown_timers: &HashMap, bindings: impl IntoIterator, mod_key: ModKey, key_code: Keycode, @@ -4633,12 +4770,12 @@ fn should_intercept_key<'a>( screenshot_ui: &ScreenshotUi, disable_power_key_handling: bool, is_inhibiting_shortcuts: bool, + is_locked: bool, ) -> ShouldInterceptResult { - // 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 ShouldInterceptResult::Forward; + // A release never runs a press action, so its result depends only on the bind recorded when + // the key was pressed, and on whether that press was suppressed. + if !pressed { + return released_key_intercept_result(suppressed_keys, pending_release_binds, key_code); } let mut final_bind = find_bind( @@ -4656,7 +4793,7 @@ fn should_intercept_key<'a>( let mut use_screenshot_ui_action = true; if let Some(bind) = &final_bind { - if allowed_during_screenshot(&bind.action) { + if bind_allowed_during_screenshot(bind, true) { use_screenshot_ui_action = false; } } @@ -4669,7 +4806,7 @@ fn should_intercept_key<'a>( // Not entirely correct but it doesn't matter in how we currently use it. modifiers: Modifiers::empty(), }, - action, + action: BoundAction::Press(action), repeat: true, cooldown: None, allow_when_locked: false, @@ -4683,25 +4820,46 @@ fn should_intercept_key<'a>( } } - match (final_bind, pressed) { - (Some(bind), true) => { + match final_bind { + Some(bind) => { if is_inhibiting_shortcuts && bind.allow_inhibiting { ShouldInterceptResult::Forward + } else if bind.has_press() && is_bind_on_cooldown(&bind, cooldown_timers) { + // If on cooldown, do not run the press action, record a release action, + // or forward the press. + suppressed_keys.insert(key_code); + ShouldInterceptResult::InterceptOnly + } else if is_keysym_modifier(modified) { + if should_record_release_bind(&bind, is_locked, cooldown_timers) { + pending_release_binds.insert(key_code, bind.clone()); + } + if bind.has_press() { + suppressed_keys.insert(key_code); + // A bind with a press action takes the key press. Applications will still learn + // about the modifier state via `advertise_modifier_state()`. + ShouldInterceptResult::InterceptAndHandle(bind) + } else { + // This is to ensure that, if you have a modifier-triggered release bind like + // Ctrl+Alt, We still forward the Ctrl and Alt presses to the application + // to use for its own shortcuts. + ShouldInterceptResult::Forward + } } else { + if should_record_release_bind(&bind, is_locked, cooldown_timers) { + pending_release_binds.insert(key_code, bind.clone()); + } suppressed_keys.insert(key_code); - ShouldInterceptResult::InterceptAndHandle(bind) + if bind.has_press() { + ShouldInterceptResult::InterceptAndHandle(bind) + } else { + // Release-only bind: intercept the key press so that it doesn't reach the + // client, and remember to trigger the release action when the key is + // released. + ShouldInterceptResult::InterceptOnly + } } } - (_, false) => { - // By this point, we know that the key was suppressed on press. Even if we're inhibiting - // shortcuts, we should still suppress the release. - // But we don't need to check for shortcuts inhibition here, because - // if it was inhibited on press (forwarded to the client), it wouldn't be suppressed, - // so the release would already have been forwarded at the start of this function. - suppressed_keys.remove(&key_code); - ShouldInterceptResult::InterceptOnly - } - (None, true) => ShouldInterceptResult::Forward, + None => ShouldInterceptResult::Forward, } } @@ -4733,7 +4891,7 @@ fn find_bind<'a>( trigger: Trigger::Keysym(modified), modifiers: Modifiers::empty(), }, - action, + action: BoundAction::Press(action), // Repeating VT switches and power off doesn't make sense (and it actually happens on // FreeBSD where it doesn't get released and ends up broken). repeat: false, @@ -4749,42 +4907,89 @@ fn find_bind<'a>( }); } - let trigger = Trigger::Keysym(raw?); - find_configured_bind(bindings, mod_key, trigger, mods) + let raw = raw?; + + let modifiers = modifiers_from_state(mods); + + // A modifier key can trigger binds bound as the compositor mod key (`Mod`), by its own keysym + // (like `Alt_L`), or as the modifier itself (like `Alt`). Return the first bind that matches. + bindings + .into_iter() + .find(|bind| { + // Modifier-only binds can be written in several ways: + // - `Mod { quit; }` - Trigger::CompositorMod + // - `Super { quit; }` - Trigger::Modifier(_) + // - `Super_L { quit; }` - Trigger::Keysym(_) + // + // These only matter for keyboard keys and not for mouse or others. So, check them here, + // and then pass the bind's trigger itself to the simpler matching function. + let bind_trigger = bind.key.trigger; + trigger_matches_keysym(bind_trigger, raw, mod_key) + && bind_matches_trigger(bind, bind_trigger, mod_key, modifiers) + }) + .cloned() +} + +fn trigger_matches_keysym(trigger: Trigger, raw: Keysym, mod_key: ModKey) -> bool { + match trigger { + Trigger::CompositorMod => mod_key.matches_keysym(raw), + Trigger::Keysym(keysym) => keysym == raw, + Trigger::Modifier(modifier) => modifier.matches_keysym(raw), + _ => false, + } } +/// Finds the configured bind for a trigger and held modifiers. +/// +/// Returns the first bind with this exact trigger whose modifiers match, so overlapping binds +/// like `Mod+Q` and `Super+Q` are resolved by definition order. fn find_configured_bind<'a>( bindings: impl IntoIterator, mod_key: ModKey, trigger: Trigger, mods: ModifiersState, ) -> Option { - // Handle configured binds. - let mut modifiers = modifiers_from_state(mods); + let modifiers = modifiers_from_state(mods); + + bindings + .into_iter() + .find(|bind| bind_matches_trigger(bind, trigger, mod_key, modifiers)) + .cloned() +} - let mod_down = modifiers_from_state(mods).contains(mod_key.to_modifiers()); - if mod_down { - modifiers |= Modifiers::COMPOSITOR; +fn bind_matches_trigger(bind: &Bind, trigger: Trigger, mod_key: ModKey, mods: Modifiers) -> bool { + if bind.key.trigger != trigger { + return false; } - for bind in bindings { - if bind.key.trigger != trigger { - continue; - } + let mut held_modifiers = mods; + let mut required_modifiers = bind.key.modifiers; - let mut bind_modifiers = bind.key.modifiers; - if bind_modifiers.contains(Modifiers::COMPOSITOR) { - bind_modifiers |= mod_key.to_modifiers(); - } else if bind_modifiers.contains(mod_key.to_modifiers()) { - bind_modifiers |= Modifiers::COMPOSITOR; - } + // Check if the trigger is the mod key itself, either as `Mod`, as its own keysym (like + // `Super_L`), or as the modifier itself (like `Super`). If so, normalize the modifiers not + // to need it. + let trigger_is_mod_key = match trigger { + Trigger::CompositorMod => true, + Trigger::Modifier(modifier) => modifier == mod_key, + Trigger::Keysym(keysym) => mod_key.matches_keysym(keysym), + _ => false, + }; - if bind_modifiers == modifiers { - return Some(bind.clone()); + if trigger_is_mod_key { + held_modifiers.remove(mod_key.to_modifiers()); + required_modifiers.remove(Modifiers::COMPOSITOR | mod_key.to_modifiers()); + } else { + if held_modifiers.contains(mod_key.to_modifiers()) { + held_modifiers |= Modifiers::COMPOSITOR; + } + if required_modifiers.contains(Modifiers::COMPOSITOR) { + required_modifiers |= mod_key.to_modifiers(); + } else if required_modifiers.contains(mod_key.to_modifiers()) { + required_modifiers |= Modifiers::COMPOSITOR; } } - None + required_modifiers == held_modifiers } fn find_configured_switch_action( @@ -4912,6 +5117,36 @@ fn allowed_when_locked(action: &Action) -> bool { ) } +fn bind_allowed_when_locked(bind: &Bind, pressed: bool) -> bool { + if bind.allow_when_locked { + return true; + } + + match &bind.action { + BoundAction::Press(action) | BoundAction::Release(action) => allowed_when_locked(action), + BoundAction::Both { press, release } => { + if pressed { + allowed_when_locked(press) && allowed_when_locked(release) + } else { + // The press ran, so the release must run too. + true + } + } + } +} + +fn should_record_release_bind( + bind: &Bind, + is_locked: bool, + cooldown_timers: &HashMap, +) -> bool { + if bind.has_press() && is_bind_on_cooldown(bind, cooldown_timers) { + return false; + } + + bind.has_release() && (!is_locked || bind_allowed_when_locked(bind, true)) +} + fn allowed_during_screenshot(action: &Action) -> bool { matches!( action, @@ -4953,6 +5188,22 @@ fn allowed_during_screenshot(action: &Action) -> bool { ) } +fn bind_allowed_during_screenshot(bind: &Bind, pressed: bool) -> bool { + match &bind.action { + BoundAction::Press(action) | BoundAction::Release(action) => { + allowed_during_screenshot(action) + } + BoundAction::Both { press, release } => { + if pressed { + allowed_during_screenshot(press) && allowed_during_screenshot(release) + } else { + // The press ran, so the release must run too. + true + } + } + } +} + fn hardcoded_overview_bind(raw: Keysym, mods: ModifiersState) -> Option { let mods = modifiers_from_state(mods); if !mods.is_empty() { @@ -4979,7 +5230,7 @@ fn hardcoded_overview_bind(raw: Keysym, mods: ModifiersState) -> Option { trigger: Trigger::Keysym(raw), modifiers: Modifiers::empty(), }, - action, + action: BoundAction::Press(action), repeat, cooldown: None, allow_when_locked: false, @@ -5417,7 +5668,7 @@ mod tests { trigger: Trigger::Keysym(Keysym::q), modifiers: Modifiers::COMPOSITOR, }, - action: Action::CloseWindow, + action: BoundAction::Press(Action::CloseWindow), repeat: true, cooldown: None, allow_when_locked: false, @@ -5429,7 +5680,7 @@ mod tests { trigger: Trigger::Keysym(Keysym::h), modifiers: Modifiers::SUPER, }, - action: Action::FocusColumnLeft, + action: BoundAction::Press(Action::FocusColumnLeft), repeat: true, cooldown: None, allow_when_locked: false, @@ -5441,7 +5692,7 @@ mod tests { trigger: Trigger::Keysym(Keysym::j), modifiers: Modifiers::empty(), }, - action: Action::FocusWindowDown, + action: BoundAction::Press(Action::FocusWindowDown), repeat: true, cooldown: None, allow_when_locked: false, @@ -5453,7 +5704,7 @@ mod tests { trigger: Trigger::Keysym(Keysym::k), modifiers: Modifiers::COMPOSITOR | Modifiers::SUPER, }, - action: Action::FocusWindowUp, + action: BoundAction::Press(Action::FocusWindowUp), repeat: true, cooldown: None, allow_when_locked: false, @@ -5465,13 +5716,25 @@ mod tests { trigger: Trigger::Keysym(Keysym::l), modifiers: Modifiers::SUPER | Modifiers::ALT, }, - action: Action::FocusColumnRight, + action: BoundAction::Press(Action::FocusColumnRight), repeat: true, cooldown: None, allow_when_locked: false, allow_inhibiting: true, hotkey_overlay_title: None, }, + Bind { + key: Key { + trigger: Trigger::Keysym(Keysym::Super_L), + modifiers: Modifiers::empty(), + }, + action: BoundAction::Release(Action::ToggleOverview), + repeat: false, + cooldown: None, + allow_when_locked: false, + allow_inhibiting: true, + hotkey_overlay_title: None, + }, ]); assert_eq!( @@ -5482,7 +5745,7 @@ mod tests { ModifiersState { logo: true, ..Default::default() - } + }, ) .as_ref(), Some(&bindings.0[0]) @@ -5505,7 +5768,7 @@ mod tests { ModifiersState { logo: true, ..Default::default() - } + }, ) .as_ref(), Some(&bindings.0[1]) @@ -5528,7 +5791,7 @@ mod tests { ModifiersState { logo: true, ..Default::default() - } + }, ), None, ); @@ -5551,7 +5814,7 @@ mod tests { ModifiersState { logo: true, ..Default::default() - } + }, ) .as_ref(), Some(&bindings.0[3]) @@ -5575,7 +5838,7 @@ mod tests { logo: true, alt: true, ..Default::default() - } + }, ) .as_ref(), Some(&bindings.0[4]) @@ -5592,5 +5855,18 @@ mod tests { ), None, ); + + // A release-only bind is found the same as any other: what to do with it depends on the + // event, not on the lookup. + assert_eq!( + find_configured_bind( + &bindings.0, + ModKey::Super, + Trigger::Keysym(Keysym::Super_L), + ModifiersState::default(), + ) + .as_ref(), + Some(&bindings.0[5]) + ); } } diff --git a/src/niri.rs b/src/niri.rs index 2f3c4581..578e0f03 100644 --- a/src/niri.rs +++ b/src/niri.rs @@ -17,7 +17,7 @@ use niri_config::debug::PreviewRender; use niri_config::output::MaxBpc; use niri_config::window_rule::VrrRule; use niri_config::{ - Config, FloatOrInt, Key, Modifiers, OutputName, TrackLayout, WarpMouseToFocusMode, + Bind, Config, FloatOrInt, Key, Modifiers, OutputName, TrackLayout, WarpMouseToFocusMode, WorkspaceReference, Xkb, }; use smithay::backend::allocator::Fourcc; @@ -359,6 +359,8 @@ pub struct Niri { pub suppressed_keys: HashSet, /// Button codes of the mouse buttons to suppress. pub suppressed_buttons: HashSet, + /// Binds whose release action is pending, keyed by the key code. + pub pending_release_binds: HashMap, pub bind_cooldown_timers: HashMap, pub bind_repeat_timer: Option, pub keyboard_focus: KeyboardFocus, @@ -2837,6 +2839,7 @@ impl Niri { popup_grab: None, suppressed_keys: HashSet::new(), suppressed_buttons: HashSet::new(), + pending_release_binds: HashMap::new(), bind_cooldown_timers: HashMap::new(), bind_repeat_timer: Option::default(), presentation_state, @@ -6590,6 +6593,17 @@ impl Niri { Ok(()) } + pub fn clear_input_state(&mut self) { + self.suppressed_keys.clear(); + self.suppressed_buttons.clear(); + self.pending_release_binds.clear(); + + // Stop ongoing key repeat if any. + if let Some(token) = self.bind_repeat_timer.take() { + self.event_loop.remove(token); + } + } + pub fn is_locked(&self) -> bool { match self.lock_state { LockState::Unlocked | LockState::WaitingForSurfaces { .. } => false, diff --git a/src/tests/binds.rs b/src/tests/binds.rs index eb199a51..df3e0bbc 100644 --- a/src/tests/binds.rs +++ b/src/tests/binds.rs @@ -1,7 +1,7 @@ use std::fmt::Write as _; use insta::assert_snapshot; -use niri_config::{Action, Config}; +use niri_config::{Action, BoundAction, Config}; use smithay::backend::input::{InputEvent, InputTime, KeyState, Keycode}; use smithay::input::keyboard::xkb::Keymap; use wayland_client::protocol::wl_surface::WlSurface; @@ -39,7 +39,14 @@ fn set_up(config: &str) -> (Fixture, ClientId, WlSurface) { let mut config = Config::parse_mem(config).unwrap(); // knuffel doesn't understand #[cfg(test)]... for bind in &mut config.binds.0 { - bind.action = Action::TestAction; + bind.action = match &bind.action { + BoundAction::Press(_) => BoundAction::Press(Action::TestAction), + BoundAction::Release(_) => BoundAction::Release(Action::TestAction), + BoundAction::Both { .. } => BoundAction::Both { + press: Action::TestAction, + release: Action::TestAction, + }, + }; } let mut f = Fixture::with_config(config); diff --git a/src/ui/hotkey_overlay.rs b/src/ui/hotkey_overlay.rs index f95518d0..0b92e474 100644 --- a/src/ui/hotkey_overlay.rs +++ b/src/ui/hotkey_overlay.rs @@ -152,13 +152,23 @@ impl HotkeyOverlay { } } +/// Returns the actions that a bind triggers. +fn bind_actions(bind: &Bind) -> impl Iterator { + bind.press_action().into_iter().chain(bind.release_action()) +} + +/// Whether the bind triggers the action, on press or on release. +fn bind_triggers(bind: &Bind, action: &Action) -> bool { + bind.press_action() == Some(action) || bind.release_action() == Some(action) +} + fn format_bind(binds: &[Bind], action: &Action) -> Option<(Option, String)> { let mut bind_with_non_null = None; let mut bind_with_custom_title = None; let mut found_null_title = false; for bind in binds { - if bind.action != *action { + if !bind_triggers(bind, action) { continue; } @@ -202,9 +212,15 @@ fn collect_actions(config: &Config) -> Vec<&Action> { // Prefer Quit(false) if found, otherwise try Quit(true), and if there's neither, fall back to // Quit(false). - if binds.iter().any(|bind| bind.action == Action::Quit(false)) { + if binds + .iter() + .any(|bind| bind_triggers(bind, &Action::Quit(false))) + { actions.push(&Action::Quit(false)); - } else if binds.iter().any(|bind| bind.action == Action::Quit(true)) { + } else if binds + .iter() + .any(|bind| bind_triggers(bind, &Action::Quit(true))) + { actions.push(&Action::Quit(true)); } else { actions.push(&Action::Quit(false)); @@ -221,14 +237,16 @@ fn collect_actions(config: &Config) -> Vec<&Action> { ]); // Prefer move-column-to-workspace-down, but fall back to move-window-to-workspace-down. - if let Some(bind) = binds + if let Some(action) = binds .iter() - .find(|bind| matches!(bind.action, Action::MoveColumnToWorkspaceDown(_))) + .flat_map(bind_actions) + .find(|action| matches!(action, Action::MoveColumnToWorkspaceDown(_))) { - actions.push(&bind.action); + actions.push(action); } else if binds .iter() - .any(|bind| matches!(bind.action, Action::MoveWindowToWorkspaceDown(_))) + .flat_map(bind_actions) + .any(|action| matches!(action, Action::MoveWindowToWorkspaceDown(_))) { actions.push(&Action::MoveWindowToWorkspaceDown(true)); } else { @@ -236,14 +254,16 @@ fn collect_actions(config: &Config) -> Vec<&Action> { } // Same for -up. - if let Some(bind) = binds + if let Some(action) = binds .iter() - .find(|bind| matches!(bind.action, Action::MoveColumnToWorkspaceUp(_))) + .flat_map(bind_actions) + .find(|action| matches!(action, Action::MoveColumnToWorkspaceUp(_))) { - actions.push(&bind.action); + actions.push(action); } else if binds .iter() - .any(|bind| matches!(bind.action, Action::MoveWindowToWorkspaceUp(_))) + .flat_map(bind_actions) + .any(|action| matches!(action, Action::MoveWindowToWorkspaceUp(_))) { actions.push(&Action::MoveWindowToWorkspaceUp(true)); } else { @@ -261,34 +281,42 @@ fn collect_actions(config: &Config) -> Vec<&Action> { ]); // Screenshot is not as important, can omit if not bound. - if let Some(bind) = binds + if let Some(action) = binds .iter() - .find(|bind| matches!(bind.action, Action::Screenshot(_, _))) + .flat_map(bind_actions) + .find(|action| matches!(action, Action::Screenshot(_, _))) { - actions.push(&bind.action); + actions.push(action); } // Add actions with a custom hotkey-overlay-title. for bind in binds { if matches!(bind.hotkey_overlay_title, Some(Some(_))) { // Avoid duplicate actions. - if !actions.contains(&&bind.action) { - actions.push(&bind.action); + if let Some(action) = bind_actions(bind).next() { + if !actions.contains(&action) { + actions.push(action); + } } } } // Add the spawn actions. - for bind in binds.iter().filter(|bind| { - matches!(bind.action, Action::Spawn(_) | Action::SpawnSh(_)) - // Only show binds with Mod or Super to filter out stuff like volume up/down. - && (bind.key.modifiers.contains(Modifiers::COMPOSITOR) - || bind.key.modifiers.contains(Modifiers::SUPER)) - // Also filter out wheel and touchpad scroll binds. - && matches!(bind.key.trigger, Trigger::Keysym(_)) + for action in binds.iter().filter_map(|bind| { + // Includes the trigger's implied modifier. + let modifiers = bind.key.modifiers; + + // Only show binds with Mod or Super to filter out stuff like volume up/down. + // Also filter out wheel and touchpad scroll binds. + if bind.key.trigger.is_keyboard() + && modifiers.intersects(Modifiers::COMPOSITOR | Modifiers::SUPER) + { + bind_actions(bind) + .find(|action| matches!(action, Action::Spawn(_) | Action::SpawnSh(_))) + } else { + None + } }) { - let action = &bind.action; - // We only show one bind for each action, so we need to deduplicate the Spawn actions. if !actions.contains(&action) { actions.push(action); @@ -297,7 +325,7 @@ fn collect_actions(config: &Config) -> Vec<&Action> { if config.hotkey_overlay.hide_not_bound { // Only keep actions that have been bound - actions.retain(|&action| binds.iter().any(|bind| bind.action == *action)) + actions.retain(|&action| binds.iter().any(|bind| bind_triggers(bind, action))) } actions @@ -497,7 +525,13 @@ fn key_name(screen_reader: bool, mod_key: ModKey, key: &Key) -> String { let mut name = String::new(); // Do not show modifiers implied by the trigger. - let modifiers = key.modifiers & !key.trigger.implied_modifier(); + let mut implied = key.trigger.implied_modifier(); + // Spellings of the mod key also imply the compositor modifier (e.g. Mod+Super_L). + let mod_modifiers = Modifiers::COMPOSITOR | mod_key.to_modifiers(); + if implied.intersects(mod_modifiers) { + implied |= mod_modifiers; + } + let modifiers = key.modifiers & !implied; let has_comp_mod = modifiers.contains(Modifiers::COMPOSITOR); @@ -713,6 +747,33 @@ mod tests { @" Super + Control_R : Close Focused Window" ); + // A release bind is shown too. + assert_snapshot!( + check( + r#"binds { + Mod { + release { toggle-overview; } + } + }"#, + Action::ToggleOverview, + ), + @" Super : Open the Overview" + ); + + // Same for the release action of a bind with both actions. + assert_snapshot!( + check( + r#"binds { + Mod+Shift+Q { + press { close-window; } + release { toggle-overview; } + } + }"#, + Action::ToggleOverview, + ), + @" Super + Shift + Q : Open the Overview" + ); + // Bound with a default title. assert_snapshot!( check( @@ -794,5 +855,110 @@ mod tests { ), @" Super + P : Hello" ); + + // Mod overlapping with trigger. + assert_snapshot!( + check( + r#"binds { + Mod+Super_L { screenshot; } + }"#, + Action::Screenshot(true, None), + ), + @" Super_L : Take a Screenshot" + ); + assert_snapshot!( + check( + r#"binds { + Mod+Super { screenshot; } + }"#, + Action::Screenshot(true, None), + ), + @" Super : Take a Screenshot" + ); + assert_snapshot!( + check( + r#"binds { + Super+Mod { screenshot; } + }"#, + Action::Screenshot(true, None), + ), + @" Super : Take a Screenshot" + ); + } + + #[test] + fn test_collect_actions() { + // Release binds count as bound, both for the actions that are always listed and for the + // ones that are only listed when bound. + let config = Config::parse_mem( + r#"binds { + Alt { + release { screenshot; } + } + Mod { + release { spawn "foot"; } + } + }"#, + ) + .unwrap(); + + let actions = collect_actions(&config); + assert!(actions.contains(&&Action::Screenshot(true, None))); + assert!(actions.contains(&&Action::Spawn(vec![String::from("foot")]))); + + // Release binds keep actions in the list with hide-not-bound. + let config = Config::parse_mem( + r#"binds { + Mod { + release { toggle-overview; } + } + } + hotkey-overlay { hide-not-bound; }"#, + ) + .unwrap(); + + assert!(collect_actions(&config).contains(&&Action::ToggleOverview)); + + // A release bind with a custom title adds its action to the list. + let config = Config::parse_mem( + r#"binds { + Mod+Q hotkey-overlay-title="Custom" { + release { center-column; } + } + }"#, + ) + .unwrap(); + + assert!(collect_actions(&config).contains(&&Action::CenterColumn)); + + // Various filtering behavior. + let config = Config::parse_mem( + r#"binds { + XF86AudioMute { spawn "Mute"; } + Super_L { spawn "Super_L"; } + Mod { spawn "Mod"; } + Shift_L { spawn "Shift_L"; } + Alt { spawn "Alt"; } + Mod+Shift_L { spawn "Mod+Shift_L"; } + Super+Ctrl { spawn "Super+Ctrl"; } + Mod+Alt { spawn "Mod+Alt"; } + }"#, + ) + .unwrap(); + + let mut snapshot = String::new(); + for action in collect_actions(&config) { + if let Action::Spawn(args) = action { + snapshot.push_str(&args[0]); + snapshot.push('\n'); + } + } + assert_snapshot!(snapshot, @" + Super_L + Mod + Mod+Shift_L + Super+Ctrl + Mod+Alt + "); } } diff --git a/src/ui/mru.rs b/src/ui/mru.rs index d8ec6de1..c0afaaaf 100644 --- a/src/ui/mru.rs +++ b/src/ui/mru.rs @@ -7,8 +7,8 @@ use std::time::Duration; use anyhow::ensure; use niri_config::{ - Action, Bind, Color, Config, CornerRadius, GradientInterpolation, Key, Modifiers, MruDirection, - MruFilter, MruScope, Trigger, + Action, Bind, BoundAction, Color, Config, CornerRadius, GradientInterpolation, Key, Modifiers, + MruDirection, MruFilter, MruScope, Trigger, }; use pango::FontDescription; use pangocairo::cairo::{self, ImageSurface}; @@ -1834,7 +1834,7 @@ fn make_preset_opened_binds() -> Vec { // The modifier is filled dynamically. modifiers: Modifiers::empty(), }, - action, + action: BoundAction::Press(action), repeat: true, cooldown: None, allow_when_locked: false, @@ -1882,7 +1882,11 @@ fn make_dynamic_opened_binds(config: &Config) -> Vec { let mut binds: HashMap> = HashMap::new(); for bind in &config.binds.0 { - let action = match &bind.action { + let Some(press_action) = bind.press_action() else { + continue; + }; + + let action = match press_action { Action::FocusColumnRight | Action::FocusColumnRightOrFirst | Action::FocusColumnOrMonitorRight @@ -1907,7 +1911,7 @@ fn make_dynamic_opened_binds(config: &Config) -> Vec { }; binds.entry(bind.key.trigger).or_default().push(Bind { - action, + action: BoundAction::Press(action), ..bind.clone() }); }