tony / oxwm

Branch: 9817677
Switch branches/tags
master
tonybtw Added proper error handling in blocks, and font. added error modal so config syntax error doesnt crash when you reload your oxwm, added keybind overlay modal to show the important keybinds (inspired by niri), moved keysms helper function into const file to reduce code duplication. ad06fa5 2025-11-09
586 lines · 19.8 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::keysyms::{self, Keysym};
5 use crate::keyboard::{Arg, KeyAction};
6 use crate::{ColorScheme, LayoutSymbolOverride};
7 use mlua::{Lua, Table, Value};
8 use x11rb::protocol::xproto::KeyButMask;
9
10 pub fn parse_lua_config(
11 input: &str,
12 config_dir: Option<&std::path::Path>,
13 ) -> Result<crate::Config, ConfigError> {
14 let lua = Lua::new();
15
16 if let Some(dir) = config_dir {
17 if let Some(dir_str) = dir.to_str() {
18 let setup_code = format!("package.path = '{}/?.lua;' .. package.path", dir_str);
19 lua.load(&setup_code)
20 .exec()
21 .map_err(|e| ConfigError::LuaError(format!("Failed to set package.path: {}", e)))?;
22 }
23 }
24
25 let config: Table = lua
26 .load(input)
27 .eval()
28 .map_err(|e| ConfigError::LuaError(format!("Failed to execute Lua config: {}", e)))?;
29 let border_width: u32 = get_table_field(&config, "border_width")?;
30 let border_focused: u32 = parse_color(&config, "border_focused")?;
31 let border_unfocused: u32 = parse_color(&config, "border_unfocused")?;
32 let font: String = get_table_field(&config, "font")?;
33
34 let gaps_enabled: bool = get_table_field(&config, "gaps_enabled")?;
35 let gap_inner_horizontal: u32 = get_table_field(&config, "gap_inner_horizontal")?;
36 let gap_inner_vertical: u32 = get_table_field(&config, "gap_inner_vertical")?;
37 let gap_outer_horizontal: u32 = get_table_field(&config, "gap_outer_horizontal")?;
38 let gap_outer_vertical: u32 = get_table_field(&config, "gap_outer_vertical")?;
39
40 let terminal: String = get_table_field(&config, "terminal")?;
41 let modkey = parse_modkey(&config)?;
42
43 let tags = parse_tags(&config)?;
44 let layout_symbols = parse_layout_symbols(&config)?;
45 let keybindings = parse_keybindings(&config, modkey)?;
46 let status_blocks = parse_status_blocks(&config)?;
47
48 let scheme_normal = parse_color_scheme(&config, "scheme_normal")?;
49 let scheme_occupied = parse_color_scheme(&config, "scheme_occupied")?;
50 let scheme_selected = parse_color_scheme(&config, "scheme_selected")?;
51
52 let autostart = parse_autostart(&config)?;
53
54 Ok(crate::Config {
55 border_width,
56 border_focused,
57 border_unfocused,
58 font,
59 gaps_enabled,
60 gap_inner_horizontal,
61 gap_inner_vertical,
62 gap_outer_horizontal,
63 gap_outer_vertical,
64 terminal,
65 modkey,
66 tags,
67 layout_symbols,
68 keybindings,
69 status_blocks,
70 scheme_normal,
71 scheme_occupied,
72 scheme_selected,
73 autostart,
74 })
75 }
76
77 fn get_table_field<T>(table: &Table, field: &str) -> Result<T, ConfigError>
78 where
79 T: mlua::FromLua,
80 {
81 table
82 .get::<T>(field)
83 .map_err(|e| ConfigError::LuaError(format!("Failed to get field '{}': {}", field, e)))
84 }
85
86 fn parse_color(table: &Table, field: &str) -> Result<u32, ConfigError> {
87 let value: Value = table.get(field).map_err(|e| {
88 ConfigError::LuaError(format!("Failed to get color field '{}': {}", field, e))
89 })?;
90
91 match value {
92 Value::String(s) => {
93 let s = s.to_str().map_err(|e| {
94 ConfigError::LuaError(format!("Invalid UTF-8 in color string: {}", e))
95 })?;
96 parse_color_string(&s)
97 }
98 Value::Integer(i) => Ok(i as u32),
99 Value::Number(n) => Ok(n as u32),
100 _ => Err(ConfigError::LuaError(format!(
101 "Color field '{}' must be a string or number",
102 field
103 ))),
104 }
105 }
106
107 fn parse_color_string(s: &str) -> Result<u32, ConfigError> {
108 let s = s.trim();
109 if s.starts_with('#') {
110 u32::from_str_radix(&s[1..], 16)
111 .map_err(|e| ConfigError::LuaError(format!("Invalid hex color '{}': {}", s, e)))
112 } else if s.starts_with("0x") {
113 u32::from_str_radix(&s[2..], 16)
114 .map_err(|e| ConfigError::LuaError(format!("Invalid hex color '{}': {}", s, e)))
115 } else {
116 s.parse::<u32>()
117 .map_err(|e| ConfigError::LuaError(format!("Invalid color '{}': {}", s, e)))
118 }
119 }
120
121 fn parse_modkey(config: &Table) -> Result<KeyButMask, ConfigError> {
122 let modkey_str: String = get_table_field(config, "modkey")?;
123 parse_modkey_string(&modkey_str)
124 }
125
126 fn parse_modkey_string(s: &str) -> Result<KeyButMask, ConfigError> {
127 match s {
128 "Mod1" => Ok(KeyButMask::MOD1),
129 "Mod2" => Ok(KeyButMask::MOD2),
130 "Mod3" => Ok(KeyButMask::MOD3),
131 "Mod4" => Ok(KeyButMask::MOD4),
132 "Mod5" => Ok(KeyButMask::MOD5),
133 "Shift" => Ok(KeyButMask::SHIFT),
134 "Control" => Ok(KeyButMask::CONTROL),
135 _ => Err(ConfigError::InvalidModkey(s.to_string())),
136 }
137 }
138
139 fn parse_tags(config: &Table) -> Result<Vec<String>, ConfigError> {
140 let tags_table: Table = get_table_field(config, "tags")?;
141 let mut tags = Vec::new();
142
143 for i in 1..=tags_table
144 .len()
145 .map_err(|e| ConfigError::LuaError(format!("Failed to get tags length: {}", e)))?
146 {
147 let tag: String = tags_table.get(i).map_err(|e| {
148 ConfigError::LuaError(format!("Failed to get tag at index {}: {}", i, e))
149 })?;
150 tags.push(tag);
151 }
152
153 Ok(tags)
154 }
155
156 fn parse_layout_symbols(config: &Table) -> Result<Vec<LayoutSymbolOverride>, ConfigError> {
157 let layout_symbols_result: Result<Table, _> = config.get("layout_symbols");
158
159 match layout_symbols_result {
160 Ok(layout_symbols_table) => {
161 let mut layout_symbols = Vec::new();
162
163 for i in 1..=layout_symbols_table.len().map_err(|e| {
164 ConfigError::LuaError(format!("Failed to get layout_symbols length: {}", e))
165 })? {
166 let entry: Table = layout_symbols_table.get(i).map_err(|e| {
167 ConfigError::LuaError(format!(
168 "Failed to get layout_symbol at index {}: {}",
169 i, e
170 ))
171 })?;
172
173 let name: String = get_table_field(&entry, "name")?;
174 let symbol: String = get_table_field(&entry, "symbol")?;
175
176 layout_symbols.push(LayoutSymbolOverride { name, symbol });
177 }
178
179 Ok(layout_symbols)
180 }
181 Err(_) => Ok(Vec::new()),
182 }
183 }
184
185 fn parse_keybindings(config: &Table, modkey: KeyButMask) -> Result<Vec<KeyBinding>, ConfigError> {
186 let keybindings_table: Table = get_table_field(config, "keybindings")?;
187 let mut keybindings = Vec::new();
188
189 for i in 1..=keybindings_table
190 .len()
191 .map_err(|e| ConfigError::LuaError(format!("Failed to get keybindings length: {}", e)))?
192 {
193 let kb_table: Table = keybindings_table.get(i).map_err(|e| {
194 ConfigError::LuaError(format!("Failed to get keybinding at index {}: {}", i, e))
195 })?;
196
197 let keys = parse_keypress_list(&kb_table, modkey)?;
198 let action = parse_key_action(&kb_table)?;
199 let arg = parse_arg(&kb_table)?;
200
201 keybindings.push(KeyBinding::new(keys, action, arg));
202 }
203
204 Ok(keybindings)
205 }
206
207 fn parse_keypress_list(kb_table: &Table, modkey: KeyButMask) -> Result<Vec<KeyPress>, ConfigError> {
208 let keys_result: Result<Table, _> = kb_table.get("keys");
209
210 if let Ok(keys_table) = keys_result {
211 let mut keys = Vec::new();
212 for i in 1..=keys_table
213 .len()
214 .map_err(|e| ConfigError::LuaError(format!("Failed to get keys length: {}", e)))?
215 {
216 let key_entry: Table = keys_table.get(i).map_err(|e| {
217 ConfigError::LuaError(format!("Failed to get key at index {}: {}", i, e))
218 })?;
219
220 let modifiers = parse_modifiers(&key_entry, "modifiers", modkey)?;
221 let keysym = parse_keysym(&key_entry, "key")?;
222
223 keys.push(KeyPress { modifiers, keysym });
224 }
225 Ok(keys)
226 } else {
227 let modifiers = parse_modifiers(kb_table, "modifiers", modkey)?;
228 let keysym = parse_keysym(kb_table, "key")?;
229
230 Ok(vec![KeyPress { modifiers, keysym }])
231 }
232 }
233
234 fn parse_modifiers(
235 table: &Table,
236 field: &str,
237 modkey: KeyButMask,
238 ) -> Result<Vec<KeyButMask>, ConfigError> {
239 let mods_table: Table = get_table_field(table, field)?;
240 let mut modifiers = Vec::new();
241
242 for i in 1..=mods_table
243 .len()
244 .map_err(|e| ConfigError::LuaError(format!("Failed to get modifiers length: {}", e)))?
245 {
246 let mod_str: String = mods_table.get(i).map_err(|e| {
247 ConfigError::LuaError(format!("Failed to get modifier at index {}: {}", i, e))
248 })?;
249
250 let modifier = if mod_str == "Mod" {
251 modkey
252 } else {
253 parse_modkey_string(&mod_str)?
254 };
255
256 modifiers.push(modifier);
257 }
258
259 Ok(modifiers)
260 }
261
262 fn parse_keysym(table: &Table, field: &str) -> Result<Keysym, ConfigError> {
263 let key_str: String = get_table_field(table, field)?;
264 string_to_keysym(&key_str)
265 }
266
267 fn string_to_keysym(s: &str) -> Result<Keysym, ConfigError> {
268 let keysym = match s {
269 "Return" => keysyms::XK_RETURN,
270 "Q" => keysyms::XK_Q,
271 "Escape" => keysyms::XK_ESCAPE,
272 "Space" => keysyms::XK_SPACE,
273 "Tab" => keysyms::XK_TAB,
274 "Backspace" => keysyms::XK_BACKSPACE,
275 "Delete" => keysyms::XK_DELETE,
276 "F1" => keysyms::XK_F1,
277 "F2" => keysyms::XK_F2,
278 "F3" => keysyms::XK_F3,
279 "F4" => keysyms::XK_F4,
280 "F5" => keysyms::XK_F5,
281 "F6" => keysyms::XK_F6,
282 "F7" => keysyms::XK_F7,
283 "F8" => keysyms::XK_F8,
284 "F9" => keysyms::XK_F9,
285 "F10" => keysyms::XK_F10,
286 "F11" => keysyms::XK_F11,
287 "F12" => keysyms::XK_F12,
288 "A" => keysyms::XK_A,
289 "B" => keysyms::XK_B,
290 "C" => keysyms::XK_C,
291 "D" => keysyms::XK_D,
292 "E" => keysyms::XK_E,
293 "F" => keysyms::XK_F,
294 "G" => keysyms::XK_G,
295 "H" => keysyms::XK_H,
296 "I" => keysyms::XK_I,
297 "J" => keysyms::XK_J,
298 "K" => keysyms::XK_K,
299 "L" => keysyms::XK_L,
300 "M" => keysyms::XK_M,
301 "N" => keysyms::XK_N,
302 "O" => keysyms::XK_O,
303 "P" => keysyms::XK_P,
304 "R" => keysyms::XK_R,
305 "S" => keysyms::XK_S,
306 "T" => keysyms::XK_T,
307 "U" => keysyms::XK_U,
308 "V" => keysyms::XK_V,
309 "W" => keysyms::XK_W,
310 "X" => keysyms::XK_X,
311 "Y" => keysyms::XK_Y,
312 "Z" => keysyms::XK_Z,
313 "0" => keysyms::XK_0,
314 "1" => keysyms::XK_1,
315 "2" => keysyms::XK_2,
316 "3" => keysyms::XK_3,
317 "4" => keysyms::XK_4,
318 "5" => keysyms::XK_5,
319 "6" => keysyms::XK_6,
320 "7" => keysyms::XK_7,
321 "8" => keysyms::XK_8,
322 "9" => keysyms::XK_9,
323 "Left" => keysyms::XK_LEFT,
324 "Right" => keysyms::XK_RIGHT,
325 "Up" => keysyms::XK_UP,
326 "Down" => keysyms::XK_DOWN,
327 "Home" => keysyms::XK_HOME,
328 "End" => keysyms::XK_END,
329 "PageUp" => keysyms::XK_PAGE_UP,
330 "PageDown" => keysyms::XK_PAGE_DOWN,
331 "Insert" => keysyms::XK_INSERT,
332 "Minus" => keysyms::XK_MINUS,
333 "Equal" => keysyms::XK_EQUAL,
334 "BracketLeft" => keysyms::XK_LEFT_BRACKET,
335 "BracketRight" => keysyms::XK_RIGHT_BRACKET,
336 "Semicolon" => keysyms::XK_SEMICOLON,
337 "Apostrophe" => keysyms::XK_APOSTROPHE,
338 "Grave" => keysyms::XK_GRAVE,
339 "Backslash" => keysyms::XK_BACKSLASH,
340 "Comma" => keysyms::XK_COMMA,
341 "Period" => keysyms::XK_PERIOD,
342 "Slash" => keysyms::XK_SLASH,
343 "AudioRaiseVolume" => keysyms::XF86_AUDIO_RAISE_VOLUME,
344 "AudioLowerVolume" => keysyms::XF86_AUDIO_LOWER_VOLUME,
345 "AudioMute" => keysyms::XF86_AUDIO_MUTE,
346 "MonBrightnessUp" => keysyms::XF86_MON_BRIGHTNESS_UP,
347 "MonBrightnessDown" => keysyms::XF86_MON_BRIGHTNESS_DOWN,
348 _ => return Err(ConfigError::UnknownKey(s.to_string())),
349 };
350
351 Ok(keysym)
352 }
353
354 fn parse_key_action(kb_table: &Table) -> Result<KeyAction, ConfigError> {
355 let action_str: String = get_table_field(kb_table, "action")?;
356 string_to_key_action(&action_str)
357 }
358
359 fn string_to_key_action(s: &str) -> Result<KeyAction, ConfigError> {
360 let action = match s {
361 "Spawn" => KeyAction::Spawn,
362 "KillClient" => KeyAction::KillClient,
363 "FocusStack" => KeyAction::FocusStack,
364 "FocusDirection" => KeyAction::FocusDirection,
365 "SwapDirection" => KeyAction::SwapDirection,
366 "Quit" => KeyAction::Quit,
367 "Restart" => KeyAction::Restart,
368 "Recompile" => KeyAction::Recompile,
369 "ViewTag" => KeyAction::ViewTag,
370 "ToggleGaps" => KeyAction::ToggleGaps,
371 "ToggleFullScreen" => KeyAction::ToggleFullScreen,
372 "ToggleFloating" => KeyAction::ToggleFloating,
373 "ChangeLayout" => KeyAction::ChangeLayout,
374 "CycleLayout" => KeyAction::CycleLayout,
375 "MoveToTag" => KeyAction::MoveToTag,
376 "FocusMonitor" => KeyAction::FocusMonitor,
377 "SmartMoveWin" => KeyAction::SmartMoveWin,
378 "ExchangeClient" => KeyAction::ExchangeClient,
379 "ShowKeybindOverlay" => KeyAction::ShowKeybindOverlay,
380 "None" => KeyAction::None,
381 _ => return Err(ConfigError::UnknownAction(s.to_string())),
382 };
383
384 Ok(action)
385 }
386
387 fn parse_arg(kb_table: &Table) -> Result<Arg, ConfigError> {
388 let arg_result: Result<Value, _> = kb_table.get("arg");
389
390 match arg_result {
391 Ok(Value::Nil) | Err(_) => Ok(Arg::None),
392 Ok(Value::String(s)) => {
393 let s = s
394 .to_str()
395 .map_err(|e| ConfigError::LuaError(format!("Invalid UTF-8 in arg: {}", e)))?;
396 Ok(Arg::Str(s.to_string()))
397 }
398 Ok(Value::Integer(i)) => Ok(Arg::Int(i as i32)),
399 Ok(Value::Number(n)) => Ok(Arg::Int(n as i32)),
400 Ok(Value::Table(t)) => {
401 let mut arr = Vec::new();
402 for i in 1..=t.len().map_err(|e| {
403 ConfigError::LuaError(format!("Failed to get arg array length: {}", e))
404 })? {
405 let item: String = t.get(i).map_err(|e| {
406 ConfigError::LuaError(format!(
407 "Failed to get arg array item at index {}: {}",
408 i, e
409 ))
410 })?;
411 arr.push(item);
412 }
413 Ok(Arg::Array(arr))
414 }
415 Ok(_) => Err(ConfigError::LuaError(
416 "Arg must be nil, string, number, or array".to_string(),
417 )),
418 }
419 }
420
421 fn parse_status_blocks(config: &Table) -> Result<Vec<BlockConfig>, ConfigError> {
422 let blocks_table: Table = get_table_field(config, "status_blocks")?;
423 let mut blocks = Vec::new();
424
425 for i in 1..=blocks_table
426 .len()
427 .map_err(|e| ConfigError::LuaError(format!("Failed to get status_blocks length: {}", e)))?
428 {
429 let block_table: Table = blocks_table.get(i).map_err(|e| {
430 ConfigError::LuaError(format!("Failed to get status_block at index {}: {}", i, e))
431 })?;
432
433 let format: String = get_table_field(&block_table, "format")?;
434 let command_str: String = get_table_field(&block_table, "command")?;
435
436 let interval_secs: u64 = {
437 let value: Value = block_table.get("interval_secs").map_err(|e| {
438 ConfigError::LuaError(format!("Failed to get interval_secs: {}", e))
439 })?;
440 match value {
441 Value::Integer(i) => i as u64,
442 Value::Number(n) => n as u64,
443 _ => {
444 return Err(ConfigError::LuaError(
445 "interval_secs must be a number".to_string(),
446 ));
447 }
448 }
449 };
450
451 let color: u32 = parse_color(&block_table, "color")?;
452 let underline: bool = get_table_field(&block_table, "underline")?;
453
454 let command = match command_str.as_str() {
455 "DateTime" => {
456 let fmt: String = get_table_field(&block_table, "command_arg")?;
457 BlockCommand::DateTime(fmt)
458 }
459 "Shell" => {
460 let cmd: String = get_table_field(&block_table, "command_arg")?;
461 BlockCommand::Shell(cmd)
462 }
463 "Ram" => BlockCommand::Ram,
464 "Static" => {
465 let text_result: Result<String, _> = block_table.get("command_arg");
466 let text = text_result.unwrap_or_default();
467 BlockCommand::Static(text)
468 }
469 "Battery" => {
470 let formats_table: Table = get_table_field(&block_table, "battery_formats")?;
471 let format_charging: String = get_table_field(&formats_table, "charging")?;
472 let format_discharging: String = get_table_field(&formats_table, "discharging")?;
473 let format_full: String = get_table_field(&formats_table, "full")?;
474
475 BlockCommand::Battery {
476 format_charging,
477 format_discharging,
478 format_full,
479 }
480 }
481 _ => return Err(ConfigError::UnknownBlockCommand(command_str)),
482 };
483
484 blocks.push(BlockConfig {
485 format,
486 command,
487 interval_secs,
488 color,
489 underline,
490 });
491 }
492
493 Ok(blocks)
494 }
495
496 fn parse_color_scheme(config: &Table, field: &str) -> Result<ColorScheme, ConfigError> {
497 let scheme_table: Table = get_table_field(config, field)?;
498
499 let foreground = parse_color(&scheme_table, "foreground")?;
500 let background = parse_color(&scheme_table, "background")?;
501 let underline = parse_color(&scheme_table, "underline")?;
502
503 Ok(ColorScheme {
504 foreground,
505 background,
506 underline,
507 })
508 }
509
510 fn parse_autostart(config: &Table) -> Result<Vec<String>, ConfigError> {
511 let autostart_result: Result<Table, _> = config.get("autostart");
512
513 match autostart_result {
514 Ok(autostart_table) => {
515 let mut autostart = Vec::new();
516
517 for i in 1..=autostart_table.len().map_err(|e| {
518 ConfigError::LuaError(format!("Failed to get autostart length: {}", e))
519 })? {
520 let cmd: String = autostart_table.get(i).map_err(|e| {
521 ConfigError::LuaError(format!(
522 "Failed to get autostart command at index {}: {}",
523 i, e
524 ))
525 })?;
526 autostart.push(cmd);
527 }
528
529 Ok(autostart)
530 }
531 Err(_) => Ok(Vec::new()),
532 }
533 }
534
535 #[cfg(test)]
536 mod tests {
537 use super::*;
538
539 #[test]
540 fn test_parse_minimal_lua_config() {
541 let config_str = r#"
542 return {
543 border_width = 2,
544 border_focused = 0x6dade3,
545 border_unfocused = 0xbbbbbb,
546 font = "monospace:style=Bold:size=10",
547
548 gaps_enabled = true,
549 gap_inner_horizontal = 5,
550 gap_inner_vertical = 5,
551 gap_outer_horizontal = 5,
552 gap_outer_vertical = 5,
553
554 modkey = "Mod4",
555 terminal = "st",
556
557 tags = {"1", "2", "3"},
558
559 keybindings = {
560 {modifiers = {"Mod4"}, key = "Return", action = "Spawn", arg = "st"},
561 {modifiers = {"Mod4"}, key = "Q", action = "KillClient"},
562 },
563
564 status_blocks = {
565 {format = "{}", command = "DateTime", command_arg = "%H:%M", interval_secs = 1, color = 0xffffff, underline = true},
566 },
567
568 scheme_normal = {foreground = 0xffffff, background = 0x000000, underline = 0x444444},
569 scheme_occupied = {foreground = 0xffffff, background = 0x000000, underline = 0x444444},
570 scheme_selected = {foreground = 0xffffff, background = 0x000000, underline = 0x444444},
571
572 autostart = {},
573 }
574 "#;
575
576 let config = parse_lua_config(config_str, None).expect("Failed to parse config");
577
578 assert_eq!(config.border_width, 2);
579 assert_eq!(config.border_focused, 0x6dade3);
580 assert_eq!(config.terminal, "st");
581 assert_eq!(config.tags.len(), 3);
582 assert_eq!(config.keybindings.len(), 2);
583 assert_eq!(config.status_blocks.len(), 1);
584 assert!(config.gaps_enabled);
585 }
586 }