tony / oxwm

Merge pull request #29 from tonybanters/keychord-implementation Browse files
Keychord implementation
Emzy committed 2025-10-31 parents 334f1e8 7a4cc10 commit d9e78cebb3598668e28e4196dfa51df41ddbaf82
Showing 8 changed files with 497 additions and 82 deletions. UnifiedSplit
+19 −1 src/bar/bar.rs
@@ -172,6 +172,7 @@ impl Bar {
172 172 occupied_tags: u32,
173 173 draw_blocks: bool,
174 174 layout_symbol: &str,
175 + keychord_indicator: Option<&str>,
175 176 ) -> Result<(), X11Error> {
176 177 if !self.needs_redraw {
177 178 return Ok(());
@@ -258,9 +259,26 @@ impl Bar {
258 259 self.scheme_normal.foreground,
259 260 text_x,
260 261 text_y,
261 - layout_symbol
262 + layout_symbol,
262 263 );
263 264
265 + x_position += font.text_width(layout_symbol) as i16;
266 +
267 + if let Some(indicator) = keychord_indicator {
268 + x_position += 10;
269 +
270 + let text_x = x_position;
271 + let text_y = top_padding + font.ascent();
272 +
273 + self.font_draw.draw_text(
274 + font,
275 + self.scheme_selected.foreground,
276 + text_x,
277 + text_y,
278 + indicator,
279 + );
280 + }
281 +
264 282 if draw_blocks && !self.status_text.is_empty() {
265 283 let padding = 10;
266 284 let mut x_position = self.width as i16 - padding;
+136 −10 src/config/mod.rs
@@ -1,6 +1,6 @@
1 1 use crate::bar::{BlockCommand, BlockConfig};
2 2 use crate::errors::ConfigError;
3 -use crate::keyboard::handlers::Key;
3 +use crate::keyboard::handlers::{KeyBinding, KeyPress};
4 4 use crate::keyboard::keycodes;
5 5 use crate::keyboard::{Arg, KeyAction};
6 6 use serde::Deserialize;
@@ -9,6 +9,7 @@ use x11rb::protocol::xproto::{KeyButMask, Keycode};
9 9
10 10 #[derive(Debug, Deserialize)]
11 11 pub enum ModKey {
12 + Mod,
12 13 Mod1,
13 14 Mod2,
14 15 Mod3,
@@ -21,6 +22,7 @@ pub enum ModKey {
21 22 impl ModKey {
22 23 fn to_keybut_mask(&self) -> KeyButMask {
23 24 match self {
25 + ModKey::Mod => panic!("ModKey::Mod should be replaced during config parsing"),
24 26 ModKey::Mod1 => KeyButMask::MOD1,
25 27 ModKey::Mod2 => KeyButMask::MOD2,
26 28 ModKey::Mod3 => KeyButMask::MOD3,
@@ -155,6 +157,91 @@ impl KeyData {
155 157 KeyData::Slash => keycodes::SLASH,
156 158 }
157 159 }
160 +
161 + // Adding this reverse lookup for now so converting to KeySyms is no longer
162 + // an 'unsafe' call to a C FFI (Sorry Bugsy...)
163 + // This will set us up in the future to move away from hardcoded keycodes,
164 + // and directly convert keysyms to keydata at runtime for international
165 + // keyboard support.
166 + pub fn from_keycode(keycode: Keycode) -> Option<&'static str> {
167 + match keycode {
168 + keycodes::RETURN => Some("Return"),
169 + keycodes::Q => Some("q"),
170 + keycodes::ESCAPE => Some("Esc"),
171 + keycodes::SPACE => Some("Space"),
172 + keycodes::TAB => Some("Tab"),
173 + keycodes::BACKSPACE => Some("Backspace"),
174 + keycodes::DELETE => Some("Del"),
175 + keycodes::F1 => Some("F1"),
176 + keycodes::F2 => Some("F2"),
177 + keycodes::F3 => Some("F3"),
178 + keycodes::F4 => Some("F4"),
179 + keycodes::F5 => Some("F5"),
180 + keycodes::F6 => Some("F6"),
181 + keycodes::F7 => Some("F7"),
182 + keycodes::F8 => Some("F8"),
183 + keycodes::F9 => Some("F9"),
184 + keycodes::F10 => Some("F10"),
185 + keycodes::F11 => Some("F11"),
186 + keycodes::F12 => Some("F12"),
187 + keycodes::A => Some("a"),
188 + keycodes::B => Some("b"),
189 + keycodes::C => Some("c"),
190 + keycodes::D => Some("d"),
191 + keycodes::E => Some("e"),
192 + keycodes::F => Some("f"),
193 + keycodes::G => Some("g"),
194 + keycodes::H => Some("h"),
195 + keycodes::I => Some("i"),
196 + keycodes::J => Some("j"),
197 + keycodes::K => Some("k"),
198 + keycodes::L => Some("l"),
199 + keycodes::M => Some("m"),
200 + keycodes::N => Some("n"),
201 + keycodes::O => Some("o"),
202 + keycodes::P => Some("p"),
203 + keycodes::R => Some("r"),
204 + keycodes::S => Some("s"),
205 + keycodes::T => Some("t"),
206 + keycodes::U => Some("u"),
207 + keycodes::V => Some("v"),
208 + keycodes::W => Some("w"),
209 + keycodes::X => Some("x"),
210 + keycodes::Y => Some("y"),
211 + keycodes::Z => Some("z"),
212 + keycodes::KEY_0 => Some("0"),
213 + keycodes::KEY_1 => Some("1"),
214 + keycodes::KEY_2 => Some("2"),
215 + keycodes::KEY_3 => Some("3"),
216 + keycodes::KEY_4 => Some("4"),
217 + keycodes::KEY_5 => Some("5"),
218 + keycodes::KEY_6 => Some("6"),
219 + keycodes::KEY_7 => Some("7"),
220 + keycodes::KEY_8 => Some("8"),
221 + keycodes::KEY_9 => Some("9"),
222 + keycodes::LEFT => Some("Left"),
223 + keycodes::RIGHT => Some("Right"),
224 + keycodes::UP => Some("Up"),
225 + keycodes::DOWN => Some("Down"),
226 + keycodes::HOME => Some("Home"),
227 + keycodes::END => Some("End"),
228 + keycodes::PAGE_UP => Some("PgUp"),
229 + keycodes::PAGE_DOWN => Some("PgDn"),
230 + keycodes::INSERT => Some("Ins"),
231 + keycodes::MINUS => Some("-"),
232 + keycodes::EQUAL => Some("="),
233 + keycodes::LEFT_BRACKET => Some("["),
234 + keycodes::RIGHT_BRACKET => Some("]"),
235 + keycodes::SEMICOLON => Some(";"),
236 + keycodes::APOSTROPHE => Some("'"),
237 + keycodes::GRAVE => Some("`"),
238 + keycodes::BACKSLASH => Some("\\"),
239 + keycodes::COMMA => Some(","),
240 + keycodes::PERIOD => Some("."),
241 + keycodes::SLASH => Some("/"),
242 + _ => None,
243 + }
244 + }
158 245 }
159 246
160 247 fn preprocess_variables(input: &str) -> Result<String, ConfigError> {
@@ -246,13 +333,23 @@ struct ConfigData {
246 333
247 334 #[derive(Debug, Deserialize)]
248 335 struct KeybindingData {
249 - modifiers: Vec<ModKey>,
250 - key: KeyData,
336 + #[serde(default)]
337 + keys: Option<Vec<KeyPressData>>,
338 + #[serde(default)]
339 + modifiers: Option<Vec<ModKey>>,
340 + #[serde(default)]
341 + key: Option<KeyData>,
251 342 action: KeyAction,
252 343 #[serde(default)]
253 344 arg: ArgData,
254 345 }
255 346
347 +#[derive(Debug, Deserialize)]
348 +struct KeyPressData {
349 + modifiers: Vec<ModKey>,
350 + key: KeyData,
351 +}
352 +
256 353 #[derive(Debug, Deserialize)]
257 354 #[serde(untagged)]
258 355 enum ArgData {
@@ -300,17 +397,46 @@ fn config_data_to_config(data: ConfigData) -> Result<crate::Config, ConfigError>
300 397
301 398 let mut keybindings = Vec::new();
302 399 for kb_data in data.keybindings {
303 - let modifiers = kb_data
304 - .modifiers
305 - .iter()
306 - .map(|m| m.to_keybut_mask())
307 - .collect();
400 + let keys = if let Some(keys_data) = kb_data.keys {
401 + keys_data
402 + .into_iter()
403 + .map(|kp| {
404 + let modifiers = kp
405 + .modifiers
406 + .iter()
407 + .map(|m| match m {
408 + ModKey::Mod => modkey,
409 + _ => m.to_keybut_mask(),
410 + })
411 + .collect();
412 +
413 + KeyPress {
414 + modifiers,
415 + key: kp.key.to_keycode(),
416 + }
417 + })
418 + .collect()
419 + } else if let (Some(modifiers), Some(key)) = (kb_data.modifiers, kb_data.key) {
420 + vec![KeyPress {
421 + modifiers: modifiers
422 + .iter()
423 + .map(|m| match m {
424 + ModKey::Mod => modkey,
425 + _ => m.to_keybut_mask(),
426 + })
427 + .collect(),
428 + key: key.to_keycode(),
429 + }]
430 + } else {
431 + return Err(ConfigError::ValidationError(
432 + "Keybinding must have either 'keys' or 'modifiers'+'key'".to_string(),
433 + ));
434 + };
308 435
309 - let key = kb_data.key.to_keycode();
310 436 let action = kb_data.action;
311 437 let arg = arg_data_to_arg(kb_data.arg)?;
312 438
313 - keybindings.push(Key::new(modifiers, key, action, arg));
439 + keybindings.push(KeyBinding::new(keys, action, arg));
314 440 }
315 441
316 442 let mut status_blocks = Vec::new();
+12 −2 src/errors.rs
@@ -25,6 +25,7 @@ pub enum ConfigError {
25 25 UnknownAction(String),
26 26 UnknownBlockCommand(String),
27 27 MissingCommandArg { command: String, field: String },
28 + ValidationError(String),
28 29 InvalidVariableName(String),
29 30 InvalidDefine(String),
30 31 UndefinedVariable(String),
@@ -70,14 +71,23 @@ impl std::fmt::Display for ConfigError {
70 71 Self::MissingCommandArg { command, field } => {
71 72 write!(f, "{} command requires {}", command, field)
72 73 }
74 + Self::ValidationError(msg) => write!(f, "Config validation error: {}", msg),
73 75 Self::InvalidVariableName(name) => {
74 76 write!(f, "Invalid variable name '{}': must start with $", name)
75 77 }
76 78 Self::InvalidDefine(line) => {
77 - write!(f, "Invalid #DEFINE syntax: '{}'. Expected: #DEFINE $var_name = value", line)
79 + write!(
80 + f,
81 + "Invalid #DEFINE syntax: '{}'. Expected: #DEFINE $var_name = value",
82 + line
83 + )
78 84 }
79 85 Self::UndefinedVariable(var) => {
80 - write!(f, "Undefined variable '{}': define it with #DEFINE before use", var)
86 + write!(
87 + f,
88 + "Undefined variable '{}': define it with #DEFINE before use",
89 + var
90 + )
81 91 }
82 92 }
83 93 }
+154 −29 src/keyboard/handlers.rs
@@ -1,4 +1,6 @@
1 +use std::collections::HashSet;
1 2 use std::io;
3 +use std::io::ErrorKind;
2 4 use std::process::Command;
3 5
4 6 use serde::Deserialize;
@@ -6,6 +8,7 @@ use x11rb::connection::Connection;
6 8 use x11rb::protocol::xproto::*;
7 9
8 10 use crate::errors::X11Error;
11 +use crate::keyboard::keycodes;
9 12
10 13 #[derive(Debug, Copy, Clone, Deserialize)]
11 14 pub enum KeyAction {
@@ -42,26 +45,52 @@ impl Arg {
42 45 }
43 46 }
44 47
45 -#[derive(Clone)]
46 -pub struct Key {
48 +#[derive(Clone, Debug)]
49 +pub struct KeyPress {
47 50 pub(crate) modifiers: Vec<KeyButMask>,
48 51 pub(crate) key: Keycode,
52 +}
53 +
54 +#[derive(Clone)]
55 +pub struct KeyBinding {
56 + pub(crate) keys: Vec<KeyPress>,
49 57 pub(crate) func: KeyAction,
50 58 pub(crate) arg: Arg,
51 59 }
52 60
53 -impl Key {
54 - pub fn new(modifiers: Vec<KeyButMask>, key: Keycode, func: KeyAction, arg: Arg) -> Self {
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 {
55 67 Self {
56 - modifiers,
57 - key,
68 + keys: vec![KeyPress { modifiers, key }],
58 69 func,
59 70 arg,
60 71 }
61 72 }
62 73 }
63 74
64 -fn modifiers_to_mask(modifiers: &[KeyButMask]) -> u16 {
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 {
65 94 modifiers
66 95 .iter()
67 96 .fold(0u16, |acc, &modifier| acc | u16::from(modifier))
@@ -70,47 +99,143 @@ fn modifiers_to_mask(modifiers: &[KeyButMask]) -> u16 {
70 99 pub fn setup_keybinds(
71 100 connection: &impl Connection,
72 101 root: Window,
73 - keybindings: &[Key],
102 + keybindings: &[KeyBinding],
74 103 ) -> Result<(), X11Error> {
104 + let mut grabbed_keys: HashSet<(u16, Keycode)> = HashSet::new();
105 +
75 106 for keybinding in keybindings {
76 - let modifier_mask = modifiers_to_mask(&keybinding.modifiers);
77 -
78 - connection.grab_key(
79 - false,
80 - root,
81 - modifier_mask.into(),
82 - keybinding.key,
83 - GrabMode::ASYNC,
84 - GrabMode::ASYNC,
85 - )?;
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 + }
86 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 +
87 136 Ok(())
88 137 }
89 138
90 -pub fn handle_key_press(event: KeyPressEvent, keybindings: &[Key]) -> (KeyAction, Arg) {
91 - for keybinding in keybindings {
92 - let modifier_mask = modifiers_to_mask(&keybinding.modifiers);
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 + }
93 150
94 - if event.detail == keybinding.key && event.state == modifier_mask.into() {
95 - return (keybinding.func, keybinding.arg.clone());
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 + }
96 218 }
97 219 }
98 220
99 - (KeyAction::None, Arg::None)
221 + if new_candidates.is_empty() {
222 + KeychordResult::Cancelled
223 + } else {
224 + KeychordResult::InProgress(new_candidates)
225 + }
100 226 }
101 227
102 228 pub fn handle_spawn_action(action: KeyAction, arg: &Arg) -> io::Result<()> {
103 - use io::ErrorKind;
104 229 if let KeyAction::Spawn = action {
105 230 match arg {
106 231 Arg::Str(command) => match Command::new(command.as_str()).spawn() {
107 - Err(err) if err.kind() == ErrorKind::NotFound => {
232 + Err(error) if error.kind() == ErrorKind::NotFound => {
108 233 eprintln!(
109 234 "KeyAction::Spawn failed: could not spawn \"{}\", command not found",
110 235 command
111 236 );
112 237 }
113 - Err(err) => Err(err)?,
238 + Err(error) => Err(error)?,
114 239 _ => (),
115 240 },
116 241 Arg::Array(command) => {
@@ -120,13 +245,13 @@ pub fn handle_spawn_action(action: KeyAction, arg: &Arg) -> io::Result<()> {
120 245
121 246 let args_str: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
122 247 match Command::new(cmd.as_str()).args(&args_str).spawn() {
123 - Err(err) if err.kind() == ErrorKind::NotFound => {
248 + Err(error) if error.kind() == ErrorKind::NotFound => {
124 249 eprintln!(
125 250 "KeyAction::Spawn failed: could not spawn \"{}\", command not found",
126 251 cmd
127 252 );
128 253 }
129 - Err(err) => Err(err)?,
254 + Err(error) => Err(error)?,
130 255 _ => (),
131 256 }
132 257 }
+35 −35 src/lib.rs
@@ -10,7 +10,7 @@ pub mod prelude {
10 10 pub use crate::ColorScheme;
11 11 pub use crate::LayoutSymbolOverride;
12 12 pub use crate::bar::{BlockCommand, BlockConfig};
13 - pub use crate::keyboard::{Arg, KeyAction, handlers::Key, keycodes};
13 + pub use crate::keyboard::{Arg, KeyAction, handlers::KeyBinding, keycodes};
14 14 pub use x11rb::protocol::xproto::KeyButMask;
15 15 }
16 16
@@ -66,7 +66,7 @@ pub struct ColorScheme {
66 66
67 67 impl Default for Config {
68 68 fn default() -> Self {
69 - use crate::keyboard::handlers::Key;
69 + use crate::keyboard::handlers::KeyBinding;
70 70 use crate::keyboard::{Arg, KeyAction, keycodes};
71 71 use x11rb::protocol::xproto::KeyButMask;
72 72
@@ -93,13 +93,13 @@ impl Default for Config {
93 93 .collect(),
94 94 layout_symbols: vec![],
95 95 keybindings: vec![
96 - Key::new(
96 + KeyBinding::single_key(
97 97 vec![MODKEY],
98 98 keycodes::RETURN,
99 99 KeyAction::Spawn,
100 100 Arg::Str(TERMINAL.to_string()),
101 101 ),
102 - Key::new(
102 + KeyBinding::single_key(
103 103 vec![MODKEY],
104 104 keycodes::D,
105 105 KeyAction::Spawn,
@@ -109,167 +109,167 @@ impl Default for Config {
109 109 "dmenu_run -l 10".to_string(),
110 110 ]),
111 111 ),
112 - Key::new(vec![MODKEY], keycodes::Q, KeyAction::KillClient, Arg::None),
113 - Key::new(vec![MODKEY], keycodes::N, KeyAction::CycleLayout, Arg::None),
114 - Key::new(
112 + KeyBinding::single_key(vec![MODKEY], keycodes::Q, KeyAction::KillClient, Arg::None),
113 + KeyBinding::single_key(vec![MODKEY], keycodes::N, KeyAction::CycleLayout, Arg::None),
114 + KeyBinding::single_key(
115 115 vec![MODKEY, SHIFT],
116 116 keycodes::F,
117 117 KeyAction::ToggleFullScreen,
118 118 Arg::None,
119 119 ),
120 - Key::new(vec![MODKEY], keycodes::A, KeyAction::ToggleGaps, Arg::None),
121 - Key::new(vec![MODKEY, SHIFT], keycodes::Q, KeyAction::Quit, Arg::None),
122 - Key::new(
120 + KeyBinding::single_key(vec![MODKEY], keycodes::A, KeyAction::ToggleGaps, Arg::None),
121 + KeyBinding::single_key(vec![MODKEY, SHIFT], keycodes::Q, KeyAction::Quit, Arg::None),
122 + KeyBinding::single_key(
123 123 vec![MODKEY, SHIFT],
124 124 keycodes::R,
125 125 KeyAction::Restart,
126 126 Arg::None,
127 127 ),
128 - Key::new(
128 + KeyBinding::single_key(
129 129 vec![MODKEY],
130 130 keycodes::F,
131 131 KeyAction::ToggleFloating,
132 132 Arg::None,
133 133 ),
134 - Key::new(
134 + KeyBinding::single_key(
135 135 vec![MODKEY],
136 136 keycodes::J,
137 137 KeyAction::FocusStack,
138 138 Arg::Int(-1),
139 139 ),
140 - Key::new(
140 + KeyBinding::single_key(
141 141 vec![MODKEY],
142 142 keycodes::K,
143 143 KeyAction::FocusStack,
144 144 Arg::Int(1),
145 145 ),
146 - Key::new(
146 + KeyBinding::single_key(
147 147 vec![MODKEY, SHIFT],
148 148 keycodes::K,
149 149 KeyAction::ExchangeClient,
150 150 Arg::Int(0), // UP
151 151 ),
152 - Key::new(
152 + KeyBinding::single_key(
153 153 vec![MODKEY, SHIFT],
154 154 keycodes::J,
155 155 KeyAction::ExchangeClient,
156 156 Arg::Int(1), // DOWN
157 157 ),
158 - Key::new(
158 + KeyBinding::single_key(
159 159 vec![MODKEY, SHIFT],
160 160 keycodes::H,
161 161 KeyAction::ExchangeClient,
162 162 Arg::Int(2), // LEFT
163 163 ),
164 - Key::new(
164 + KeyBinding::single_key(
165 165 vec![MODKEY, SHIFT],
166 166 keycodes::L,
167 167 KeyAction::ExchangeClient,
168 168 Arg::Int(3), // RIGHT
169 169 ),
170 - Key::new(
170 + KeyBinding::single_key(
171 171 vec![MODKEY],
172 172 keycodes::KEY_1,
173 173 KeyAction::ViewTag,
174 174 Arg::Int(0),
175 175 ),
176 - Key::new(
176 + KeyBinding::single_key(
177 177 vec![MODKEY],
178 178 keycodes::KEY_2,
179 179 KeyAction::ViewTag,
180 180 Arg::Int(1),
181 181 ),
182 - Key::new(
182 + KeyBinding::single_key(
183 183 vec![MODKEY],
184 184 keycodes::KEY_3,
185 185 KeyAction::ViewTag,
186 186 Arg::Int(2),
187 187 ),
188 - Key::new(
188 + KeyBinding::single_key(
189 189 vec![MODKEY],
190 190 keycodes::KEY_4,
191 191 KeyAction::ViewTag,
192 192 Arg::Int(3),
193 193 ),
194 - Key::new(
194 + KeyBinding::single_key(
195 195 vec![MODKEY],
196 196 keycodes::KEY_5,
197 197 KeyAction::ViewTag,
198 198 Arg::Int(4),
199 199 ),
200 - Key::new(
200 + KeyBinding::single_key(
201 201 vec![MODKEY],
202 202 keycodes::KEY_6,
203 203 KeyAction::ViewTag,
204 204 Arg::Int(5),
205 205 ),
206 - Key::new(
206 + KeyBinding::single_key(
207 207 vec![MODKEY],
208 208 keycodes::KEY_7,
209 209 KeyAction::ViewTag,
210 210 Arg::Int(6),
211 211 ),
212 - Key::new(
212 + KeyBinding::single_key(
213 213 vec![MODKEY],
214 214 keycodes::KEY_8,
215 215 KeyAction::ViewTag,
216 216 Arg::Int(7),
217 217 ),
218 - Key::new(
218 + KeyBinding::single_key(
219 219 vec![MODKEY],
220 220 keycodes::KEY_9,
221 221 KeyAction::ViewTag,
222 222 Arg::Int(8),
223 223 ),
224 - Key::new(
224 + KeyBinding::single_key(
225 225 vec![MODKEY, SHIFT],
226 226 keycodes::KEY_1,
227 227 KeyAction::MoveToTag,
228 228 Arg::Int(0),
229 229 ),
230 - Key::new(
230 + KeyBinding::single_key(
231 231 vec![MODKEY, SHIFT],
232 232 keycodes::KEY_2,
233 233 KeyAction::MoveToTag,
234 234 Arg::Int(1),
235 235 ),
236 - Key::new(
236 + KeyBinding::single_key(
237 237 vec![MODKEY, SHIFT],
238 238 keycodes::KEY_3,
239 239 KeyAction::MoveToTag,
240 240 Arg::Int(2),
241 241 ),
242 - Key::new(
242 + KeyBinding::single_key(
243 243 vec![MODKEY, SHIFT],
244 244 keycodes::KEY_4,
245 245 KeyAction::MoveToTag,
246 246 Arg::Int(3),
247 247 ),
248 - Key::new(
248 + KeyBinding::single_key(
249 249 vec![MODKEY, SHIFT],
250 250 keycodes::KEY_5,
251 251 KeyAction::MoveToTag,
252 252 Arg::Int(4),
253 253 ),
254 - Key::new(
254 + KeyBinding::single_key(
255 255 vec![MODKEY, SHIFT],
256 256 keycodes::KEY_6,
257 257 KeyAction::MoveToTag,
258 258 Arg::Int(5),
259 259 ),
260 - Key::new(
260 + KeyBinding::single_key(
261 261 vec![MODKEY, SHIFT],
262 262 keycodes::KEY_7,
263 263 KeyAction::MoveToTag,
264 264 Arg::Int(6),
265 265 ),
266 - Key::new(
266 + KeyBinding::single_key(
267 267 vec![MODKEY, SHIFT],
268 268 keycodes::KEY_8,
269 269 KeyAction::MoveToTag,
270 270 Arg::Int(7),
271 271 ),
272 - Key::new(
272 + KeyBinding::single_key(
273 273 vec![MODKEY, SHIFT],
274 274 keycodes::KEY_9,
275 275 KeyAction::MoveToTag,
+120 −5 src/window_manager.rs
@@ -68,6 +68,7 @@ pub struct WindowManager {
68 68 previous_focused: Option<Window>,
69 69 display: *mut x11::xlib::Display,
70 70 font: crate::bar::font::Font,
71 + keychord_state: keyboard::handlers::KeychordState,
71 72 }
72 73
73 74 type WmResult<T> = Result<T, WmError>;
@@ -176,6 +177,7 @@ impl WindowManager {
176 177 previous_focused: None,
177 178 display,
178 179 font,
180 + keychord_state: keyboard::handlers::KeychordState::Idle,
179 181 };
180 182
181 183 window_manager.scan_existing_windows()?;
@@ -799,8 +801,55 @@ impl WindowManager {
799 801 .unwrap_or_else(|| self.layout.symbol().to_string())
800 802 }
801 803
804 + fn get_keychord_indicator(&self) -> Option<String> {
805 + match &self.keychord_state {
806 + keyboard::handlers::KeychordState::Idle => None,
807 + keyboard::handlers::KeychordState::InProgress { candidates, keys_pressed } => {
808 + if candidates.is_empty() {
809 + return None;
810 + }
811 +
812 + let binding = &self.config.keybindings[candidates[0]];
813 + let mut indicator = String::new();
814 +
815 + for (i, key_press) in binding.keys.iter().take(*keys_pressed).enumerate() {
816 + if i > 0 {
817 + indicator.push(' ');
818 + }
819 +
820 + for modifier in &key_press.modifiers {
821 + indicator.push_str(Self::format_modifier(*modifier));
822 + indicator.push('+');
823 + }
824 +
825 + indicator.push_str(&self.format_keycode(key_press.key));
826 + }
827 +
828 + indicator.push('-');
829 + Some(indicator)
830 + }
831 + }
832 + }
833 +
834 + fn format_modifier(modifier: KeyButMask) -> &'static str {
835 + match modifier {
836 + KeyButMask::MOD1 => "Alt",
837 + KeyButMask::MOD4 => "Super",
838 + KeyButMask::SHIFT => "Shift",
839 + KeyButMask::CONTROL => "Ctrl",
840 + _ => "Mod",
841 + }
842 + }
843 +
844 + fn format_keycode(&self, keycode: Keycode) -> String {
845 + crate::config::KeyData::from_keycode(keycode)
846 + .unwrap_or("?")
847 + .to_string()
848 + }
849 +
802 850 fn update_bar(&mut self) -> WmResult<()> {
803 851 let layout_symbol = self.get_layout_symbol();
852 + let keychord_indicator = self.get_keychord_indicator();
804 853
805 854 for (monitor_index, monitor) in self.monitors.iter().enumerate() {
806 855 if let Some(bar) = self.bars.get_mut(monitor_index) {
@@ -821,6 +870,7 @@ impl WindowManager {
821 870 occupied_tags,
822 871 draw_blocks,
823 872 &layout_symbol,
873 + keychord_indicator.as_deref(),
824 874 )?;
825 875 }
826 876 }
@@ -1124,6 +1174,39 @@ impl WindowManager {
1124 1174 Ok(())
1125 1175 }
1126 1176
1177 + fn grab_next_keys(&self, candidates: &[usize], keys_pressed: usize) -> WmResult<()> {
1178 + let mut grabbed_keys: HashSet<(u16, Keycode)> = HashSet::new();
1179 +
1180 + for &candidate_index in candidates {
1181 + let binding = &self.config.keybindings[candidate_index];
1182 + if keys_pressed < binding.keys.len() {
1183 + let next_key = &binding.keys[keys_pressed];
1184 + let modifier_mask = keyboard::handlers::modifiers_to_mask(&next_key.modifiers);
1185 + let key_tuple = (modifier_mask, next_key.key);
1186 +
1187 + if grabbed_keys.insert(key_tuple) {
1188 + self.connection.grab_key(
1189 + false,
1190 + self.root,
1191 + modifier_mask.into(),
1192 + next_key.key,
1193 + GrabMode::ASYNC,
1194 + GrabMode::ASYNC,
1195 + )?;
1196 + }
1197 + }
1198 + }
1199 + self.connection.flush()?;
1200 + Ok(())
1201 + }
1202 +
1203 + fn ungrab_chord_keys(&self) -> WmResult<()> {
1204 + self.connection.ungrab_key(x11rb::protocol::xproto::Grab::ANY, self.root, ModMask::ANY)?;
1205 + keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
1206 + self.connection.flush()?;
1207 + Ok(())
1208 + }
1209 +
1127 1210 pub fn set_focus(&mut self, window: Window) -> WmResult<()> {
1128 1211 let old_focused = self.previous_focused;
1129 1212
@@ -1372,11 +1455,43 @@ impl WindowManager {
1372 1455 }
1373 1456 }
1374 1457 Event::KeyPress(event) => {
1375 - let (action, arg) = keyboard::handle_key_press(event, &self.config.keybindings);
1376 - match action {
1377 - KeyAction::Quit => return Ok(Some(false)),
1378 - KeyAction::Restart => return Ok(Some(true)),
1379 - _ => self.handle_key_action(action, &arg)?,
1458 + let result = keyboard::handle_key_press(
1459 + event,
1460 + &self.config.keybindings,
1461 + &self.keychord_state,
1462 + );
1463 +
1464 + match result {
1465 + keyboard::handlers::KeychordResult::Completed(action, arg) => {
1466 + self.keychord_state = keyboard::handlers::KeychordState::Idle;
1467 + self.ungrab_chord_keys()?;
1468 + self.update_bar()?;
1469 +
1470 + match action {
1471 + KeyAction::Quit => return Ok(Some(false)),
1472 + KeyAction::Restart => return Ok(Some(true)),
1473 + _ => self.handle_key_action(action, &arg)?,
1474 + }
1475 + }
1476 + keyboard::handlers::KeychordResult::InProgress(candidates) => {
1477 + let keys_pressed = match &self.keychord_state {
1478 + keyboard::handlers::KeychordState::Idle => 1,
1479 + keyboard::handlers::KeychordState::InProgress { keys_pressed, .. } => keys_pressed + 1,
1480 + };
1481 +
1482 + self.keychord_state = keyboard::handlers::KeychordState::InProgress {
1483 + candidates: candidates.clone(),
1484 + keys_pressed,
1485 + };
1486 +
1487 + self.grab_next_keys(&candidates, keys_pressed)?;
1488 + self.update_bar()?;
1489 + }
1490 + keyboard::handlers::KeychordResult::Cancelled | keyboard::handlers::KeychordResult::None => {
1491 + self.keychord_state = keyboard::handlers::KeychordState::Idle;
1492 + self.ungrab_chord_keys()?;
1493 + self.update_bar()?;
1494 + }
1380 1495 }
1381 1496 }
1382 1497 Event::ButtonPress(event) => {
+20 −0 templates/config.ron
@@ -38,7 +38,22 @@
38 38 (name: "normie", symbol: "[F]"),
39 39 ],
40 40
41 + // Keybinding Format:
42 + //
43 + // New format (supports keychords - multi-key sequences):
44 + // (keys: [(modifiers: [...], key: X), (modifiers: [...], key: Y)], action: ..., arg: ...)
45 + //
46 + // Old format (single key, backwards compatible):
47 + // (modifiers: [...], key: X, action: ..., arg: ...)
48 + //
49 + // Examples:
50 + // Single key: (keys: [(modifiers: [Mod4], key: Return)], action: Spawn, arg: "st")
51 + // Keychord: (keys: [(modifiers: [Mod4], key: Space), (modifiers: [], key: F)], action: Spawn, arg: "firefox")
52 + //
53 + // You can cancel any in-progress keychord by pressing Escape.
54 +
41 55 keybindings: [
56 + // Basic keybindings (old format for backwards compatibility)
42 57 (modifiers: [$modkey], key: Return, action: Spawn, arg: $terminal),
43 58 (modifiers: [$modkey], key: D, action: Spawn, arg: ["sh", "-c", "dmenu_run -l 10"]),
44 59 (modifiers: [$modkey], key: S, action: Spawn, arg: ["sh", "-c", "maim -s | xclip -selection clipboard -t image/png"]),
@@ -85,6 +100,11 @@
85 100 (modifiers: [$modkey, Shift], key: J, action: ExchangeClient, arg: 1), // DOWN
86 101 (modifiers: [$modkey, Shift], key: H, action: ExchangeClient, arg: 2), // LEFT
87 102 (modifiers: [$modkey, Shift], key: L, action: ExchangeClient, arg: 3), // RIGHT
103 +
104 + // Example keychord bindings (uncomment to use):
105 + // KEYCHORDS
106 + // Press Mod4+Space, then t to spawn terminal
107 + (keys: [(modifiers: [Mod4], key: Space), (modifiers: [], key: T)], action: Spawn, arg: $terminal),
88 108 ],
89 109
90 110 status_blocks: [
+1 −0 test-config.ron
@@ -42,6 +42,7 @@
42 42 ],
43 43
44 44 keybindings: [
45 + (keys: [(modifiers: [Mod1], key: Space), (modifiers: [], key: T)], action: Spawn, arg: "st"),
45 46 (modifiers: [Mod1], key: Return, action: Spawn, arg: $terminal),
46 47 (modifiers: [Mod1], key: D, action: Spawn, arg: ["sh", "-c", "dmenu_run -l 10"]),
47 48 (modifiers: [Mod1], key: S, action: Spawn, arg: ["sh", "-c", "maim -s | xclip -selection clipboard -t image/png"]),