tony / oxwm

Branch: f188c77
Switch branches/tags
master
tonybtw Fixed box::leak issue. f188c77 2025-10-15
132 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 ToggleFloating,
21 MoveToTag,
22 None,
23 }
24
25 #[derive(Debug, Clone)]
26 pub enum Arg {
27 None,
28 Int(i32),
29 Str(String),
30 Array(Vec<String>),
31 }
32
33 impl Arg {
34 pub const fn none() -> Self {
35 Arg::None
36 }
37 }
38
39 #[derive(Clone)]
40 pub struct Key {
41 pub(crate) modifiers: Vec<KeyButMask>,
42 pub(crate) key: Keycode,
43 pub(crate) func: KeyAction,
44 pub(crate) arg: Arg,
45 }
46
47 impl Key {
48 pub fn new(modifiers: Vec<KeyButMask>, key: Keycode, func: KeyAction, arg: Arg) -> 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<(), X11Error> {
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]) -> (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 (keybinding.func, keybinding.arg.clone());
90 }
91 }
92
93 (KeyAction::None, Arg::None)
94 }
95
96 pub fn handle_spawn_action(action: KeyAction, arg: &Arg) -> io::Result<()> {
97 use io::ErrorKind;
98 if let KeyAction::Spawn = action {
99 match arg {
100 Arg::Str(command) => match Command::new(command.as_str()).spawn() {
101 Err(err) if err.kind() == ErrorKind::NotFound => {
102 eprintln!(
103 "KeyAction::Spawn failed: could not spawn \"{}\", command not found",
104 command
105 );
106 }
107 Err(err) => Err(err)?,
108 _ => (),
109 },
110 Arg::Array(command) => {
111 let Some((cmd, args)) = command.split_first() else {
112 return Ok(());
113 };
114
115 let args_str: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
116 match Command::new(cmd.as_str()).args(&args_str).spawn() {
117 Err(err) if err.kind() == ErrorKind::NotFound => {
118 eprintln!(
119 "KeyAction::Spawn failed: could not spawn \"{}\", command not found",
120 cmd
121 );
122 }
123 Err(err) => Err(err)?,
124 _ => (),
125 }
126 }
127 _ => {}
128 }
129 }
130
131 Ok(())
132 }