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