tony / oxwm

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