tony / oxwm

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