tony / oxwm

keychords Browse files
tonybtw committed 2025-10-28 parent c46b018 commit 2809716423b958b733761c1af4e4b681c077729a
Showing 8 changed files with 447 additions and 79 deletions. UnifiedSplit
+20 −0 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(());
@@ -261,6 +262,25 @@ impl Bar {
261 262 layout_symbol
262 263 );
263 264
265 + // Update x_position after layout symbol
266 + x_position += font.text_width(layout_symbol) as i16;
267 +
268 + // Draw keychord indicator if present
269 + if let Some(indicator) = keychord_indicator {
270 + x_position += 10;
271 +
272 + let text_x = x_position;
273 + let text_y = top_padding + font.ascent();
274 +
275 + self.font_draw.draw_text(
276 + font,
277 + self.scheme_selected.foreground,
278 + text_x,
279 + text_y,
280 + indicator,
281 + );
282 + }
283 +
264 284 if draw_blocks && !self.status_text.is_empty() {
265 285 let padding = 10;
266 286 let mut x_position = self.width as i16 - padding;
+51 −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;
@@ -8,6 +8,7 @@ use x11rb::protocol::xproto::{KeyButMask, Keycode};
8 8
9 9 #[derive(Debug, Deserialize)]
10 10 pub enum ModKey {
11 + Mod,
11 12 Mod1,
12 13 Mod2,
13 14 Mod3,
@@ -20,6 +21,7 @@ pub enum ModKey {
20 21 impl ModKey {
21 22 fn to_keybut_mask(&self) -> KeyButMask {
22 23 match self {
24 + ModKey::Mod => panic!("ModKey::Mod should be replaced during config parsing"),
23 25 ModKey::Mod1 => KeyButMask::MOD1,
24 26 ModKey::Mod2 => KeyButMask::MOD2,
25 27 ModKey::Mod3 => KeyButMask::MOD3,
@@ -196,13 +198,23 @@ struct ConfigData {
196 198
197 199 #[derive(Debug, Deserialize)]
198 200 struct KeybindingData {
199 - modifiers: Vec<ModKey>,
200 - key: KeyData,
201 + #[serde(default)]
202 + keys: Option<Vec<KeyPressData>>, // New format
203 + #[serde(default)]
204 + modifiers: Option<Vec<ModKey>>, // Old format (backwards compat)
205 + #[serde(default)]
206 + key: Option<KeyData>, // Old format (backwards compat)
201 207 action: KeyAction,
202 208 #[serde(default)]
203 209 arg: ArgData,
204 210 }
205 211
212 +#[derive(Debug, Deserialize)]
213 +struct KeyPressData {
214 + modifiers: Vec<ModKey>,
215 + key: KeyData,
216 +}
217 +
206 218 #[derive(Debug, Deserialize)]
207 219 #[serde(untagged)]
208 220 enum ArgData {
@@ -250,17 +262,46 @@ fn config_data_to_config(data: ConfigData) -> Result<crate::Config, ConfigError>
250 262
251 263 let mut keybindings = Vec::new();
252 264 for kb_data in data.keybindings {
253 - let modifiers = kb_data
254 - .modifiers
255 - .iter()
256 - .map(|m| m.to_keybut_mask())
257 - .collect();
265 + let keys = if let Some(keys_data) = kb_data.keys {
266 + // New format: multiple keys
267 + keys_data
268 + .into_iter()
269 + .map(|kp| {
270 + let modifiers = kp
271 + .modifiers
272 + .iter()
273 + .map(|m| match m {
274 + ModKey::Mod => modkey,
275 + _ => m.to_keybut_mask(),
276 + })
277 + .collect();
278 +
279 + KeyPress {
280 + modifiers,
281 + key: kp.key.to_keycode(),
282 + }
283 + })
284 + .collect()
285 + } else if let (Some(modifiers), Some(key)) = (kb_data.modifiers, kb_data.key) {
286 + // Old format: single key (backwards compatibility)
287 + vec![KeyPress {
288 + modifiers: modifiers
289 + .iter()
290 + .map(|m| match m {
291 + ModKey::Mod => modkey,
292 + _ => m.to_keybut_mask(),
293 + })
294 + .collect(),
295 + key: key.to_keycode(),
296 + }]
297 + } else {
298 + return Err(ConfigError::ValidationError("Keybinding must have either 'keys' or 'modifiers'+'key'".to_string()));
299 + };
258 300
259 - let key = kb_data.key.to_keycode();
260 301 let action = kb_data.action;
261 302 let arg = arg_data_to_arg(kb_data.arg)?;
262 303
263 - keybindings.push(Key::new(modifiers, key, action, arg));
304 + keybindings.push(KeyBinding::new(keys, action, arg));
264 305 }
265 306
266 307 let mut status_blocks = Vec::new();
+2 −0 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 }
29 30
30 31 impl std::fmt::Display for WmError {
@@ -67,6 +68,7 @@ impl std::fmt::Display for ConfigError {
67 68 Self::MissingCommandArg { command, field } => {
68 69 write!(f, "{} command requires {}", command, field)
69 70 }
71 + Self::ValidationError(msg) => write!(f, "Config validation error: {}", msg),
70 72 }
71 73 }
72 74 }
+170 −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,58 @@ impl Arg {
42 45 }
43 46 }
44 47
45 -#[derive(Clone)]
46 -pub struct Key {
48 +// Individual key press in a sequence
49 +#[derive(Clone, Debug)]
50 +pub struct KeyPress {
47 51 pub(crate) modifiers: Vec<KeyButMask>,
48 52 pub(crate) key: Keycode,
53 +}
54 +
55 +// Keybinding that can be a single key or a chord (sequence of keys)
56 +#[derive(Clone)]
57 +pub struct KeyBinding {
58 + pub(crate) keys: Vec<KeyPress>,
49 59 pub(crate) func: KeyAction,
50 60 pub(crate) arg: Arg,
51 61 }
52 62
53 -impl Key {
54 - pub fn new(modifiers: Vec<KeyButMask>, key: Keycode, func: KeyAction, arg: Arg) -> Self {
63 +impl KeyBinding {
64 + pub fn new(keys: Vec<KeyPress>, func: KeyAction, arg: Arg) -> Self {
65 + Self { keys, func, arg }
66 + }
67 +
68 + // Helper for backwards compatibility with single-key bindings
69 + pub fn single_key(modifiers: Vec<KeyButMask>, key: Keycode, func: KeyAction, arg: Arg) -> Self {
55 70 Self {
56 - modifiers,
57 - key,
71 + keys: vec![KeyPress { modifiers, key }],
58 72 func,
59 73 arg,
60 74 }
61 75 }
62 76 }
63 77
64 -fn modifiers_to_mask(modifiers: &[KeyButMask]) -> u16 {
78 +// For backwards compatibility during migration
79 +pub type Key = KeyBinding;
80 +
81 +#[derive(Debug, Clone)]
82 +pub enum KeychordState {
83 + Idle,
84 + InProgress {
85 + // Indices of keybindings that could still match
86 + candidates: Vec<usize>,
87 + // How many keys have been pressed in the sequence
88 + keys_pressed: usize,
89 + },
90 +}
91 +
92 +pub enum KeychordResult {
93 + Completed(KeyAction, Arg),
94 + InProgress(Vec<usize>),
95 + None,
96 + Cancelled,
97 +}
98 +
99 +pub fn modifiers_to_mask(modifiers: &[KeyButMask]) -> u16 {
65 100 modifiers
66 101 .iter()
67 102 .fold(0u16, |acc, &modifier| acc | u16::from(modifier))
@@ -70,47 +105,153 @@ fn modifiers_to_mask(modifiers: &[KeyButMask]) -> u16 {
70 105 pub fn setup_keybinds(
71 106 connection: &impl Connection,
72 107 root: Window,
73 - keybindings: &[Key],
108 + keybindings: &[KeyBinding],
74 109 ) -> Result<(), X11Error> {
110 + let mut grabbed_keys: HashSet<(u16, Keycode)> = HashSet::new();
111 +
75 112 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 - )?;
113 + if keybinding.keys.is_empty() {
114 + continue;
115 + }
116 +
117 + let first_key = &keybinding.keys[0];
118 + let modifier_mask = modifiers_to_mask(&first_key.modifiers);
119 + let key_tuple = (modifier_mask, first_key.key);
120 +
121 + if grabbed_keys.insert(key_tuple) {
122 + connection.grab_key(
123 + false,
124 + root,
125 + modifier_mask.into(),
126 + first_key.key,
127 + GrabMode::ASYNC,
128 + GrabMode::ASYNC,
129 + )?;
130 + }
86 131 }
132 +
133 + connection.grab_key(
134 + false,
135 + root,
136 + ModMask::from(0u16),
137 + keycodes::ESCAPE,
138 + GrabMode::ASYNC,
139 + GrabMode::ASYNC,
140 + )?;
141 +
87 142 Ok(())
88 143 }
89 144
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);
145 +pub fn handle_key_press(
146 + event: KeyPressEvent,
147 + keybindings: &[KeyBinding],
148 + keychord_state: &KeychordState,
149 +) -> KeychordResult {
150 + if event.detail == keycodes::ESCAPE {
151 + return match keychord_state {
152 + KeychordState::InProgress { .. } => KeychordResult::Cancelled,
153 + KeychordState::Idle => KeychordResult::None,
154 + };
155 + }
156 +
157 + match keychord_state {
158 + KeychordState::Idle => {
159 + handle_first_key(event, keybindings)
160 + }
161 + KeychordState::InProgress { candidates, keys_pressed } => {
162 + handle_next_key(event, keybindings, candidates, *keys_pressed)
163 + }
164 + }
165 +}
166 +
167 +fn handle_first_key(
168 + event: KeyPressEvent,
169 + keybindings: &[KeyBinding],
170 +) -> KeychordResult {
171 + let mut candidates = Vec::new();
172 +
173 + for (keybinding_index, keybinding) in keybindings.iter().enumerate() {
174 + if keybinding.keys.is_empty() {
175 + continue;
176 + }
177 +
178 + let first_key = &keybinding.keys[0];
179 + let modifier_mask = modifiers_to_mask(&first_key.modifiers);
93 180
94 - if event.detail == keybinding.key && event.state == modifier_mask.into() {
95 - return (keybinding.func, keybinding.arg.clone());
181 + if event.detail == first_key.key && event.state == modifier_mask.into() {
182 + if keybinding.keys.len() == 1 {
183 + return KeychordResult::Completed(
184 + keybinding.func,
185 + keybinding.arg.clone(),
186 + );
187 + } else {
188 + candidates.push(keybinding_index);
189 + }
96 190 }
97 191 }
98 192
99 - (KeyAction::None, Arg::None)
193 + if candidates.is_empty() {
194 + KeychordResult::None
195 + } else {
196 + KeychordResult::InProgress(candidates)
197 + }
198 +}
199 +
200 +fn handle_next_key(
201 + event: KeyPressEvent,
202 + keybindings: &[KeyBinding],
203 + candidates: &[usize],
204 + keys_pressed: usize,
205 +) -> KeychordResult {
206 + let mut new_candidates = Vec::new();
207 +
208 + for &candidate_index in candidates {
209 + let keybinding = &keybindings[candidate_index];
210 +
211 + if keys_pressed >= keybinding.keys.len() {
212 + continue;
213 + }
214 +
215 + let next_key = &keybinding.keys[keys_pressed];
216 + let required_mask = modifiers_to_mask(&next_key.modifiers);
217 + let event_state: u16 = event.state.into();
218 +
219 + let modifiers_match = if next_key.modifiers.is_empty() {
220 + true
221 + } else {
222 + (event_state & required_mask) == required_mask
223 + };
224 +
225 + if event.detail == next_key.key && modifiers_match {
226 + if keys_pressed + 1 == keybinding.keys.len() {
227 + return KeychordResult::Completed(
228 + keybinding.func,
229 + keybinding.arg.clone(),
230 + );
231 + } else {
232 + new_candidates.push(candidate_index);
233 + }
234 + }
235 + }
236 +
237 + if new_candidates.is_empty() {
238 + KeychordResult::Cancelled
239 + } else {
240 + KeychordResult::InProgress(new_candidates)
241 + }
100 242 }
101 243
102 244 pub fn handle_spawn_action(action: KeyAction, arg: &Arg) -> io::Result<()> {
103 - use io::ErrorKind;
104 245 if let KeyAction::Spawn = action {
105 246 match arg {
106 247 Arg::Str(command) => match Command::new(command.as_str()).spawn() {
107 - Err(err) if err.kind() == ErrorKind::NotFound => {
248 + Err(error) if error.kind() == ErrorKind::NotFound => {
108 249 eprintln!(
109 250 "KeyAction::Spawn failed: could not spawn \"{}\", command not found",
110 251 command
111 252 );
112 253 }
113 - Err(err) => Err(err)?,
254 + Err(error) => Err(error)?,
114 255 _ => (),
115 256 },
116 257 Arg::Array(command) => {
@@ -120,13 +261,13 @@ pub fn handle_spawn_action(action: KeyAction, arg: &Arg) -> io::Result<()> {
120 261
121 262 let args_str: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
122 263 match Command::new(cmd.as_str()).args(&args_str).spawn() {
123 - Err(err) if err.kind() == ErrorKind::NotFound => {
264 + Err(error) if error.kind() == ErrorKind::NotFound => {
124 265 eprintln!(
125 266 "KeyAction::Spawn failed: could not spawn \"{}\", command not found",
126 267 cmd
127 268 );
128 269 }
129 - Err(err) => Err(err)?,
270 + Err(error) => Err(error)?,
130 271 _ => (),
131 272 }
132 273 }
+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,
+140 −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,75 @@ 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 + unsafe {
846 + let keysym = x11::xlib::XKeycodeToKeysym(self.display, keycode, 0);
847 + if keysym == 0 {
848 + return "?".to_string();
849 + }
850 +
851 + let name_ptr = x11::xlib::XKeysymToString(keysym);
852 + if name_ptr.is_null() {
853 + return "?".to_string();
854 + }
855 +
856 + let c_str = std::ffi::CStr::from_ptr(name_ptr);
857 + match c_str.to_str() {
858 + Ok(s) => {
859 + if s.len() == 1 {
860 + s.to_lowercase()
861 + } else {
862 + s.to_string()
863 + }
864 + }
865 + Err(_) => "?".to_string(),
866 + }
867 + }
868 + }
869 +
802 870 fn update_bar(&mut self) -> WmResult<()> {
803 871 let layout_symbol = self.get_layout_symbol();
872 + let keychord_indicator = self.get_keychord_indicator();
804 873
805 874 for (monitor_index, monitor) in self.monitors.iter().enumerate() {
806 875 if let Some(bar) = self.bars.get_mut(monitor_index) {
@@ -821,6 +890,7 @@ impl WindowManager {
821 890 occupied_tags,
822 891 draw_blocks,
823 892 &layout_symbol,
893 + keychord_indicator.as_deref(),
824 894 )?;
825 895 }
826 896 }
@@ -1124,6 +1194,39 @@ impl WindowManager {
1124 1194 Ok(())
1125 1195 }
1126 1196
1197 + fn grab_next_keys(&self, candidates: &[usize], keys_pressed: usize) -> WmResult<()> {
1198 + let mut grabbed_keys: HashSet<(u16, Keycode)> = HashSet::new();
1199 +
1200 + for &candidate_index in candidates {
1201 + let binding = &self.config.keybindings[candidate_index];
1202 + if keys_pressed < binding.keys.len() {
1203 + let next_key = &binding.keys[keys_pressed];
1204 + let modifier_mask = keyboard::handlers::modifiers_to_mask(&next_key.modifiers);
1205 + let key_tuple = (modifier_mask, next_key.key);
1206 +
1207 + if grabbed_keys.insert(key_tuple) {
1208 + self.connection.grab_key(
1209 + false,
1210 + self.root,
1211 + modifier_mask.into(),
1212 + next_key.key,
1213 + GrabMode::ASYNC,
1214 + GrabMode::ASYNC,
1215 + )?;
1216 + }
1217 + }
1218 + }
1219 + self.connection.flush()?;
1220 + Ok(())
1221 + }
1222 +
1223 + fn ungrab_chord_keys(&self) -> WmResult<()> {
1224 + self.connection.ungrab_key(x11rb::protocol::xproto::Grab::ANY, self.root, ModMask::ANY)?;
1225 + keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
1226 + self.connection.flush()?;
1227 + Ok(())
1228 + }
1229 +
1127 1230 pub fn set_focus(&mut self, window: Window) -> WmResult<()> {
1128 1231 let old_focused = self.previous_focused;
1129 1232
@@ -1372,11 +1475,43 @@ impl WindowManager {
1372 1475 }
1373 1476 }
1374 1477 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)?,
1478 + let result = keyboard::handle_key_press(
1479 + event,
1480 + &self.config.keybindings,
1481 + &self.keychord_state,
1482 + );
1483 +
1484 + match result {
1485 + keyboard::handlers::KeychordResult::Completed(action, arg) => {
1486 + self.keychord_state = keyboard::handlers::KeychordState::Idle;
1487 + self.ungrab_chord_keys()?;
1488 + self.update_bar()?;
1489 +
1490 + match action {
1491 + KeyAction::Quit => return Ok(Some(false)),
1492 + KeyAction::Restart => return Ok(Some(true)),
1493 + _ => self.handle_key_action(action, &arg)?,
1494 + }
1495 + }
1496 + keyboard::handlers::KeychordResult::InProgress(candidates) => {
1497 + let keys_pressed = match &self.keychord_state {
1498 + keyboard::handlers::KeychordState::Idle => 1,
1499 + keyboard::handlers::KeychordState::InProgress { keys_pressed, .. } => keys_pressed + 1,
1500 + };
1501 +
1502 + self.keychord_state = keyboard::handlers::KeychordState::InProgress {
1503 + candidates: candidates.clone(),
1504 + keys_pressed,
1505 + };
1506 +
1507 + self.grab_next_keys(&candidates, keys_pressed)?;
1508 + self.update_bar()?;
1509 + }
1510 + keyboard::handlers::KeychordResult::Cancelled | keyboard::handlers::KeychordResult::None => {
1511 + self.keychord_state = keyboard::handlers::KeychordState::Idle;
1512 + self.ungrab_chord_keys()?;
1513 + self.update_bar()?;
1514 + }
1380 1515 }
1381 1516 }
1382 1517 Event::ButtonPress(event) => {
+28 −0 templates/config.ron
@@ -23,7 +23,22 @@
23 23 (name: "normie", symbol: "[F]"),
24 24 ],
25 25
26 + // Keybinding Format:
27 + //
28 + // New format (supports keychords - multi-key sequences):
29 + // (keys: [(modifiers: [...], key: X), (modifiers: [...], key: Y)], action: ..., arg: ...)
30 + //
31 + // Old format (single key, backwards compatible):
32 + // (modifiers: [...], key: X, action: ..., arg: ...)
33 + //
34 + // Examples:
35 + // Single key: (keys: [(modifiers: [Mod4], key: Return)], action: Spawn, arg: "st")
36 + // Keychord: (keys: [(modifiers: [Mod4], key: Space), (modifiers: [], key: F)], action: Spawn, arg: "firefox")
37 + //
38 + // You can cancel any in-progress keychord by pressing Escape.
39 +
26 40 keybindings: [
41 + // Basic keybindings (old format for backwards compatibility)
27 42 (modifiers: [Mod4], key: Return, action: Spawn, arg: "st"),
28 43 (modifiers: [Mod4], key: D, action: Spawn, arg: ["sh", "-c", "dmenu_run -l 10"]),
29 44 (modifiers: [Mod4], key: S, action: Spawn, arg: ["sh", "-c", "maim -s | xclip -selection clipboard -t image/png"]),
@@ -70,6 +85,19 @@
70 85 (modifiers: [Mod4, Shift], key: J, action: ExchangeClient, arg: 1), // DOWN
71 86 (modifiers: [Mod4, Shift], key: H, action: ExchangeClient, arg: 2), // LEFT
72 87 (modifiers: [Mod4, Shift], key: L, action: ExchangeClient, arg: 3), // RIGHT
88 +
89 + // Example keychord bindings (uncomment to use):
90 + // Press Mod4+Space, then f to spawn firefox
91 + // (keys: [(modifiers: [Mod4], key: Space), (modifiers: [], key: F)], action: Spawn, arg: "firefox"),
92 +
93 + // Press Mod4+Space, then t to spawn terminal
94 + // (keys: [(modifiers: [Mod4], key: Space), (modifiers: [], key: T)], action: Spawn, arg: "st"),
95 +
96 + // Press Mod4+e, then e to spawn a text editor (same key twice)
97 + // (keys: [(modifiers: [Mod4], key: E), (modifiers: [], key: E)], action: Spawn, arg: "nvim"),
98 +
99 + // Press Mod4+x, then Shift+c to kill client (modifier on second key)
100 + // (keys: [(modifiers: [Mod4], key: X), (modifiers: [Shift], key: C)], action: KillClient),
73 101 ],
74 102
75 103 status_blocks: [
+1 −0 test-config.ron
@@ -31,6 +31,7 @@
31 31
32 32 keybindings: [
33 33 (modifiers: [Mod1], key: Return, action: Spawn, arg: "st"),
34 + (keys: [(modifiers: [Mod1], key: Space), (modifiers: [], key: T)], action: Spawn, arg: "st"),
34 35 (modifiers: [Mod1], key: D, action: Spawn, arg: ["sh", "-c", "dmenu_run -l 10"]),
35 36 (modifiers: [Mod1], key: S, action: Spawn, arg: ["sh", "-c", "maim -s | xclip -selection clipboard -t image/png"]),
36 37 (modifiers: [Mod1], key: Q, action: KillClient),