tony / oxwm

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