| 1 | use std::collections::HashSet; |
| 2 | use std::io; |
| 3 | use std::io::ErrorKind; |
| 4 | use std::process::Command; |
| 5 | |
| 6 | use serde::Deserialize; |
| 7 | use x11rb::connection::Connection; |
| 8 | use x11rb::protocol::xproto::*; |
| 9 | |
| 10 | use crate::errors::X11Error; |
| 11 | use crate::keyboard::keycodes; |
| 12 | |
| 13 | #[derive(Debug, Copy, Clone, Deserialize)] |
| 14 | pub enum KeyAction { |
| 15 | Spawn, |
| 16 | KillClient, |
| 17 | FocusStack, |
| 18 | Quit, |
| 19 | Restart, |
| 20 | Recompile, |
| 21 | ViewTag, |
| 22 | ToggleGaps, |
| 23 | ToggleFullScreen, |
| 24 | ToggleFloating, |
| 25 | ChangeLayout, |
| 26 | CycleLayout, |
| 27 | MoveToTag, |
| 28 | FocusMonitor, |
| 29 | SmartMoveWin, |
| 30 | ExchangeClient, |
| 31 | None, |
| 32 | } |
| 33 | |
| 34 | #[derive(Debug, Clone)] |
| 35 | pub enum Arg { |
| 36 | None, |
| 37 | Int(i32), |
| 38 | Str(String), |
| 39 | Array(Vec<String>), |
| 40 | } |
| 41 | |
| 42 | impl Arg { |
| 43 | pub const fn none() -> Self { |
| 44 | Arg::None |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | // Individual key press in a sequence |
| 49 | #[derive(Clone, Debug)] |
| 50 | pub struct KeyPress { |
| 51 | pub(crate) modifiers: Vec<KeyButMask>, |
| 52 | pub(crate) key: Keycode, |
| 53 | } |
| 54 | |
| 55 | // Keybinding that can be a single key or a chord (sequence of keys) |
| 56 | #[derive(Clone)] |
| 57 | pub struct KeyBinding { |
| 58 | pub(crate) keys: Vec<KeyPress>, |
| 59 | pub(crate) func: KeyAction, |
| 60 | pub(crate) arg: Arg, |
| 61 | } |
| 62 | |
| 63 | impl KeyBinding { |
| 64 | pub fn new(keys: Vec<KeyPress>, func: KeyAction, arg: Arg) -> Self { |
| 65 | Self { keys, func, arg } |
| 66 | } |
| 67 | |
| 68 | // Helper for backwards compatibility with single-key bindings |
| 69 | pub fn single_key(modifiers: Vec<KeyButMask>, key: Keycode, func: KeyAction, arg: Arg) -> Self { |
| 70 | Self { |
| 71 | keys: vec![KeyPress { modifiers, key }], |
| 72 | func, |
| 73 | arg, |
| 74 | } |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | // For backwards compatibility during migration |
| 79 | pub type Key = KeyBinding; |
| 80 | |
| 81 | #[derive(Debug, Clone)] |
| 82 | pub enum KeychordState { |
| 83 | Idle, |
| 84 | InProgress { |
| 85 | // Indices of keybindings that could still match |
| 86 | candidates: Vec<usize>, |
| 87 | // How many keys have been pressed in the sequence |
| 88 | keys_pressed: usize, |
| 89 | }, |
| 90 | } |
| 91 | |
| 92 | pub enum KeychordResult { |
| 93 | Completed(KeyAction, Arg), |
| 94 | InProgress(Vec<usize>), |
| 95 | None, |
| 96 | Cancelled, |
| 97 | } |
| 98 | |
| 99 | pub fn modifiers_to_mask(modifiers: &[KeyButMask]) -> u16 { |
| 100 | modifiers |
| 101 | .iter() |
| 102 | .fold(0u16, |acc, &modifier| acc | u16::from(modifier)) |
| 103 | } |
| 104 | |
| 105 | pub fn setup_keybinds( |
| 106 | connection: &impl Connection, |
| 107 | root: Window, |
| 108 | keybindings: &[KeyBinding], |
| 109 | ) -> Result<(), X11Error> { |
| 110 | let mut grabbed_keys: HashSet<(u16, Keycode)> = HashSet::new(); |
| 111 | |
| 112 | for keybinding in keybindings { |
| 113 | if keybinding.keys.is_empty() { |
| 114 | continue; |
| 115 | } |
| 116 | |
| 117 | let first_key = &keybinding.keys[0]; |
| 118 | let modifier_mask = modifiers_to_mask(&first_key.modifiers); |
| 119 | let key_tuple = (modifier_mask, first_key.key); |
| 120 | |
| 121 | if grabbed_keys.insert(key_tuple) { |
| 122 | connection.grab_key( |
| 123 | false, |
| 124 | root, |
| 125 | modifier_mask.into(), |
| 126 | first_key.key, |
| 127 | GrabMode::ASYNC, |
| 128 | GrabMode::ASYNC, |
| 129 | )?; |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | connection.grab_key( |
| 134 | false, |
| 135 | root, |
| 136 | ModMask::from(0u16), |
| 137 | keycodes::ESCAPE, |
| 138 | GrabMode::ASYNC, |
| 139 | GrabMode::ASYNC, |
| 140 | )?; |
| 141 | |
| 142 | Ok(()) |
| 143 | } |
| 144 | |
| 145 | pub fn handle_key_press( |
| 146 | event: KeyPressEvent, |
| 147 | keybindings: &[KeyBinding], |
| 148 | keychord_state: &KeychordState, |
| 149 | ) -> KeychordResult { |
| 150 | if event.detail == keycodes::ESCAPE { |
| 151 | return match keychord_state { |
| 152 | KeychordState::InProgress { .. } => KeychordResult::Cancelled, |
| 153 | KeychordState::Idle => KeychordResult::None, |
| 154 | }; |
| 155 | } |
| 156 | |
| 157 | match keychord_state { |
| 158 | KeychordState::Idle => { |
| 159 | handle_first_key(event, keybindings) |
| 160 | } |
| 161 | KeychordState::InProgress { candidates, keys_pressed } => { |
| 162 | handle_next_key(event, keybindings, candidates, *keys_pressed) |
| 163 | } |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | fn handle_first_key( |
| 168 | event: KeyPressEvent, |
| 169 | keybindings: &[KeyBinding], |
| 170 | ) -> KeychordResult { |
| 171 | let mut candidates = Vec::new(); |
| 172 | |
| 173 | for (keybinding_index, keybinding) in keybindings.iter().enumerate() { |
| 174 | if keybinding.keys.is_empty() { |
| 175 | continue; |
| 176 | } |
| 177 | |
| 178 | let first_key = &keybinding.keys[0]; |
| 179 | let modifier_mask = modifiers_to_mask(&first_key.modifiers); |
| 180 | |
| 181 | if event.detail == first_key.key && event.state == modifier_mask.into() { |
| 182 | if keybinding.keys.len() == 1 { |
| 183 | return KeychordResult::Completed( |
| 184 | keybinding.func, |
| 185 | keybinding.arg.clone(), |
| 186 | ); |
| 187 | } else { |
| 188 | candidates.push(keybinding_index); |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | if candidates.is_empty() { |
| 194 | KeychordResult::None |
| 195 | } else { |
| 196 | KeychordResult::InProgress(candidates) |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | fn handle_next_key( |
| 201 | event: KeyPressEvent, |
| 202 | keybindings: &[KeyBinding], |
| 203 | candidates: &[usize], |
| 204 | keys_pressed: usize, |
| 205 | ) -> KeychordResult { |
| 206 | let mut new_candidates = Vec::new(); |
| 207 | |
| 208 | for &candidate_index in candidates { |
| 209 | let keybinding = &keybindings[candidate_index]; |
| 210 | |
| 211 | if keys_pressed >= keybinding.keys.len() { |
| 212 | continue; |
| 213 | } |
| 214 | |
| 215 | let next_key = &keybinding.keys[keys_pressed]; |
| 216 | let required_mask = modifiers_to_mask(&next_key.modifiers); |
| 217 | let event_state: u16 = event.state.into(); |
| 218 | |
| 219 | let modifiers_match = if next_key.modifiers.is_empty() { |
| 220 | true |
| 221 | } else { |
| 222 | (event_state & required_mask) == required_mask |
| 223 | }; |
| 224 | |
| 225 | if event.detail == next_key.key && modifiers_match { |
| 226 | if keys_pressed + 1 == keybinding.keys.len() { |
| 227 | return KeychordResult::Completed( |
| 228 | keybinding.func, |
| 229 | keybinding.arg.clone(), |
| 230 | ); |
| 231 | } else { |
| 232 | new_candidates.push(candidate_index); |
| 233 | } |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | if new_candidates.is_empty() { |
| 238 | KeychordResult::Cancelled |
| 239 | } else { |
| 240 | KeychordResult::InProgress(new_candidates) |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | pub fn handle_spawn_action(action: KeyAction, arg: &Arg) -> io::Result<()> { |
| 245 | if let KeyAction::Spawn = action { |
| 246 | match arg { |
| 247 | Arg::Str(command) => match Command::new(command.as_str()).spawn() { |
| 248 | Err(error) if error.kind() == ErrorKind::NotFound => { |
| 249 | eprintln!( |
| 250 | "KeyAction::Spawn failed: could not spawn \"{}\", command not found", |
| 251 | command |
| 252 | ); |
| 253 | } |
| 254 | Err(error) => Err(error)?, |
| 255 | _ => (), |
| 256 | }, |
| 257 | Arg::Array(command) => { |
| 258 | let Some((cmd, args)) = command.split_first() else { |
| 259 | return Ok(()); |
| 260 | }; |
| 261 | |
| 262 | let args_str: Vec<&str> = args.iter().map(|s| s.as_str()).collect(); |
| 263 | match Command::new(cmd.as_str()).args(&args_str).spawn() { |
| 264 | Err(error) if error.kind() == ErrorKind::NotFound => { |
| 265 | eprintln!( |
| 266 | "KeyAction::Spawn failed: could not spawn \"{}\", command not found", |
| 267 | cmd |
| 268 | ); |
| 269 | } |
| 270 | Err(error) => Err(error)?, |
| 271 | _ => (), |
| 272 | } |
| 273 | } |
| 274 | _ => {} |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | Ok(()) |
| 279 | } |