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 occupied_tags: u32, 172 occupied_tags: u32,
173 draw_blocks: bool, 173 draw_blocks: bool,
174 layout_symbol: &str, 174 layout_symbol: &str,
175 + keychord_indicator: Option<&str>,
175 ) -> Result<(), X11Error> { 176 ) -> Result<(), X11Error> {
176 if !self.needs_redraw { 177 if !self.needs_redraw {
177 return Ok(()); 178 return Ok(());
@@ -261,6 +262,25 @@ impl Bar {
261 layout_symbol 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 if draw_blocks && !self.status_text.is_empty() { 284 if draw_blocks && !self.status_text.is_empty() {
265 let padding = 10; 285 let padding = 10;
266 let mut x_position = self.width as i16 - padding; 286 let mut x_position = self.width as i16 - padding;
+51 −10 src/config/mod.rs
@@ -1,6 +1,6 @@
1 use crate::bar::{BlockCommand, BlockConfig}; 1 use crate::bar::{BlockCommand, BlockConfig};
2 use crate::errors::ConfigError; 2 use crate::errors::ConfigError;
3 -use crate::keyboard::handlers::Key; 3 +use crate::keyboard::handlers::{KeyBinding, KeyPress};
4 use crate::keyboard::keycodes; 4 use crate::keyboard::keycodes;
5 use crate::keyboard::{Arg, KeyAction}; 5 use crate::keyboard::{Arg, KeyAction};
6 use serde::Deserialize; 6 use serde::Deserialize;
@@ -8,6 +8,7 @@ use x11rb::protocol::xproto::{KeyButMask, Keycode};
8 8
9 #[derive(Debug, Deserialize)] 9 #[derive(Debug, Deserialize)]
10 pub enum ModKey { 10 pub enum ModKey {
11 + Mod,
11 Mod1, 12 Mod1,
12 Mod2, 13 Mod2,
13 Mod3, 14 Mod3,
@@ -20,6 +21,7 @@ pub enum ModKey {
20 impl ModKey { 21 impl ModKey {
21 fn to_keybut_mask(&self) -> KeyButMask { 22 fn to_keybut_mask(&self) -> KeyButMask {
22 match self { 23 match self {
24 + ModKey::Mod => panic!("ModKey::Mod should be replaced during config parsing"),
23 ModKey::Mod1 => KeyButMask::MOD1, 25 ModKey::Mod1 => KeyButMask::MOD1,
24 ModKey::Mod2 => KeyButMask::MOD2, 26 ModKey::Mod2 => KeyButMask::MOD2,
25 ModKey::Mod3 => KeyButMask::MOD3, 27 ModKey::Mod3 => KeyButMask::MOD3,
@@ -196,13 +198,23 @@ struct ConfigData {
196 198
197 #[derive(Debug, Deserialize)] 199 #[derive(Debug, Deserialize)]
198 struct KeybindingData { 200 struct KeybindingData {
199 - modifiers: Vec<ModKey>, 201 + #[serde(default)]
200 - key: KeyData, 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 action: KeyAction, 207 action: KeyAction,
202 #[serde(default)] 208 #[serde(default)]
203 arg: ArgData, 209 arg: ArgData,
204 } 210 }
205 211
212 +#[derive(Debug, Deserialize)]
213 +struct KeyPressData {
214 + modifiers: Vec<ModKey>,
215 + key: KeyData,
216 +}
217 +
206 #[derive(Debug, Deserialize)] 218 #[derive(Debug, Deserialize)]
207 #[serde(untagged)] 219 #[serde(untagged)]
208 enum ArgData { 220 enum ArgData {
@@ -250,17 +262,46 @@ fn config_data_to_config(data: ConfigData) -> Result<crate::Config, ConfigError>
250 262
251 let mut keybindings = Vec::new(); 263 let mut keybindings = Vec::new();
252 for kb_data in data.keybindings { 264 for kb_data in data.keybindings {
253 - let modifiers = kb_data 265 + let keys = if let Some(keys_data) = kb_data.keys {
254 - .modifiers 266 + // New format: multiple keys
255 - .iter() 267 + keys_data
256 - .map(|m| m.to_keybut_mask()) 268 + .into_iter()
257 - .collect(); 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 let action = kb_data.action; 301 let action = kb_data.action;
261 let arg = arg_data_to_arg(kb_data.arg)?; 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 let mut status_blocks = Vec::new(); 307 let mut status_blocks = Vec::new();
+2 −0 src/errors.rs
@@ -25,6 +25,7 @@ pub enum ConfigError {
25 UnknownAction(String), 25 UnknownAction(String),
26 UnknownBlockCommand(String), 26 UnknownBlockCommand(String),
27 MissingCommandArg { command: String, field: String }, 27 MissingCommandArg { command: String, field: String },
28 + ValidationError(String),
28 } 29 }
29 30
30 impl std::fmt::Display for WmError { 31 impl std::fmt::Display for WmError {
@@ -67,6 +68,7 @@ impl std::fmt::Display for ConfigError {
67 Self::MissingCommandArg { command, field } => { 68 Self::MissingCommandArg { command, field } => {
68 write!(f, "{} command requires {}", command, field) 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 use std::io; 2 use std::io;
3 +use std::io::ErrorKind;
2 use std::process::Command; 4 use std::process::Command;
3 5
4 use serde::Deserialize; 6 use serde::Deserialize;
@@ -6,6 +8,7 @@ use x11rb::connection::Connection;
6 use x11rb::protocol::xproto::*; 8 use x11rb::protocol::xproto::*;
7 9
8 use crate::errors::X11Error; 10 use crate::errors::X11Error;
11 +use crate::keyboard::keycodes;
9 12
10 #[derive(Debug, Copy, Clone, Deserialize)] 13 #[derive(Debug, Copy, Clone, Deserialize)]
11 pub enum KeyAction { 14 pub enum KeyAction {
@@ -42,26 +45,58 @@ impl Arg {
42 } 45 }
43 } 46 }
44 47
45 -#[derive(Clone)] 48 +// Individual key press in a sequence
46 -pub struct Key { 49 +#[derive(Clone, Debug)]
50 +pub struct KeyPress {
47 pub(crate) modifiers: Vec<KeyButMask>, 51 pub(crate) modifiers: Vec<KeyButMask>,
48 pub(crate) key: Keycode, 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 pub(crate) func: KeyAction, 59 pub(crate) func: KeyAction,
50 pub(crate) arg: Arg, 60 pub(crate) arg: Arg,
51 } 61 }
52 62
53 -impl Key { 63 +impl KeyBinding {
54 - pub fn new(modifiers: Vec<KeyButMask>, key: Keycode, func: KeyAction, arg: Arg) -> Self { 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 Self { 70 Self {
56 - modifiers, 71 + keys: vec![KeyPress { modifiers, key }],
57 - key,
58 func, 72 func,
59 arg, 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 modifiers 100 modifiers
66 .iter() 101 .iter()
67 .fold(0u16, |acc, &modifier| acc | u16::from(modifier)) 102 .fold(0u16, |acc, &modifier| acc | u16::from(modifier))
@@ -70,47 +105,153 @@ fn modifiers_to_mask(modifiers: &[KeyButMask]) -> u16 {
70 pub fn setup_keybinds( 105 pub fn setup_keybinds(
71 connection: &impl Connection, 106 connection: &impl Connection,
72 root: Window, 107 root: Window,
73 - keybindings: &[Key], 108 + keybindings: &[KeyBinding],
74 ) -> Result<(), X11Error> { 109 ) -> Result<(), X11Error> {
110 + let mut grabbed_keys: HashSet<(u16, Keycode)> = HashSet::new();
111 +
75 for keybinding in keybindings { 112 for keybinding in keybindings {
76 - let modifier_mask = modifiers_to_mask(&keybinding.modifiers); 113 + if keybinding.keys.is_empty() {
77 - 114 + continue;
78 - connection.grab_key( 115 + }
79 - false, 116 +
80 - root, 117 + let first_key = &keybinding.keys[0];
81 - modifier_mask.into(), 118 + let modifier_mask = modifiers_to_mask(&first_key.modifiers);
82 - keybinding.key, 119 + let key_tuple = (modifier_mask, first_key.key);
83 - GrabMode::ASYNC, 120 +
84 - GrabMode::ASYNC, 121 + if grabbed_keys.insert(key_tuple) {
85 - )?; 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 Ok(()) 142 Ok(())
88 } 143 }
89 144
90 -pub fn handle_key_press(event: KeyPressEvent, keybindings: &[Key]) -> (KeyAction, Arg) { 145 +pub fn handle_key_press(
91 - for keybinding in keybindings { 146 + event: KeyPressEvent,
92 - let modifier_mask = modifiers_to_mask(&keybinding.modifiers); 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() { 181 + if event.detail == first_key.key && event.state == modifier_mask.into() {
95 - return (keybinding.func, keybinding.arg.clone()); 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 pub fn handle_spawn_action(action: KeyAction, arg: &Arg) -> io::Result<()> { 244 pub fn handle_spawn_action(action: KeyAction, arg: &Arg) -> io::Result<()> {
103 - use io::ErrorKind;
104 if let KeyAction::Spawn = action { 245 if let KeyAction::Spawn = action {
105 match arg { 246 match arg {
106 Arg::Str(command) => match Command::new(command.as_str()).spawn() { 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 eprintln!( 249 eprintln!(
109 "KeyAction::Spawn failed: could not spawn \"{}\", command not found", 250 "KeyAction::Spawn failed: could not spawn \"{}\", command not found",
110 command 251 command
111 ); 252 );
112 } 253 }
113 - Err(err) => Err(err)?, 254 + Err(error) => Err(error)?,
114 _ => (), 255 _ => (),
115 }, 256 },
116 Arg::Array(command) => { 257 Arg::Array(command) => {
@@ -120,13 +261,13 @@ pub fn handle_spawn_action(action: KeyAction, arg: &Arg) -> io::Result<()> {
120 261
121 let args_str: Vec<&str> = args.iter().map(|s| s.as_str()).collect(); 262 let args_str: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
122 match Command::new(cmd.as_str()).args(&args_str).spawn() { 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 eprintln!( 265 eprintln!(
125 "KeyAction::Spawn failed: could not spawn \"{}\", command not found", 266 "KeyAction::Spawn failed: could not spawn \"{}\", command not found",
126 cmd 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 pub use crate::ColorScheme; 10 pub use crate::ColorScheme;
11 pub use crate::LayoutSymbolOverride; 11 pub use crate::LayoutSymbolOverride;
12 pub use crate::bar::{BlockCommand, BlockConfig}; 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 pub use x11rb::protocol::xproto::KeyButMask; 14 pub use x11rb::protocol::xproto::KeyButMask;
15 } 15 }
16 16
@@ -66,7 +66,7 @@ pub struct ColorScheme {
66 66
67 impl Default for Config { 67 impl Default for Config {
68 fn default() -> Self { 68 fn default() -> Self {
69 - use crate::keyboard::handlers::Key; 69 + use crate::keyboard::handlers::KeyBinding;
70 use crate::keyboard::{Arg, KeyAction, keycodes}; 70 use crate::keyboard::{Arg, KeyAction, keycodes};
71 use x11rb::protocol::xproto::KeyButMask; 71 use x11rb::protocol::xproto::KeyButMask;
72 72
@@ -93,13 +93,13 @@ impl Default for Config {
93 .collect(), 93 .collect(),
94 layout_symbols: vec![], 94 layout_symbols: vec![],
95 keybindings: vec![ 95 keybindings: vec![
96 - Key::new( 96 + KeyBinding::single_key(
97 vec![MODKEY], 97 vec![MODKEY],
98 keycodes::RETURN, 98 keycodes::RETURN,
99 KeyAction::Spawn, 99 KeyAction::Spawn,
100 Arg::Str(TERMINAL.to_string()), 100 Arg::Str(TERMINAL.to_string()),
101 ), 101 ),
102 - Key::new( 102 + KeyBinding::single_key(
103 vec![MODKEY], 103 vec![MODKEY],
104 keycodes::D, 104 keycodes::D,
105 KeyAction::Spawn, 105 KeyAction::Spawn,
@@ -109,167 +109,167 @@ impl Default for Config {
109 "dmenu_run -l 10".to_string(), 109 "dmenu_run -l 10".to_string(),
110 ]), 110 ]),
111 ), 111 ),
112 - Key::new(vec![MODKEY], keycodes::Q, KeyAction::KillClient, Arg::None), 112 + KeyBinding::single_key(vec![MODKEY], keycodes::Q, KeyAction::KillClient, Arg::None),
113 - Key::new(vec![MODKEY], keycodes::N, KeyAction::CycleLayout, Arg::None), 113 + KeyBinding::single_key(vec![MODKEY], keycodes::N, KeyAction::CycleLayout, Arg::None),
114 - Key::new( 114 + KeyBinding::single_key(
115 vec![MODKEY, SHIFT], 115 vec![MODKEY, SHIFT],
116 keycodes::F, 116 keycodes::F,
117 KeyAction::ToggleFullScreen, 117 KeyAction::ToggleFullScreen,
118 Arg::None, 118 Arg::None,
119 ), 119 ),
120 - Key::new(vec![MODKEY], keycodes::A, KeyAction::ToggleGaps, Arg::None), 120 + KeyBinding::single_key(vec![MODKEY], keycodes::A, KeyAction::ToggleGaps, Arg::None),
121 - Key::new(vec![MODKEY, SHIFT], keycodes::Q, KeyAction::Quit, Arg::None), 121 + KeyBinding::single_key(vec![MODKEY, SHIFT], keycodes::Q, KeyAction::Quit, Arg::None),
122 - Key::new( 122 + KeyBinding::single_key(
123 vec![MODKEY, SHIFT], 123 vec![MODKEY, SHIFT],
124 keycodes::R, 124 keycodes::R,
125 KeyAction::Restart, 125 KeyAction::Restart,
126 Arg::None, 126 Arg::None,
127 ), 127 ),
128 - Key::new( 128 + KeyBinding::single_key(
129 vec![MODKEY], 129 vec![MODKEY],
130 keycodes::F, 130 keycodes::F,
131 KeyAction::ToggleFloating, 131 KeyAction::ToggleFloating,
132 Arg::None, 132 Arg::None,
133 ), 133 ),
134 - Key::new( 134 + KeyBinding::single_key(
135 vec![MODKEY], 135 vec![MODKEY],
136 keycodes::J, 136 keycodes::J,
137 KeyAction::FocusStack, 137 KeyAction::FocusStack,
138 Arg::Int(-1), 138 Arg::Int(-1),
139 ), 139 ),
140 - Key::new( 140 + KeyBinding::single_key(
141 vec![MODKEY], 141 vec![MODKEY],
142 keycodes::K, 142 keycodes::K,
143 KeyAction::FocusStack, 143 KeyAction::FocusStack,
144 Arg::Int(1), 144 Arg::Int(1),
145 ), 145 ),
146 - Key::new( 146 + KeyBinding::single_key(
147 vec![MODKEY, SHIFT], 147 vec![MODKEY, SHIFT],
148 keycodes::K, 148 keycodes::K,
149 KeyAction::ExchangeClient, 149 KeyAction::ExchangeClient,
150 Arg::Int(0), // UP 150 Arg::Int(0), // UP
151 ), 151 ),
152 - Key::new( 152 + KeyBinding::single_key(
153 vec![MODKEY, SHIFT], 153 vec![MODKEY, SHIFT],
154 keycodes::J, 154 keycodes::J,
155 KeyAction::ExchangeClient, 155 KeyAction::ExchangeClient,
156 Arg::Int(1), // DOWN 156 Arg::Int(1), // DOWN
157 ), 157 ),
158 - Key::new( 158 + KeyBinding::single_key(
159 vec![MODKEY, SHIFT], 159 vec![MODKEY, SHIFT],
160 keycodes::H, 160 keycodes::H,
161 KeyAction::ExchangeClient, 161 KeyAction::ExchangeClient,
162 Arg::Int(2), // LEFT 162 Arg::Int(2), // LEFT
163 ), 163 ),
164 - Key::new( 164 + KeyBinding::single_key(
165 vec![MODKEY, SHIFT], 165 vec![MODKEY, SHIFT],
166 keycodes::L, 166 keycodes::L,
167 KeyAction::ExchangeClient, 167 KeyAction::ExchangeClient,
168 Arg::Int(3), // RIGHT 168 Arg::Int(3), // RIGHT
169 ), 169 ),
170 - Key::new( 170 + KeyBinding::single_key(
171 vec![MODKEY], 171 vec![MODKEY],
172 keycodes::KEY_1, 172 keycodes::KEY_1,
173 KeyAction::ViewTag, 173 KeyAction::ViewTag,
174 Arg::Int(0), 174 Arg::Int(0),
175 ), 175 ),
176 - Key::new( 176 + KeyBinding::single_key(
177 vec![MODKEY], 177 vec![MODKEY],
178 keycodes::KEY_2, 178 keycodes::KEY_2,
179 KeyAction::ViewTag, 179 KeyAction::ViewTag,
180 Arg::Int(1), 180 Arg::Int(1),
181 ), 181 ),
182 - Key::new( 182 + KeyBinding::single_key(
183 vec![MODKEY], 183 vec![MODKEY],
184 keycodes::KEY_3, 184 keycodes::KEY_3,
185 KeyAction::ViewTag, 185 KeyAction::ViewTag,
186 Arg::Int(2), 186 Arg::Int(2),
187 ), 187 ),
188 - Key::new( 188 + KeyBinding::single_key(
189 vec![MODKEY], 189 vec![MODKEY],
190 keycodes::KEY_4, 190 keycodes::KEY_4,
191 KeyAction::ViewTag, 191 KeyAction::ViewTag,
192 Arg::Int(3), 192 Arg::Int(3),
193 ), 193 ),
194 - Key::new( 194 + KeyBinding::single_key(
195 vec![MODKEY], 195 vec![MODKEY],
196 keycodes::KEY_5, 196 keycodes::KEY_5,
197 KeyAction::ViewTag, 197 KeyAction::ViewTag,
198 Arg::Int(4), 198 Arg::Int(4),
199 ), 199 ),
200 - Key::new( 200 + KeyBinding::single_key(
201 vec![MODKEY], 201 vec![MODKEY],
202 keycodes::KEY_6, 202 keycodes::KEY_6,
203 KeyAction::ViewTag, 203 KeyAction::ViewTag,
204 Arg::Int(5), 204 Arg::Int(5),
205 ), 205 ),
206 - Key::new( 206 + KeyBinding::single_key(
207 vec![MODKEY], 207 vec![MODKEY],
208 keycodes::KEY_7, 208 keycodes::KEY_7,
209 KeyAction::ViewTag, 209 KeyAction::ViewTag,
210 Arg::Int(6), 210 Arg::Int(6),
211 ), 211 ),
212 - Key::new( 212 + KeyBinding::single_key(
213 vec![MODKEY], 213 vec![MODKEY],
214 keycodes::KEY_8, 214 keycodes::KEY_8,
215 KeyAction::ViewTag, 215 KeyAction::ViewTag,
216 Arg::Int(7), 216 Arg::Int(7),
217 ), 217 ),
218 - Key::new( 218 + KeyBinding::single_key(
219 vec![MODKEY], 219 vec![MODKEY],
220 keycodes::KEY_9, 220 keycodes::KEY_9,
221 KeyAction::ViewTag, 221 KeyAction::ViewTag,
222 Arg::Int(8), 222 Arg::Int(8),
223 ), 223 ),
224 - Key::new( 224 + KeyBinding::single_key(
225 vec![MODKEY, SHIFT], 225 vec![MODKEY, SHIFT],
226 keycodes::KEY_1, 226 keycodes::KEY_1,
227 KeyAction::MoveToTag, 227 KeyAction::MoveToTag,
228 Arg::Int(0), 228 Arg::Int(0),
229 ), 229 ),
230 - Key::new( 230 + KeyBinding::single_key(
231 vec![MODKEY, SHIFT], 231 vec![MODKEY, SHIFT],
232 keycodes::KEY_2, 232 keycodes::KEY_2,
233 KeyAction::MoveToTag, 233 KeyAction::MoveToTag,
234 Arg::Int(1), 234 Arg::Int(1),
235 ), 235 ),
236 - Key::new( 236 + KeyBinding::single_key(
237 vec![MODKEY, SHIFT], 237 vec![MODKEY, SHIFT],
238 keycodes::KEY_3, 238 keycodes::KEY_3,
239 KeyAction::MoveToTag, 239 KeyAction::MoveToTag,
240 Arg::Int(2), 240 Arg::Int(2),
241 ), 241 ),
242 - Key::new( 242 + KeyBinding::single_key(
243 vec![MODKEY, SHIFT], 243 vec![MODKEY, SHIFT],
244 keycodes::KEY_4, 244 keycodes::KEY_4,
245 KeyAction::MoveToTag, 245 KeyAction::MoveToTag,
246 Arg::Int(3), 246 Arg::Int(3),
247 ), 247 ),
248 - Key::new( 248 + KeyBinding::single_key(
249 vec![MODKEY, SHIFT], 249 vec![MODKEY, SHIFT],
250 keycodes::KEY_5, 250 keycodes::KEY_5,
251 KeyAction::MoveToTag, 251 KeyAction::MoveToTag,
252 Arg::Int(4), 252 Arg::Int(4),
253 ), 253 ),
254 - Key::new( 254 + KeyBinding::single_key(
255 vec![MODKEY, SHIFT], 255 vec![MODKEY, SHIFT],
256 keycodes::KEY_6, 256 keycodes::KEY_6,
257 KeyAction::MoveToTag, 257 KeyAction::MoveToTag,
258 Arg::Int(5), 258 Arg::Int(5),
259 ), 259 ),
260 - Key::new( 260 + KeyBinding::single_key(
261 vec![MODKEY, SHIFT], 261 vec![MODKEY, SHIFT],
262 keycodes::KEY_7, 262 keycodes::KEY_7,
263 KeyAction::MoveToTag, 263 KeyAction::MoveToTag,
264 Arg::Int(6), 264 Arg::Int(6),
265 ), 265 ),
266 - Key::new( 266 + KeyBinding::single_key(
267 vec![MODKEY, SHIFT], 267 vec![MODKEY, SHIFT],
268 keycodes::KEY_8, 268 keycodes::KEY_8,
269 KeyAction::MoveToTag, 269 KeyAction::MoveToTag,
270 Arg::Int(7), 270 Arg::Int(7),
271 ), 271 ),
272 - Key::new( 272 + KeyBinding::single_key(
273 vec![MODKEY, SHIFT], 273 vec![MODKEY, SHIFT],
274 keycodes::KEY_9, 274 keycodes::KEY_9,
275 KeyAction::MoveToTag, 275 KeyAction::MoveToTag,
+140 −5 src/window_manager.rs
@@ -68,6 +68,7 @@ pub struct WindowManager {
68 previous_focused: Option<Window>, 68 previous_focused: Option<Window>,
69 display: *mut x11::xlib::Display, 69 display: *mut x11::xlib::Display,
70 font: crate::bar::font::Font, 70 font: crate::bar::font::Font,
71 + keychord_state: keyboard::handlers::KeychordState,
71 } 72 }
72 73
73 type WmResult<T> = Result<T, WmError>; 74 type WmResult<T> = Result<T, WmError>;
@@ -176,6 +177,7 @@ impl WindowManager {
176 previous_focused: None, 177 previous_focused: None,
177 display, 178 display,
178 font, 179 font,
180 + keychord_state: keyboard::handlers::KeychordState::Idle,
179 }; 181 };
180 182
181 window_manager.scan_existing_windows()?; 183 window_manager.scan_existing_windows()?;
@@ -799,8 +801,75 @@ impl WindowManager {
799 .unwrap_or_else(|| self.layout.symbol().to_string()) 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 fn update_bar(&mut self) -> WmResult<()> { 870 fn update_bar(&mut self) -> WmResult<()> {
803 let layout_symbol = self.get_layout_symbol(); 871 let layout_symbol = self.get_layout_symbol();
872 + let keychord_indicator = self.get_keychord_indicator();
804 873
805 for (monitor_index, monitor) in self.monitors.iter().enumerate() { 874 for (monitor_index, monitor) in self.monitors.iter().enumerate() {
806 if let Some(bar) = self.bars.get_mut(monitor_index) { 875 if let Some(bar) = self.bars.get_mut(monitor_index) {
@@ -821,6 +890,7 @@ impl WindowManager {
821 occupied_tags, 890 occupied_tags,
822 draw_blocks, 891 draw_blocks,
823 &layout_symbol, 892 &layout_symbol,
893 + keychord_indicator.as_deref(),
824 )?; 894 )?;
825 } 895 }
826 } 896 }
@@ -1124,6 +1194,39 @@ impl WindowManager {
1124 Ok(()) 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 pub fn set_focus(&mut self, window: Window) -> WmResult<()> { 1230 pub fn set_focus(&mut self, window: Window) -> WmResult<()> {
1128 let old_focused = self.previous_focused; 1231 let old_focused = self.previous_focused;
1129 1232
@@ -1372,11 +1475,43 @@ impl WindowManager {
1372 } 1475 }
1373 } 1476 }
1374 Event::KeyPress(event) => { 1477 Event::KeyPress(event) => {
1375 - let (action, arg) = keyboard::handle_key_press(event, &self.config.keybindings); 1478 + let result = keyboard::handle_key_press(
1376 - match action { 1479 + event,
1377 - KeyAction::Quit => return Ok(Some(false)), 1480 + &self.config.keybindings,
1378 - KeyAction::Restart => return Ok(Some(true)), 1481 + &self.keychord_state,
1379 - _ => self.handle_key_action(action, &arg)?, 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 Event::ButtonPress(event) => { 1517 Event::ButtonPress(event) => {
+28 −0 templates/config.ron
@@ -23,7 +23,22 @@
23 (name: "normie", symbol: "[F]"), 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 keybindings: [ 40 keybindings: [
41 + // Basic keybindings (old format for backwards compatibility)
27 (modifiers: [Mod4], key: Return, action: Spawn, arg: "st"), 42 (modifiers: [Mod4], key: Return, action: Spawn, arg: "st"),
28 (modifiers: [Mod4], key: D, action: Spawn, arg: ["sh", "-c", "dmenu_run -l 10"]), 43 (modifiers: [Mod4], key: D, action: Spawn, arg: ["sh", "-c", "dmenu_run -l 10"]),
29 (modifiers: [Mod4], key: S, action: Spawn, arg: ["sh", "-c", "maim -s | xclip -selection clipboard -t image/png"]), 44 (modifiers: [Mod4], key: S, action: Spawn, arg: ["sh", "-c", "maim -s | xclip -selection clipboard -t image/png"]),
@@ -70,6 +85,19 @@
70 (modifiers: [Mod4, Shift], key: J, action: ExchangeClient, arg: 1), // DOWN 85 (modifiers: [Mod4, Shift], key: J, action: ExchangeClient, arg: 1), // DOWN
71 (modifiers: [Mod4, Shift], key: H, action: ExchangeClient, arg: 2), // LEFT 86 (modifiers: [Mod4, Shift], key: H, action: ExchangeClient, arg: 2), // LEFT
72 (modifiers: [Mod4, Shift], key: L, action: ExchangeClient, arg: 3), // RIGHT 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 status_blocks: [ 103 status_blocks: [
+1 −0 test-config.ron
@@ -31,6 +31,7 @@
31 31
32 keybindings: [ 32 keybindings: [
33 (modifiers: [Mod1], key: Return, action: Spawn, arg: "st"), 33 (modifiers: [Mod1], key: Return, action: Spawn, arg: "st"),
34 + (keys: [(modifiers: [Mod1], key: Space), (modifiers: [], key: T)], action: Spawn, arg: "st"),
34 (modifiers: [Mod1], key: D, action: Spawn, arg: ["sh", "-c", "dmenu_run -l 10"]), 35 (modifiers: [Mod1], key: D, action: Spawn, arg: ["sh", "-c", "dmenu_run -l 10"]),
35 (modifiers: [Mod1], key: S, action: Spawn, arg: ["sh", "-c", "maim -s | xclip -selection clipboard -t image/png"]), 36 (modifiers: [Mod1], key: S, action: Spawn, arg: ["sh", "-c", "maim -s | xclip -selection clipboard -t image/png"]),
36 (modifiers: [Mod1], key: Q, action: KillClient), 37 (modifiers: [Mod1], key: Q, action: KillClient),