tony / oxwm

Branch: 6e5e280
Switch branches/tags
master
tonybtw Added keycode -> string map in enum for reverse lookup, to avoid unsafe call to C FFI bind. Sorry bugsy 7a4cc10 2025-10-31
544 lines · 17.2 KB Raw Blame History
1 use crate::bar::{BlockCommand, BlockConfig};
2 use crate::errors::ConfigError;
3 use crate::keyboard::handlers::{KeyBinding, KeyPress};
4 use crate::keyboard::keycodes;
5 use crate::keyboard::{Arg, KeyAction};
6 use serde::Deserialize;
7 use std::collections::HashMap;
8 use x11rb::protocol::xproto::{KeyButMask, Keycode};
9
10 #[derive(Debug, Deserialize)]
11 pub enum ModKey {
12 Mod,
13 Mod1,
14 Mod2,
15 Mod3,
16 Mod4,
17 Mod5,
18 Shift,
19 Control,
20 }
21
22 impl ModKey {
23 fn to_keybut_mask(&self) -> KeyButMask {
24 match self {
25 ModKey::Mod => panic!("ModKey::Mod should be replaced during config parsing"),
26 ModKey::Mod1 => KeyButMask::MOD1,
27 ModKey::Mod2 => KeyButMask::MOD2,
28 ModKey::Mod3 => KeyButMask::MOD3,
29 ModKey::Mod4 => KeyButMask::MOD4,
30 ModKey::Mod5 => KeyButMask::MOD5,
31 ModKey::Shift => KeyButMask::SHIFT,
32 ModKey::Control => KeyButMask::CONTROL,
33 }
34 }
35 }
36
37 #[rustfmt::skip]
38 #[derive(Debug, Deserialize)]
39 pub enum KeyData {
40 Return,
41 Q,
42 Escape,
43 Space,
44 Tab,
45 Backspace,
46 Delete,
47 F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12,
48 A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, R, S, T, U, V, W, X, Y, Z,
49 Key0,
50 Key1,
51 Key2,
52 Key3,
53 Key4,
54 Key5,
55 Key6,
56 Key7,
57 Key8,
58 Key9,
59 Left,
60 Right,
61 Up,
62 Down,
63 Home,
64 End,
65 PageUp,
66 PageDown,
67 Insert,
68 Minus,
69 Equal,
70 BracketLeft,
71 BracketRight,
72 Semicolon,
73 Apostrophe,
74 Grave,
75 Backslash,
76 Comma,
77 Period,
78 Slash,
79 }
80
81 impl KeyData {
82 fn to_keycode(&self) -> Keycode {
83 match self {
84 KeyData::Return => keycodes::RETURN,
85 KeyData::Q => keycodes::Q,
86 KeyData::Escape => keycodes::ESCAPE,
87 KeyData::Space => keycodes::SPACE,
88 KeyData::Tab => keycodes::TAB,
89 KeyData::Backspace => keycodes::BACKSPACE,
90 KeyData::Delete => keycodes::DELETE,
91 KeyData::F1 => keycodes::F1,
92 KeyData::F2 => keycodes::F2,
93 KeyData::F3 => keycodes::F3,
94 KeyData::F4 => keycodes::F4,
95 KeyData::F5 => keycodes::F5,
96 KeyData::F6 => keycodes::F6,
97 KeyData::F7 => keycodes::F7,
98 KeyData::F8 => keycodes::F8,
99 KeyData::F9 => keycodes::F9,
100 KeyData::F10 => keycodes::F10,
101 KeyData::F11 => keycodes::F11,
102 KeyData::F12 => keycodes::F12,
103 KeyData::A => keycodes::A,
104 KeyData::B => keycodes::B,
105 KeyData::C => keycodes::C,
106 KeyData::D => keycodes::D,
107 KeyData::E => keycodes::E,
108 KeyData::F => keycodes::F,
109 KeyData::G => keycodes::G,
110 KeyData::H => keycodes::H,
111 KeyData::I => keycodes::I,
112 KeyData::J => keycodes::J,
113 KeyData::K => keycodes::K,
114 KeyData::L => keycodes::L,
115 KeyData::M => keycodes::M,
116 KeyData::N => keycodes::N,
117 KeyData::O => keycodes::O,
118 KeyData::P => keycodes::P,
119 KeyData::R => keycodes::R,
120 KeyData::S => keycodes::S,
121 KeyData::T => keycodes::T,
122 KeyData::U => keycodes::U,
123 KeyData::V => keycodes::V,
124 KeyData::W => keycodes::W,
125 KeyData::X => keycodes::X,
126 KeyData::Y => keycodes::Y,
127 KeyData::Z => keycodes::Z,
128 KeyData::Key0 => keycodes::KEY_0,
129 KeyData::Key1 => keycodes::KEY_1,
130 KeyData::Key2 => keycodes::KEY_2,
131 KeyData::Key3 => keycodes::KEY_3,
132 KeyData::Key4 => keycodes::KEY_4,
133 KeyData::Key5 => keycodes::KEY_5,
134 KeyData::Key6 => keycodes::KEY_6,
135 KeyData::Key7 => keycodes::KEY_7,
136 KeyData::Key8 => keycodes::KEY_8,
137 KeyData::Key9 => keycodes::KEY_9,
138 KeyData::Left => keycodes::LEFT,
139 KeyData::Right => keycodes::RIGHT,
140 KeyData::Up => keycodes::UP,
141 KeyData::Down => keycodes::DOWN,
142 KeyData::Home => keycodes::HOME,
143 KeyData::End => keycodes::END,
144 KeyData::PageUp => keycodes::PAGE_UP,
145 KeyData::PageDown => keycodes::PAGE_DOWN,
146 KeyData::Insert => keycodes::INSERT,
147 KeyData::Minus => keycodes::MINUS,
148 KeyData::Equal => keycodes::EQUAL,
149 KeyData::BracketLeft => keycodes::LEFT_BRACKET,
150 KeyData::BracketRight => keycodes::RIGHT_BRACKET,
151 KeyData::Semicolon => keycodes::SEMICOLON,
152 KeyData::Apostrophe => keycodes::APOSTROPHE,
153 KeyData::Grave => keycodes::GRAVE,
154 KeyData::Backslash => keycodes::BACKSLASH,
155 KeyData::Comma => keycodes::COMMA,
156 KeyData::Period => keycodes::PERIOD,
157 KeyData::Slash => keycodes::SLASH,
158 }
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 }
245 }
246
247 fn preprocess_variables(input: &str) -> Result<String, ConfigError> {
248 let mut variables: HashMap<String, String> = HashMap::new();
249 let mut result = String::new();
250
251 for line in input.lines() {
252 let trimmed = line.trim();
253
254 if trimmed.starts_with("#DEFINE") {
255 let rest = trimmed.strip_prefix("#DEFINE").unwrap().trim();
256
257 if let Some(eq_pos) = rest.find('=') {
258 let var_name = rest[..eq_pos].trim();
259 let value = rest[eq_pos + 1..].trim().trim_end_matches(',');
260
261 if !var_name.starts_with('$') {
262 return Err(ConfigError::InvalidVariableName(var_name.to_string()));
263 }
264
265 variables.insert(var_name.to_string(), value.to_string());
266 } else {
267 return Err(ConfigError::InvalidDefine(trimmed.to_string()));
268 }
269
270 result.push('\n');
271 } else {
272 let mut processed_line = line.to_string();
273 for (var_name, value) in &variables {
274 processed_line = processed_line.replace(var_name, value);
275 }
276 result.push_str(&processed_line);
277 result.push('\n');
278 }
279 }
280
281 for line in result.lines() {
282 if let Some(var_start) = line.find('$') {
283 let rest = &line[var_start..];
284 let var_end = rest[1..]
285 .find(|c: char| !c.is_alphanumeric() && c != '_')
286 .unwrap_or(rest.len() - 1)
287 + 1;
288 let undefined_var = &rest[..var_end];
289 return Err(ConfigError::UndefinedVariable(undefined_var.to_string()));
290 }
291 }
292 Ok(result)
293 }
294
295 pub fn parse_config(input: &str) -> Result<crate::Config, ConfigError> {
296 let preprocessed = preprocess_variables(input)?;
297 let config_data: ConfigData = ron::from_str(&preprocessed)?;
298 config_data_to_config(config_data)
299 }
300
301 #[derive(Debug, Deserialize)]
302 struct LayoutSymbolOverrideData {
303 name: String,
304 symbol: String,
305 }
306
307 #[derive(Debug, Deserialize)]
308 struct ConfigData {
309 border_width: u32,
310 border_focused: u32,
311 border_unfocused: u32,
312 font: String,
313
314 gaps_enabled: bool,
315 gap_inner_horizontal: u32,
316 gap_inner_vertical: u32,
317 gap_outer_horizontal: u32,
318 gap_outer_vertical: u32,
319
320 terminal: String,
321 modkey: ModKey,
322
323 tags: Vec<String>,
324 #[serde(default)]
325 layout_symbols: Vec<LayoutSymbolOverrideData>,
326 keybindings: Vec<KeybindingData>,
327 status_blocks: Vec<StatusBlockData>,
328
329 scheme_normal: ColorSchemeData,
330 scheme_occupied: ColorSchemeData,
331 scheme_selected: ColorSchemeData,
332 }
333
334 #[derive(Debug, Deserialize)]
335 struct KeybindingData {
336 #[serde(default)]
337 keys: Option<Vec<KeyPressData>>,
338 #[serde(default)]
339 modifiers: Option<Vec<ModKey>>,
340 #[serde(default)]
341 key: Option<KeyData>,
342 action: KeyAction,
343 #[serde(default)]
344 arg: ArgData,
345 }
346
347 #[derive(Debug, Deserialize)]
348 struct KeyPressData {
349 modifiers: Vec<ModKey>,
350 key: KeyData,
351 }
352
353 #[derive(Debug, Deserialize)]
354 #[serde(untagged)]
355 enum ArgData {
356 None,
357 String(String),
358 Int(i32),
359 Array(Vec<String>),
360 }
361
362 impl Default for ArgData {
363 fn default() -> Self {
364 ArgData::None
365 }
366 }
367
368 #[derive(Debug, Deserialize)]
369 struct StatusBlockData {
370 format: String,
371 command: String,
372 #[serde(default)]
373 command_arg: Option<String>,
374 #[serde(default)]
375 battery_formats: Option<BatteryFormats>,
376 interval_secs: u64,
377 color: u32,
378 underline: bool,
379 }
380
381 #[derive(Debug, Deserialize)]
382 struct BatteryFormats {
383 charging: String,
384 discharging: String,
385 full: String,
386 }
387
388 #[derive(Debug, Deserialize)]
389 struct ColorSchemeData {
390 foreground: u32,
391 background: u32,
392 underline: u32,
393 }
394
395 fn config_data_to_config(data: ConfigData) -> Result<crate::Config, ConfigError> {
396 let modkey = data.modkey.to_keybut_mask();
397
398 let mut keybindings = Vec::new();
399 for kb_data in data.keybindings {
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 };
435
436 let action = kb_data.action;
437 let arg = arg_data_to_arg(kb_data.arg)?;
438
439 keybindings.push(KeyBinding::new(keys, action, arg));
440 }
441
442 let mut status_blocks = Vec::new();
443 for block_data in data.status_blocks {
444 let command = match block_data.command.as_str() {
445 "DateTime" => {
446 let fmt = block_data
447 .command_arg
448 .ok_or_else(|| ConfigError::MissingCommandArg {
449 command: "DateTime".to_string(),
450 field: "command_arg".to_string(),
451 })?;
452 BlockCommand::DateTime(fmt)
453 }
454 "Shell" => {
455 let cmd = block_data
456 .command_arg
457 .ok_or_else(|| ConfigError::MissingCommandArg {
458 command: "Shell".to_string(),
459 field: "command_arg".to_string(),
460 })?;
461 BlockCommand::Shell(cmd)
462 }
463 "Ram" => BlockCommand::Ram,
464 "Static" => {
465 let text = block_data.command_arg.unwrap_or_default();
466 BlockCommand::Static(text)
467 }
468 "Battery" => {
469 let formats =
470 block_data
471 .battery_formats
472 .ok_or_else(|| ConfigError::MissingCommandArg {
473 command: "Battery".to_string(),
474 field: "battery_formats".to_string(),
475 })?;
476 BlockCommand::Battery {
477 format_charging: formats.charging,
478 format_discharging: formats.discharging,
479 format_full: formats.full,
480 }
481 }
482 _ => return Err(ConfigError::UnknownBlockCommand(block_data.command)),
483 };
484
485 status_blocks.push(BlockConfig {
486 format: block_data.format,
487 command,
488 interval_secs: block_data.interval_secs,
489 color: block_data.color,
490 underline: block_data.underline,
491 });
492 }
493
494 let layout_symbols = data
495 .layout_symbols
496 .into_iter()
497 .map(|l| crate::LayoutSymbolOverride {
498 name: l.name,
499 symbol: l.symbol,
500 })
501 .collect();
502
503 Ok(crate::Config {
504 border_width: data.border_width,
505 border_focused: data.border_focused,
506 border_unfocused: data.border_unfocused,
507 font: data.font,
508 gaps_enabled: data.gaps_enabled,
509 gap_inner_horizontal: data.gap_inner_horizontal,
510 gap_inner_vertical: data.gap_inner_vertical,
511 gap_outer_horizontal: data.gap_outer_horizontal,
512 gap_outer_vertical: data.gap_outer_vertical,
513 terminal: data.terminal,
514 modkey,
515 tags: data.tags,
516 layout_symbols,
517 keybindings,
518 status_blocks,
519 scheme_normal: crate::ColorScheme {
520 foreground: data.scheme_normal.foreground,
521 background: data.scheme_normal.background,
522 underline: data.scheme_normal.underline,
523 },
524 scheme_occupied: crate::ColorScheme {
525 foreground: data.scheme_occupied.foreground,
526 background: data.scheme_occupied.background,
527 underline: data.scheme_occupied.underline,
528 },
529 scheme_selected: crate::ColorScheme {
530 foreground: data.scheme_selected.foreground,
531 background: data.scheme_selected.background,
532 underline: data.scheme_selected.underline,
533 },
534 })
535 }
536
537 fn arg_data_to_arg(data: ArgData) -> Result<Arg, ConfigError> {
538 match data {
539 ArgData::None => Ok(Arg::None),
540 ArgData::String(s) => Ok(Arg::Str(s)),
541 ArgData::Int(n) => Ok(Arg::Int(n)),
542 ArgData::Array(arr) => Ok(Arg::Array(arr)),
543 }
544 }