tony / oxwm

Branch: e932c2c
Switch branches/tags
master
tonybtw deprecated directional/exchange client movement for now since they interfere with core window/client management structural logic. 51b0e02 2025-12-01
337 lines · 9.4 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 SpawnTerminal,
16 KillClient,
17 FocusStack,
18 Quit,
19 Restart,
20 Recompile,
21 ViewTag,
22 ToggleView,
23 MoveToTag,
24 ToggleTag,
25 ToggleGaps,
26 ToggleFullScreen,
27 ToggleFloating,
28 ChangeLayout,
29 CycleLayout,
30 FocusMonitor,
31 TagMonitor,
32 ShowKeybindOverlay,
33 SetMasterFactor,
34 IncNumMaster,
35 None,
36 }
37
38 #[derive(Debug, Clone)]
39 pub enum Arg {
40 None,
41 Int(i32),
42 Str(String),
43 Array(Vec<String>),
44 }
45
46 impl Arg {
47 pub const fn none() -> Self {
48 Arg::None
49 }
50 }
51
52 #[derive(Clone, Debug)]
53 pub struct KeyPress {
54 pub(crate) modifiers: Vec<KeyButMask>,
55 pub(crate) keysym: Keysym,
56 }
57
58 #[derive(Clone)]
59 pub struct KeyBinding {
60 pub(crate) keys: Vec<KeyPress>,
61 pub(crate) func: KeyAction,
62 pub(crate) arg: Arg,
63 }
64
65 impl KeyBinding {
66 pub fn new(keys: Vec<KeyPress>, func: KeyAction, arg: Arg) -> Self {
67 Self { keys, func, arg }
68 }
69
70 pub fn single_key(
71 modifiers: Vec<KeyButMask>,
72 keysym: Keysym,
73 func: KeyAction,
74 arg: Arg,
75 ) -> Self {
76 Self {
77 keys: vec![KeyPress { modifiers, keysym }],
78 func,
79 arg,
80 }
81 }
82 }
83
84 pub type Key = KeyBinding;
85
86 #[derive(Debug, Clone)]
87 pub enum KeychordState {
88 Idle,
89 InProgress {
90 candidates: Vec<usize>,
91 keys_pressed: usize,
92 },
93 }
94
95 pub enum KeychordResult {
96 Completed(KeyAction, Arg),
97 InProgress(Vec<usize>),
98 None,
99 Cancelled,
100 }
101
102 pub fn modifiers_to_mask(modifiers: &[KeyButMask]) -> u16 {
103 modifiers
104 .iter()
105 .fold(0u16, |acc, &modifier| acc | u16::from(modifier))
106 }
107
108 fn build_keysym_maps(
109 connection: &impl Connection,
110 ) -> std::result::Result<(HashMap<Keysym, Vec<Keycode>>, HashMap<Keycode, Keysym>), X11Error> {
111 let setup = connection.setup();
112 let min_keycode = setup.min_keycode;
113 let max_keycode = setup.max_keycode;
114
115 let keyboard_mapping = connection
116 .get_keyboard_mapping(min_keycode, max_keycode - min_keycode + 1)?
117 .reply()?;
118
119 let mut keysym_to_keycode: HashMap<Keysym, Vec<Keycode>> = HashMap::new();
120 let mut keycode_to_keysym: HashMap<Keycode, Keysym> = HashMap::new();
121 let keysyms_per_keycode = keyboard_mapping.keysyms_per_keycode;
122
123 for keycode in min_keycode..=max_keycode {
124 let index = (keycode - min_keycode) as usize * keysyms_per_keycode as usize;
125
126 for i in 0..keysyms_per_keycode as usize {
127 if let Some(&keysym) = keyboard_mapping.keysyms.get(index + i) {
128 if keysym != 0 {
129 keysym_to_keycode
130 .entry(keysym)
131 .or_insert_with(Vec::new)
132 .push(keycode);
133 keycode_to_keysym.entry(keycode).or_insert(keysym);
134 }
135 }
136 }
137 }
138
139 Ok((keysym_to_keycode, keycode_to_keysym))
140 }
141
142 pub fn setup_keybinds(
143 connection: &impl Connection,
144 root: Window,
145 keybindings: &[KeyBinding],
146 ) -> std::result::Result<(), X11Error> {
147 use std::collections::HashSet;
148
149 let (keysym_to_keycode, _) = build_keysym_maps(connection)?;
150 let mut grabbed_keys: HashSet<(u16, Keycode)> = HashSet::new();
151
152 let ignore_modifiers = [
153 0,
154 u16::from(ModMask::LOCK),
155 u16::from(ModMask::M2),
156 u16::from(ModMask::LOCK | ModMask::M2),
157 ];
158
159 for keybinding in keybindings {
160 if keybinding.keys.is_empty() {
161 continue;
162 }
163
164 let first_key = &keybinding.keys[0];
165 let modifier_mask = modifiers_to_mask(&first_key.modifiers);
166
167 if let Some(keycodes) = keysym_to_keycode.get(&first_key.keysym) {
168 if let Some(&keycode) = keycodes.first() {
169 for &ignore_mask in &ignore_modifiers {
170 let grab_mask = modifier_mask | ignore_mask;
171 let key_tuple = (grab_mask, keycode);
172
173 if grabbed_keys.insert(key_tuple) {
174 connection.grab_key(
175 false,
176 root,
177 grab_mask.into(),
178 keycode,
179 GrabMode::ASYNC,
180 GrabMode::ASYNC,
181 )?;
182 }
183 }
184 }
185 }
186 }
187
188 Ok(())
189 }
190
191 pub fn handle_key_press(
192 event: KeyPressEvent,
193 keybindings: &[KeyBinding],
194 keychord_state: &KeychordState,
195 connection: &impl Connection,
196 ) -> std::result::Result<KeychordResult, X11Error> {
197 let (_, keycode_to_keysym) = build_keysym_maps(connection)?;
198 let event_keysym = keycode_to_keysym.get(&event.detail).copied().unwrap_or(0);
199
200 if event_keysym == keysyms::XK_ESCAPE {
201 return Ok(match keychord_state {
202 KeychordState::InProgress { .. } => KeychordResult::Cancelled,
203 KeychordState::Idle => KeychordResult::None,
204 });
205 }
206
207 Ok(match keychord_state {
208 KeychordState::Idle => handle_first_key(event, event_keysym, keybindings),
209 KeychordState::InProgress {
210 candidates,
211 keys_pressed,
212 } => handle_next_key(event, event_keysym, keybindings, candidates, *keys_pressed),
213 })
214 }
215
216 fn handle_first_key(
217 event: KeyPressEvent,
218 event_keysym: Keysym,
219 keybindings: &[KeyBinding],
220 ) -> KeychordResult {
221 let mut candidates = Vec::new();
222
223 let clean_state = event.state & !(u16::from(ModMask::LOCK) | u16::from(ModMask::M2));
224
225 for (keybinding_index, keybinding) in keybindings.iter().enumerate() {
226 if keybinding.keys.is_empty() {
227 continue;
228 }
229
230 let first_key = &keybinding.keys[0];
231 let modifier_mask = modifiers_to_mask(&first_key.modifiers);
232
233 if event_keysym == first_key.keysym && clean_state == modifier_mask.into() {
234 if keybinding.keys.len() == 1 {
235 return KeychordResult::Completed(keybinding.func, keybinding.arg.clone());
236 } else {
237 candidates.push(keybinding_index);
238 }
239 }
240 }
241
242 if candidates.is_empty() {
243 KeychordResult::None
244 } else {
245 KeychordResult::InProgress(candidates)
246 }
247 }
248
249 fn handle_next_key(
250 event: KeyPressEvent,
251 event_keysym: Keysym,
252 keybindings: &[KeyBinding],
253 candidates: &[usize],
254 keys_pressed: usize,
255 ) -> KeychordResult {
256 let mut new_candidates = Vec::new();
257
258 let clean_state = event.state & !(u16::from(ModMask::LOCK) | u16::from(ModMask::M2));
259
260 for &candidate_index in candidates {
261 let keybinding = &keybindings[candidate_index];
262
263 if keys_pressed >= keybinding.keys.len() {
264 continue;
265 }
266
267 let next_key = &keybinding.keys[keys_pressed];
268 let required_mask = modifiers_to_mask(&next_key.modifiers);
269
270 let modifiers_match = if next_key.modifiers.is_empty() {
271 true
272 } else {
273 (clean_state & required_mask) == required_mask.into()
274 };
275
276 if event_keysym == next_key.keysym && modifiers_match {
277 if keys_pressed + 1 == keybinding.keys.len() {
278 return KeychordResult::Completed(keybinding.func, keybinding.arg.clone());
279 } else {
280 new_candidates.push(candidate_index);
281 }
282 }
283 }
284
285 if new_candidates.is_empty() {
286 KeychordResult::Cancelled
287 } else {
288 KeychordResult::InProgress(new_candidates)
289 }
290 }
291
292 pub fn handle_spawn_action(action: KeyAction, arg: &Arg, selected_monitor: usize) -> Result<()> {
293 if let KeyAction::Spawn = action {
294 match arg {
295 Arg::Str(command) => match Command::new(command.as_str()).spawn() {
296 Err(error) if error.kind() == ErrorKind::NotFound => {
297 eprintln!(
298 "KeyAction::Spawn failed: could not spawn \"{}\", command not found",
299 command
300 );
301 }
302 Err(error) => Err(error)?,
303 _ => (),
304 },
305 Arg::Array(command) => {
306 let Some((cmd, args)) = command.split_first() else {
307 return Ok(());
308 };
309
310 let mut args_vec: Vec<String> = args.to_vec();
311
312 let is_dmenu = cmd.contains("dmenu");
313 let has_monitor_flag = args.iter().any(|arg| arg == "-m");
314
315 if is_dmenu && !has_monitor_flag {
316 args_vec.insert(0, selected_monitor.to_string());
317 args_vec.insert(0, "-m".to_string());
318 }
319
320 let args_str: Vec<&str> = args_vec.iter().map(|s| s.as_str()).collect();
321 match Command::new(cmd.as_str()).args(&args_str).spawn() {
322 Err(error) if error.kind() == ErrorKind::NotFound => {
323 eprintln!(
324 "KeyAction::Spawn failed: could not spawn \"{}\", command not found",
325 cmd
326 );
327 }
328 Err(error) => Err(error)?,
329 _ => (),
330 }
331 }
332 _ => {}
333 }
334 }
335
336 Ok(())
337 }