| 1 | use anyhow::Result; |
| 2 | use x11rb::connection::Connection; |
| 3 | use x11rb::protocol::xproto::*; |
| 4 | |
| 5 | #[derive(Debug, Copy, Clone)] |
| 6 | pub enum KeyAction { |
| 7 | Spawn, |
| 8 | KillClient, |
| 9 | FocusStack, |
| 10 | Quit, |
| 11 | Restart, |
| 12 | Recompile, |
| 13 | ViewTag, |
| 14 | ToggleGaps, |
| 15 | ToggleFullScreen, |
| 16 | MoveToTag, |
| 17 | None, |
| 18 | } |
| 19 | |
| 20 | #[derive(Debug, Clone)] |
| 21 | pub enum Arg { |
| 22 | None, |
| 23 | Int(i32), |
| 24 | Str(&'static str), |
| 25 | Array(&'static [&'static str]), |
| 26 | } |
| 27 | |
| 28 | impl Arg { |
| 29 | pub const fn none() -> Self { |
| 30 | Arg::None |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | #[derive(Clone)] |
| 35 | pub struct Key { |
| 36 | pub(crate) modifiers: &'static [KeyButMask], |
| 37 | pub(crate) key: Keycode, |
| 38 | pub(crate) func: KeyAction, |
| 39 | pub(crate) arg: Arg, |
| 40 | } |
| 41 | |
| 42 | impl Key { |
| 43 | pub const fn new( |
| 44 | modifiers: &'static [KeyButMask], |
| 45 | key: Keycode, |
| 46 | func: KeyAction, |
| 47 | arg: Arg, |
| 48 | ) -> Self { |
| 49 | Self { |
| 50 | modifiers, |
| 51 | key, |
| 52 | func, |
| 53 | arg, |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | fn modifiers_to_mask(modifiers: &[KeyButMask]) -> u16 { |
| 59 | modifiers |
| 60 | .iter() |
| 61 | .fold(0u16, |acc, &modifier| acc | u16::from(modifier)) |
| 62 | } |
| 63 | |
| 64 | pub fn setup_keybinds( |
| 65 | connection: &impl Connection, |
| 66 | root: Window, |
| 67 | keybindings: &[Key], |
| 68 | ) -> Result<()> { |
| 69 | for keybinding in keybindings { |
| 70 | let modifier_mask = modifiers_to_mask(keybinding.modifiers); |
| 71 | |
| 72 | connection.grab_key( |
| 73 | false, |
| 74 | root, |
| 75 | modifier_mask.into(), |
| 76 | keybinding.key, |
| 77 | GrabMode::ASYNC, |
| 78 | GrabMode::ASYNC, |
| 79 | )?; |
| 80 | } |
| 81 | Ok(()) |
| 82 | } |
| 83 | |
| 84 | pub fn handle_key_press(event: KeyPressEvent, keybindings: &[Key]) -> Result<(KeyAction, Arg)> { |
| 85 | for keybinding in keybindings { |
| 86 | let modifier_mask = modifiers_to_mask(keybinding.modifiers); |
| 87 | |
| 88 | if event.detail == keybinding.key && event.state == modifier_mask.into() { |
| 89 | return Ok((keybinding.func, keybinding.arg.clone())); |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | Ok((KeyAction::None, Arg::None)) |
| 94 | } |