tony / oxwm

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