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