tony / oxwm

Branch: 258ec1d
Switch branches/tags
master
tonybtw Added proper error handling in blocks, and font. added error modal so config syntax error doesnt crash when you reload your oxwm, added keybind overlay modal to show the important keybinds (inspired by niri), moved keysms helper function into const file to reduce code duplication. ad06fa5 2025-11-09
312 lines · 8.5 KB Raw Blame History
1 use std::collections::HashMap;
2 use std::io::{ErrorKind, Result};
3 use std::process::Command;
4
5 use serde::Deserialize;
6 use x11rb::connection::Connection;
7 use x11rb::protocol::xproto::*;
8
9 use crate::errors::X11Error;
10 use crate::keyboard::keysyms::{self, Keysym};
11
12 #[derive(Debug, Copy, Clone, Deserialize, PartialEq)]
13 pub enum KeyAction {
14 Spawn,
15 KillClient,
16 FocusStack,
17 FocusDirection,
18 SwapDirection,
19 Quit,
20 Restart,
21 Recompile,
22 ViewTag,
23 ToggleGaps,
24 ToggleFullScreen,
25 ToggleFloating,
26 ChangeLayout,
27 CycleLayout,
28 MoveToTag,
29 FocusMonitor,
30 SmartMoveWin,
31 ExchangeClient,
32 ShowKeybindOverlay,
33 None,
34 }
35
36 #[derive(Debug, Clone)]
37 pub enum Arg {
38 None,
39 Int(i32),
40 Str(String),
41 Array(Vec<String>),
42 }
43
44 impl Arg {
45 pub const fn none() -> Self {
46 Arg::None
47 }
48 }
49
50 #[derive(Clone, Debug)]
51 pub struct KeyPress {
52 pub(crate) modifiers: Vec<KeyButMask>,
53 pub(crate) keysym: Keysym,
54 }
55
56 #[derive(Clone)]
57 pub struct KeyBinding {
58 pub(crate) keys: Vec<KeyPress>,
59 pub(crate) func: KeyAction,
60 pub(crate) arg: Arg,
61 }
62
63 impl KeyBinding {
64 pub fn new(keys: Vec<KeyPress>, func: KeyAction, arg: Arg) -> Self {
65 Self { keys, func, arg }
66 }
67
68 pub fn single_key(
69 modifiers: Vec<KeyButMask>,
70 keysym: Keysym,
71 func: KeyAction,
72 arg: Arg,
73 ) -> Self {
74 Self {
75 keys: vec![KeyPress { modifiers, keysym }],
76 func,
77 arg,
78 }
79 }
80 }
81
82 pub type Key = KeyBinding;
83
84 #[derive(Debug, Clone)]
85 pub enum KeychordState {
86 Idle,
87 InProgress {
88 candidates: Vec<usize>,
89 keys_pressed: usize,
90 },
91 }
92
93 pub enum KeychordResult {
94 Completed(KeyAction, Arg),
95 InProgress(Vec<usize>),
96 None,
97 Cancelled,
98 }
99
100 pub fn modifiers_to_mask(modifiers: &[KeyButMask]) -> u16 {
101 modifiers
102 .iter()
103 .fold(0u16, |acc, &modifier| acc | u16::from(modifier))
104 }
105
106 fn build_keysym_maps(
107 connection: &impl Connection,
108 ) -> std::result::Result<(HashMap<Keysym, Vec<Keycode>>, HashMap<Keycode, Keysym>), X11Error> {
109 let setup = connection.setup();
110 let min_keycode = setup.min_keycode;
111 let max_keycode = setup.max_keycode;
112
113 let keyboard_mapping = connection
114 .get_keyboard_mapping(min_keycode, max_keycode - min_keycode + 1)?
115 .reply()?;
116
117 let mut keysym_to_keycode: HashMap<Keysym, Vec<Keycode>> = HashMap::new();
118 let mut keycode_to_keysym: HashMap<Keycode, Keysym> = HashMap::new();
119 let keysyms_per_keycode = keyboard_mapping.keysyms_per_keycode;
120
121 for keycode in min_keycode..=max_keycode {
122 let index = (keycode - min_keycode) as usize * keysyms_per_keycode as usize;
123
124 for i in 0..keysyms_per_keycode as usize {
125 if let Some(&keysym) = keyboard_mapping.keysyms.get(index + i) {
126 if keysym != 0 {
127 keysym_to_keycode
128 .entry(keysym)
129 .or_insert_with(Vec::new)
130 .push(keycode);
131 keycode_to_keysym.entry(keycode).or_insert(keysym);
132 }
133 }
134 }
135 }
136
137 Ok((keysym_to_keycode, keycode_to_keysym))
138 }
139
140 pub fn setup_keybinds(
141 connection: &impl Connection,
142 root: Window,
143 keybindings: &[KeyBinding],
144 ) -> std::result::Result<(), X11Error> {
145 use std::collections::HashSet;
146
147 let (keysym_to_keycode, _) = build_keysym_maps(connection)?;
148 let mut grabbed_keys: HashSet<(u16, Keycode)> = HashSet::new();
149
150 for keybinding in keybindings {
151 if keybinding.keys.is_empty() {
152 continue;
153 }
154
155 let first_key = &keybinding.keys[0];
156 let modifier_mask = modifiers_to_mask(&first_key.modifiers);
157
158 if let Some(keycodes) = keysym_to_keycode.get(&first_key.keysym) {
159 if let Some(&keycode) = keycodes.first() {
160 let key_tuple = (modifier_mask, keycode);
161
162 if grabbed_keys.insert(key_tuple) {
163 connection.grab_key(
164 false,
165 root,
166 modifier_mask.into(),
167 keycode,
168 GrabMode::ASYNC,
169 GrabMode::ASYNC,
170 )?;
171 }
172 }
173 }
174 }
175
176 Ok(())
177 }
178
179 pub fn handle_key_press(
180 event: KeyPressEvent,
181 keybindings: &[KeyBinding],
182 keychord_state: &KeychordState,
183 connection: &impl Connection,
184 ) -> std::result::Result<KeychordResult, X11Error> {
185 let (_, keycode_to_keysym) = build_keysym_maps(connection)?;
186 let event_keysym = keycode_to_keysym.get(&event.detail).copied().unwrap_or(0);
187
188 if event_keysym == keysyms::XK_ESCAPE {
189 return Ok(match keychord_state {
190 KeychordState::InProgress { .. } => KeychordResult::Cancelled,
191 KeychordState::Idle => KeychordResult::None,
192 });
193 }
194
195 Ok(match keychord_state {
196 KeychordState::Idle => handle_first_key(event, event_keysym, keybindings),
197 KeychordState::InProgress {
198 candidates,
199 keys_pressed,
200 } => handle_next_key(event, event_keysym, keybindings, candidates, *keys_pressed),
201 })
202 }
203
204 fn handle_first_key(
205 event: KeyPressEvent,
206 event_keysym: Keysym,
207 keybindings: &[KeyBinding],
208 ) -> KeychordResult {
209 let mut candidates = Vec::new();
210
211 for (keybinding_index, keybinding) in keybindings.iter().enumerate() {
212 if keybinding.keys.is_empty() {
213 continue;
214 }
215
216 let first_key = &keybinding.keys[0];
217 let modifier_mask = modifiers_to_mask(&first_key.modifiers);
218
219 if event_keysym == first_key.keysym && event.state == modifier_mask.into() {
220 if keybinding.keys.len() == 1 {
221 return KeychordResult::Completed(keybinding.func, keybinding.arg.clone());
222 } else {
223 candidates.push(keybinding_index);
224 }
225 }
226 }
227
228 if candidates.is_empty() {
229 KeychordResult::None
230 } else {
231 KeychordResult::InProgress(candidates)
232 }
233 }
234
235 fn handle_next_key(
236 event: KeyPressEvent,
237 event_keysym: Keysym,
238 keybindings: &[KeyBinding],
239 candidates: &[usize],
240 keys_pressed: usize,
241 ) -> KeychordResult {
242 let mut new_candidates = Vec::new();
243
244 for &candidate_index in candidates {
245 let keybinding = &keybindings[candidate_index];
246
247 if keys_pressed >= keybinding.keys.len() {
248 continue;
249 }
250
251 let next_key = &keybinding.keys[keys_pressed];
252 let required_mask = modifiers_to_mask(&next_key.modifiers);
253 let event_state: u16 = event.state.into();
254
255 let modifiers_match = if next_key.modifiers.is_empty() {
256 true
257 } else {
258 (event_state & required_mask) == required_mask
259 };
260
261 if event_keysym == next_key.keysym && modifiers_match {
262 if keys_pressed + 1 == keybinding.keys.len() {
263 return KeychordResult::Completed(keybinding.func, keybinding.arg.clone());
264 } else {
265 new_candidates.push(candidate_index);
266 }
267 }
268 }
269
270 if new_candidates.is_empty() {
271 KeychordResult::Cancelled
272 } else {
273 KeychordResult::InProgress(new_candidates)
274 }
275 }
276
277 pub fn handle_spawn_action(action: KeyAction, arg: &Arg) -> Result<()> {
278 if let KeyAction::Spawn = action {
279 match arg {
280 Arg::Str(command) => match Command::new(command.as_str()).spawn() {
281 Err(error) if error.kind() == ErrorKind::NotFound => {
282 eprintln!(
283 "KeyAction::Spawn failed: could not spawn \"{}\", command not found",
284 command
285 );
286 }
287 Err(error) => Err(error)?,
288 _ => (),
289 },
290 Arg::Array(command) => {
291 let Some((cmd, args)) = command.split_first() else {
292 return Ok(());
293 };
294
295 let args_str: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
296 match Command::new(cmd.as_str()).args(&args_str).spawn() {
297 Err(error) if error.kind() == ErrorKind::NotFound => {
298 eprintln!(
299 "KeyAction::Spawn failed: could not spawn \"{}\", command not found",
300 cmd
301 );
302 }
303 Err(error) => Err(error)?,
304 _ => (),
305 }
306 }
307 _ => {}
308 }
309 }
310
311 Ok(())
312 }