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