tony / oxwm

Branch: d90e50d
Switch branches/tags
master
tonybtw Removed libc as a dep, and used a double-fork strategy to handle zombie processes instead of the dwm method due to shell being required as a hanging process for the bar. d90e50d 2025-12-12
342 lines · 8.9 KB Raw Blame History
1 use std::io::Result;
2
3 use serde::Deserialize;
4 use x11rb::connection::Connection;
5 use x11rb::protocol::xproto::*;
6
7 use crate::errors::X11Error;
8 use crate::keyboard::keysyms::{self, Keysym};
9
10 #[derive(Debug, Copy, Clone, Deserialize, PartialEq)]
11 pub enum KeyAction {
12 Spawn,
13 SpawnTerminal,
14 KillClient,
15 FocusStack,
16 MoveStack,
17 Quit,
18 Restart,
19 ViewTag,
20 ToggleView,
21 MoveToTag,
22 ToggleTag,
23 ToggleGaps,
24 ToggleFullScreen,
25 ToggleFloating,
26 ChangeLayout,
27 CycleLayout,
28 FocusMonitor,
29 TagMonitor,
30 ShowKeybindOverlay,
31 SetMasterFactor,
32 IncNumMaster,
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 pub struct KeyboardMapping {
107 pub syms: Vec<Keysym>,
108 pub keysyms_per_keycode: u8,
109 pub min_keycode: Keycode,
110 }
111
112 impl KeyboardMapping {
113 pub fn keycode_to_keysym(&self, keycode: Keycode) -> Keysym {
114 if keycode < self.min_keycode {
115 return 0;
116 }
117 let index = (keycode - self.min_keycode) as usize * self.keysyms_per_keycode as usize;
118 self.syms.get(index).copied().unwrap_or(0)
119 }
120
121 pub fn find_keycode(&self, keysym: Keysym, min_keycode: Keycode, max_keycode: Keycode) -> Option<Keycode> {
122 for keycode in min_keycode..=max_keycode {
123 let index = (keycode - self.min_keycode) as usize * self.keysyms_per_keycode as usize;
124 if let Some(&sym) = self.syms.get(index) {
125 if sym == keysym {
126 return Some(keycode);
127 }
128 }
129 }
130 None
131 }
132 }
133
134 pub fn get_keyboard_mapping(
135 connection: &impl Connection,
136 ) -> std::result::Result<KeyboardMapping, X11Error> {
137 let setup = connection.setup();
138 let min_keycode = setup.min_keycode;
139 let max_keycode = setup.max_keycode;
140
141 let mapping = connection
142 .get_keyboard_mapping(min_keycode, max_keycode - min_keycode + 1)?
143 .reply()?;
144
145 Ok(KeyboardMapping {
146 syms: mapping.keysyms,
147 keysyms_per_keycode: mapping.keysyms_per_keycode,
148 min_keycode,
149 })
150 }
151
152 pub fn grab_keys(
153 connection: &impl Connection,
154 root: Window,
155 keybindings: &[KeyBinding],
156 current_key: usize,
157 ) -> std::result::Result<KeyboardMapping, X11Error> {
158 let setup = connection.setup();
159 let min_keycode = setup.min_keycode;
160 let max_keycode = setup.max_keycode;
161
162 let mapping = get_keyboard_mapping(connection)?;
163
164 connection.ungrab_key(x11rb::protocol::xproto::Grab::ANY, root, ModMask::ANY)?;
165
166 let modifiers = [
167 0u16,
168 u16::from(ModMask::LOCK),
169 u16::from(ModMask::M2),
170 u16::from(ModMask::LOCK | ModMask::M2),
171 ];
172
173 for keycode in min_keycode..=max_keycode {
174 for keybinding in keybindings {
175 if current_key >= keybinding.keys.len() {
176 continue;
177 }
178
179 let key = &keybinding.keys[current_key];
180 if key.keysym == mapping.keycode_to_keysym(keycode) {
181 let modifier_mask = modifiers_to_mask(&key.modifiers);
182 for &ignore_mask in &modifiers {
183 connection.grab_key(
184 true,
185 root,
186 (modifier_mask | ignore_mask).into(),
187 keycode,
188 GrabMode::ASYNC,
189 GrabMode::ASYNC,
190 )?;
191 }
192 }
193 }
194 }
195
196 if current_key > 0 {
197 if let Some(escape_keycode) = mapping.find_keycode(keysyms::XK_ESCAPE, min_keycode, max_keycode) {
198 connection.grab_key(
199 true,
200 root,
201 ModMask::ANY,
202 escape_keycode,
203 GrabMode::ASYNC,
204 GrabMode::ASYNC,
205 )?;
206 }
207 }
208
209 connection.flush()?;
210 Ok(mapping)
211 }
212
213 pub fn handle_key_press(
214 event: KeyPressEvent,
215 keybindings: &[KeyBinding],
216 keychord_state: &KeychordState,
217 mapping: &KeyboardMapping,
218 ) -> KeychordResult {
219 let keysym = mapping.keycode_to_keysym(event.detail);
220
221 if keysym == keysyms::XK_ESCAPE {
222 return match keychord_state {
223 KeychordState::InProgress { .. } => KeychordResult::Cancelled,
224 KeychordState::Idle => KeychordResult::None,
225 };
226 }
227
228 match keychord_state {
229 KeychordState::Idle => handle_first_key(event, keysym, keybindings),
230 KeychordState::InProgress {
231 candidates,
232 keys_pressed,
233 } => handle_next_key(event, keysym, keybindings, candidates, *keys_pressed),
234 }
235 }
236
237 fn handle_first_key(
238 event: KeyPressEvent,
239 event_keysym: Keysym,
240 keybindings: &[KeyBinding],
241 ) -> KeychordResult {
242 let mut candidates = Vec::new();
243
244 let clean_state = event.state & !(u16::from(ModMask::LOCK) | u16::from(ModMask::M2));
245
246 for (keybinding_index, keybinding) in keybindings.iter().enumerate() {
247 if keybinding.keys.is_empty() {
248 continue;
249 }
250
251 let first_key = &keybinding.keys[0];
252 let modifier_mask = modifiers_to_mask(&first_key.modifiers);
253
254 if event_keysym == first_key.keysym && clean_state == modifier_mask.into() {
255 if keybinding.keys.len() == 1 {
256 return KeychordResult::Completed(keybinding.func, keybinding.arg.clone());
257 } else {
258 candidates.push(keybinding_index);
259 }
260 }
261 }
262
263 if candidates.is_empty() {
264 KeychordResult::None
265 } else {
266 KeychordResult::InProgress(candidates)
267 }
268 }
269
270 fn handle_next_key(
271 event: KeyPressEvent,
272 event_keysym: Keysym,
273 keybindings: &[KeyBinding],
274 candidates: &[usize],
275 keys_pressed: usize,
276 ) -> KeychordResult {
277 let mut new_candidates = Vec::new();
278
279 let clean_state = event.state & !(u16::from(ModMask::LOCK) | u16::from(ModMask::M2));
280
281 for &candidate_index in candidates {
282 let keybinding = &keybindings[candidate_index];
283
284 if keys_pressed >= keybinding.keys.len() {
285 continue;
286 }
287
288 let next_key = &keybinding.keys[keys_pressed];
289 let required_mask = modifiers_to_mask(&next_key.modifiers);
290
291 let modifiers_match = if next_key.modifiers.is_empty() {
292 true
293 } else {
294 (clean_state & required_mask) == required_mask.into()
295 };
296
297 if event_keysym == next_key.keysym && modifiers_match {
298 if keys_pressed + 1 == keybinding.keys.len() {
299 return KeychordResult::Completed(keybinding.func, keybinding.arg.clone());
300 } else {
301 new_candidates.push(candidate_index);
302 }
303 }
304 }
305
306 if new_candidates.is_empty() {
307 KeychordResult::Cancelled
308 } else {
309 KeychordResult::InProgress(new_candidates)
310 }
311 }
312
313 pub fn handle_spawn_action(action: KeyAction, arg: &Arg, selected_monitor: usize) -> Result<()> {
314 if let KeyAction::Spawn = action {
315 match arg {
316 Arg::Str(command) => {
317 crate::signal::spawn_detached(command);
318 }
319 Arg::Array(command) => {
320 let Some((cmd, args)) = command.split_first() else {
321 return Ok(());
322 };
323
324 let mut args_vec: Vec<String> = args.to_vec();
325
326 let is_dmenu = cmd.contains("dmenu");
327 let has_monitor_flag = args.iter().any(|arg| arg == "-m");
328
329 if is_dmenu && !has_monitor_flag {
330 args_vec.insert(0, selected_monitor.to_string());
331 args_vec.insert(0, "-m".to_string());
332 }
333
334 let args_str: Vec<&str> = args_vec.iter().map(|s| s.as_str()).collect();
335 crate::signal::spawn_detached_with_args(cmd, &args_str);
336 }
337 _ => {}
338 }
339 }
340
341 Ok(())
342 }