tony / oxwm

Branch: fa60658
Switch branches/tags
master
emzywastaken move errors to `error` module 953e629 2025-10-14
136 lines · 3.2 KB Raw Blame History
1 use std::io;
2 use std::process::Command;
3
4 use x11rb::connection::Connection;
5 use x11rb::protocol::xproto::*;
6
7 use crate::errors::X11Error;
8
9 #[derive(Debug, Copy, Clone)]
10 pub enum KeyAction {
11 Spawn,
12 KillClient,
13 FocusStack,
14 Quit,
15 Restart,
16 Recompile,
17 ViewTag,
18 ToggleGaps,
19 ToggleFullScreen,
20 MoveToTag,
21 None,
22 }
23
24 #[derive(Debug, Clone)]
25 pub enum Arg {
26 None,
27 Int(i32),
28 Str(&'static str),
29 Array(&'static [&'static str]),
30 }
31
32 impl Arg {
33 pub const fn none() -> Self {
34 Arg::None
35 }
36 }
37
38 #[derive(Clone)]
39 pub struct Key {
40 pub(crate) modifiers: &'static [KeyButMask],
41 pub(crate) key: Keycode,
42 pub(crate) func: KeyAction,
43 pub(crate) arg: Arg,
44 }
45
46 impl Key {
47 pub const fn new(
48 modifiers: &'static [KeyButMask],
49 key: Keycode,
50 func: KeyAction,
51 arg: Arg,
52 ) -> Self {
53 Self {
54 modifiers,
55 key,
56 func,
57 arg,
58 }
59 }
60 }
61
62 fn modifiers_to_mask(modifiers: &[KeyButMask]) -> u16 {
63 modifiers
64 .iter()
65 .fold(0u16, |acc, &modifier| acc | u16::from(modifier))
66 }
67
68 pub fn setup_keybinds(
69 connection: &impl Connection,
70 root: Window,
71 keybindings: &[Key],
72 ) -> Result<(), X11Error> {
73 for keybinding in keybindings {
74 let modifier_mask = modifiers_to_mask(keybinding.modifiers);
75
76 connection.grab_key(
77 false,
78 root,
79 modifier_mask.into(),
80 keybinding.key,
81 GrabMode::ASYNC,
82 GrabMode::ASYNC,
83 )?;
84 }
85 Ok(())
86 }
87
88 pub fn handle_key_press(event: KeyPressEvent, keybindings: &[Key]) -> (KeyAction, Arg) {
89 for keybinding in keybindings {
90 let modifier_mask = modifiers_to_mask(keybinding.modifiers);
91
92 if event.detail == keybinding.key && event.state == modifier_mask.into() {
93 return (keybinding.func, keybinding.arg.clone());
94 }
95 }
96
97 (KeyAction::None, Arg::None)
98 }
99
100 pub fn handle_spawn_action(action: KeyAction, arg: &Arg) -> io::Result<()> {
101 use io::ErrorKind;
102 match action {
103 KeyAction::Spawn => match arg {
104 Arg::Str(command) => match Command::new(command).spawn() {
105 Err(err) if err.kind() == ErrorKind::NotFound => {
106 eprintln!(
107 "KeyAction::Spawn failed: could not spawn \"{}\", command not found",
108 command
109 );
110 }
111 Err(err) => Err(err)?,
112 _ => (),
113 },
114 Arg::Array(command) => {
115 let Some((cmd, args)) = command.split_first() else {
116 return Ok(());
117 };
118
119 match Command::new(cmd).args(args).spawn() {
120 Err(err) if err.kind() == ErrorKind::NotFound => {
121 eprintln!(
122 "KeyAction::Spawn failed: could not spawn \"{}\", command not found",
123 cmd
124 );
125 }
126 Err(err) => Err(err)?,
127 _ => (),
128 }
129 }
130 _ => {}
131 },
132 _ => {}
133 }
134
135 Ok(())
136 }