| 1 | use std::collections::HashMap; |
| 2 | use std::io::{ErrorKind, Result}; |
| 3 | use std::process::Command; |
| 4 | |
| 5 | use serde::Deserialize; |
| 6 | use x11rb::connection::Connection; |
| 7 | use x11rb::protocol::xproto::*; |
| 8 | |
| 9 | use crate::errors::X11Error; |
| 10 | use crate::keyboard::keysyms::{self, Keysym}; |
| 11 | |
| 12 | #[derive(Debug, Copy, Clone, Deserialize, PartialEq)] |
| 13 | pub enum KeyAction { |
| 14 | Spawn, |
| 15 | SpawnTerminal, |
| 16 | KillClient, |
| 17 | FocusStack, |
| 18 | FocusDirection, |
| 19 | SwapDirection, |
| 20 | Quit, |
| 21 | Restart, |
| 22 | Recompile, |
| 23 | ViewTag, |
| 24 | ToggleView, |
| 25 | MoveToTag, |
| 26 | ToggleTag, |
| 27 | ToggleGaps, |
| 28 | ToggleFullScreen, |
| 29 | ToggleFloating, |
| 30 | ChangeLayout, |
| 31 | CycleLayout, |
| 32 | FocusMonitor, |
| 33 | TagMonitor, |
| 34 | ExchangeClient, |
| 35 | ShowKeybindOverlay, |
| 36 | SetMasterFactor, |
| 37 | IncNumMaster, |
| 38 | None, |
| 39 | } |
| 40 | |
| 41 | #[derive(Debug, Clone)] |
| 42 | pub enum Arg { |
| 43 | None, |
| 44 | Int(i32), |
| 45 | Str(String), |
| 46 | Array(Vec<String>), |
| 47 | } |
| 48 | |
| 49 | impl Arg { |
| 50 | pub const fn none() -> Self { |
| 51 | Arg::None |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | #[derive(Clone, Debug)] |
| 56 | pub struct KeyPress { |
| 57 | pub(crate) modifiers: Vec<KeyButMask>, |
| 58 | pub(crate) keysym: Keysym, |
| 59 | } |
| 60 | |
| 61 | #[derive(Clone)] |
| 62 | pub struct KeyBinding { |
| 63 | pub(crate) keys: Vec<KeyPress>, |
| 64 | pub(crate) func: KeyAction, |
| 65 | pub(crate) arg: Arg, |
| 66 | } |
| 67 | |
| 68 | impl KeyBinding { |
| 69 | pub fn new(keys: Vec<KeyPress>, func: KeyAction, arg: Arg) -> Self { |
| 70 | Self { keys, func, arg } |
| 71 | } |
| 72 | |
| 73 | pub fn single_key( |
| 74 | modifiers: Vec<KeyButMask>, |
| 75 | keysym: Keysym, |
| 76 | func: KeyAction, |
| 77 | arg: Arg, |
| 78 | ) -> Self { |
| 79 | Self { |
| 80 | keys: vec![KeyPress { modifiers, keysym }], |
| 81 | func, |
| 82 | arg, |
| 83 | } |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | pub type Key = KeyBinding; |
| 88 | |
| 89 | #[derive(Debug, Clone)] |
| 90 | pub enum KeychordState { |
| 91 | Idle, |
| 92 | InProgress { |
| 93 | candidates: Vec<usize>, |
| 94 | keys_pressed: usize, |
| 95 | }, |
| 96 | } |
| 97 | |
| 98 | pub enum KeychordResult { |
| 99 | Completed(KeyAction, Arg), |
| 100 | InProgress(Vec<usize>), |
| 101 | None, |
| 102 | Cancelled, |
| 103 | } |
| 104 | |
| 105 | pub fn modifiers_to_mask(modifiers: &[KeyButMask]) -> u16 { |
| 106 | modifiers |
| 107 | .iter() |
| 108 | .fold(0u16, |acc, &modifier| acc | u16::from(modifier)) |
| 109 | } |
| 110 | |
| 111 | fn build_keysym_maps( |
| 112 | connection: &impl Connection, |
| 113 | ) -> std::result::Result<(HashMap<Keysym, Vec<Keycode>>, HashMap<Keycode, Keysym>), X11Error> { |
| 114 | let setup = connection.setup(); |
| 115 | let min_keycode = setup.min_keycode; |
| 116 | let max_keycode = setup.max_keycode; |
| 117 | |
| 118 | let keyboard_mapping = connection |
| 119 | .get_keyboard_mapping(min_keycode, max_keycode - min_keycode + 1)? |
| 120 | .reply()?; |
| 121 | |
| 122 | let mut keysym_to_keycode: HashMap<Keysym, Vec<Keycode>> = HashMap::new(); |
| 123 | let mut keycode_to_keysym: HashMap<Keycode, Keysym> = HashMap::new(); |
| 124 | let keysyms_per_keycode = keyboard_mapping.keysyms_per_keycode; |
| 125 | |
| 126 | for keycode in min_keycode..=max_keycode { |
| 127 | let index = (keycode - min_keycode) as usize * keysyms_per_keycode as usize; |
| 128 | |
| 129 | for i in 0..keysyms_per_keycode as usize { |
| 130 | if let Some(&keysym) = keyboard_mapping.keysyms.get(index + i) { |
| 131 | if keysym != 0 { |
| 132 | keysym_to_keycode |
| 133 | .entry(keysym) |
| 134 | .or_insert_with(Vec::new) |
| 135 | .push(keycode); |
| 136 | keycode_to_keysym.entry(keycode).or_insert(keysym); |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | Ok((keysym_to_keycode, keycode_to_keysym)) |
| 143 | } |
| 144 | |
| 145 | pub fn setup_keybinds( |
| 146 | connection: &impl Connection, |
| 147 | root: Window, |
| 148 | keybindings: &[KeyBinding], |
| 149 | ) -> std::result::Result<(), X11Error> { |
| 150 | use std::collections::HashSet; |
| 151 | |
| 152 | let (keysym_to_keycode, _) = build_keysym_maps(connection)?; |
| 153 | let mut grabbed_keys: HashSet<(u16, Keycode)> = HashSet::new(); |
| 154 | |
| 155 | let ignore_modifiers = [ |
| 156 | 0, |
| 157 | u16::from(ModMask::LOCK), |
| 158 | u16::from(ModMask::M2), |
| 159 | u16::from(ModMask::LOCK | ModMask::M2), |
| 160 | ]; |
| 161 | |
| 162 | for keybinding in keybindings { |
| 163 | if keybinding.keys.is_empty() { |
| 164 | continue; |
| 165 | } |
| 166 | |
| 167 | let first_key = &keybinding.keys[0]; |
| 168 | let modifier_mask = modifiers_to_mask(&first_key.modifiers); |
| 169 | |
| 170 | if let Some(keycodes) = keysym_to_keycode.get(&first_key.keysym) { |
| 171 | if let Some(&keycode) = keycodes.first() { |
| 172 | for &ignore_mask in &ignore_modifiers { |
| 173 | let grab_mask = modifier_mask | ignore_mask; |
| 174 | let key_tuple = (grab_mask, keycode); |
| 175 | |
| 176 | if grabbed_keys.insert(key_tuple) { |
| 177 | connection.grab_key( |
| 178 | false, |
| 179 | root, |
| 180 | grab_mask.into(), |
| 181 | keycode, |
| 182 | GrabMode::ASYNC, |
| 183 | GrabMode::ASYNC, |
| 184 | )?; |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | Ok(()) |
| 192 | } |
| 193 | |
| 194 | pub fn handle_key_press( |
| 195 | event: KeyPressEvent, |
| 196 | keybindings: &[KeyBinding], |
| 197 | keychord_state: &KeychordState, |
| 198 | connection: &impl Connection, |
| 199 | ) -> std::result::Result<KeychordResult, X11Error> { |
| 200 | let (_, keycode_to_keysym) = build_keysym_maps(connection)?; |
| 201 | let event_keysym = keycode_to_keysym.get(&event.detail).copied().unwrap_or(0); |
| 202 | |
| 203 | if event_keysym == keysyms::XK_ESCAPE { |
| 204 | return Ok(match keychord_state { |
| 205 | KeychordState::InProgress { .. } => KeychordResult::Cancelled, |
| 206 | KeychordState::Idle => KeychordResult::None, |
| 207 | }); |
| 208 | } |
| 209 | |
| 210 | Ok(match keychord_state { |
| 211 | KeychordState::Idle => handle_first_key(event, event_keysym, keybindings), |
| 212 | KeychordState::InProgress { |
| 213 | candidates, |
| 214 | keys_pressed, |
| 215 | } => handle_next_key(event, event_keysym, keybindings, candidates, *keys_pressed), |
| 216 | }) |
| 217 | } |
| 218 | |
| 219 | fn handle_first_key( |
| 220 | event: KeyPressEvent, |
| 221 | event_keysym: Keysym, |
| 222 | keybindings: &[KeyBinding], |
| 223 | ) -> KeychordResult { |
| 224 | let mut candidates = Vec::new(); |
| 225 | |
| 226 | let clean_state = event.state & !(u16::from(ModMask::LOCK) | u16::from(ModMask::M2)); |
| 227 | |
| 228 | for (keybinding_index, keybinding) in keybindings.iter().enumerate() { |
| 229 | if keybinding.keys.is_empty() { |
| 230 | continue; |
| 231 | } |
| 232 | |
| 233 | let first_key = &keybinding.keys[0]; |
| 234 | let modifier_mask = modifiers_to_mask(&first_key.modifiers); |
| 235 | |
| 236 | if event_keysym == first_key.keysym && clean_state == modifier_mask.into() { |
| 237 | if keybinding.keys.len() == 1 { |
| 238 | return KeychordResult::Completed(keybinding.func, keybinding.arg.clone()); |
| 239 | } else { |
| 240 | candidates.push(keybinding_index); |
| 241 | } |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | if candidates.is_empty() { |
| 246 | KeychordResult::None |
| 247 | } else { |
| 248 | KeychordResult::InProgress(candidates) |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | fn handle_next_key( |
| 253 | event: KeyPressEvent, |
| 254 | event_keysym: Keysym, |
| 255 | keybindings: &[KeyBinding], |
| 256 | candidates: &[usize], |
| 257 | keys_pressed: usize, |
| 258 | ) -> KeychordResult { |
| 259 | let mut new_candidates = Vec::new(); |
| 260 | |
| 261 | let clean_state = event.state & !(u16::from(ModMask::LOCK) | u16::from(ModMask::M2)); |
| 262 | |
| 263 | for &candidate_index in candidates { |
| 264 | let keybinding = &keybindings[candidate_index]; |
| 265 | |
| 266 | if keys_pressed >= keybinding.keys.len() { |
| 267 | continue; |
| 268 | } |
| 269 | |
| 270 | let next_key = &keybinding.keys[keys_pressed]; |
| 271 | let required_mask = modifiers_to_mask(&next_key.modifiers); |
| 272 | |
| 273 | let modifiers_match = if next_key.modifiers.is_empty() { |
| 274 | true |
| 275 | } else { |
| 276 | (clean_state & required_mask) == required_mask.into() |
| 277 | }; |
| 278 | |
| 279 | if event_keysym == next_key.keysym && modifiers_match { |
| 280 | if keys_pressed + 1 == keybinding.keys.len() { |
| 281 | return KeychordResult::Completed(keybinding.func, keybinding.arg.clone()); |
| 282 | } else { |
| 283 | new_candidates.push(candidate_index); |
| 284 | } |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | if new_candidates.is_empty() { |
| 289 | KeychordResult::Cancelled |
| 290 | } else { |
| 291 | KeychordResult::InProgress(new_candidates) |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | pub fn handle_spawn_action(action: KeyAction, arg: &Arg, selected_monitor: usize) -> Result<()> { |
| 296 | if let KeyAction::Spawn = action { |
| 297 | match arg { |
| 298 | Arg::Str(command) => match Command::new(command.as_str()).spawn() { |
| 299 | Err(error) if error.kind() == ErrorKind::NotFound => { |
| 300 | eprintln!( |
| 301 | "KeyAction::Spawn failed: could not spawn \"{}\", command not found", |
| 302 | command |
| 303 | ); |
| 304 | } |
| 305 | Err(error) => Err(error)?, |
| 306 | _ => (), |
| 307 | }, |
| 308 | Arg::Array(command) => { |
| 309 | let Some((cmd, args)) = command.split_first() else { |
| 310 | return Ok(()); |
| 311 | }; |
| 312 | |
| 313 | let mut args_vec: Vec<String> = args.to_vec(); |
| 314 | |
| 315 | let is_dmenu = cmd.contains("dmenu"); |
| 316 | let has_monitor_flag = args.iter().any(|arg| arg == "-m"); |
| 317 | |
| 318 | if is_dmenu && !has_monitor_flag { |
| 319 | args_vec.insert(0, selected_monitor.to_string()); |
| 320 | args_vec.insert(0, "-m".to_string()); |
| 321 | } |
| 322 | |
| 323 | let args_str: Vec<&str> = args_vec.iter().map(|s| s.as_str()).collect(); |
| 324 | match Command::new(cmd.as_str()).args(&args_str).spawn() { |
| 325 | Err(error) if error.kind() == ErrorKind::NotFound => { |
| 326 | eprintln!( |
| 327 | "KeyAction::Spawn failed: could not spawn \"{}\", command not found", |
| 328 | cmd |
| 329 | ); |
| 330 | } |
| 331 | Err(error) => Err(error)?, |
| 332 | _ => (), |
| 333 | } |
| 334 | } |
| 335 | _ => {} |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | Ok(()) |
| 340 | } |