tony / oxwm

Branch: 8a5cf95
Switch branches/tags
master
tonybtw Updated error handling in lua api, and configured restart correctly with super shift r keybind. also handled bar redraw correctly. 27a77c7 2025-11-13
721 lines · 31.6 KB Raw Blame History
1 use mlua::{Lua, Table, Value};
2 use std::cell::RefCell;
3 use std::rc::Rc;
4
5 use crate::bar::BlockConfig;
6 use crate::errors::ConfigError;
7 use crate::keyboard::handlers::{Arg, KeyAction, KeyBinding, KeyPress};
8 use crate::keyboard::keysyms::{self, Keysym};
9 use crate::ColorScheme;
10 use x11rb::protocol::xproto::KeyButMask;
11
12 #[derive(Clone)]
13 pub struct ConfigBuilder {
14 pub border_width: u32,
15 pub border_focused: u32,
16 pub border_unfocused: u32,
17 pub font: String,
18 pub gaps_enabled: bool,
19 pub gap_inner_horizontal: u32,
20 pub gap_inner_vertical: u32,
21 pub gap_outer_horizontal: u32,
22 pub gap_outer_vertical: u32,
23 pub terminal: String,
24 pub modkey: KeyButMask,
25 pub tags: Vec<String>,
26 pub layout_symbols: Vec<crate::LayoutSymbolOverride>,
27 pub keybindings: Vec<KeyBinding>,
28 pub status_blocks: Vec<BlockConfig>,
29 pub scheme_normal: ColorScheme,
30 pub scheme_occupied: ColorScheme,
31 pub scheme_selected: ColorScheme,
32 pub autostart: Vec<String>,
33 }
34
35 impl Default for ConfigBuilder {
36 fn default() -> Self {
37 Self {
38 border_width: 2,
39 border_focused: 0x6dade3,
40 border_unfocused: 0xbbbbbb,
41 font: "monospace:style=Bold:size=10".to_string(),
42 gaps_enabled: true,
43 gap_inner_horizontal: 5,
44 gap_inner_vertical: 5,
45 gap_outer_horizontal: 5,
46 gap_outer_vertical: 5,
47 terminal: "st".to_string(),
48 modkey: KeyButMask::MOD4,
49 tags: vec!["1".into(), "2".into(), "3".into()],
50 layout_symbols: Vec::new(),
51 keybindings: Vec::new(),
52 status_blocks: Vec::new(),
53 scheme_normal: ColorScheme {
54 foreground: 0xffffff,
55 background: 0x000000,
56 underline: 0x444444,
57 },
58 scheme_occupied: ColorScheme {
59 foreground: 0xffffff,
60 background: 0x000000,
61 underline: 0x444444,
62 },
63 scheme_selected: ColorScheme {
64 foreground: 0xffffff,
65 background: 0x000000,
66 underline: 0x444444,
67 },
68 autostart: Vec::new(),
69 }
70 }
71 }
72
73 type SharedBuilder = Rc<RefCell<ConfigBuilder>>;
74
75 pub fn register_api(lua: &Lua) -> Result<SharedBuilder, ConfigError> {
76 let builder = Rc::new(RefCell::new(ConfigBuilder::default()));
77
78 let oxwm_table = lua.create_table()
79 .map_err(|e| ConfigError::LuaError(format!("Failed to create oxwm table: {}", e)))?;
80
81 register_spawn(&lua, &oxwm_table, builder.clone())?;
82 register_key_module(&lua, &oxwm_table, builder.clone())?;
83 register_gaps_module(&lua, &oxwm_table, builder.clone())?;
84 register_border_module(&lua, &oxwm_table, builder.clone())?;
85 register_client_module(&lua, &oxwm_table)?;
86 register_layout_module(&lua, &oxwm_table)?;
87 register_tag_module(&lua, &oxwm_table)?;
88 register_bar_module(&lua, &oxwm_table, builder.clone())?;
89 register_misc(&lua, &oxwm_table, builder.clone())?;
90
91 lua.globals().set("oxwm", oxwm_table)
92 .map_err(|e| ConfigError::LuaError(format!("Failed to set oxwm global: {}", e)))?;
93
94 Ok(builder)
95 }
96
97 fn register_spawn(lua: &Lua, parent: &Table, _builder: SharedBuilder) -> Result<(), ConfigError> {
98 let spawn = lua.create_function(|lua, cmd: Value| {
99 create_action_table(lua, "Spawn", cmd)
100 }).map_err(|e| ConfigError::LuaError(format!("Failed to create spawn: {}", e)))?;
101 parent.set("spawn", spawn)
102 .map_err(|e| ConfigError::LuaError(format!("Failed to set spawn: {}", e)))?;
103 Ok(())
104 }
105
106 fn register_key_module(lua: &Lua, parent: &Table, builder: SharedBuilder) -> Result<(), ConfigError> {
107 let key_table = lua.create_table()
108 .map_err(|e| ConfigError::LuaError(format!("Failed to create key table: {}", e)))?;
109
110 let builder_clone = builder.clone();
111 let bind = lua.create_function(move |lua, (mods, key, action): (Value, String, Value)| {
112 let modifiers = parse_modifiers_value(lua, mods)?;
113 let keysym = parse_keysym(&key)?;
114 let (key_action, arg) = parse_action_value(lua, action)?;
115
116 let binding = KeyBinding::single_key(modifiers, keysym, key_action, arg);
117 builder_clone.borrow_mut().keybindings.push(binding);
118
119 Ok(())
120 }).map_err(|e| ConfigError::LuaError(format!("Failed to create bind: {}", e)))?;
121
122 let builder_clone = builder.clone();
123 let chord = lua.create_function(move |lua, (keys, action): (Table, Value)| {
124 let mut key_presses = Vec::new();
125
126 for i in 1..=keys.len()? {
127 let key_spec: Table = keys.get(i)?;
128 let mods: Value = key_spec.get(1)?;
129 let key: String = key_spec.get(2)?;
130
131 let modifiers = parse_modifiers_value(lua, mods)?;
132 let keysym = parse_keysym(&key)?;
133
134 key_presses.push(KeyPress { modifiers, keysym });
135 }
136
137 let (key_action, arg) = parse_action_value(lua, action)?;
138 let binding = KeyBinding::new(key_presses, key_action, arg);
139 builder_clone.borrow_mut().keybindings.push(binding);
140
141 Ok(())
142 }).map_err(|e| ConfigError::LuaError(format!("Failed to create chord: {}", e)))?;
143
144 key_table.set("bind", bind)
145 .map_err(|e| ConfigError::LuaError(format!("Failed to set bind: {}", e)))?;
146 key_table.set("chord", chord)
147 .map_err(|e| ConfigError::LuaError(format!("Failed to set chord: {}", e)))?;
148 parent.set("key", key_table)
149 .map_err(|e| ConfigError::LuaError(format!("Failed to set key: {}", e)))?;
150 Ok(())
151 }
152
153 fn register_gaps_module(lua: &Lua, parent: &Table, builder: SharedBuilder) -> Result<(), ConfigError> {
154 let gaps_table = lua.create_table()
155 .map_err(|e| ConfigError::LuaError(format!("Failed to create gaps table: {}", e)))?;
156
157 let builder_clone = builder.clone();
158 let set_enabled = lua.create_function(move |_, enabled: bool| {
159 builder_clone.borrow_mut().gaps_enabled = enabled;
160 Ok(())
161 }).map_err(|e| ConfigError::LuaError(format!("Failed to create set_enabled: {}", e)))?;
162
163 let builder_clone = builder.clone();
164 let enable = lua.create_function(move |_, ()| {
165 builder_clone.borrow_mut().gaps_enabled = true;
166 Ok(())
167 }).map_err(|e| ConfigError::LuaError(format!("Failed to create enable: {}", e)))?;
168
169 let builder_clone = builder.clone();
170 let disable = lua.create_function(move |_, ()| {
171 builder_clone.borrow_mut().gaps_enabled = false;
172 Ok(())
173 }).map_err(|e| ConfigError::LuaError(format!("Failed to create disable: {}", e)))?;
174
175 let builder_clone = builder.clone();
176 let set_inner = lua.create_function(move |_, (h, v): (u32, u32)| {
177 let mut b = builder_clone.borrow_mut();
178 b.gap_inner_horizontal = h;
179 b.gap_inner_vertical = v;
180 Ok(())
181 }).map_err(|e| ConfigError::LuaError(format!("Failed to create set_inner: {}", e)))?;
182
183 let builder_clone = builder.clone();
184 let set_outer = lua.create_function(move |_, (h, v): (u32, u32)| {
185 let mut b = builder_clone.borrow_mut();
186 b.gap_outer_horizontal = h;
187 b.gap_outer_vertical = v;
188 Ok(())
189 }).map_err(|e| ConfigError::LuaError(format!("Failed to create set_outer: {}", e)))?;
190
191 gaps_table.set("set_enabled", set_enabled)
192 .map_err(|e| ConfigError::LuaError(format!("Failed to set set_enabled: {}", e)))?;
193 gaps_table.set("enable", enable)
194 .map_err(|e| ConfigError::LuaError(format!("Failed to set enable: {}", e)))?;
195 gaps_table.set("disable", disable)
196 .map_err(|e| ConfigError::LuaError(format!("Failed to set disable: {}", e)))?;
197 gaps_table.set("set_inner", set_inner)
198 .map_err(|e| ConfigError::LuaError(format!("Failed to set set_inner: {}", e)))?;
199 gaps_table.set("set_outer", set_outer)
200 .map_err(|e| ConfigError::LuaError(format!("Failed to set set_outer: {}", e)))?;
201 parent.set("gaps", gaps_table)
202 .map_err(|e| ConfigError::LuaError(format!("Failed to set gaps: {}", e)))?;
203 Ok(())
204 }
205
206 fn register_border_module(lua: &Lua, parent: &Table, builder: SharedBuilder) -> Result<(), ConfigError> {
207 let border_table = lua.create_table()
208 .map_err(|e| ConfigError::LuaError(format!("Failed to create border table: {}", e)))?;
209
210 let builder_clone = builder.clone();
211 let set_width = lua.create_function(move |_, width: u32| {
212 builder_clone.borrow_mut().border_width = width;
213 Ok(())
214 }).map_err(|e| ConfigError::LuaError(format!("Failed to create set_width: {}", e)))?;
215
216 let builder_clone = builder.clone();
217 let set_focused_color = lua.create_function(move |_, color: Value| {
218 let color_u32 = parse_color_value(color)?;
219 builder_clone.borrow_mut().border_focused = color_u32;
220 Ok(())
221 }).map_err(|e| ConfigError::LuaError(format!("Failed to create set_focused_color: {}", e)))?;
222
223 let builder_clone = builder.clone();
224 let set_unfocused_color = lua.create_function(move |_, color: Value| {
225 let color_u32 = parse_color_value(color)?;
226 builder_clone.borrow_mut().border_unfocused = color_u32;
227 Ok(())
228 }).map_err(|e| ConfigError::LuaError(format!("Failed to create set_unfocused_color: {}", e)))?;
229
230 border_table.set("set_width", set_width)
231 .map_err(|e| ConfigError::LuaError(format!("Failed to set set_width: {}", e)))?;
232 border_table.set("set_focused_color", set_focused_color)
233 .map_err(|e| ConfigError::LuaError(format!("Failed to set set_focused_color: {}", e)))?;
234 border_table.set("set_unfocused_color", set_unfocused_color)
235 .map_err(|e| ConfigError::LuaError(format!("Failed to set set_unfocused_color: {}", e)))?;
236 parent.set("border", border_table)
237 .map_err(|e| ConfigError::LuaError(format!("Failed to set border: {}", e)))?;
238 Ok(())
239 }
240
241 fn register_client_module(lua: &Lua, parent: &Table) -> Result<(), ConfigError> {
242 let client_table = lua.create_table()
243 .map_err(|e| ConfigError::LuaError(format!("Failed to create client table: {}", e)))?;
244
245 let kill = lua.create_function(|lua, ()| {
246 create_action_table(lua, "KillClient", Value::Nil)
247 }).map_err(|e| ConfigError::LuaError(format!("Failed to create kill: {}", e)))?;
248
249 let toggle_fullscreen = lua.create_function(|lua, ()| {
250 create_action_table(lua, "ToggleFullScreen", Value::Nil)
251 }).map_err(|e| ConfigError::LuaError(format!("Failed to create toggle_fullscreen: {}", e)))?;
252
253 let toggle_floating = lua.create_function(|lua, ()| {
254 create_action_table(lua, "ToggleFloating", Value::Nil)
255 }).map_err(|e| ConfigError::LuaError(format!("Failed to create toggle_floating: {}", e)))?;
256
257 let focus_stack = lua.create_function(|lua, dir: i32| {
258 create_action_table(lua, "FocusStack", Value::Integer(dir as i64))
259 }).map_err(|e| ConfigError::LuaError(format!("Failed to create focus_stack: {}", e)))?;
260
261 let focus_direction = lua.create_function(|lua, dir: String| {
262 let dir_int = direction_string_to_int(&dir)?;
263 create_action_table(lua, "FocusDirection", Value::Integer(dir_int))
264 }).map_err(|e| ConfigError::LuaError(format!("Failed to create focus_direction: {}", e)))?;
265
266 let swap_direction = lua.create_function(|lua, dir: String| {
267 let dir_int = direction_string_to_int(&dir)?;
268 create_action_table(lua, "SwapDirection", Value::Integer(dir_int))
269 }).map_err(|e| ConfigError::LuaError(format!("Failed to create swap_direction: {}", e)))?;
270
271 let smart_move = lua.create_function(|lua, dir: String| {
272 let dir_int = direction_string_to_int(&dir)?;
273 create_action_table(lua, "SmartMoveWin", Value::Integer(dir_int))
274 }).map_err(|e| ConfigError::LuaError(format!("Failed to create smart_move: {}", e)))?;
275
276 let exchange = lua.create_function(|lua, ()| {
277 create_action_table(lua, "ExchangeClient", Value::Nil)
278 }).map_err(|e| ConfigError::LuaError(format!("Failed to create exchange: {}", e)))?;
279
280 client_table.set("kill", kill)
281 .map_err(|e| ConfigError::LuaError(format!("Failed to set kill: {}", e)))?;
282 client_table.set("toggle_fullscreen", toggle_fullscreen)
283 .map_err(|e| ConfigError::LuaError(format!("Failed to set toggle_fullscreen: {}", e)))?;
284 client_table.set("toggle_floating", toggle_floating)
285 .map_err(|e| ConfigError::LuaError(format!("Failed to set toggle_floating: {}", e)))?;
286 client_table.set("focus_stack", focus_stack)
287 .map_err(|e| ConfigError::LuaError(format!("Failed to set focus_stack: {}", e)))?;
288 client_table.set("focus_direction", focus_direction)
289 .map_err(|e| ConfigError::LuaError(format!("Failed to set focus_direction: {}", e)))?;
290 client_table.set("swap_direction", swap_direction)
291 .map_err(|e| ConfigError::LuaError(format!("Failed to set swap_direction: {}", e)))?;
292 client_table.set("smart_move", smart_move)
293 .map_err(|e| ConfigError::LuaError(format!("Failed to set smart_move: {}", e)))?;
294 client_table.set("exchange", exchange)
295 .map_err(|e| ConfigError::LuaError(format!("Failed to set exchange: {}", e)))?;
296
297 parent.set("client", client_table)
298 .map_err(|e| ConfigError::LuaError(format!("Failed to set client: {}", e)))?;
299 Ok(())
300 }
301
302 fn register_layout_module(lua: &Lua, parent: &Table) -> Result<(), ConfigError> {
303 let layout_table = lua.create_table()
304 .map_err(|e| ConfigError::LuaError(format!("Failed to create layout table: {}", e)))?;
305
306 let cycle = lua.create_function(|lua, ()| {
307 create_action_table(lua, "CycleLayout", Value::Nil)
308 }).map_err(|e| ConfigError::LuaError(format!("Failed to create cycle: {}", e)))?;
309
310 let set = lua.create_function(|lua, name: String| {
311 create_action_table(lua, "ChangeLayout", Value::String(lua.create_string(&name)?))
312 }).map_err(|e| ConfigError::LuaError(format!("Failed to create set: {}", e)))?;
313
314 layout_table.set("cycle", cycle)
315 .map_err(|e| ConfigError::LuaError(format!("Failed to set cycle: {}", e)))?;
316 layout_table.set("set", set)
317 .map_err(|e| ConfigError::LuaError(format!("Failed to set set: {}", e)))?;
318 parent.set("layout", layout_table)
319 .map_err(|e| ConfigError::LuaError(format!("Failed to set layout: {}", e)))?;
320 Ok(())
321 }
322
323 fn register_tag_module(lua: &Lua, parent: &Table) -> Result<(), ConfigError> {
324 let tag_table = lua.create_table()
325 .map_err(|e| ConfigError::LuaError(format!("Failed to create tag table: {}", e)))?;
326
327 let view = lua.create_function(|lua, idx: i32| {
328 create_action_table(lua, "ViewTag", Value::Integer(idx as i64))
329 }).map_err(|e| ConfigError::LuaError(format!("Failed to create view: {}", e)))?;
330
331 let move_to = lua.create_function(|lua, idx: i32| {
332 create_action_table(lua, "MoveToTag", Value::Integer(idx as i64))
333 }).map_err(|e| ConfigError::LuaError(format!("Failed to create move_to: {}", e)))?;
334
335 tag_table.set("view", view)
336 .map_err(|e| ConfigError::LuaError(format!("Failed to set view: {}", e)))?;
337 tag_table.set("move_to", move_to)
338 .map_err(|e| ConfigError::LuaError(format!("Failed to set move_to: {}", e)))?;
339 parent.set("tag", tag_table)
340 .map_err(|e| ConfigError::LuaError(format!("Failed to set tag: {}", e)))?;
341 Ok(())
342 }
343
344 fn register_bar_module(lua: &Lua, parent: &Table, builder: SharedBuilder) -> Result<(), ConfigError> {
345 let bar_table = lua.create_table()
346 .map_err(|e| ConfigError::LuaError(format!("Failed to create bar table: {}", e)))?;
347
348 let builder_clone = builder.clone();
349 let set_font = lua.create_function(move |_, font: String| {
350 builder_clone.borrow_mut().font = font;
351 Ok(())
352 }).map_err(|e| ConfigError::LuaError(format!("Failed to create set_font: {}", e)))?;
353
354 let builder_clone = builder.clone();
355 let add_block = lua.create_function(move |_, (format, command, arg, interval, color, underline): (String, String, Option<Value>, u64, Value, bool)| {
356 use crate::bar::BlockCommand;
357
358 let cmd = match command.as_str() {
359 "DateTime" => {
360 let fmt = arg.and_then(|v| {
361 if let Value::String(s) = v {
362 s.to_str().ok().map(|s| s.to_string())
363 } else {
364 None
365 }
366 }).ok_or_else(|| mlua::Error::RuntimeError("oxwm.bar.add_block: DateTime command requires a format string as the third argument. example: oxwm.bar.add_block(\"\", \"DateTime\", \"%H:%M\", 60, 0xffffff, false)".into()))?;
367 BlockCommand::DateTime(fmt)
368 }
369 "Shell" => {
370 let cmd_str = arg.and_then(|v| {
371 if let Value::String(s) = v {
372 s.to_str().ok().map(|s| s.to_string())
373 } else {
374 None
375 }
376 }).ok_or_else(|| mlua::Error::RuntimeError("oxwm.bar.add_block: Shell command requires a shell command string as the third argument. example: oxwm.bar.add_block(\"\", \"Shell\", \"date +%H:%M\", 60, 0xffffff, false)".into()))?;
377 BlockCommand::Shell(cmd_str)
378 }
379 "Ram" => BlockCommand::Ram,
380 "Static" => {
381 let text = arg.and_then(|v| {
382 if let Value::String(s) = v {
383 s.to_str().ok().map(|s| s.to_string())
384 } else {
385 None
386 }
387 }).unwrap_or_default();
388 BlockCommand::Static(text)
389 }
390 "Battery" => {
391 let formats = arg.and_then(|v| {
392 if let Value::Table(t) = v {
393 Some(t)
394 } else {
395 None
396 }
397 }).ok_or_else(|| mlua::Error::RuntimeError("oxwm.bar.add_block: Battery command requires a formats table as the third argument. example: {charging=\"CHR {percentage}%\", discharging=\"BAT {percentage}%\", full=\"FULL\"}".into()))?;
398
399 let charging: String = formats.get("charging")?;
400 let discharging: String = formats.get("discharging")?;
401 let full: String = formats.get("full")?;
402
403 BlockCommand::Battery {
404 format_charging: charging,
405 format_discharging: discharging,
406 format_full: full,
407 }
408 }
409 _ => return Err(mlua::Error::RuntimeError(format!("oxwm.bar.add_block: unknown block command '{}'. valid commands: DateTime, Shell, Ram, Static, Battery", command))),
410 };
411
412 let color_u32 = parse_color_value(color)?;
413
414 let block = crate::bar::BlockConfig {
415 format,
416 command: cmd,
417 interval_secs: interval,
418 color: color_u32,
419 underline,
420 };
421
422 builder_clone.borrow_mut().status_blocks.push(block);
423 Ok(())
424 }).map_err(|e| ConfigError::LuaError(format!("Failed to create add_block: {}", e)))?;
425
426 let builder_clone = builder.clone();
427 let set_scheme_normal = lua.create_function(move |_, (fg, bg, ul): (Value, Value, Value)| {
428 let foreground = parse_color_value(fg)?;
429 let background = parse_color_value(bg)?;
430 let underline = parse_color_value(ul)?;
431
432 builder_clone.borrow_mut().scheme_normal = ColorScheme {
433 foreground,
434 background,
435 underline,
436 };
437 Ok(())
438 }).map_err(|e| ConfigError::LuaError(format!("Failed to create set_scheme_normal: {}", e)))?;
439
440 let builder_clone = builder.clone();
441 let set_scheme_occupied = lua.create_function(move |_, (fg, bg, ul): (Value, Value, Value)| {
442 let foreground = parse_color_value(fg)?;
443 let background = parse_color_value(bg)?;
444 let underline = parse_color_value(ul)?;
445
446 builder_clone.borrow_mut().scheme_occupied = ColorScheme {
447 foreground,
448 background,
449 underline,
450 };
451 Ok(())
452 }).map_err(|e| ConfigError::LuaError(format!("Failed to create set_scheme_occupied: {}", e)))?;
453
454 let builder_clone = builder.clone();
455 let set_scheme_selected = lua.create_function(move |_, (fg, bg, ul): (Value, Value, Value)| {
456 let foreground = parse_color_value(fg)?;
457 let background = parse_color_value(bg)?;
458 let underline = parse_color_value(ul)?;
459
460 builder_clone.borrow_mut().scheme_selected = ColorScheme {
461 foreground,
462 background,
463 underline,
464 };
465 Ok(())
466 }).map_err(|e| ConfigError::LuaError(format!("Failed to create set_scheme_selected: {}", e)))?;
467
468 bar_table.set("set_font", set_font)
469 .map_err(|e| ConfigError::LuaError(format!("Failed to set set_font: {}", e)))?;
470 bar_table.set("add_block", add_block)
471 .map_err(|e| ConfigError::LuaError(format!("Failed to set add_block: {}", e)))?;
472 bar_table.set("set_scheme_normal", set_scheme_normal)
473 .map_err(|e| ConfigError::LuaError(format!("Failed to set set_scheme_normal: {}", e)))?;
474 bar_table.set("set_scheme_occupied", set_scheme_occupied)
475 .map_err(|e| ConfigError::LuaError(format!("Failed to set set_scheme_occupied: {}", e)))?;
476 bar_table.set("set_scheme_selected", set_scheme_selected)
477 .map_err(|e| ConfigError::LuaError(format!("Failed to set set_scheme_selected: {}", e)))?;
478 parent.set("bar", bar_table)
479 .map_err(|e| ConfigError::LuaError(format!("Failed to set bar: {}", e)))?;
480 Ok(())
481 }
482
483 fn register_misc(lua: &Lua, parent: &Table, builder: SharedBuilder) -> Result<(), ConfigError> {
484 let builder_clone = builder.clone();
485 let set_terminal = lua.create_function(move |_, term: String| {
486 builder_clone.borrow_mut().terminal = term;
487 Ok(())
488 }).map_err(|e| ConfigError::LuaError(format!("Failed to create set_terminal: {}", e)))?;
489
490 let builder_clone = builder.clone();
491 let set_modkey = lua.create_function(move |_, modkey_str: String| {
492 let modkey = parse_modkey_string(&modkey_str)
493 .map_err(|e| mlua::Error::RuntimeError(format!("{}", e)))?;
494 builder_clone.borrow_mut().modkey = modkey;
495 Ok(())
496 }).map_err(|e| ConfigError::LuaError(format!("Failed to create set_modkey: {}", e)))?;
497
498 let builder_clone = builder.clone();
499 let set_tags = lua.create_function(move |_, tags: Vec<String>| {
500 builder_clone.borrow_mut().tags = tags;
501 Ok(())
502 }).map_err(|e| ConfigError::LuaError(format!("Failed to create set_tags: {}", e)))?;
503
504 let quit = lua.create_function(|lua, ()| {
505 create_action_table(lua, "Quit", Value::Nil)
506 }).map_err(|e| ConfigError::LuaError(format!("Failed to create quit: {}", e)))?;
507
508 let restart = lua.create_function(|lua, ()| {
509 create_action_table(lua, "Restart", Value::Nil)
510 }).map_err(|e| ConfigError::LuaError(format!("Failed to create restart: {}", e)))?;
511
512 let recompile = lua.create_function(|lua, ()| {
513 create_action_table(lua, "Recompile", Value::Nil)
514 }).map_err(|e| ConfigError::LuaError(format!("Failed to create recompile: {}", e)))?;
515
516 let toggle_gaps = lua.create_function(|lua, ()| {
517 create_action_table(lua, "ToggleGaps", Value::Nil)
518 }).map_err(|e| ConfigError::LuaError(format!("Failed to create toggle_gaps: {}", e)))?;
519
520 let show_keybinds = lua.create_function(|lua, ()| {
521 create_action_table(lua, "ShowKeybindOverlay", Value::Nil)
522 }).map_err(|e| ConfigError::LuaError(format!("Failed to create show_keybinds: {}", e)))?;
523
524 let focus_monitor = lua.create_function(|lua, idx: i32| {
525 create_action_table(lua, "FocusMonitor", Value::Integer(idx as i64))
526 }).map_err(|e| ConfigError::LuaError(format!("Failed to create focus_monitor: {}", e)))?;
527
528 let builder_clone = builder.clone();
529 let set_layout_symbol = lua.create_function(move |_, (name, symbol): (String, String)| {
530 builder_clone.borrow_mut().layout_symbols.push(crate::LayoutSymbolOverride {
531 name,
532 symbol,
533 });
534 Ok(())
535 }).map_err(|e| ConfigError::LuaError(format!("Failed to create set_layout_symbol: {}", e)))?;
536
537 let builder_clone = builder.clone();
538 let autostart = lua.create_function(move |_, cmd: String| {
539 builder_clone.borrow_mut().autostart.push(cmd);
540 Ok(())
541 }).map_err(|e| ConfigError::LuaError(format!("Failed to create autostart: {}", e)))?;
542
543 parent.set("set_terminal", set_terminal)
544 .map_err(|e| ConfigError::LuaError(format!("Failed to set set_terminal: {}", e)))?;
545 parent.set("set_modkey", set_modkey)
546 .map_err(|e| ConfigError::LuaError(format!("Failed to set set_modkey: {}", e)))?;
547 parent.set("set_tags", set_tags)
548 .map_err(|e| ConfigError::LuaError(format!("Failed to set set_tags: {}", e)))?;
549 parent.set("set_layout_symbol", set_layout_symbol)
550 .map_err(|e| ConfigError::LuaError(format!("Failed to set set_layout_symbol: {}", e)))?;
551 parent.set("autostart", autostart)
552 .map_err(|e| ConfigError::LuaError(format!("Failed to set autostart: {}", e)))?;
553 parent.set("quit", quit)
554 .map_err(|e| ConfigError::LuaError(format!("Failed to set quit: {}", e)))?;
555 parent.set("restart", restart)
556 .map_err(|e| ConfigError::LuaError(format!("Failed to set restart: {}", e)))?;
557 parent.set("recompile", recompile)
558 .map_err(|e| ConfigError::LuaError(format!("Failed to set recompile: {}", e)))?;
559 parent.set("toggle_gaps", toggle_gaps)
560 .map_err(|e| ConfigError::LuaError(format!("Failed to set toggle_gaps: {}", e)))?;
561 parent.set("show_keybinds", show_keybinds)
562 .map_err(|e| ConfigError::LuaError(format!("Failed to set show_keybinds: {}", e)))?;
563 parent.set("focus_monitor", focus_monitor)
564 .map_err(|e| ConfigError::LuaError(format!("Failed to set focus_monitor: {}", e)))?;
565 Ok(())
566 }
567
568 fn parse_modifiers_value(_lua: &Lua, value: Value) -> mlua::Result<Vec<KeyButMask>> {
569 match value {
570 Value::Table(t) => {
571 let mut mods = Vec::new();
572 for i in 1..=t.len()? {
573 let mod_str: String = t.get(i)?;
574 let mask = parse_modkey_string(&mod_str)
575 .map_err(|e| mlua::Error::RuntimeError(format!("oxwm.key.bind: invalid modifier - {}", e)))?;
576 mods.push(mask);
577 }
578 Ok(mods)
579 }
580 Value::String(s) => {
581 let s_str = s.to_str()?;
582 let mask = parse_modkey_string(&s_str)
583 .map_err(|e| mlua::Error::RuntimeError(format!("oxwm.key.bind: invalid modifier - {}", e)))?;
584 Ok(vec![mask])
585 }
586 _ => Err(mlua::Error::RuntimeError(
587 "oxwm.key.bind: first argument must be a table of modifiers like {\"Mod4\"} or {\"Mod4\", \"Shift\"}".into(),
588 )),
589 }
590 }
591
592 fn parse_modkey_string(s: &str) -> Result<KeyButMask, ConfigError> {
593 match s {
594 "Mod1" => Ok(KeyButMask::MOD1),
595 "Mod2" => Ok(KeyButMask::MOD2),
596 "Mod3" => Ok(KeyButMask::MOD3),
597 "Mod4" => Ok(KeyButMask::MOD4),
598 "Mod5" => Ok(KeyButMask::MOD5),
599 "Shift" => Ok(KeyButMask::SHIFT),
600 "Control" => Ok(KeyButMask::CONTROL),
601 _ => Err(ConfigError::InvalidModkey(format!("'{}' is not a valid modifier. Use one of: Mod1, Mod4, Shift, Control", s))),
602 }
603 }
604
605 fn parse_keysym(key: &str) -> mlua::Result<Keysym> {
606 keysyms::keysym_from_str(key)
607 .ok_or_else(|| mlua::Error::RuntimeError(format!("unknown key '{}'. valid keys include: Return, Space, A-Z, 0-9, F1-F12, Left, Right, Up, Down, etc. check oxwm.lua type definitions for the complete list", key)))
608 }
609
610 fn parse_action_value(_lua: &Lua, value: Value) -> mlua::Result<(KeyAction, Arg)> {
611 match value {
612 Value::Function(_) => {
613 Err(mlua::Error::RuntimeError(
614 "action must be a function call, not a function reference. did you forget ()? example: oxwm.spawn('st') not oxwm.spawn".into()
615 ))
616 }
617 Value::Table(t) => {
618 if let Ok(action_name) = t.get::<String>("__action") {
619 let action = string_to_action(&action_name)?;
620 let arg = if let Ok(arg_val) = t.get::<Value>("__arg") {
621 value_to_arg(arg_val)?
622 } else {
623 Arg::None
624 };
625 return Ok((action, arg));
626 }
627
628 Err(mlua::Error::RuntimeError(
629 "action must be a table returned by oxwm functions like oxwm.spawn(), oxwm.client.kill(), oxwm.quit(), etc.".into(),
630 ))
631 }
632 _ => Err(mlua::Error::RuntimeError(
633 "action must be a table returned by oxwm functions like oxwm.spawn(), oxwm.client.kill(), oxwm.quit(), etc.".into(),
634 )),
635 }
636 }
637
638 fn string_to_action(s: &str) -> mlua::Result<KeyAction> {
639 match s {
640 "Spawn" => Ok(KeyAction::Spawn),
641 "KillClient" => Ok(KeyAction::KillClient),
642 "FocusStack" => Ok(KeyAction::FocusStack),
643 "FocusDirection" => Ok(KeyAction::FocusDirection),
644 "SwapDirection" => Ok(KeyAction::SwapDirection),
645 "Quit" => Ok(KeyAction::Quit),
646 "Restart" => Ok(KeyAction::Restart),
647 "Recompile" => Ok(KeyAction::Recompile),
648 "ViewTag" => Ok(KeyAction::ViewTag),
649 "ToggleGaps" => Ok(KeyAction::ToggleGaps),
650 "ToggleFullScreen" => Ok(KeyAction::ToggleFullScreen),
651 "ToggleFloating" => Ok(KeyAction::ToggleFloating),
652 "ChangeLayout" => Ok(KeyAction::ChangeLayout),
653 "CycleLayout" => Ok(KeyAction::CycleLayout),
654 "MoveToTag" => Ok(KeyAction::MoveToTag),
655 "FocusMonitor" => Ok(KeyAction::FocusMonitor),
656 "SmartMoveWin" => Ok(KeyAction::SmartMoveWin),
657 "ExchangeClient" => Ok(KeyAction::ExchangeClient),
658 "ShowKeybindOverlay" => Ok(KeyAction::ShowKeybindOverlay),
659 _ => Err(mlua::Error::RuntimeError(format!("unknown action '{}'. this is an internal error, please report it", s))),
660 }
661 }
662
663 fn value_to_arg(value: Value) -> mlua::Result<Arg> {
664 match value {
665 Value::Nil => Ok(Arg::None),
666 Value::String(s) => Ok(Arg::Str(s.to_str()?.to_string())),
667 Value::Integer(i) => Ok(Arg::Int(i as i32)),
668 Value::Number(n) => Ok(Arg::Int(n as i32)),
669 Value::Table(t) => {
670 let mut arr = Vec::new();
671 for i in 1..=t.len()? {
672 let item: String = t.get(i)?;
673 arr.push(item);
674 }
675 Ok(Arg::Array(arr))
676 }
677 _ => Ok(Arg::None),
678 }
679 }
680
681 fn create_action_table(lua: &Lua, action_name: &str, arg: Value) -> mlua::Result<Table> {
682 let table = lua.create_table()?;
683 table.set("__action", action_name)?;
684 table.set("__arg", arg)?;
685 Ok(table)
686 }
687
688 fn direction_string_to_int(dir: &str) -> mlua::Result<i64> {
689 match dir {
690 "up" => Ok(0),
691 "down" => Ok(1),
692 "left" => Ok(2),
693 "right" => Ok(3),
694 _ => Err(mlua::Error::RuntimeError(
695 format!("invalid direction '{}'. must be one of: up, down, left, right", dir)
696 )),
697 }
698 }
699
700 fn parse_color_value(value: Value) -> mlua::Result<u32> {
701 match value {
702 Value::Integer(i) => Ok(i as u32),
703 Value::Number(n) => Ok(n as u32),
704 Value::String(s) => {
705 let s = s.to_str()?;
706 if s.starts_with('#') {
707 u32::from_str_radix(&s[1..], 16)
708 .map_err(|e| mlua::Error::RuntimeError(format!("invalid hex color '{}': {}. use format like #ff0000 or 0xff0000", s, e)))
709 } else if s.starts_with("0x") {
710 u32::from_str_radix(&s[2..], 16)
711 .map_err(|e| mlua::Error::RuntimeError(format!("invalid hex color '{}': {}. use format like 0xff0000 or #ff0000", s, e)))
712 } else {
713 s.parse::<u32>()
714 .map_err(|e| mlua::Error::RuntimeError(format!("invalid color '{}': {}. use hex format like 0xff0000 or #ff0000", s, e)))
715 }
716 }
717 _ => Err(mlua::Error::RuntimeError(
718 "color must be a number (0xff0000) or string ('#ff0000' or '0xff0000')".into(),
719 )),
720 }
721 }