tony / oxwm

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