tony / oxwm

Branch: c07ef11
Switch branches/tags
master
tonybtw removed unneeded comments c07ef11 2025-10-29
263 lines · 6.6 KB Raw Blame History
1 use std::collections::HashSet;
2 use std::io;
3 use std::io::ErrorKind;
4 use std::process::Command;
5
6 use serde::Deserialize;
7 use x11rb::connection::Connection;
8 use x11rb::protocol::xproto::*;
9
10 use crate::errors::X11Error;
11 use crate::keyboard::keycodes;
12
13 #[derive(Debug, Copy, Clone, Deserialize)]
14 pub enum KeyAction {
15 Spawn,
16 KillClient,
17 FocusStack,
18 Quit,
19 Restart,
20 Recompile,
21 ViewTag,
22 ToggleGaps,
23 ToggleFullScreen,
24 ToggleFloating,
25 ChangeLayout,
26 CycleLayout,
27 MoveToTag,
28 FocusMonitor,
29 SmartMoveWin,
30 ExchangeClient,
31 None,
32 }
33
34 #[derive(Debug, Clone)]
35 pub enum Arg {
36 None,
37 Int(i32),
38 Str(String),
39 Array(Vec<String>),
40 }
41
42 impl Arg {
43 pub const fn none() -> Self {
44 Arg::None
45 }
46 }
47
48 #[derive(Clone, Debug)]
49 pub struct KeyPress {
50 pub(crate) modifiers: Vec<KeyButMask>,
51 pub(crate) key: Keycode,
52 }
53
54 #[derive(Clone)]
55 pub struct KeyBinding {
56 pub(crate) keys: Vec<KeyPress>,
57 pub(crate) func: KeyAction,
58 pub(crate) arg: Arg,
59 }
60
61 impl KeyBinding {
62 pub fn new(keys: Vec<KeyPress>, func: KeyAction, arg: Arg) -> Self {
63 Self { keys, func, arg }
64 }
65
66 pub fn single_key(modifiers: Vec<KeyButMask>, key: Keycode, func: KeyAction, arg: Arg) -> Self {
67 Self {
68 keys: vec![KeyPress { modifiers, key }],
69 func,
70 arg,
71 }
72 }
73 }
74
75 pub type Key = KeyBinding;
76
77 #[derive(Debug, Clone)]
78 pub enum KeychordState {
79 Idle,
80 InProgress {
81 candidates: Vec<usize>,
82 keys_pressed: usize,
83 },
84 }
85
86 pub enum KeychordResult {
87 Completed(KeyAction, Arg),
88 InProgress(Vec<usize>),
89 None,
90 Cancelled,
91 }
92
93 pub fn modifiers_to_mask(modifiers: &[KeyButMask]) -> u16 {
94 modifiers
95 .iter()
96 .fold(0u16, |acc, &modifier| acc | u16::from(modifier))
97 }
98
99 pub fn setup_keybinds(
100 connection: &impl Connection,
101 root: Window,
102 keybindings: &[KeyBinding],
103 ) -> Result<(), X11Error> {
104 let mut grabbed_keys: HashSet<(u16, Keycode)> = HashSet::new();
105
106 for keybinding in keybindings {
107 if keybinding.keys.is_empty() {
108 continue;
109 }
110
111 let first_key = &keybinding.keys[0];
112 let modifier_mask = modifiers_to_mask(&first_key.modifiers);
113 let key_tuple = (modifier_mask, first_key.key);
114
115 if grabbed_keys.insert(key_tuple) {
116 connection.grab_key(
117 false,
118 root,
119 modifier_mask.into(),
120 first_key.key,
121 GrabMode::ASYNC,
122 GrabMode::ASYNC,
123 )?;
124 }
125 }
126
127 connection.grab_key(
128 false,
129 root,
130 ModMask::from(0u16),
131 keycodes::ESCAPE,
132 GrabMode::ASYNC,
133 GrabMode::ASYNC,
134 )?;
135
136 Ok(())
137 }
138
139 pub fn handle_key_press(
140 event: KeyPressEvent,
141 keybindings: &[KeyBinding],
142 keychord_state: &KeychordState,
143 ) -> KeychordResult {
144 if event.detail == keycodes::ESCAPE {
145 return match keychord_state {
146 KeychordState::InProgress { .. } => KeychordResult::Cancelled,
147 KeychordState::Idle => KeychordResult::None,
148 };
149 }
150
151 match keychord_state {
152 KeychordState::Idle => handle_first_key(event, keybindings),
153 KeychordState::InProgress {
154 candidates,
155 keys_pressed,
156 } => handle_next_key(event, keybindings, candidates, *keys_pressed),
157 }
158 }
159
160 fn handle_first_key(event: KeyPressEvent, keybindings: &[KeyBinding]) -> KeychordResult {
161 let mut candidates = Vec::new();
162
163 for (keybinding_index, keybinding) in keybindings.iter().enumerate() {
164 if keybinding.keys.is_empty() {
165 continue;
166 }
167
168 let first_key = &keybinding.keys[0];
169 let modifier_mask = modifiers_to_mask(&first_key.modifiers);
170
171 if event.detail == first_key.key && event.state == modifier_mask.into() {
172 if keybinding.keys.len() == 1 {
173 return KeychordResult::Completed(keybinding.func, keybinding.arg.clone());
174 } else {
175 candidates.push(keybinding_index);
176 }
177 }
178 }
179
180 if candidates.is_empty() {
181 KeychordResult::None
182 } else {
183 KeychordResult::InProgress(candidates)
184 }
185 }
186
187 fn handle_next_key(
188 event: KeyPressEvent,
189 keybindings: &[KeyBinding],
190 candidates: &[usize],
191 keys_pressed: usize,
192 ) -> KeychordResult {
193 let mut new_candidates = Vec::new();
194
195 for &candidate_index in candidates {
196 let keybinding = &keybindings[candidate_index];
197
198 if keys_pressed >= keybinding.keys.len() {
199 continue;
200 }
201
202 let next_key = &keybinding.keys[keys_pressed];
203 let required_mask = modifiers_to_mask(&next_key.modifiers);
204 let event_state: u16 = event.state.into();
205
206 let modifiers_match = if next_key.modifiers.is_empty() {
207 true
208 } else {
209 (event_state & required_mask) == required_mask
210 };
211
212 if event.detail == next_key.key && modifiers_match {
213 if keys_pressed + 1 == keybinding.keys.len() {
214 return KeychordResult::Completed(keybinding.func, keybinding.arg.clone());
215 } else {
216 new_candidates.push(candidate_index);
217 }
218 }
219 }
220
221 if new_candidates.is_empty() {
222 KeychordResult::Cancelled
223 } else {
224 KeychordResult::InProgress(new_candidates)
225 }
226 }
227
228 pub fn handle_spawn_action(action: KeyAction, arg: &Arg) -> io::Result<()> {
229 if let KeyAction::Spawn = action {
230 match arg {
231 Arg::Str(command) => match Command::new(command.as_str()).spawn() {
232 Err(error) if error.kind() == ErrorKind::NotFound => {
233 eprintln!(
234 "KeyAction::Spawn failed: could not spawn \"{}\", command not found",
235 command
236 );
237 }
238 Err(error) => Err(error)?,
239 _ => (),
240 },
241 Arg::Array(command) => {
242 let Some((cmd, args)) = command.split_first() else {
243 return Ok(());
244 };
245
246 let args_str: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
247 match Command::new(cmd.as_str()).args(&args_str).spawn() {
248 Err(error) if error.kind() == ErrorKind::NotFound => {
249 eprintln!(
250 "KeyAction::Spawn failed: could not spawn \"{}\", command not found",
251 cmd
252 );
253 }
254 Err(error) => Err(error)?,
255 _ => (),
256 }
257 }
258 _ => {}
259 }
260 }
261
262 Ok(())
263 }