tony / oxwm

Lua Api. Browse files
tonybtw committed 2025-11-12 parent 9817677 commit 89f2203e0a5e15fd0dbf23c1f13c9bc7ea45d064
Showing 15 changed files with 1431 additions and 1699 deletions. UnifiedSplit
+0 −22 Cargo.lock
@@ -23,20 +23,11 @@ version = "1.5.0"
23 source = "registry+https://github.com/rust-lang/crates.io-index" 23 source = "registry+https://github.com/rust-lang/crates.io-index"
24 checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" 24 checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
25 25
26 -[[package]]
27 -name = "base64"
28 -version = "0.21.7"
29 -source = "registry+https://github.com/rust-lang/crates.io-index"
30 -checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
31 -
32 [[package]] 26 [[package]]
33 name = "bitflags" 27 name = "bitflags"
34 version = "2.10.0" 28 version = "2.10.0"
35 source = "registry+https://github.com/rust-lang/crates.io-index" 29 source = "registry+https://github.com/rust-lang/crates.io-index"
36 checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" 30 checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"
37 -dependencies = [
38 - "serde_core",
39 -]
40 31
41 [[package]] 32 [[package]]
42 name = "bstr" 33 name = "bstr"
@@ -312,7 +303,6 @@ dependencies = [
312 "chrono", 303 "chrono",
313 "dirs", 304 "dirs",
314 "mlua", 305 "mlua",
315 - "ron",
316 "serde", 306 "serde",
317 "x11", 307 "x11",
318 "x11rb", 308 "x11rb",
@@ -385,18 +375,6 @@ dependencies = [
385 "thiserror", 375 "thiserror",
386 ] 376 ]
387 377
388 -[[package]]
389 -name = "ron"
390 -version = "0.8.1"
391 -source = "registry+https://github.com/rust-lang/crates.io-index"
392 -checksum = "b91f7eff05f748767f183df4320a63d6936e9c6107d97c9e6bdd9784f4289c94"
393 -dependencies = [
394 - "base64",
395 - "bitflags",
396 - "serde",
397 - "serde_derive",
398 -]
399 -
400 [[package]] 378 [[package]]
401 name = "rustc-hash" 379 name = "rustc-hash"
402 version = "2.1.1" 380 version = "2.1.1"
+0 −1 Cargo.toml
@@ -18,5 +18,4 @@ anyhow = "1"
18 chrono = "0.4" 18 chrono = "0.4"
19 dirs = "5.0" 19 dirs = "5.0"
20 serde = { version = "1.0", features = ["derive"] } 20 serde = { version = "1.0", features = ["derive"] }
21 -ron = "0.8"
22 mlua = { version = "0.10", features = ["lua54", "vendored"] } 21 mlua = { version = "0.10", features = ["lua54", "vendored"] }
+104 −74 readme.org
@@ -30,7 +30,7 @@
30 - [[#license][License]] 30 - [[#license][License]]
31 31
32 * OXWM — DWM but Better (and oxidized) 32 * OXWM — DWM but Better (and oxidized)
33 -A dynamic window manager written in Rust, inspired by dwm but designed to evolve on its own. Configuration is done in Rust source code, ditching the suckless philosophy of *"edit + recompile."*, and instead focusing on lowering friction for users, with sane defaults and no arbitrary elitism enforcing bad variable names and bad file structure topology. 33 +A dynamic window manager written in Rust, inspired by dwm but designed to evolve beyond it. OXWM features a clean, functional Lua API for configuration with hot-reloading support, ditching the suckless philosophy of *"edit + recompile"*. Instead, we focus on lowering friction for users with sane defaults, LSP-powered autocomplete, and instant configuration changes without restarting your X session.
34 34
35 * Installation 35 * Installation
36 ** NixOS (with Flakes) 36 ** NixOS (with Flakes)
@@ -154,27 +154,62 @@ startx
154 If using a display manager (LightDM, GDM, SDDM), OXWM should appear in the session list after installation. 154 If using a display manager (LightDM, GDM, SDDM), OXWM should appear in the session list after installation.
155 155
156 * Configuration 156 * Configuration
157 -OXWM was inspired by dwm, but ditched the suckless philosophy. This philosophy quite literally discourages users from using the software for the sake of 'elitism'. I find that quite nonsensical, so I went ahead and created this project to be user friendly. The configuration is done by editing =~/.config/oxwm/config.lua= and the binary can be reloaded with a hotkey (Super+Shift+R by default). 157 +OXWM uses a clean, functional Lua API for configuration. On first run, a default config is automatically created at =~/.config/oxwm/config.lua=.
158 +
159 +** Quick Example
160 +Here's what the new functional API looks like:
161 +
162 +#+begin_src lua
163 +-- Set basic options
164 +oxwm.set_terminal("st")
165 +oxwm.set_modkey("Mod4")
166 +oxwm.set_tags({ "1", "2", "3", "4", "5", "6", "7", "8", "9" })
167 +
168 +-- Configure borders
169 +oxwm.border.set_width(2)
170 +oxwm.border.set_focused_color("#6dade3")
171 +oxwm.border.set_unfocused_color("#bbbbbb")
172 +
173 +-- Configure gaps
174 +oxwm.gaps.set_enabled(true)
175 +oxwm.gaps.set_inner(5, 5) -- horizontal, vertical
176 +oxwm.gaps.set_outer(5, 5)
177 +
178 +-- Set up keybindings
179 +oxwm.key.bind({ "Mod4" }, "Return", oxwm.spawn("st"))
180 +oxwm.key.bind({ "Mod4" }, "Q", oxwm.client.kill())
181 +oxwm.key.bind({ "Mod4", "Shift" }, "Q", oxwm.quit())
182 +
183 +-- Add status bar blocks
184 +oxwm.bar.add_block("{}", "DateTime", "%H:%M", 60, "#0db9d7", true)
185 +oxwm.bar.add_block("RAM: {used}/{total} GB", "Ram", nil, 5, "#7aa2f7", true)
186 +#+end_src
187 +
188 +** Features
189 +- *Hot-reload*: Changes take effect immediately with =Mod+Shift+R= (no X restart needed)
190 +- *LSP Support*: Full autocomplete and type hints for the API (=oxwm.lua= definitions included)
191 +- *Functional API*: Clean, discoverable functions instead of nested tables
192 +- *No compilation*: Edit and reload instantly
158 193
194 +** Key Configuration Areas
159 Edit =~/.config/oxwm/config.lua= to customize: 195 Edit =~/.config/oxwm/config.lua= to customize:
160 -- Keybindings 196 +- Basic settings (terminal, modkey, tags)
161 -- Colors and appearance 197 +- Borders and colors
162 -- Status bar blocks 198 +- Window gaps
163 -- Gaps and borders 199 +- Status bar (font, blocks, color schemes)
164 -- Terminal and applications 200 +- Keybindings and keychords
201 +- Layout symbols
202 +- Autostart commands
165 203
166 After making changes, reload OXWM with =Mod+Shift+R= 204 After making changes, reload OXWM with =Mod+Shift+R=
167 205
168 -** Migrating from RON 206 +** Creating Your Config
169 -If you have an old RON config (=config.ron=), use the migration tool to automatically convert it: 207 +Generate the default config:
170 -
171 #+begin_src sh 208 #+begin_src sh
172 -oxwm --migrate 209 +oxwm --init
173 -# Or specify a path:
174 -oxwm --migrate ~/.config/oxwm/config.ron
175 #+end_src 210 #+end_src
176 211
177 -This will convert your =config.ron= to =config.lua=, preserving all your settings. Your old config will remain intact for backup. 212 +Or just start OXWM - it will create one automatically on first run.
178 213
179 * Contributing 214 * Contributing
180 When contributing to OXWM: 215 When contributing to OXWM:
@@ -236,9 +271,13 @@ DISPLAY=:1 cargo run
236 * Project Structure 271 * Project Structure
237 #+begin_src sh 272 #+begin_src sh
238 src/ 273 src/
239 -├── main.rs 274 +├── bin/
240 -│ └── main() 275 +│ └── main.rs [Entry point - handles CLI args, config loading, WM init]
241 -│ └── Creates WindowManager and calls .run() 276 +│ ├── main() [Parse args, load config, start WM]
277 +│ ├── load_config() [Lua config loading with auto-init]
278 +│ └── init_config() [Create default config.lua + oxwm.lua]
279 +│
280 +├── lib.rs [Library exports]
242 │ 281 │
243 ├── window_manager.rs [CORE - X11 event handling] 282 ├── window_manager.rs [CORE - X11 event handling]
244 │ ├── struct WindowManager 283 │ ├── struct WindowManager
@@ -248,42 +287,28 @@ src/
248 │ │ ├── layout: Box<dyn Layout> 287 │ │ ├── layout: Box<dyn Layout>
249 │ │ ├── window_tags: HashMap<Window, TagMask> 288 │ │ ├── window_tags: HashMap<Window, TagMask>
250 │ │ ├── selected_tags: TagMask 289 │ │ ├── selected_tags: TagMask
251 -│ │ └── bar: Bar [Status bar] 290 +│ │ └── bars: Vec<Bar> [Status bars (multi-monitor)]
252 │ │ 291 │ │
253 │ ├── new() [Initialize WM, grab root, restore tags, scan windows] 292 │ ├── new() [Initialize WM, grab root, restore tags, scan windows]
254 │ ├── run() [Main event loop with block updates] 293 │ ├── run() [Main event loop with block updates]
255 │ ├── handle_event() [Route X11 events] 294 │ ├── handle_event() [Route X11 events]
256 -│ │ ├── MapRequest → add window, apply layout, update bar, save tag 295 +│ ├── try_reload_config() [Hot-reload Lua config]
257 -│ │ ├── UnmapNotify → remove window, update bar 296 +│ └── ... [Window/tag/focus management]
258 -│ │ ├── DestroyNotify → remove window, update bar
259 -│ │ ├── KeyPress → get action, handle it (includes Restart)
260 -│ │ ├── ButtonPress → handle bar clicks
261 -│ │ └── Expose → redraw bar
262 -│ ├── handle_key_action() [Execute keyboard actions]
263 -│ ├── get_saved_selected_tags() [Restore selected tags from _NET_CURRENT_DESKTOP]
264 -│ ├── save_selected_tags() [Persist selected tags to root window]
265 -│ ├── get_saved_tag() [Restore window tag from _NET_CLIENT_INFO]
266 -│ ├── save_client_tag() [Persist window tag to window property]
267 -│ ├── scan_existing_windows() [Manage windows on startup]
268 -│ ├── remove_window() [Remove from Vec, reapply layout]
269 -│ ├── set_focus() [Focus window, update visuals]
270 -│ ├── cycle_focus() [Move focus to next/prev window]
271 -│ ├── view_tag() [Switch to tag/workspace, update visibility]
272 -│ ├── move_to_tag() [Move window to tag]
273 -│ ├── update_bar() [Calculate occupied tags, redraw bar]
274 -│ ├── update_focus_visuals() [Set border colors]
275 -│ ├── update_window_visibility() [Map/unmap windows based on tags]
276 -│ └── apply_layout() [Position all windows below bar]
277 │ 297 │
278 -├── config.rs [CONFIGURATION - all settings here] 298 +├── config/
279 -│ ├── BORDER_WIDTH, BORDER_FOCUSED, BORDER_UNFOCUSED 299 +│ ├── mod.rs [Config module exports]
280 -│ ├── FONT [XFT font string] 300 +│ ├── lua.rs [Lua config parser - loads and executes config.lua]
281 -│ ├── TAG_COUNT, TAGS [Workspace configuration] 301 +│ └── lua_api.rs [Functional Lua API implementation]
282 -│ ├── TERMINAL, MODKEY 302 +│ ├── register_api() [Set up oxwm.* functions in Lua]
283 -│ ├── ColorScheme [Foreground, background, border colors] 303 +│ ├── register_spawn() [oxwm.spawn()]
284 -│ ├── SCHEME_NORMAL, SCHEME_OCCUPIED, SCHEME_SELECTED 304 +│ ├── register_key_module() [oxwm.key.bind(), oxwm.key.chord()]
285 -│ ├── KEYBINDINGS [All keybinds as const array] 305 +│ ├── register_gaps_module() [oxwm.gaps.*]
286 -│ └── STATUS_BLOCKS [Block configurations with format, command, interval] 306 +│ ├── register_border_module() [oxwm.border.*]
307 +│ ├── register_client_module() [oxwm.client.*]
308 +│ ├── register_layout_module() [oxwm.layout.*]
309 +│ ├── register_tag_module() [oxwm.tag.*]
310 +│ ├── register_bar_module() [oxwm.bar.*]
311 +│ └── register_misc() [oxwm.set_terminal(), etc.]
287 │ 312 │
288 ├── bar/ 313 ├── bar/
289 │ ├── mod.rs [Re-exports: Bar, BlockCommand, BlockConfig] 314 │ ├── mod.rs [Re-exports: Bar, BlockCommand, BlockConfig]
@@ -292,35 +317,46 @@ src/
292 │ │ ├── new() [Create bar X11 window, load font, init blocks] 317 │ │ ├── new() [Create bar X11 window, load font, init blocks]
293 │ │ ├── draw() [Render tags + blocks with underlines] 318 │ │ ├── draw() [Render tags + blocks with underlines]
294 │ │ ├── update_blocks() [Update block content based on intervals] 319 │ │ ├── update_blocks() [Update block content based on intervals]
295 -│ │ ├── handle_click() [Detect which tag was clicked] 320 +│ │ └── handle_click() [Detect which tag was clicked]
296 -│ │ └── invalidate() [Mark bar as needing redraw]
297 │ ├── font.rs 321 │ ├── font.rs
298 │ │ ├── struct Font [XFT font wrapper] 322 │ │ ├── struct Font [XFT font wrapper]
299 -│ │ ├── struct FontDraw [XFT drawing context]
300 │ │ └── draw_text() [Render text with color] 323 │ │ └── draw_text() [Render text with color]
301 │ └── blocks/ 324 │ └── blocks/
302 │ ├── mod.rs [Block trait, BlockConfig, BlockCommand enum] 325 │ ├── mod.rs [Block trait, BlockConfig, BlockCommand enum]
303 │ ├── battery.rs [Battery status block] 326 │ ├── battery.rs [Battery status block]
304 │ ├── datetime.rs [Date/time formatting block] 327 │ ├── datetime.rs [Date/time formatting block]
305 -│ └── shell.rs [Shell command execution block] 328 +│ ├── ram.rs [RAM usage block]
329 +│ ├── shell.rs [Shell command execution block]
330 +│ └── static.rs [Static text block]
306 │ 331 │
307 ├── keyboard/ 332 ├── keyboard/
308 │ ├── mod.rs [Re-exports] 333 │ ├── mod.rs [Re-exports]
309 -│ ├── keycodes.rs [Key constants: Q, J, RETURN, etc] 334 +│ ├── keysyms.rs [X11 keysym constants]
310 │ └── handlers.rs 335 │ └── handlers.rs
311 -│ ├── enum KeyAction [Spawn, KillClient, FocusStack, ViewTag, Restart, etc] 336 +│ ├── enum KeyAction [All keyboard actions]
312 -│ ├── enum Arg [None, Int, Str, Array] 337 +│ ├── enum Arg [Action arguments]
313 -│ ├── struct Key [Keybinding definition] 338 +│ ├── struct KeyBinding [Keybinding + keychord support]
314 -│ ├── setup_keybinds() [Register keys with X11] 339 +│ └── struct KeyPress [Individual key press in chord]
315 -│ └── handle_key_press() [Parse KeyPressEvent → KeyAction] 340 +│
341 +├── layout/
342 +│ ├── mod.rs [Layout trait definition]
343 +│ └── tiling.rs [Tiling layout implementation]
316 │ 344 │
317 -└── layout/ 345 +└── errors.rs [Error types: WmError, ConfigError, etc.]
318 - ├── mod.rs [Layout trait definition] 346 +
319 - └── tiling.rs 347 +templates/
320 - └── TilingLayout::arrange() [Calculate window positions] 348 +├── config.lua [Default config with functional API]
349 +└── oxwm.lua [LSP type definitions for autocomplete]
321 #+end_src 350 #+end_src
322 351
323 * Architecture Notes 352 * Architecture Notes
353 +** Lua Configuration System
354 +OXWM uses mlua to embed a Lua interpreter. The functional API is implemented in =src/config/lua_api.rs=:
355 +- Each API function (e.g., =oxwm.border.set_width()=) is registered as a Lua function
356 +- Functions modify a shared ConfigBuilder that accumulates settings
357 +- When config execution completes, the builder produces the final Config struct
358 +- Type definitions in =templates/oxwm.lua= provide LSP autocomplete and documentation
359 +
324 ** Tag System 360 ** Tag System
325 Tags are implemented as bitmasks (TagMask = u32), allowing windows to belong to multiple tags simultaneously. Each window has an associated TagMask stored in a HashMap. Tags persist across WM restarts using X11 properties (_NET_CURRENT_DESKTOP for selected tags, _NET_CLIENT_INFO for per-window tags). 361 Tags are implemented as bitmasks (TagMask = u32), allowing windows to belong to multiple tags simultaneously. Each window has an associated TagMask stored in a HashMap. Tags persist across WM restarts using X11 properties (_NET_CURRENT_DESKTOP for selected tags, _NET_CLIENT_INFO for per-window tags).
326 362
@@ -330,6 +366,7 @@ The bar uses a performance-optimized approach with a modular block system:
330 - Pre-calculates tag widths on creation 366 - Pre-calculates tag widths on creation
331 - Blocks update independently based on their configured intervals 367 - Blocks update independently based on their configured intervals
332 - Supports custom colors and underline indicators 368 - Supports custom colors and underline indicators
369 +- Color schemes (normal/occupied/selected) control tag appearance
333 - Easily extensible - add new block types in src/bar/blocks/ 370 - Easily extensible - add new block types in src/bar/blocks/
334 371
335 ** Layout System 372 ** Layout System
@@ -345,24 +382,17 @@ The tiling layout divides the screen into a master area (left half) and stack ar
345 - Fullscreen state should be maintained when switching tags 382 - Fullscreen state should be maintained when switching tags
346 - Window should remain fullscreen when returning to its tag 383 - Window should remain fullscreen when returning to its tag
347 384
348 -** PRIORITY Medium [1/4] 385 +** PRIORITY Medium [2/4]
349 - [ ] Add keybindings to increase/decrease window size 386 - [ ] Add keybindings to increase/decrease window size
350 - Master area resize (Mod+H / Mod+L) 387 - Master area resize (Mod+H / Mod+L)
351 - Individual window resize for floating windows 388 - Individual window resize for floating windows
352 -- [ ] Keychords: 389 +- [X] Keychords
353 - - Desired Behaviour: 390 + - Implemented with =oxwm.key.chord()= in the functional API
354 -#+begin_src rust 391 + - Example: =oxwm.key.chord({ { {"Mod4"}, "Space" }, { {}, "T" } }, oxwm.spawn("st"))=
355 -// Keychord: Mod+f, then f (same key twice)
356 -(keys: [
357 - (modifiers: [Mod], key: F),
358 - (modifiers: [], key: F),
359 -], action: Spawn, arg: "repos-dmenu.sh"),
360 -
361 -#+end_src
362 - [X] Fix cursor on hover for bar 392 - [X] Fix cursor on hover for bar
363 - Bar should show pointer cursor on hover 393 - Bar should show pointer cursor on hover
364 - Indicate clickable tag areas 394 - Indicate clickable tag areas
365 -- [ ] Add guess_terminal() function to default config.rs 395 +- [ ] Add auto-detect terminal to default config
366 - Auto-detect available terminal emulator 396 - Auto-detect available terminal emulator
367 - Priority order: st → alacritty → kitty → wezterm → xterm 397 - Priority order: st → alacritty → kitty → wezterm → xterm
368 - Fallback to xterm if none found 398 - Fallback to xterm if none found
+127 −174 resources/test-config.lua
@@ -1,180 +1,133 @@
1 --- OXWM Configuration File (Lua) 1 +---@meta
2 --- Migrated from config.ron 2 +---OXWM Test Configuration File (Lua)
3 --- Edit this file and reload with Mod+Shift+R (no compilation needed!) 3 +---Using the new functional API
4 +---Edit this file and reload with Mod+Alt+R
4 5
5 -local terminal = "st" 6 +---Load type definitions for LSP
6 -local modkey = "Mod4" 7 +---@module 'oxwm'
7 8
8 -- Color palette 9 -- Color palette
9 local colors = { 10 local colors = {
10 - lavender = "#a9b1d6", 11 + lavender = 0xa9b1d6,
11 - light_blue = "#7aa2f7", 12 + light_blue = 0x7aa2f7,
12 - grey = "#bbbbbb", 13 + grey = 0xbbbbbb,
13 - purple = "#ad8ee6", 14 + purple = 0xad8ee6,
14 - cyan = "#0db9d7", 15 + cyan = 0x0db9d7,
15 - bg = "#1a1b26", 16 + bg = 0x1a1b26,
16 - green = "#9ece6a", 17 + green = 0x9ece6a,
17 - red = "#f7768e", 18 + red = 0xf7768e,
18 - fg = "#bbbbbb", 19 + fg = 0xbbbbbb,
19 - blue = "#6dade3", 20 + blue = 0x6dade3,
20 } 21 }
21 22
22 --- Main configuration table 23 +-- Basic settings
23 -return { 24 +oxwm.set_terminal("st")
24 - -- Appearance 25 +oxwm.set_modkey("Mod1")
25 - border_width = 2, 26 +oxwm.set_tags({ "1", "2", "3", "4", "5", "6", "7", "8", "9" })
26 - border_focused = colors.blue, 27 +
27 - border_unfocused = colors.grey, 28 +-- Layout symbol overrides
28 - font = "JetBrainsMono Nerd Font:style=Bold:size=12", 29 +oxwm.set_layout_symbol("tiling", "[T]")
29 - 30 +oxwm.set_layout_symbol("normie", "[F]")
30 - -- Window gaps 31 +
31 - gaps_enabled = true, 32 +-- Border configuration
32 - gap_inner_horizontal = 5, 33 +oxwm.border.set_width(2)
33 - gap_inner_vertical = 5, 34 +oxwm.border.set_focused_color(colors.blue)
34 - gap_outer_horizontal = 5, 35 +oxwm.border.set_unfocused_color(colors.grey)
35 - gap_outer_vertical = 5, 36 +
36 - 37 +-- Gap configuration
37 - -- Basics 38 +oxwm.gaps.set_enabled(true)
38 - modkey = "Mod1", 39 +oxwm.gaps.set_inner(5, 5)
39 - terminal = "st", 40 +oxwm.gaps.set_outer(5, 5)
40 - 41 +
41 - -- Workspace tags 42 +-- Bar configuration
42 - tags = { "1", "2", "3", "4", "5", "6", "7", "8", "9" }, 43 +oxwm.bar.set_font("JetBrainsMono Nerd Font:style=Bold:size=12")
43 - 44 +
44 - -- Layout symbol overrides 45 +-- Bar color schemes (for tag display)
45 - layout_symbols = { 46 +oxwm.bar.set_scheme_normal(colors.fg, colors.bg, 0x444444)
46 - { name = "tiling", symbol = "[T]" }, 47 +oxwm.bar.set_scheme_occupied(colors.cyan, colors.bg, colors.cyan)
47 - { name = "normie", symbol = "[F]" }, 48 +oxwm.bar.set_scheme_selected(colors.cyan, colors.bg, colors.purple)
48 - }, 49 +
49 - 50 +-- Keybindings
50 - -- Keybindings 51 +
51 - keybindings = { 52 +-- Keychord: Mod1+Space then T to spawn terminal
52 - { 53 +oxwm.key.chord({
53 - keys = { 54 + { { "Mod1" }, "Space" },
54 - { modifiers = { "Mod1" }, key = "Space" }, 55 + { {}, "T" }
55 - { modifiers = { }, key = "T" }, 56 +}, oxwm.spawn("st"))
56 - }, 57 +
57 - action = "Spawn", 58 +-- Basic window management
58 - arg = "st" 59 +oxwm.key.bind({ "Mod1" }, "Return", oxwm.spawn("st"))
59 - }, 60 +oxwm.key.bind({ "Mod1" }, "D", oxwm.spawn({ "sh", "-c", "dmenu_run -l 10" }))
60 - { modifiers = { "Mod1" }, key = "Return", action = "Spawn", arg = "st" }, 61 +oxwm.key.bind({ "Mod1" }, "S", oxwm.spawn({ "sh", "-c", "maim -s | xclip -selection clipboard -t image/png" }))
61 - { modifiers = { "Mod1" }, key = "D", action = "Spawn", arg = { "sh", "-c", "dmenu_run -l 10" } }, 62 +oxwm.key.bind({ "Mod1" }, "Q", oxwm.client.kill())
62 - { modifiers = { "Mod1" }, key = "S", action = "Spawn", arg = { "sh", "-c", "maim -s | xclip -selection clipboard -t image/png" } }, 63 +
63 - { modifiers = { "Mod1" }, key = "Q", action = "KillClient" }, 64 +-- Keybind overlay
64 - { modifiers = { "Mod1", "Shift" }, key = "Slash", action = "ShowKeybindOverlay" }, 65 +oxwm.key.bind({ "Mod1", "Shift" }, "Slash", oxwm.show_keybinds())
65 - { modifiers = { "Mod1", "Shift" }, key = "F", action = "ToggleFullScreen" }, 66 +
66 - { modifiers = { "Mod1", "Shift" }, key = "Space", action = "ToggleFloating" }, 67 +-- Client actions
67 - { modifiers = { "Mod1" }, key = "F", action = "ChangeLayout", arg = "normie" }, 68 +oxwm.key.bind({ "Mod1", "Shift" }, "F", oxwm.client.toggle_fullscreen())
68 - { modifiers = { "Mod1" }, key = "C", action = "ChangeLayout", arg = "tiling" }, 69 +oxwm.key.bind({ "Mod1", "Shift" }, "Space", oxwm.client.toggle_floating())
69 - { modifiers = { "Mod1" }, key = "N", action = "CycleLayout" }, 70 +
70 - { modifiers = { "Mod1" }, key = "A", action = "ToggleGaps" }, 71 +-- Layout management
71 - { modifiers = { "Mod1", "Shift" }, key = "Q", action = "Quit" }, 72 +oxwm.key.bind({ "Mod1" }, "F", oxwm.layout.set("normie"))
72 - { modifiers = { "Mod1", "Shift" }, key = "R", action = "Restart" }, 73 +oxwm.key.bind({ "Mod1" }, "C", oxwm.layout.set("tiling"))
73 - { modifiers = { "Mod1" }, key = "H", action = "FocusDirection", arg = 2 }, 74 +oxwm.key.bind({ "Mod1" }, "N", oxwm.layout.cycle())
74 - { modifiers = { "Mod1" }, key = "J", action = "FocusDirection", arg = 1 }, 75 +
75 - { modifiers = { "Mod1" }, key = "K", action = "FocusDirection", arg = 0 }, 76 +-- Gaps toggle
76 - { modifiers = { "Mod1" }, key = "L", action = "FocusDirection", arg = 3 }, 77 +oxwm.key.bind({ "Mod1" }, "A", oxwm.toggle_gaps())
77 - { modifiers = { "Mod1", "Shift" }, key = "H", action = "SwapDirection", arg = 2 }, 78 +
78 - { modifiers = { "Mod1", "Shift" }, key = "J", action = "SwapDirection", arg = 1 }, 79 +-- WM controls
79 - { modifiers = { "Mod1", "Shift" }, key = "K", action = "SwapDirection", arg = 0 }, 80 +oxwm.key.bind({ "Mod1", "Shift" }, "Q", oxwm.quit())
80 - { modifiers = { "Mod1", "Shift" }, key = "L", action = "SwapDirection", arg = 3 }, 81 +oxwm.key.bind({ "Mod1", "Shift" }, "R", oxwm.restart())
81 - { modifiers = { "Mod1" }, key = "1", action = "ViewTag", arg = 0 }, 82 +
82 - { modifiers = { "Mod1" }, key = "2", action = "ViewTag", arg = 1 }, 83 +-- Focus direction (vim keys)
83 - { modifiers = { "Mod1" }, key = "3", action = "ViewTag", arg = 2 }, 84 +oxwm.key.bind({ "Mod1" }, "H", oxwm.client.focus_direction("left"))
84 - { modifiers = { "Mod1" }, key = "4", action = "ViewTag", arg = 3 }, 85 +oxwm.key.bind({ "Mod1" }, "J", oxwm.client.focus_direction("down"))
85 - { modifiers = { "Mod1" }, key = "5", action = "ViewTag", arg = 4 }, 86 +oxwm.key.bind({ "Mod1" }, "K", oxwm.client.focus_direction("up"))
86 - { modifiers = { "Mod1" }, key = "6", action = "ViewTag", arg = 5 }, 87 +oxwm.key.bind({ "Mod1" }, "L", oxwm.client.focus_direction("right"))
87 - { modifiers = { "Mod1" }, key = "7", action = "ViewTag", arg = 6 }, 88 +
88 - { modifiers = { "Mod1" }, key = "8", action = "ViewTag", arg = 7 }, 89 +-- Swap windows in direction
89 - { modifiers = { "Mod1" }, key = "9", action = "ViewTag", arg = 8 }, 90 +oxwm.key.bind({ "Mod1", "Shift" }, "H", oxwm.client.swap_direction("left"))
90 - { modifiers = { "Mod1", "Shift" }, key = "1", action = "MoveToTag", arg = 0 }, 91 +oxwm.key.bind({ "Mod1", "Shift" }, "J", oxwm.client.swap_direction("down"))
91 - { modifiers = { "Mod1", "Shift" }, key = "2", action = "MoveToTag", arg = 1 }, 92 +oxwm.key.bind({ "Mod1", "Shift" }, "K", oxwm.client.swap_direction("up"))
92 - { modifiers = { "Mod1", "Shift" }, key = "3", action = "MoveToTag", arg = 2 }, 93 +oxwm.key.bind({ "Mod1", "Shift" }, "L", oxwm.client.swap_direction("right"))
93 - { modifiers = { "Mod1", "Shift" }, key = "4", action = "MoveToTag", arg = 3 }, 94 +
94 - { modifiers = { "Mod1", "Shift" }, key = "5", action = "MoveToTag", arg = 4 }, 95 +-- Tag viewing
95 - { modifiers = { "Mod1", "Shift" }, key = "6", action = "MoveToTag", arg = 5 }, 96 +oxwm.key.bind({ "Mod1" }, "1", oxwm.tag.view(0))
96 - { modifiers = { "Mod1", "Shift" }, key = "7", action = "MoveToTag", arg = 6 }, 97 +oxwm.key.bind({ "Mod1" }, "2", oxwm.tag.view(1))
97 - { modifiers = { "Mod1", "Shift" }, key = "8", action = "MoveToTag", arg = 7 }, 98 +oxwm.key.bind({ "Mod1" }, "3", oxwm.tag.view(2))
98 - { modifiers = { "Mod1", "Shift" }, key = "9", action = "MoveToTag", arg = 8 }, 99 +oxwm.key.bind({ "Mod1" }, "4", oxwm.tag.view(3))
99 - }, 100 +oxwm.key.bind({ "Mod1" }, "5", oxwm.tag.view(4))
100 - 101 +oxwm.key.bind({ "Mod1" }, "6", oxwm.tag.view(5))
101 - -- Status bar blocks 102 +oxwm.key.bind({ "Mod1" }, "7", oxwm.tag.view(6))
102 - status_blocks = { 103 +oxwm.key.bind({ "Mod1" }, "8", oxwm.tag.view(7))
103 - { 104 +oxwm.key.bind({ "Mod1" }, "9", oxwm.tag.view(8))
104 - format = "", 105 +
105 - command = "Battery", 106 +-- Move window to tag
106 - battery_formats = { 107 +oxwm.key.bind({ "Mod1", "Shift" }, "1", oxwm.tag.move_to(0))
107 - charging = "󰂄 Bat: {}%", 108 +oxwm.key.bind({ "Mod1", "Shift" }, "2", oxwm.tag.move_to(1))
108 - discharging = "󰁹 Bat:{}%", 109 +oxwm.key.bind({ "Mod1", "Shift" }, "3", oxwm.tag.move_to(2))
109 - full = "󰁹 Bat: {}%" 110 +oxwm.key.bind({ "Mod1", "Shift" }, "4", oxwm.tag.move_to(3))
110 - }, 111 +oxwm.key.bind({ "Mod1", "Shift" }, "5", oxwm.tag.move_to(4))
111 - interval_secs = 30, 112 +oxwm.key.bind({ "Mod1", "Shift" }, "6", oxwm.tag.move_to(5))
112 - color = colors.green, 113 +oxwm.key.bind({ "Mod1", "Shift" }, "7", oxwm.tag.move_to(6))
113 - underline = true 114 +oxwm.key.bind({ "Mod1", "Shift" }, "8", oxwm.tag.move_to(7))
114 - }, 115 +oxwm.key.bind({ "Mod1", "Shift" }, "9", oxwm.tag.move_to(8))
115 - { 116 +
116 - format = " │ ", 117 +-- Status bar blocks
117 - command = "Static", 118 +oxwm.bar.add_block("", "Battery", {
118 - interval_secs = 999999999, 119 + charging = "󰂄 Bat: {}%",
119 - color = colors.lavender, 120 + discharging = "󰁹 Bat:{}%",
120 - underline = false 121 + full = "󰁹 Bat: {}%"
121 - }, 122 +}, 30, colors.green, true)
122 - { 123 +
123 - format = "󰍛 {used}/{total} GB", 124 +oxwm.bar.add_block(" │ ", "Static", "", 999999999, colors.lavender, false)
124 - command = "Ram", 125 +oxwm.bar.add_block("󰍛 {used}/{total} GB", "Ram", nil, 5, colors.light_blue, true)
125 - interval_secs = 5, 126 +oxwm.bar.add_block(" │ ", "Static", "", 999999999, colors.lavender, false)
126 - color = colors.light_blue, 127 +oxwm.bar.add_block(" {}", "Shell", "uname -r", 999999999, colors.red, true)
127 - underline = true 128 +oxwm.bar.add_block(" │ ", "Static", "", 999999999, colors.lavender, false)
128 - }, 129 +oxwm.bar.add_block("󰸘 {}", "DateTime", "%a, %b %d - %-I:%M %P", 1, colors.cyan, true)
129 - { 130 +
130 - format = " │ ", 131 +-- Autostart commands (runs once at startup)
131 - command = "Static", 132 +-- oxwm.autostart("picom")
132 - interval_secs = 999999999, 133 +-- oxwm.autostart("feh --bg-scale ~/wallpaper.jpg")
133 - color = colors.lavender,
134 - underline = false
135 - },
136 - {
137 - format = " {}",
138 - command = "Shell",
139 - command_arg = "uname -r",
140 - interval_secs = 999999999,
141 - color = colors.red,
142 - underline = true
143 - },
144 - {
145 - format = " │ ",
146 - command = "Static",
147 - interval_secs = 999999999,
148 - color = colors.lavender,
149 - underline = false
150 - },
151 - {
152 - format = "󰸘 {}",
153 - command = "DateTime",
154 - command_arg = "%a, %b %d - %-I:%M %P",
155 - interval_secs = 1,
156 - color = colors.cyan,
157 - underline = true
158 - },
159 - },
160 -
161 - -- Color schemes for bar
162 - scheme_normal = {
163 - foreground = colors.fg,
164 - background = colors.bg,
165 - underline = "#444444"
166 - },
167 - scheme_occupied = {
168 - foreground = colors.cyan,
169 - background = colors.bg,
170 - underline = colors.cyan
171 - },
172 - scheme_selected = {
173 - foreground = colors.cyan,
174 - background = colors.bg,
175 - underline = colors.purple
176 - },
177 -
178 - -- Autostart commands
179 - autostart = {},
180 -}
+29 −72 src/bin/main.rs
@@ -19,11 +19,6 @@ fn main() -> Result<()> {
19 init_config()?; 19 init_config()?;
20 return Ok(()); 20 return Ok(());
21 } 21 }
22 - Some("--migrate") => {
23 - let path = args.get(2).map(PathBuf::from);
24 - migrate_config(path)?;
25 - return Ok(());
26 - }
27 Some("--config") => { 22 Some("--config") => {
28 if let Some(path) = args.get(2) { 23 if let Some(path) = args.get(2) {
29 custom_config_path = Some(PathBuf::from(path)); 24 custom_config_path = Some(PathBuf::from(path));
@@ -57,48 +52,52 @@ fn load_config(custom_path: Option<PathBuf>) -> Result<oxwm::Config> {
57 } else { 52 } else {
58 let config_dir = get_config_path(); 53 let config_dir = get_config_path();
59 let lua_path = config_dir.join("config.lua"); 54 let lua_path = config_dir.join("config.lua");
60 - let ron_path = config_dir.join("config.ron");
61 55
62 - if lua_path.exists() { 56 + if !lua_path.exists() {
63 - lua_path 57 + // Check if user had an old RON config
64 - } else if ron_path.exists() { 58 + let ron_path = config_dir.join("config.ron");
65 - ron_path 59 + let had_ron_config = ron_path.exists();
66 - } else { 60 +
67 println!("No config found at {:?}", config_dir); 61 println!("No config found at {:?}", config_dir);
68 println!("Creating default Lua config..."); 62 println!("Creating default Lua config...");
69 init_config()?; 63 init_config()?;
70 - config_dir.join("config.lua") 64 +
65 + if had_ron_config {
66 + println!("\n⚠️ NOTICE: OXWM has migrated to Lua configuration.");
67 + println!(" Your old config.ron has been preserved, but is no longer used.");
68 + println!(" Your settings have been reset to defaults.");
69 + println!(" Please manually port your configuration to the new Lua format.");
70 + println!(" See the new config.lua template for examples.\n");
71 + }
71 } 72 }
73 +
74 + lua_path
72 }; 75 };
73 76
74 let config_str = 77 let config_str =
75 std::fs::read_to_string(&config_path).with_context(|| "Failed to read config file")?; 78 std::fs::read_to_string(&config_path).with_context(|| "Failed to read config file")?;
76 79
77 - let is_lua = config_path 80 + let config_dir = config_path.parent();
78 - .extension() 81 + oxwm::config::parse_lua_config(&config_str, config_dir)
79 - .and_then(|s| s.to_str()) 82 + .with_context(|| "Failed to parse Lua config")
80 - .map(|s| s == "lua")
81 - .unwrap_or(false);
82 -
83 - if is_lua {
84 - let config_dir = config_path.parent();
85 - oxwm::config::parse_lua_config(&config_str, config_dir)
86 - .with_context(|| "Failed to parse Lua config")
87 - } else {
88 - oxwm::config::parse_config(&config_str).with_context(|| "Failed to parse RON config")
89 - }
90 } 83 }
91 84
92 fn init_config() -> Result<()> { 85 fn init_config() -> Result<()> {
93 let config_dir = get_config_path(); 86 let config_dir = get_config_path();
94 std::fs::create_dir_all(&config_dir)?; 87 std::fs::create_dir_all(&config_dir)?;
95 88
89 + // Copy config.lua template
96 let config_template = include_str!("../../templates/config.lua"); 90 let config_template = include_str!("../../templates/config.lua");
97 let config_path = config_dir.join("config.lua"); 91 let config_path = config_dir.join("config.lua");
98 -
99 std::fs::write(&config_path, config_template)?; 92 std::fs::write(&config_path, config_template)?;
100 93
94 + // Copy oxwm.lua API definitions for LSP support
95 + let oxwm_lua_template = include_str!("../../templates/oxwm.lua");
96 + let oxwm_lua_path = config_dir.join("oxwm.lua");
97 + std::fs::write(&oxwm_lua_path, oxwm_lua_template)?;
98 +
101 println!("✓ Config created at {:?}", config_path); 99 println!("✓ Config created at {:?}", config_path);
100 + println!("✓ LSP definitions installed at {:?}", oxwm_lua_path);
102 println!(" Edit the file and reload with Mod+Shift+R"); 101 println!(" Edit the file and reload with Mod+Shift+R");
103 println!(" No compilation needed - changes take effect immediately!"); 102 println!(" No compilation needed - changes take effect immediately!");
104 103
@@ -111,62 +110,20 @@ fn get_config_path() -> PathBuf {
111 .join("oxwm") 110 .join("oxwm")
112 } 111 }
113 112
114 -fn migrate_config(custom_path: Option<PathBuf>) -> Result<()> {
115 - let ron_path = if let Some(path) = custom_path {
116 - path
117 - } else {
118 - get_config_path().join("config.ron")
119 - };
120 -
121 - if !ron_path.exists() {
122 - eprintln!("Error: RON config file not found at {:?}", ron_path);
123 - eprintln!("Please specify a path: oxwm --migrate <path/to/config.ron>");
124 - std::process::exit(1);
125 - }
126 -
127 - println!("Migrating RON config to Lua...");
128 - println!(" Reading: {:?}", ron_path);
129 -
130 - let ron_content = std::fs::read_to_string(&ron_path)
131 - .with_context(|| format!("Failed to read RON config from {:?}", ron_path))?;
132 -
133 - let lua_content = oxwm::config::migrate::ron_to_lua(&ron_content)
134 - .with_context(|| "Failed to migrate RON config to Lua")?;
135 -
136 - let lua_path = ron_path.with_extension("lua");
137 -
138 - std::fs::write(&lua_path, lua_content)
139 - .with_context(|| format!("Failed to write Lua config to {:?}", lua_path))?;
140 -
141 - println!("✓ Migration complete!");
142 - println!(" Output: {:?}", lua_path);
143 - println!("\nYour old config.ron is still intact.");
144 - println!(
145 - "Review the new config.lua and then you can delete config.ron if everything looks good."
146 - );
147 -
148 - Ok(())
149 -}
150 -
151 fn print_help() { 113 fn print_help() {
152 println!("OXWM - A dynamic window manager written in Rust\n"); 114 println!("OXWM - A dynamic window manager written in Rust\n");
153 println!("USAGE:"); 115 println!("USAGE:");
154 println!(" oxwm [OPTIONS]\n"); 116 println!(" oxwm [OPTIONS]\n");
155 println!("OPTIONS:"); 117 println!("OPTIONS:");
156 println!(" --init Create default config in ~/.config/oxwm/config.lua"); 118 println!(" --init Create default config in ~/.config/oxwm/config.lua");
157 - println!( 119 + println!(" --config <PATH> Use custom config file");
158 - " --migrate [PATH] Convert RON config to Lua (default: ~/.config/oxwm/config.ron)"
159 - );
160 - println!(" --config <PATH> Use custom config file (.lua or .ron)");
161 println!(" --version Print version information"); 120 println!(" --version Print version information");
162 println!(" --help Print this help message\n"); 121 println!(" --help Print this help message\n");
163 println!("CONFIG:"); 122 println!("CONFIG:");
164 - println!(" Location: ~/.config/oxwm/config.lua (or config.ron for legacy)"); 123 + println!(" Location: ~/.config/oxwm/config.lua");
165 println!(" Edit the config file and use Mod+Shift+R to reload"); 124 println!(" Edit the config file and use Mod+Shift+R to reload");
166 - println!(" No compilation needed - instant hot-reload!\n"); 125 + println!(" No compilation needed - instant hot-reload!");
167 - println!("MIGRATION:"); 126 + println!(" LSP support included with oxwm.lua type definitions\n");
168 - println!(" To migrate from RON to Lua: oxwm --migrate");
169 - println!(" Or specify a custom path: oxwm --migrate /path/to/config.ron\n");
170 println!("FIRST RUN:"); 127 println!("FIRST RUN:");
171 println!(" Run 'oxwm --init' to create a config file"); 128 println!(" Run 'oxwm --init' to create a config file");
172 println!(" Or just start oxwm and it will create one automatically\n"); 129 println!(" Or just start oxwm and it will create one automatically\n");
+35 −0 src/config/lua.rs
@@ -7,6 +7,8 @@ use crate::{ColorScheme, LayoutSymbolOverride};
7 use mlua::{Lua, Table, Value}; 7 use mlua::{Lua, Table, Value};
8 use x11rb::protocol::xproto::KeyButMask; 8 use x11rb::protocol::xproto::KeyButMask;
9 9
10 +use super::lua_api;
11 +
10 pub fn parse_lua_config( 12 pub fn parse_lua_config(
11 input: &str, 13 input: &str,
12 config_dir: Option<&std::path::Path>, 14 config_dir: Option<&std::path::Path>,
@@ -22,6 +24,38 @@ pub fn parse_lua_config(
22 } 24 }
23 } 25 }
24 26
27 + let builder = lua_api::register_api(&lua)?;
28 +
29 + lua.load(input)
30 + .exec()
31 + .map_err(|e| ConfigError::LuaError(format!("Failed to execute Lua config: {}", e)))?;
32 +
33 + let builder_data = builder.borrow().clone();
34 +
35 + return Ok(crate::Config {
36 + border_width: builder_data.border_width,
37 + border_focused: builder_data.border_focused,
38 + border_unfocused: builder_data.border_unfocused,
39 + font: builder_data.font,
40 + gaps_enabled: builder_data.gaps_enabled,
41 + gap_inner_horizontal: builder_data.gap_inner_horizontal,
42 + gap_inner_vertical: builder_data.gap_inner_vertical,
43 + gap_outer_horizontal: builder_data.gap_outer_horizontal,
44 + gap_outer_vertical: builder_data.gap_outer_vertical,
45 + terminal: builder_data.terminal,
46 + modkey: builder_data.modkey,
47 + tags: builder_data.tags,
48 + layout_symbols: builder_data.layout_symbols,
49 + keybindings: builder_data.keybindings,
50 + status_blocks: builder_data.status_blocks,
51 + scheme_normal: builder_data.scheme_normal,
52 + scheme_occupied: builder_data.scheme_occupied,
53 + scheme_selected: builder_data.scheme_selected,
54 + autostart: builder_data.autostart,
55 + });
56 +
57 + #[allow(unreachable_code)]
58 + {
25 let config: Table = lua 59 let config: Table = lua
26 .load(input) 60 .load(input)
27 .eval() 61 .eval()
@@ -72,6 +106,7 @@ pub fn parse_lua_config(
72 scheme_selected, 106 scheme_selected,
73 autostart, 107 autostart,
74 }) 108 })
109 + }
75 } 110 }
76 111
77 fn get_table_field<T>(table: &Table, field: &str) -> Result<T, ConfigError> 112 fn get_table_field<T>(table: &Table, field: &str) -> Result<T, ConfigError>
+717 −0 src/config/lua_api.rs new file mode 100644 Large diff collapsed, click to expand
@@ -0,0 +1,717 @@
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("DateTime requires format string".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("Shell requires command string".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("Battery requires formats table".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!("Unknown block command: {}", 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!("{}", 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!("{}", e)))?;
584 + Ok(vec![mask])
585 + }
586 + _ => Err(mlua::Error::RuntimeError(
587 + "modifiers must be string or table".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(s.to_string())),
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: {}", key)))
608 +}
609 +
610 +fn parse_action_value(_lua: &Lua, value: Value) -> mlua::Result<(KeyAction, Arg)> {
611 + match value {
612 + Value::Table(t) => {
613 + // Check if this table has our action metadata
614 + if let Ok(action_name) = t.get::<String>("__action") {
615 + let action = string_to_action(&action_name)?;
616 + let arg = if let Ok(arg_val) = t.get::<Value>("__arg") {
617 + value_to_arg(arg_val)?
618 + } else {
619 + Arg::None
620 + };
621 + return Ok((action, arg));
622 + }
623 +
624 + Err(mlua::Error::RuntimeError(
625 + "action table missing __action field".into(),
626 + ))
627 + }
628 + _ => Err(mlua::Error::RuntimeError(
629 + "action must be a table returned by oxwm actions".into(),
630 + )),
631 + }
632 +}
633 +
634 +fn string_to_action(s: &str) -> mlua::Result<KeyAction> {
635 + match s {
636 + "Spawn" => Ok(KeyAction::Spawn),
637 + "KillClient" => Ok(KeyAction::KillClient),
638 + "FocusStack" => Ok(KeyAction::FocusStack),
639 + "FocusDirection" => Ok(KeyAction::FocusDirection),
640 + "SwapDirection" => Ok(KeyAction::SwapDirection),
641 + "Quit" => Ok(KeyAction::Quit),
642 + "Restart" => Ok(KeyAction::Restart),
643 + "Recompile" => Ok(KeyAction::Recompile),
644 + "ViewTag" => Ok(KeyAction::ViewTag),
645 + "ToggleGaps" => Ok(KeyAction::ToggleGaps),
646 + "ToggleFullScreen" => Ok(KeyAction::ToggleFullScreen),
647 + "ToggleFloating" => Ok(KeyAction::ToggleFloating),
648 + "ChangeLayout" => Ok(KeyAction::ChangeLayout),
649 + "CycleLayout" => Ok(KeyAction::CycleLayout),
650 + "MoveToTag" => Ok(KeyAction::MoveToTag),
651 + "FocusMonitor" => Ok(KeyAction::FocusMonitor),
652 + "SmartMoveWin" => Ok(KeyAction::SmartMoveWin),
653 + "ExchangeClient" => Ok(KeyAction::ExchangeClient),
654 + "ShowKeybindOverlay" => Ok(KeyAction::ShowKeybindOverlay),
655 + _ => Err(mlua::Error::RuntimeError(format!("Unknown action: {}", s))),
656 + }
657 +}
658 +
659 +fn value_to_arg(value: Value) -> mlua::Result<Arg> {
660 + match value {
661 + Value::Nil => Ok(Arg::None),
662 + Value::String(s) => Ok(Arg::Str(s.to_str()?.to_string())),
663 + Value::Integer(i) => Ok(Arg::Int(i as i32)),
664 + Value::Number(n) => Ok(Arg::Int(n as i32)),
665 + Value::Table(t) => {
666 + let mut arr = Vec::new();
667 + for i in 1..=t.len()? {
668 + let item: String = t.get(i)?;
669 + arr.push(item);
670 + }
671 + Ok(Arg::Array(arr))
672 + }
673 + _ => Ok(Arg::None),
674 + }
675 +}
676 +
677 +fn create_action_table(lua: &Lua, action_name: &str, arg: Value) -> mlua::Result<Table> {
678 + let table = lua.create_table()?;
679 + table.set("__action", action_name)?;
680 + table.set("__arg", arg)?;
681 + Ok(table)
682 +}
683 +
684 +fn direction_string_to_int(dir: &str) -> mlua::Result<i64> {
685 + match dir {
686 + "up" => Ok(0),
687 + "down" => Ok(1),
688 + "left" => Ok(2),
689 + "right" => Ok(3),
690 + _ => Err(mlua::Error::RuntimeError(
691 + format!("Invalid direction '{}', must be one of: up, down, left, right", dir)
692 + )),
693 + }
694 +}
695 +
696 +fn parse_color_value(value: Value) -> mlua::Result<u32> {
697 + match value {
698 + Value::Integer(i) => Ok(i as u32),
699 + Value::Number(n) => Ok(n as u32),
700 + Value::String(s) => {
701 + let s = s.to_str()?;
702 + if s.starts_with('#') {
703 + u32::from_str_radix(&s[1..], 16)
704 + .map_err(|e| mlua::Error::RuntimeError(format!("Invalid hex color: {}", e)))
705 + } else if s.starts_with("0x") {
706 + u32::from_str_radix(&s[2..], 16)
707 + .map_err(|e| mlua::Error::RuntimeError(format!("Invalid hex color: {}", e)))
708 + } else {
709 + s.parse::<u32>()
710 + .map_err(|e| mlua::Error::RuntimeError(format!("Invalid color: {}", e)))
711 + }
712 + }
713 + _ => Err(mlua::Error::RuntimeError(
714 + "color must be number or string".into(),
715 + )),
716 + }
717 +}
+0 −553 src/config/migrate.rs deleted file mode 100644 Large diff collapsed, click to expand
@@ -1,553 +0,0 @@
1 -use crate::errors::ConfigError;
2 -use std::collections::HashMap;
3 -
4 -pub fn ron_to_lua(ron_content: &str) -> Result<String, ConfigError> {
5 - let mut lua_output = String::new();
6 - let defines = extract_defines(ron_content);
7 -
8 - lua_output.push_str("-- OXWM Configuration File (Lua)\n");
9 - lua_output.push_str("-- Migrated from config.ron\n");
10 - lua_output.push_str("-- Edit this file and reload with Mod+Shift+R (no compilation needed!)\n\n");
11 -
12 - let terminal = resolve_value(&defines.get("$terminal").cloned().unwrap_or_else(|| "\"st\"".to_string()), &defines);
13 - let modkey = resolve_value(&defines.get("$modkey").cloned().unwrap_or_else(|| "Mod4".to_string()), &defines);
14 - let secondary_modkey = defines.get("$secondary_modkey").map(|v| resolve_value(v, &defines));
15 -
16 - lua_output.push_str(&format!("local terminal = {}\n", terminal));
17 - lua_output.push_str(&format!("local modkey = \"{}\"\n", modkey.trim_matches('"')));
18 - if let Some(sec_mod) = secondary_modkey {
19 - lua_output.push_str(&format!("local secondary_modkey = \"{}\"\n", sec_mod.trim_matches('"')));
20 - }
21 - lua_output.push_str("\n");
22 -
23 - lua_output.push_str("-- Color palette\n");
24 - lua_output.push_str("local colors = {\n");
25 - for (key, value) in &defines {
26 - if key.starts_with("$color_") {
27 - let color_name = &key[7..];
28 - let color_value = if value.starts_with("0x") {
29 - format!("\"#{}\"", &value[2..])
30 - } else {
31 - value.clone()
32 - };
33 - lua_output.push_str(&format!(" {} = {},\n", color_name, color_value));
34 - }
35 - }
36 - lua_output.push_str("}\n\n");
37 -
38 - lua_output.push_str("-- Main configuration table\n");
39 - lua_output.push_str("return {\n");
40 -
41 - if let Some(config_start) = ron_content.find('(') {
42 - let config_content = &ron_content[config_start + 1..];
43 -
44 - lua_output.push_str(" -- Appearance\n");
45 - if let Some(val) = extract_field(config_content, "border_width") {
46 - lua_output.push_str(&format!(" border_width = {},\n", val));
47 - }
48 - if let Some(val) = extract_field(config_content, "border_focused") {
49 - lua_output.push_str(&format!(" border_focused = {},\n", resolve_color_value(&val, &defines)));
50 - }
51 - if let Some(val) = extract_field(config_content, "border_unfocused") {
52 - lua_output.push_str(&format!(" border_unfocused = {},\n", resolve_color_value(&val, &defines)));
53 - }
54 - if let Some(val) = extract_field(config_content, "font") {
55 - lua_output.push_str(&format!(" font = {},\n", val));
56 - }
57 -
58 - lua_output.push_str("\n -- Window gaps\n");
59 - if let Some(val) = extract_field(config_content, "gaps_enabled") {
60 - lua_output.push_str(&format!(" gaps_enabled = {},\n", val));
61 - }
62 - if let Some(val) = extract_field(config_content, "gap_inner_horizontal") {
63 - lua_output.push_str(&format!(" gap_inner_horizontal = {},\n", val));
64 - }
65 - if let Some(val) = extract_field(config_content, "gap_inner_vertical") {
66 - lua_output.push_str(&format!(" gap_inner_vertical = {},\n", val));
67 - }
68 - if let Some(val) = extract_field(config_content, "gap_outer_horizontal") {
69 - lua_output.push_str(&format!(" gap_outer_horizontal = {},\n", val));
70 - }
71 - if let Some(val) = extract_field(config_content, "gap_outer_vertical") {
72 - lua_output.push_str(&format!(" gap_outer_vertical = {},\n", val));
73 - }
74 -
75 - lua_output.push_str("\n -- Basics\n");
76 - if let Some(val) = extract_field(config_content, "modkey") {
77 - let resolved = resolve_value(&val, &defines).trim_matches('"').to_string();
78 - if resolved == "modkey" {
79 - lua_output.push_str(" modkey = modkey,\n");
80 - } else {
81 - lua_output.push_str(&format!(" modkey = \"{}\",\n", resolved));
82 - }
83 - }
84 - if let Some(val) = extract_field(config_content, "terminal") {
85 - let resolved = resolve_value(&val, &defines);
86 - if resolved == "terminal" {
87 - lua_output.push_str(" terminal = terminal,\n");
88 - } else {
89 - lua_output.push_str(&format!(" terminal = {},\n", resolved));
90 - }
91 - }
92 -
93 - lua_output.push_str("\n -- Workspace tags\n");
94 - if let Some(val) = extract_field(config_content, "tags") {
95 - lua_output.push_str(&format!(" tags = {},\n", convert_array_to_lua(&val)));
96 - }
97 -
98 - lua_output.push_str("\n -- Layout symbol overrides\n");
99 - if let Some(val) = extract_field(config_content, "layout_symbols") {
100 - lua_output.push_str(" layout_symbols = ");
101 - lua_output.push_str(&convert_layout_symbols(&val));
102 - lua_output.push_str(",\n");
103 - }
104 -
105 - lua_output.push_str("\n -- Keybindings\n");
106 - if let Some(val) = extract_field(config_content, "keybindings") {
107 - lua_output.push_str(" keybindings = ");
108 - lua_output.push_str(&convert_keybindings(&val, &defines));
109 - lua_output.push_str(",\n");
110 - }
111 -
112 - lua_output.push_str("\n -- Status bar blocks\n");
113 - if let Some(val) = extract_field(config_content, "status_blocks") {
114 - lua_output.push_str(" status_blocks = ");
115 - lua_output.push_str(&convert_status_blocks(&val, &defines));
116 - lua_output.push_str(",\n");
117 - }
118 -
119 - lua_output.push_str("\n -- Color schemes for bar\n");
120 - if let Some(val) = extract_field(config_content, "scheme_normal") {
121 - lua_output.push_str(" scheme_normal = ");
122 - lua_output.push_str(&convert_color_scheme(&val, &defines));
123 - lua_output.push_str(",\n");
124 - }
125 - if let Some(val) = extract_field(config_content, "scheme_occupied") {
126 - lua_output.push_str(" scheme_occupied = ");
127 - lua_output.push_str(&convert_color_scheme(&val, &defines));
128 - lua_output.push_str(",\n");
129 - }
130 - if let Some(val) = extract_field(config_content, "scheme_selected") {
131 - lua_output.push_str(" scheme_selected = ");
132 - lua_output.push_str(&convert_color_scheme(&val, &defines));
133 - lua_output.push_str(",\n");
134 - }
135 -
136 - lua_output.push_str("\n -- Autostart commands\n");
137 - if let Some(val) = extract_field(config_content, "autostart") {
138 - let converted = convert_array_to_lua(&val);
139 - lua_output.push_str(" autostart = ");
140 - lua_output.push_str(&converted);
141 - lua_output.push_str(",\n");
142 - } else {
143 - lua_output.push_str(" autostart = {},\n");
144 - }
145 - }
146 -
147 - lua_output.push_str("}\n");
148 -
149 - Ok(lua_output)
150 -}
151 -
152 -fn extract_defines(content: &str) -> HashMap<String, String> {
153 - let mut defines = HashMap::new();
154 - for line in content.lines() {
155 - let trimmed = line.trim();
156 - if trimmed.starts_with("#DEFINE") {
157 - if let Some(rest) = trimmed.strip_prefix("#DEFINE") {
158 - if let Some(eq_pos) = rest.find('=') {
159 - let var_name = rest[..eq_pos].trim().to_string();
160 - let value = rest[eq_pos + 1..].trim().trim_end_matches(',').to_string();
161 - defines.insert(var_name, value);
162 - }
163 - }
164 - }
165 - }
166 - defines
167 -}
168 -
169 -fn resolve_value(value: &str, defines: &HashMap<String, String>) -> String {
170 - if let Some(resolved) = defines.get(value) {
171 - resolved.clone()
172 - } else {
173 - value.to_string()
174 - }
175 -}
176 -
177 -fn resolve_color_value(value: &str, defines: &HashMap<String, String>) -> String {
178 - let resolved = resolve_value(value, defines);
179 - if resolved.starts_with("$color_") {
180 - format!("colors.{}", &resolved[7..])
181 - } else if value.starts_with("$color_") {
182 - format!("colors.{}", &value[7..])
183 - } else if resolved.starts_with("0x") {
184 - format!("\"#{}\"", &resolved[2..])
185 - } else {
186 - resolved
187 - }
188 -}
189 -
190 -fn extract_field(content: &str, field_name: &str) -> Option<String> {
191 - let pattern = format!("{}:", field_name);
192 - let cleaned_content = remove_comments(content);
193 -
194 - if let Some(start) = cleaned_content.find(&pattern) {
195 - let after_colon = &cleaned_content[start + pattern.len()..];
196 - let value_start = after_colon.trim_start();
197 -
198 - if value_start.starts_with('[') {
199 - extract_bracketed(value_start, '[', ']')
200 - } else if value_start.starts_with('(') {
201 - extract_bracketed(value_start, '(', ')')
202 - } else if value_start.starts_with('"') {
203 - if let Some(end) = value_start[1..].find('"') {
204 - Some(value_start[..end + 2].to_string())
205 - } else {
206 - None
207 - }
208 - } else {
209 - let end = value_start
210 - .find(|c: char| c == ',' || c == '\n' || c == ')')
211 - .unwrap_or(value_start.len());
212 - Some(value_start[..end].trim().to_string())
213 - }
214 - } else {
215 - None
216 - }
217 -}
218 -
219 -fn extract_bracketed(s: &str, open: char, close: char) -> Option<String> {
220 - if !s.starts_with(open) {
221 - return None;
222 - }
223 - let mut depth = 0;
224 - let mut end = 0;
225 - for (i, c) in s.char_indices() {
226 - if c == open {
227 - depth += 1;
228 - } else if c == close {
229 - depth -= 1;
230 - if depth == 0 {
231 - end = i + 1;
232 - break;
233 - }
234 - }
235 - }
236 - if end > 0 {
237 - Some(s[..end].to_string())
238 - } else {
239 - None
240 - }
241 -}
242 -
243 -fn convert_array_to_lua(ron_array: &str) -> String {
244 - let inner = ron_array.trim_start_matches('[').trim_end_matches(']');
245 - let items: Vec<&str> = inner.split(',').map(|s| s.trim()).filter(|s| !s.is_empty()).collect();
246 - format!("{{ {} }}", items.join(", "))
247 -}
248 -
249 -fn convert_layout_symbols(ron_array: &str) -> String {
250 - let mut result = String::from("{\n");
251 - let inner = ron_array.trim_start_matches('[').trim_end_matches(']');
252 -
253 - let items = extract_all_bracketed(inner, '(', ')');
254 - for item in items {
255 - let item_inner = item.trim_start_matches('(').trim_end_matches(')');
256 - if let (Some(name), Some(symbol)) = (extract_quoted_value(item_inner, "name"), extract_quoted_value(item_inner, "symbol")) {
257 - result.push_str(&format!(" {{ name = \"{}\", symbol = \"{}\" }},\n", name, symbol));
258 - }
259 - }
260 -
261 - result.push_str(" }");
262 - result
263 -}
264 -
265 -fn convert_keybindings(ron_array: &str, defines: &HashMap<String, String>) -> String {
266 - let mut result = String::from("{\n");
267 - let inner = ron_array.trim_start_matches('[').trim_end_matches(']');
268 -
269 - let items = extract_all_bracketed(inner, '(', ')');
270 - for item in items {
271 - let binding = convert_keybinding(&item, defines);
272 - result.push_str(&binding);
273 - result.push_str(",\n");
274 - }
275 -
276 - result.push_str(" }");
277 - result
278 -}
279 -
280 -fn convert_keybinding(ron_binding: &str, defines: &HashMap<String, String>) -> String {
281 - let inner = ron_binding.trim_start_matches('(').trim_end_matches(')');
282 -
283 - if inner.contains("keys:") {
284 - convert_keychord(inner, defines)
285 - } else {
286 - convert_single_key(inner, defines)
287 - }
288 -}
289 -
290 -fn convert_keychord(inner: &str, defines: &HashMap<String, String>) -> String {
291 - let mut result = String::from(" {\n keys = {\n");
292 -
293 - if let Some(keys_str) = extract_field(inner, "keys") {
294 - let keys = extract_all_bracketed(&keys_str, '(', ')');
295 - for key in keys {
296 - let key_inner = key.trim_start_matches('(').trim_end_matches(')');
297 - let mods = extract_modifiers(key_inner, defines);
298 - let key_name = extract_key(key_inner);
299 - result.push_str(&format!(" {{ modifiers = {{ {} }}, key = \"{}\" }},\n", mods, key_name));
300 - }
301 - }
302 -
303 - result.push_str(" },\n");
304 -
305 - if let Some(action) = extract_identifier(inner, "action") {
306 - result.push_str(&format!(" action = \"{}\",\n", action));
307 - }
308 -
309 - if let Some(arg) = extract_arg(inner, defines) {
310 - result.push_str(&format!(" arg = {}\n", arg));
311 - }
312 -
313 - result.push_str(" }");
314 - result
315 -}
316 -
317 -fn convert_single_key(inner: &str, defines: &HashMap<String, String>) -> String {
318 - let mods = extract_modifiers(inner, defines);
319 - let key = extract_key(inner);
320 - let action = extract_identifier(inner, "action").unwrap_or_default();
321 -
322 - let mut result = format!(" {{ modifiers = {{ {} }}, key = \"{}\", action = \"{}\"", mods, key, action);
323 -
324 - if let Some(arg) = extract_arg(inner, defines) {
325 - result.push_str(&format!(", arg = {}", arg));
326 - }
327 -
328 - result.push_str(" }");
329 - result
330 -}
331 -
332 -fn extract_modifiers(content: &str, defines: &HashMap<String, String>) -> String {
333 - if let Some(mods_str) = extract_field(content, "modifiers") {
334 - let inner = mods_str.trim_start_matches('[').trim_end_matches(']').trim();
335 - if inner.is_empty() {
336 - return String::new();
337 - }
338 - let mods: Vec<String> = inner
339 - .split(',')
340 - .map(|s| {
341 - let trimmed = s.trim();
342 - if !trimmed.is_empty() {
343 - let resolved = resolve_value(trimmed, defines);
344 - format!("\"{}\"", resolved)
345 - } else {
346 - String::new()
347 - }
348 - })
349 - .filter(|s| !s.is_empty())
350 - .collect();
351 - mods.join(", ")
352 - } else {
353 - String::new()
354 - }
355 -}
356 -
357 -fn extract_key(content: &str) -> String {
358 - if let Some(key_str) = extract_identifier(content, "key") {
359 - if key_str.starts_with("Key") && key_str.len() == 4 {
360 - if let Some(digit) = key_str.chars().nth(3) {
361 - if digit.is_ascii_digit() {
362 - return digit.to_string();
363 - }
364 - }
365 - }
366 - key_str
367 - } else {
368 - String::from("Return")
369 - }
370 -}
371 -
372 -fn extract_identifier(content: &str, field_name: &str) -> Option<String> {
373 - let pattern = format!("{}:", field_name);
374 - if let Some(start) = content.find(&pattern) {
375 - let after_colon = &content[start + pattern.len()..];
376 - let value_start = after_colon.trim_start();
377 - let end = value_start
378 - .find(|c: char| c == ',' || c == ')' || c == '\n')
379 - .unwrap_or(value_start.len());
380 - Some(value_start[..end].trim().to_string())
381 - } else {
382 - None
383 - }
384 -}
385 -
386 -fn extract_arg(content: &str, defines: &HashMap<String, String>) -> Option<String> {
387 - if let Some(arg_str) = extract_field(content, "arg") {
388 - let resolved = resolve_value(&arg_str, defines);
389 - if resolved.starts_with('[') {
390 - Some(convert_array_to_lua(&resolved))
391 - } else if resolved.starts_with('"') || resolved.parse::<i32>().is_ok() || resolved.starts_with("0x") {
392 - Some(resolved)
393 - } else {
394 - Some(format!("\"{}\"", resolved))
395 - }
396 - } else {
397 - None
398 - }
399 -}
400 -
401 -fn convert_status_blocks(ron_array: &str, defines: &HashMap<String, String>) -> String {
402 - let mut result = String::from("{\n");
403 - let inner = ron_array.trim_start_matches('[').trim_end_matches(']');
404 -
405 - let items = extract_all_bracketed(inner, '(', ')');
406 - for item in items {
407 - let block = convert_status_block(&item, defines);
408 - if !block.trim().ends_with("{\n }") {
409 - result.push_str(&block);
410 - result.push_str(",\n");
411 - }
412 - }
413 -
414 - result.push_str(" }");
415 - result
416 -}
417 -
418 -fn convert_status_block(ron_block: &str, defines: &HashMap<String, String>) -> String {
419 - let mut result = String::from(" {\n");
420 - let inner = ron_block.trim_start_matches('(').trim_end_matches(')');
421 -
422 - if let Some(format) = extract_field(inner, "format") {
423 - result.push_str(&format!(" format = {},\n", format));
424 - }
425 - if let Some(command) = extract_field(inner, "command") {
426 - result.push_str(&format!(" command = {},\n", command));
427 - }
428 - if let Some(command_arg) = extract_field(inner, "command_arg") {
429 - result.push_str(&format!(" command_arg = {},\n", command_arg));
430 - }
431 - if inner.contains("battery_formats:") {
432 - if let Some(battery_str) = extract_field(inner, "battery_formats") {
433 - result.push_str(" battery_formats = {\n");
434 - let battery_inner = battery_str.trim_start_matches('(').trim_end_matches(')');
435 - if let Some(charging) = extract_quoted_value(battery_inner, "charging") {
436 - result.push_str(&format!(" charging = \"{}\",\n", charging));
437 - }
438 - if let Some(discharging) = extract_quoted_value(battery_inner, "discharging") {
439 - result.push_str(&format!(" discharging = \"{}\",\n", discharging));
440 - }
441 - if let Some(full) = extract_quoted_value(battery_inner, "full") {
442 - result.push_str(&format!(" full = \"{}\"\n", full));
443 - }
444 - result.push_str(" },\n");
445 - }
446 - }
447 - if let Some(interval) = extract_field(inner, "interval_secs") {
448 - let interval_val = if interval.len() > 10 {
449 - "999999999".to_string()
450 - } else {
451 - interval
452 - };
453 - result.push_str(&format!(" interval_secs = {},\n", interval_val));
454 - }
455 - if let Some(color) = extract_field(inner, "color") {
456 - let resolved = resolve_color_value(&color, defines);
457 - result.push_str(&format!(" color = {},\n", resolved));
458 - }
459 - if let Some(underline) = extract_field(inner, "underline") {
460 - result.push_str(&format!(" underline = {}\n", underline));
461 - }
462 -
463 - result.push_str(" }");
464 - result
465 -}
466 -
467 -fn convert_color_scheme(ron_scheme: &str, defines: &HashMap<String, String>) -> String {
468 - let mut result = String::from("{\n");
469 - let inner = ron_scheme.trim_start_matches('(').trim_end_matches(')');
470 -
471 - if let Some(fg) = extract_field(inner, "foreground") {
472 - let resolved = resolve_color_value(&fg, defines);
473 - result.push_str(&format!(" foreground = {},\n", resolved));
474 - }
475 - if let Some(bg) = extract_field(inner, "background") {
476 - let resolved = resolve_color_value(&bg, defines);
477 - result.push_str(&format!(" background = {},\n", resolved));
478 - }
479 - if let Some(ul) = extract_field(inner, "underline") {
480 - let resolved = resolve_color_value(&ul, defines);
481 - result.push_str(&format!(" underline = {}\n", resolved));
482 - }
483 -
484 - result.push_str(" }");
485 - result
486 -}
487 -
488 -fn extract_all_bracketed(s: &str, open: char, close: char) -> Vec<String> {
489 - let mut results = Vec::new();
490 - let mut depth = 0;
491 - let mut start = None;
492 -
493 - let cleaned = remove_comments(s);
494 -
495 - for (i, c) in cleaned.char_indices() {
496 - if c == open {
497 - if depth == 0 {
498 - start = Some(i);
499 - }
500 - depth += 1;
501 - } else if c == close {
502 - depth -= 1;
503 - if depth == 0 {
504 - if let Some(start_idx) = start {
505 - results.push(cleaned[start_idx..=i].to_string());
506 - start = None;
507 - }
508 - }
509 - }
510 - }
511 -
512 - results
513 -}
514 -
515 -fn remove_comments(s: &str) -> String {
516 - let mut result = String::new();
517 - for line in s.lines() {
518 - let mut in_string = false;
519 - let mut comment_start = None;
520 -
521 - for (i, c) in line.char_indices() {
522 - if c == '"' && (i == 0 || line.chars().nth(i - 1) != Some('\\')) {
523 - in_string = !in_string;
524 - }
525 - if !in_string && i + 1 < line.len() && &line[i..i + 2] == "//" {
526 - comment_start = Some(i);
527 - break;
528 - }
529 - }
530 -
531 - if let Some(pos) = comment_start {
532 - result.push_str(&line[..pos]);
533 - } else {
534 - result.push_str(line);
535 - }
536 - result.push('\n');
537 - }
538 - result
539 -}
540 -
541 -fn extract_quoted_value(content: &str, field_name: &str) -> Option<String> {
542 - let pattern = format!("{}:", field_name);
543 - if let Some(start) = content.find(&pattern) {
544 - let after_colon = &content[start + pattern.len()..];
545 - let trimmed = after_colon.trim_start();
546 - if trimmed.starts_with('"') {
547 - if let Some(end) = trimmed[1..].find('"') {
548 - return Some(trimmed[1..end + 1].to_string());
549 - }
550 - }
551 - }
552 - None
553 -}
+1 −476 src/config/mod.rs
@@ -1,480 +1,5 @@
1 mod lua; 1 mod lua;
2 -pub mod migrate; 2 +mod lua_api;
3 -
4 -use crate::bar::{BlockCommand, BlockConfig};
5 -use crate::errors::ConfigError;
6 -use crate::keyboard::handlers::{KeyBinding, KeyPress};
7 -use crate::keyboard::keysyms;
8 -use crate::keyboard::{Arg, KeyAction};
9 -use crate::keyboard::keysyms::Keysym;
10 -use serde::Deserialize;
11 -use std::collections::HashMap;
12 -use x11rb::protocol::xproto::KeyButMask;
13 3
14 pub use lua::parse_lua_config; 4 pub use lua::parse_lua_config;
15 5
16 -#[derive(Debug, Deserialize)]
17 -pub enum ModKey {
18 - Mod,
19 - Mod1,
20 - Mod2,
21 - Mod3,
22 - Mod4,
23 - Mod5,
24 - Shift,
25 - Control,
26 -}
27 -
28 -impl ModKey {
29 - fn to_keybut_mask(&self) -> KeyButMask {
30 - match self {
31 - ModKey::Mod => panic!("ModKey::Mod should be replaced during config parsing"),
32 - ModKey::Mod1 => KeyButMask::MOD1,
33 - ModKey::Mod2 => KeyButMask::MOD2,
34 - ModKey::Mod3 => KeyButMask::MOD3,
35 - ModKey::Mod4 => KeyButMask::MOD4,
36 - ModKey::Mod5 => KeyButMask::MOD5,
37 - ModKey::Shift => KeyButMask::SHIFT,
38 - ModKey::Control => KeyButMask::CONTROL,
39 - }
40 - }
41 -}
42 -
43 -#[rustfmt::skip]
44 -#[derive(Debug, Deserialize)]
45 -pub enum KeyData {
46 - Return,
47 - Q,
48 - Escape,
49 - Space,
50 - Tab,
51 - Backspace,
52 - Delete,
53 - F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12,
54 - 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,
55 - Key0,
56 - Key1,
57 - Key2,
58 - Key3,
59 - Key4,
60 - Key5,
61 - Key6,
62 - Key7,
63 - Key8,
64 - Key9,
65 - Left,
66 - Right,
67 - Up,
68 - Down,
69 - Home,
70 - End,
71 - PageUp,
72 - PageDown,
73 - Insert,
74 - Minus,
75 - Equal,
76 - BracketLeft,
77 - BracketRight,
78 - Semicolon,
79 - Apostrophe,
80 - Grave,
81 - Backslash,
82 - Comma,
83 - Period,
84 - Slash,
85 - AudioRaiseVolume,
86 - AudioLowerVolume,
87 - AudioMute,
88 - MonBrightnessUp,
89 - MonBrightnessDown,
90 -}
91 -
92 -impl KeyData {
93 - fn to_keysym(&self) -> Keysym {
94 - match self {
95 - KeyData::Return => keysyms::XK_RETURN,
96 - KeyData::Q => keysyms::XK_Q,
97 - KeyData::Escape => keysyms::XK_ESCAPE,
98 - KeyData::Space => keysyms::XK_SPACE,
99 - KeyData::Tab => keysyms::XK_TAB,
100 - KeyData::Backspace => keysyms::XK_BACKSPACE,
101 - KeyData::Delete => keysyms::XK_DELETE,
102 - KeyData::F1 => keysyms::XK_F1,
103 - KeyData::F2 => keysyms::XK_F2,
104 - KeyData::F3 => keysyms::XK_F3,
105 - KeyData::F4 => keysyms::XK_F4,
106 - KeyData::F5 => keysyms::XK_F5,
107 - KeyData::F6 => keysyms::XK_F6,
108 - KeyData::F7 => keysyms::XK_F7,
109 - KeyData::F8 => keysyms::XK_F8,
110 - KeyData::F9 => keysyms::XK_F9,
111 - KeyData::F10 => keysyms::XK_F10,
112 - KeyData::F11 => keysyms::XK_F11,
113 - KeyData::F12 => keysyms::XK_F12,
114 - KeyData::A => keysyms::XK_A,
115 - KeyData::B => keysyms::XK_B,
116 - KeyData::C => keysyms::XK_C,
117 - KeyData::D => keysyms::XK_D,
118 - KeyData::E => keysyms::XK_E,
119 - KeyData::F => keysyms::XK_F,
120 - KeyData::G => keysyms::XK_G,
121 - KeyData::H => keysyms::XK_H,
122 - KeyData::I => keysyms::XK_I,
123 - KeyData::J => keysyms::XK_J,
124 - KeyData::K => keysyms::XK_K,
125 - KeyData::L => keysyms::XK_L,
126 - KeyData::M => keysyms::XK_M,
127 - KeyData::N => keysyms::XK_N,
128 - KeyData::O => keysyms::XK_O,
129 - KeyData::P => keysyms::XK_P,
130 - KeyData::R => keysyms::XK_R,
131 - KeyData::S => keysyms::XK_S,
132 - KeyData::T => keysyms::XK_T,
133 - KeyData::U => keysyms::XK_U,
134 - KeyData::V => keysyms::XK_V,
135 - KeyData::W => keysyms::XK_W,
136 - KeyData::X => keysyms::XK_X,
137 - KeyData::Y => keysyms::XK_Y,
138 - KeyData::Z => keysyms::XK_Z,
139 - KeyData::Key0 => keysyms::XK_0,
140 - KeyData::Key1 => keysyms::XK_1,
141 - KeyData::Key2 => keysyms::XK_2,
142 - KeyData::Key3 => keysyms::XK_3,
143 - KeyData::Key4 => keysyms::XK_4,
144 - KeyData::Key5 => keysyms::XK_5,
145 - KeyData::Key6 => keysyms::XK_6,
146 - KeyData::Key7 => keysyms::XK_7,
147 - KeyData::Key8 => keysyms::XK_8,
148 - KeyData::Key9 => keysyms::XK_9,
149 - KeyData::Left => keysyms::XK_LEFT,
150 - KeyData::Right => keysyms::XK_RIGHT,
151 - KeyData::Up => keysyms::XK_UP,
152 - KeyData::Down => keysyms::XK_DOWN,
153 - KeyData::Home => keysyms::XK_HOME,
154 - KeyData::End => keysyms::XK_END,
155 - KeyData::PageUp => keysyms::XK_PAGE_UP,
156 - KeyData::PageDown => keysyms::XK_PAGE_DOWN,
157 - KeyData::Insert => keysyms::XK_INSERT,
158 - KeyData::Minus => keysyms::XK_MINUS,
159 - KeyData::Equal => keysyms::XK_EQUAL,
160 - KeyData::BracketLeft => keysyms::XK_LEFT_BRACKET,
161 - KeyData::BracketRight => keysyms::XK_RIGHT_BRACKET,
162 - KeyData::Semicolon => keysyms::XK_SEMICOLON,
163 - KeyData::Apostrophe => keysyms::XK_APOSTROPHE,
164 - KeyData::Grave => keysyms::XK_GRAVE,
165 - KeyData::Backslash => keysyms::XK_BACKSLASH,
166 - KeyData::Comma => keysyms::XK_COMMA,
167 - KeyData::Period => keysyms::XK_PERIOD,
168 - KeyData::Slash => keysyms::XK_SLASH,
169 - KeyData::AudioRaiseVolume => keysyms::XF86_AUDIO_RAISE_VOLUME,
170 - KeyData::AudioLowerVolume => keysyms::XF86_AUDIO_LOWER_VOLUME,
171 - KeyData::AudioMute => keysyms::XF86_AUDIO_MUTE,
172 - KeyData::MonBrightnessUp => keysyms::XF86_MON_BRIGHTNESS_UP,
173 - KeyData::MonBrightnessDown => keysyms::XF86_MON_BRIGHTNESS_DOWN,
174 - }
175 - }
176 -
177 -}
178 -
179 -fn preprocess_variables(input: &str) -> Result<String, ConfigError> {
180 - let mut variables: HashMap<String, String> = HashMap::new();
181 - let mut result = String::new();
182 -
183 - for line in input.lines() {
184 - let trimmed = line.trim();
185 -
186 - if trimmed.starts_with("#DEFINE") {
187 - let rest = trimmed.strip_prefix("#DEFINE").unwrap().trim();
188 -
189 - if let Some(eq_pos) = rest.find('=') {
190 - let var_name = rest[..eq_pos].trim();
191 - let value = rest[eq_pos + 1..].trim().trim_end_matches(',');
192 -
193 - if !var_name.starts_with('$') {
194 - return Err(ConfigError::InvalidVariableName(var_name.to_string()));
195 - }
196 -
197 - variables.insert(var_name.to_string(), value.to_string());
198 - } else {
199 - return Err(ConfigError::InvalidDefine(trimmed.to_string()));
200 - }
201 -
202 - result.push('\n');
203 - } else {
204 - let mut processed_line = line.to_string();
205 - for (var_name, value) in &variables {
206 - processed_line = processed_line.replace(var_name, value);
207 - }
208 - result.push_str(&processed_line);
209 - result.push('\n');
210 - }
211 - }
212 -
213 - for line in result.lines() {
214 - if let Some(var_start) = line.find('$') {
215 - let rest = &line[var_start..];
216 - let var_end = rest[1..]
217 - .find(|c: char| !c.is_alphanumeric() && c != '_')
218 - .unwrap_or(rest.len() - 1)
219 - + 1;
220 - let undefined_var = &rest[..var_end];
221 - return Err(ConfigError::UndefinedVariable(undefined_var.to_string()));
222 - }
223 - }
224 - Ok(result)
225 -}
226 -
227 -pub fn parse_config(input: &str) -> Result<crate::Config, ConfigError> {
228 - let preprocessed = preprocess_variables(input)?;
229 - let config_data: ConfigData = ron::from_str(&preprocessed)?;
230 - config_data_to_config(config_data)
231 -}
232 -
233 -#[derive(Debug, Deserialize)]
234 -struct LayoutSymbolOverrideData {
235 - name: String,
236 - symbol: String,
237 -}
238 -
239 -#[derive(Debug, Deserialize)]
240 -struct ConfigData {
241 - border_width: u32,
242 - border_focused: u32,
243 - border_unfocused: u32,
244 - font: String,
245 -
246 - gaps_enabled: bool,
247 - gap_inner_horizontal: u32,
248 - gap_inner_vertical: u32,
249 - gap_outer_horizontal: u32,
250 - gap_outer_vertical: u32,
251 -
252 - terminal: String,
253 - modkey: ModKey,
254 -
255 - tags: Vec<String>,
256 - #[serde(default)]
257 - layout_symbols: Vec<LayoutSymbolOverrideData>,
258 - keybindings: Vec<KeybindingData>,
259 - status_blocks: Vec<StatusBlockData>,
260 -
261 - scheme_normal: ColorSchemeData,
262 - scheme_occupied: ColorSchemeData,
263 - scheme_selected: ColorSchemeData,
264 -
265 - #[serde(default)]
266 - autostart: Vec<String>,
267 -}
268 -
269 -#[derive(Debug, Deserialize)]
270 -struct KeybindingData {
271 - #[serde(default)]
272 - keys: Option<Vec<KeyPressData>>,
273 - #[serde(default)]
274 - modifiers: Option<Vec<ModKey>>,
275 - #[serde(default)]
276 - key: Option<KeyData>,
277 - action: KeyAction,
278 - #[serde(default)]
279 - arg: ArgData,
280 -}
281 -
282 -#[derive(Debug, Deserialize)]
283 -struct KeyPressData {
284 - modifiers: Vec<ModKey>,
285 - key: KeyData,
286 -}
287 -
288 -#[derive(Debug, Deserialize)]
289 -#[serde(untagged)]
290 -enum ArgData {
291 - None,
292 - String(String),
293 - Int(i32),
294 - Array(Vec<String>),
295 -}
296 -
297 -impl Default for ArgData {
298 - fn default() -> Self {
299 - ArgData::None
300 - }
301 -}
302 -
303 -#[derive(Debug, Deserialize)]
304 -struct StatusBlockData {
305 - format: String,
306 - command: String,
307 - #[serde(default)]
308 - command_arg: Option<String>,
309 - #[serde(default)]
310 - battery_formats: Option<BatteryFormats>,
311 - interval_secs: u64,
312 - color: u32,
313 - underline: bool,
314 -}
315 -
316 -#[derive(Debug, Deserialize)]
317 -struct BatteryFormats {
318 - charging: String,
319 - discharging: String,
320 - full: String,
321 -}
322 -
323 -#[derive(Debug, Deserialize)]
324 -struct ColorSchemeData {
325 - foreground: u32,
326 - background: u32,
327 - underline: u32,
328 -}
329 -
330 -fn config_data_to_config(data: ConfigData) -> Result<crate::Config, ConfigError> {
331 - let modkey = data.modkey.to_keybut_mask();
332 -
333 - let mut keybindings = Vec::new();
334 - for kb_data in data.keybindings {
335 - let keys = if let Some(keys_data) = kb_data.keys {
336 - keys_data
337 - .into_iter()
338 - .map(|kp| {
339 - let modifiers = kp
340 - .modifiers
341 - .iter()
342 - .map(|m| match m {
343 - ModKey::Mod => modkey,
344 - _ => m.to_keybut_mask(),
345 - })
346 - .collect();
347 -
348 - KeyPress {
349 - modifiers,
350 - keysym: kp.key.to_keysym(),
351 - }
352 - })
353 - .collect()
354 - } else if let (Some(modifiers), Some(key)) = (kb_data.modifiers, kb_data.key) {
355 - vec![KeyPress {
356 - modifiers: modifiers
357 - .iter()
358 - .map(|m| match m {
359 - ModKey::Mod => modkey,
360 - _ => m.to_keybut_mask(),
361 - })
362 - .collect(),
363 - keysym: key.to_keysym(),
364 - }]
365 - } else {
366 - return Err(ConfigError::ValidationError(
367 - "Keybinding must have either 'keys' or 'modifiers'+'key'".to_string(),
368 - ));
369 - };
370 -
371 - let action = kb_data.action;
372 - let arg = arg_data_to_arg(kb_data.arg)?;
373 -
374 - keybindings.push(KeyBinding::new(keys, action, arg));
375 - }
376 -
377 - let mut status_blocks = Vec::new();
378 - for block_data in data.status_blocks {
379 - let command = match block_data.command.as_str() {
380 - "DateTime" => {
381 - let fmt = block_data
382 - .command_arg
383 - .ok_or_else(|| ConfigError::MissingCommandArg {
384 - command: "DateTime".to_string(),
385 - field: "command_arg".to_string(),
386 - })?;
387 - BlockCommand::DateTime(fmt)
388 - }
389 - "Shell" => {
390 - let cmd = block_data
391 - .command_arg
392 - .ok_or_else(|| ConfigError::MissingCommandArg {
393 - command: "Shell".to_string(),
394 - field: "command_arg".to_string(),
395 - })?;
396 - BlockCommand::Shell(cmd)
397 - }
398 - "Ram" => BlockCommand::Ram,
399 - "Static" => {
400 - let text = block_data.command_arg.unwrap_or_default();
401 - BlockCommand::Static(text)
402 - }
403 - "Battery" => {
404 - let formats =
405 - block_data
406 - .battery_formats
407 - .ok_or_else(|| ConfigError::MissingCommandArg {
408 - command: "Battery".to_string(),
409 - field: "battery_formats".to_string(),
410 - })?;
411 - BlockCommand::Battery {
412 - format_charging: formats.charging,
413 - format_discharging: formats.discharging,
414 - format_full: formats.full,
415 - }
416 - }
417 - _ => return Err(ConfigError::UnknownBlockCommand(block_data.command)),
418 - };
419 -
420 - status_blocks.push(BlockConfig {
421 - format: block_data.format,
422 - command,
423 - interval_secs: block_data.interval_secs,
424 - color: block_data.color,
425 - underline: block_data.underline,
426 - });
427 - }
428 -
429 - let layout_symbols = data
430 - .layout_symbols
431 - .into_iter()
432 - .map(|l| crate::LayoutSymbolOverride {
433 - name: l.name,
434 - symbol: l.symbol,
435 - })
436 - .collect();
437 -
438 - Ok(crate::Config {
439 - border_width: data.border_width,
440 - border_focused: data.border_focused,
441 - border_unfocused: data.border_unfocused,
442 - font: data.font,
443 - gaps_enabled: data.gaps_enabled,
444 - gap_inner_horizontal: data.gap_inner_horizontal,
445 - gap_inner_vertical: data.gap_inner_vertical,
446 - gap_outer_horizontal: data.gap_outer_horizontal,
447 - gap_outer_vertical: data.gap_outer_vertical,
448 - terminal: data.terminal,
449 - modkey,
450 - tags: data.tags,
451 - layout_symbols,
452 - keybindings,
453 - status_blocks,
454 - scheme_normal: crate::ColorScheme {
455 - foreground: data.scheme_normal.foreground,
456 - background: data.scheme_normal.background,
457 - underline: data.scheme_normal.underline,
458 - },
459 - scheme_occupied: crate::ColorScheme {
460 - foreground: data.scheme_occupied.foreground,
461 - background: data.scheme_occupied.background,
462 - underline: data.scheme_occupied.underline,
463 - },
464 - scheme_selected: crate::ColorScheme {
465 - foreground: data.scheme_selected.foreground,
466 - background: data.scheme_selected.background,
467 - underline: data.scheme_selected.underline,
468 - },
469 - autostart: data.autostart,
470 - })
471 -}
472 -
473 -fn arg_data_to_arg(data: ArgData) -> Result<Arg, ConfigError> {
474 - match data {
475 - ArgData::None => Ok(Arg::None),
476 - ArgData::String(s) => Ok(Arg::Str(s)),
477 - ArgData::Int(n) => Ok(Arg::Int(n)),
478 - ArgData::Array(arr) => Ok(Arg::Array(arr)),
479 - }
480 -}
+0 −30 src/errors.rs
@@ -22,7 +22,6 @@ pub enum X11Error {
22 22
23 #[derive(Debug)] 23 #[derive(Debug)]
24 pub enum ConfigError { 24 pub enum ConfigError {
25 - ParseError(ron::error::SpannedError),
26 LuaError(String), 25 LuaError(String),
27 InvalidModkey(String), 26 InvalidModkey(String),
28 UnknownKey(String), 27 UnknownKey(String),
@@ -30,10 +29,6 @@ pub enum ConfigError {
30 UnknownBlockCommand(String), 29 UnknownBlockCommand(String),
31 MissingCommandArg { command: String, field: String }, 30 MissingCommandArg { command: String, field: String },
32 ValidationError(String), 31 ValidationError(String),
33 - InvalidVariableName(String),
34 - InvalidDefine(String),
35 - UndefinedVariable(String),
36 - MigrationError(String),
37 } 32 }
38 33
39 #[derive(Debug)] 34 #[derive(Debug)]
@@ -78,7 +73,6 @@ impl std::error::Error for X11Error {}
78 impl std::fmt::Display for ConfigError { 73 impl std::fmt::Display for ConfigError {
79 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 74 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80 match self { 75 match self {
81 - Self::ParseError(err) => write!(f, "Failed to parse RON config: {}", err),
82 Self::LuaError(msg) => write!(f, "Lua config error: {}", msg), 76 Self::LuaError(msg) => write!(f, "Lua config error: {}", msg),
83 Self::InvalidModkey(key) => write!(f, "Invalid modkey: {}", key), 77 Self::InvalidModkey(key) => write!(f, "Invalid modkey: {}", key),
84 Self::UnknownKey(key) => write!(f, "Unknown key: {}", key), 78 Self::UnknownKey(key) => write!(f, "Unknown key: {}", key),
@@ -88,24 +82,6 @@ impl std::fmt::Display for ConfigError {
88 write!(f, "{} command requires {}", command, field) 82 write!(f, "{} command requires {}", command, field)
89 } 83 }
90 Self::ValidationError(msg) => write!(f, "Config validation error: {}", msg), 84 Self::ValidationError(msg) => write!(f, "Config validation error: {}", msg),
91 - Self::InvalidVariableName(name) => {
92 - write!(f, "Invalid variable name '{}': must start with $", name)
93 - }
94 - Self::InvalidDefine(line) => {
95 - write!(
96 - f,
97 - "Invalid #DEFINE syntax: '{}'. Expected: #DEFINE $var_name = value",
98 - line
99 - )
100 - }
101 - Self::UndefinedVariable(var) => {
102 - write!(
103 - f,
104 - "Undefined variable '{}': define it with #DEFINE before use",
105 - var
106 - )
107 - }
108 - Self::MigrationError(msg) => write!(f, "Migration error: {}", msg),
109 } 85 }
110 } 86 }
111 } 87 }
@@ -162,12 +138,6 @@ impl From<std::num::ParseIntError> for BlockError {
162 } 138 }
163 } 139 }
164 140
165 -impl From<ron::error::SpannedError> for ConfigError {
166 - fn from(value: ron::error::SpannedError) -> Self {
167 - ConfigError::ParseError(value)
168 - }
169 -}
170 -
171 impl From<x11rb::errors::ConnectError> for X11Error { 141 impl From<x11rb::errors::ConnectError> for X11Error {
172 fn from(value: x11rb::errors::ConnectError) -> Self { 142 fn from(value: x11rb::errors::ConnectError) -> Self {
173 X11Error::ConnectError(value) 143 X11Error::ConnectError(value)
+85 −0 src/keyboard/keysyms.rs
@@ -83,6 +83,91 @@ pub const XF86_AUDIO_MUTE: Keysym = 0x1008ff12;
83 pub const XF86_MON_BRIGHTNESS_UP: Keysym = 0x1008ff02; 83 pub const XF86_MON_BRIGHTNESS_UP: Keysym = 0x1008ff02;
84 pub const XF86_MON_BRIGHTNESS_DOWN: Keysym = 0x1008ff03; 84 pub const XF86_MON_BRIGHTNESS_DOWN: Keysym = 0x1008ff03;
85 85
86 +pub fn keysym_from_str(s: &str) -> Option<Keysym> {
87 + match s {
88 + "Return" => Some(XK_RETURN),
89 + "Escape" => Some(XK_ESCAPE),
90 + "Space" => Some(XK_SPACE),
91 + "Tab" => Some(XK_TAB),
92 + "Backspace" => Some(XK_BACKSPACE),
93 + "Delete" => Some(XK_DELETE),
94 + "F1" => Some(XK_F1),
95 + "F2" => Some(XK_F2),
96 + "F3" => Some(XK_F3),
97 + "F4" => Some(XK_F4),
98 + "F5" => Some(XK_F5),
99 + "F6" => Some(XK_F6),
100 + "F7" => Some(XK_F7),
101 + "F8" => Some(XK_F8),
102 + "F9" => Some(XK_F9),
103 + "F10" => Some(XK_F10),
104 + "F11" => Some(XK_F11),
105 + "F12" => Some(XK_F12),
106 + "A" => Some(XK_A),
107 + "B" => Some(XK_B),
108 + "C" => Some(XK_C),
109 + "D" => Some(XK_D),
110 + "E" => Some(XK_E),
111 + "F" => Some(XK_F),
112 + "G" => Some(XK_G),
113 + "H" => Some(XK_H),
114 + "I" => Some(XK_I),
115 + "J" => Some(XK_J),
116 + "K" => Some(XK_K),
117 + "L" => Some(XK_L),
118 + "M" => Some(XK_M),
119 + "N" => Some(XK_N),
120 + "O" => Some(XK_O),
121 + "P" => Some(XK_P),
122 + "Q" => Some(XK_Q),
123 + "R" => Some(XK_R),
124 + "S" => Some(XK_S),
125 + "T" => Some(XK_T),
126 + "U" => Some(XK_U),
127 + "V" => Some(XK_V),
128 + "W" => Some(XK_W),
129 + "X" => Some(XK_X),
130 + "Y" => Some(XK_Y),
131 + "Z" => Some(XK_Z),
132 + "0" => Some(XK_0),
133 + "1" => Some(XK_1),
134 + "2" => Some(XK_2),
135 + "3" => Some(XK_3),
136 + "4" => Some(XK_4),
137 + "5" => Some(XK_5),
138 + "6" => Some(XK_6),
139 + "7" => Some(XK_7),
140 + "8" => Some(XK_8),
141 + "9" => Some(XK_9),
142 + "Left" => Some(XK_LEFT),
143 + "Right" => Some(XK_RIGHT),
144 + "Up" => Some(XK_UP),
145 + "Down" => Some(XK_DOWN),
146 + "Home" => Some(XK_HOME),
147 + "End" => Some(XK_END),
148 + "PageUp" => Some(XK_PAGE_UP),
149 + "PageDown" => Some(XK_PAGE_DOWN),
150 + "Insert" => Some(XK_INSERT),
151 + "Minus" => Some(XK_MINUS),
152 + "Equal" => Some(XK_EQUAL),
153 + "BracketLeft" => Some(XK_LEFT_BRACKET),
154 + "BracketRight" => Some(XK_RIGHT_BRACKET),
155 + "Semicolon" => Some(XK_SEMICOLON),
156 + "Apostrophe" => Some(XK_APOSTROPHE),
157 + "Grave" => Some(XK_GRAVE),
158 + "Backslash" => Some(XK_BACKSLASH),
159 + "Comma" => Some(XK_COMMA),
160 + "Period" => Some(XK_PERIOD),
161 + "Slash" => Some(XK_SLASH),
162 + "AudioRaiseVolume" => Some(XF86_AUDIO_RAISE_VOLUME),
163 + "AudioLowerVolume" => Some(XF86_AUDIO_LOWER_VOLUME),
164 + "AudioMute" => Some(XF86_AUDIO_MUTE),
165 + "MonBrightnessUp" => Some(XF86_MON_BRIGHTNESS_UP),
166 + "MonBrightnessDown" => Some(XF86_MON_BRIGHTNESS_DOWN),
167 + _ => None,
168 + }
169 +}
170 +
86 pub fn format_keysym(keysym: Keysym) -> String { 171 pub fn format_keysym(keysym: Keysym) -> String {
87 match keysym { 172 match keysym {
88 XK_RETURN => "Return".to_string(), 173 XK_RETURN => "Return".to_string(),
+6 −22 src/window_manager.rs
@@ -254,32 +254,16 @@ impl WindowManager {
254 }; 254 };
255 255
256 let lua_path = config_dir.join("config.lua"); 256 let lua_path = config_dir.join("config.lua");
257 - let ron_path = config_dir.join("config.ron");
258 257
259 - let config_path = if lua_path.exists() { 258 + if !lua_path.exists() {
260 - lua_path 259 + return Err("No config.lua file found".to_string());
261 - } else if ron_path.exists() { 260 + }
262 - ron_path
263 - } else {
264 - return Err("No config file found".to_string());
265 - };
266 261
267 - let config_str = std::fs::read_to_string(&config_path) 262 + let config_str = std::fs::read_to_string(&lua_path)
268 .map_err(|e| format!("Failed to read config: {}", e))?; 263 .map_err(|e| format!("Failed to read config: {}", e))?;
269 264
270 - let is_lua = config_path 265 + let new_config = crate::config::parse_lua_config(&config_str, Some(&config_dir))
271 - .extension() 266 + .map_err(|e| format!("Config error: {}", e))?;
272 - .and_then(|s| s.to_str())
273 - .map(|s| s == "lua")
274 - .unwrap_or(false);
275 -
276 - let new_config = if is_lua {
277 - let config_dir = config_path.parent();
278 - crate::config::parse_lua_config(&config_str, config_dir)
279 - .map_err(|e| format!("Config error: {}", e))?
280 - } else {
281 - crate::config::parse_config(&config_str).map_err(|e| format!("Config error: {}", e))?
282 - };
283 267
284 self.config = new_config; 268 self.config = new_config;
285 self.error_message = None; 269 self.error_message = None;
+114 −148 templates/config.lua
@@ -1,10 +1,10 @@
1 --- OXWM Configuration File (Lua) 1 +---@meta
2 --- Migrated from config.ron 2 +---OXWM Configuration File (Lua)
3 --- Edit this file and reload with Mod+Shift+R (no compilation needed!) 3 +---Using the new functional API
4 +---Edit this file and reload with Mod+Shift+R (no compilation needed!)
4 5
5 -local terminal = "st" 6 +---Load type definitions for LSP
6 -local modkey = "Mod4" 7 +---@module 'oxwm'
7 -local secondary_modkey = "Mod1"
8 8
9 -- Color palette 9 -- Color palette
10 local colors = { 10 local colors = {
@@ -20,145 +20,111 @@ local colors = {
20 purple = "#ad8ee6", 20 purple = "#ad8ee6",
21 } 21 }
22 22
23 --- Main configuration table 23 +-- Basic settings
24 -return { 24 +oxwm.set_terminal("st")
25 - -- Appearance 25 +oxwm.set_modkey("Mod4")
26 - border_width = 2, 26 +oxwm.set_tags({ "1", "2", "3", "4", "5", "6", "7", "8", "9" })
27 - border_focused = colors.blue, 27 +
28 - border_unfocused = colors.grey, 28 +-- Layout symbol overrides
29 - font = "monospace:style=Bold:size=10", 29 +oxwm.set_layout_symbol("tiling", "[T]")
30 - 30 +oxwm.set_layout_symbol("normie", "[F]")
31 - -- Window gaps 31 +
32 - gaps_enabled = true, 32 +-- Border configuration
33 - gap_inner_horizontal = 5, 33 +oxwm.border.set_width(2)
34 - gap_inner_vertical = 5, 34 +oxwm.border.set_focused_color(colors.blue)
35 - gap_outer_horizontal = 5, 35 +oxwm.border.set_unfocused_color(colors.grey)
36 - gap_outer_vertical = 5, 36 +
37 - 37 +-- Gap configuration
38 - -- Basics 38 +oxwm.gaps.set_enabled(true)
39 - modkey = "Mod4", 39 +oxwm.gaps.set_inner(5, 5) -- horizontal, vertical
40 - terminal = "st", 40 +oxwm.gaps.set_outer(5, 5) -- horizontal, vertical
41 - 41 +
42 - -- Workspace tags 42 +-- Bar configuration
43 - tags = { "1", "2", "3", "4", "5", "6", "7", "8", "9" }, 43 +oxwm.bar.set_font("monospace:style=Bold:size=10")
44 - 44 +
45 - -- Layout symbol overrides 45 +-- Bar color schemes (for tag display)
46 - layout_symbols = { 46 +oxwm.bar.set_scheme_normal(colors.fg, colors.bg, "#444444")
47 - { name = "tiling", symbol = "[T]" }, 47 +oxwm.bar.set_scheme_occupied(colors.cyan, colors.bg, colors.cyan)
48 - { name = "normie", symbol = "[F]" }, 48 +oxwm.bar.set_scheme_selected(colors.cyan, colors.bg, colors.purple)
49 - }, 49 +
50 - 50 +-- Keybindings
51 - -- Keybindings 51 +
52 - keybindings = { 52 +-- Basic window management
53 - { modifiers = { "Mod4" }, key = "Return", action = "Spawn", arg = "st" }, 53 +oxwm.key.bind({ "Mod4" }, "Return", oxwm.spawn("st"))
54 - { modifiers = { "Mod4" }, key = "D", action = "Spawn", arg = { "sh", "-c", "dmenu_run -l 10" } }, 54 +oxwm.key.bind({ "Mod4" }, "D", oxwm.spawn({ "sh", "-c", "dmenu_run -l 10" }))
55 - { modifiers = { "Mod4" }, key = "S", action = "Spawn", arg = { "sh", "-c", "maim -s | xclip -selection clipboard -t image/png" } }, 55 +oxwm.key.bind({ "Mod4" }, "S", oxwm.spawn({ "sh", "-c", "maim -s | xclip -selection clipboard -t image/png" }))
56 - { modifiers = { "Mod4" }, key = "Q", action = "KillClient" }, 56 +oxwm.key.bind({ "Mod4" }, "Q", oxwm.client.kill())
57 - { modifiers = { "Mod4", "Shift" }, key = "Slash", action = "ShowKeybindOverlay" }, 57 +
58 - { modifiers = { "Mod4", "Shift" }, key = "F", action = "ToggleFullScreen" }, 58 +-- Keybind overlay
59 - { modifiers = { "Mod4", "Shift" }, key = "Space", action = "ToggleFloating" }, 59 +oxwm.key.bind({ "Mod4", "Shift" }, "Slash", oxwm.show_keybinds())
60 - { modifiers = { "Mod4" }, key = "F", action = "ChangeLayout", arg = "normie" }, 60 +
61 - { modifiers = { "Mod4" }, key = "C", action = "ChangeLayout", arg = "tiling" }, 61 +-- Client actions
62 - { modifiers = { "Mod1" }, key = "N", action = "CycleLayout" }, 62 +oxwm.key.bind({ "Mod4", "Shift" }, "F", oxwm.client.toggle_fullscreen())
63 - { modifiers = { "Mod4" }, key = "A", action = "ToggleGaps" }, 63 +oxwm.key.bind({ "Mod4", "Shift" }, "Space", oxwm.client.toggle_floating())
64 - { modifiers = { "Mod4", "Shift" }, key = "Q", action = "Quit" }, 64 +
65 - { modifiers = { "Mod4", "Shift" }, key = "R", action = "Restart" }, 65 +-- Layout management
66 - { modifiers = { "Mod4" }, key = "H", action = "FocusDirection", arg = 2 }, 66 +oxwm.key.bind({ "Mod4" }, "F", oxwm.layout.set("normie"))
67 - { modifiers = { "Mod4" }, key = "J", action = "FocusDirection", arg = 1 }, 67 +oxwm.key.bind({ "Mod4" }, "C", oxwm.layout.set("tiling"))
68 - { modifiers = { "Mod4" }, key = "K", action = "FocusDirection", arg = 0 }, 68 +oxwm.key.bind({ "Mod1" }, "N", oxwm.layout.cycle())
69 - { modifiers = { "Mod4" }, key = "L", action = "FocusDirection", arg = 3 }, 69 +
70 - { modifiers = { "Mod4" }, key = "Comma", action = "FocusMonitor", arg = -1 }, 70 +-- Gaps toggle
71 - { modifiers = { "Mod4" }, key = "Period", action = "FocusMonitor", arg = 1 }, 71 +oxwm.key.bind({ "Mod4" }, "A", oxwm.toggle_gaps())
72 - { modifiers = { "Mod4" }, key = "1", action = "ViewTag", arg = 0 }, 72 +
73 - { modifiers = { "Mod4" }, key = "2", action = "ViewTag", arg = 1 }, 73 +-- WM controls
74 - { modifiers = { "Mod4" }, key = "3", action = "ViewTag", arg = 2 }, 74 +oxwm.key.bind({ "Mod4", "Shift" }, "Q", oxwm.quit())
75 - { modifiers = { "Mod4" }, key = "4", action = "ViewTag", arg = 3 }, 75 +oxwm.key.bind({ "Mod4", "Shift" }, "R", oxwm.restart())
76 - { modifiers = { "Mod4" }, key = "5", action = "ViewTag", arg = 4 }, 76 +
77 - { modifiers = { "Mod4" }, key = "6", action = "ViewTag", arg = 5 }, 77 +-- Focus direction (vim keys: h=left=2, j=down=1, k=up=0, l=right=3)
78 - { modifiers = { "Mod4" }, key = "7", action = "ViewTag", arg = 6 }, 78 +oxwm.key.bind({ "Mod4" }, "H", oxwm.client.focus_direction("left"))
79 - { modifiers = { "Mod4" }, key = "8", action = "ViewTag", arg = 7 }, 79 +oxwm.key.bind({ "Mod4" }, "J", oxwm.client.focus_direction("down"))
80 - { modifiers = { "Mod4" }, key = "9", action = "ViewTag", arg = 8 }, 80 +oxwm.key.bind({ "Mod4" }, "K", oxwm.client.focus_direction("up"))
81 - { modifiers = { "Mod4", "Shift" }, key = "1", action = "MoveToTag", arg = 0 }, 81 +oxwm.key.bind({ "Mod4" }, "L", oxwm.client.focus_direction("right"))
82 - { modifiers = { "Mod4", "Shift" }, key = "2", action = "MoveToTag", arg = 1 }, 82 +
83 - { modifiers = { "Mod4", "Shift" }, key = "3", action = "MoveToTag", arg = 2 }, 83 +-- Monitor focus
84 - { modifiers = { "Mod4", "Shift" }, key = "4", action = "MoveToTag", arg = 3 }, 84 +oxwm.key.bind({ "Mod4" }, "Comma", oxwm.focus_monitor(-1))
85 - { modifiers = { "Mod4", "Shift" }, key = "5", action = "MoveToTag", arg = 4 }, 85 +oxwm.key.bind({ "Mod4" }, "Period", oxwm.focus_monitor(1))
86 - { modifiers = { "Mod4", "Shift" }, key = "6", action = "MoveToTag", arg = 5 }, 86 +
87 - { modifiers = { "Mod4", "Shift" }, key = "7", action = "MoveToTag", arg = 6 }, 87 +-- Tag viewing
88 - { modifiers = { "Mod4", "Shift" }, key = "8", action = "MoveToTag", arg = 7 }, 88 +oxwm.key.bind({ "Mod4" }, "1", oxwm.tag.view(0))
89 - { modifiers = { "Mod4", "Shift" }, key = "9", action = "MoveToTag", arg = 8 }, 89 +oxwm.key.bind({ "Mod4" }, "2", oxwm.tag.view(1))
90 - { modifiers = { "Mod4", "Shift" }, key = "H", action = "SwapDirection", arg = 2 }, 90 +oxwm.key.bind({ "Mod4" }, "3", oxwm.tag.view(2))
91 - { modifiers = { "Mod4", "Shift" }, key = "J", action = "SwapDirection", arg = 1 }, 91 +oxwm.key.bind({ "Mod4" }, "4", oxwm.tag.view(3))
92 - { modifiers = { "Mod4", "Shift" }, key = "K", action = "SwapDirection", arg = 0 }, 92 +oxwm.key.bind({ "Mod4" }, "5", oxwm.tag.view(4))
93 - { modifiers = { "Mod4", "Shift" }, key = "L", action = "SwapDirection", arg = 3 }, 93 +oxwm.key.bind({ "Mod4" }, "6", oxwm.tag.view(5))
94 - { 94 +oxwm.key.bind({ "Mod4" }, "7", oxwm.tag.view(6))
95 - keys = { 95 +oxwm.key.bind({ "Mod4" }, "8", oxwm.tag.view(7))
96 - { modifiers = { "Mod4" }, key = "Space" }, 96 +oxwm.key.bind({ "Mod4" }, "9", oxwm.tag.view(8))
97 - { modifiers = { }, key = "T" }, 97 +
98 - }, 98 +-- Move window to tag
99 - action = "Spawn", 99 +oxwm.key.bind({ "Mod4", "Shift" }, "1", oxwm.tag.move_to(0))
100 - arg = "st" 100 +oxwm.key.bind({ "Mod4", "Shift" }, "2", oxwm.tag.move_to(1))
101 - }, 101 +oxwm.key.bind({ "Mod4", "Shift" }, "3", oxwm.tag.move_to(2))
102 - }, 102 +oxwm.key.bind({ "Mod4", "Shift" }, "4", oxwm.tag.move_to(3))
103 - 103 +oxwm.key.bind({ "Mod4", "Shift" }, "5", oxwm.tag.move_to(4))
104 - -- Status bar blocks 104 +oxwm.key.bind({ "Mod4", "Shift" }, "6", oxwm.tag.move_to(5))
105 - status_blocks = { 105 +oxwm.key.bind({ "Mod4", "Shift" }, "7", oxwm.tag.move_to(6))
106 - { 106 +oxwm.key.bind({ "Mod4", "Shift" }, "8", oxwm.tag.move_to(7))
107 - format = "Ram: {used}/{total} GB", 107 +oxwm.key.bind({ "Mod4", "Shift" }, "9", oxwm.tag.move_to(8))
108 - command = "Ram", 108 +
109 - interval_secs = 5, 109 +-- Swap windows in direction
110 - color = colors.light_blue, 110 +oxwm.key.bind({ "Mod4", "Shift" }, "H", oxwm.client.swap_direction("left"))
111 - underline = true 111 +oxwm.key.bind({ "Mod4", "Shift" }, "J", oxwm.client.swap_direction("down"))
112 - }, 112 +oxwm.key.bind({ "Mod4", "Shift" }, "K", oxwm.client.swap_direction("up"))
113 - { 113 +oxwm.key.bind({ "Mod4", "Shift" }, "L", oxwm.client.swap_direction("right"))
114 - format = " │ ", 114 +
115 - command = "Static", 115 +-- Keychord example: Mod4+Space then T to spawn terminal
116 - interval_secs = 999999999, 116 +oxwm.key.chord({
117 - color = colors.lavender, 117 + { { "Mod4" }, "Space" },
118 - underline = false 118 + { {}, "T" }
119 - }, 119 +}, oxwm.spawn("st"))
120 - { 120 +
121 - format = "Kernel: {}", 121 +-- Status bar blocks
122 - command = "Shell", 122 +oxwm.bar.add_block("Ram: {used}/{total} GB", "Ram", nil, 5, colors.light_blue, true)
123 - command_arg = "uname -r", 123 +oxwm.bar.add_block(" │ ", "Static", " │ ", 999999999, colors.lavender, false)
124 - interval_secs = 999999999, 124 +oxwm.bar.add_block("Kernel: {}", "Shell", "uname -r", 999999999, colors.red, true)
125 - color = colors.red, 125 +oxwm.bar.add_block(" │ ", "Static", " │ ", 999999999, colors.lavender, false)
126 - underline = true 126 +oxwm.bar.add_block("{}", "DateTime", "%a, %b %d - %-I:%M %P", 1, colors.cyan, true)
127 - }, 127 +
128 - { 128 +-- Autostart commands (runs once at startup)
129 - format = " │ ", 129 +-- oxwm.autostart("picom")
130 - command = "Static", 130 +-- oxwm.autostart("feh --bg-scale ~/wallpaper.jpg")
131 - interval_secs = 999999999,
132 - color = colors.lavender,
133 - underline = false
134 - },
135 - {
136 - format = "{}",
137 - command = "DateTime",
138 - command_arg = "%a, %b %d - %-I:%M %P",
139 - interval_secs = 1,
140 - color = colors.cyan,
141 - underline = true
142 - },
143 - },
144 -
145 - -- Color schemes for bar
146 - scheme_normal = {
147 - foreground = colors.fg,
148 - background = colors.bg,
149 - underline = "#444444"
150 - },
151 - scheme_occupied = {
152 - foreground = colors.cyan,
153 - background = colors.bg,
154 - underline = colors.cyan
155 - },
156 - scheme_selected = {
157 - foreground = colors.cyan,
158 - background = colors.bg,
159 - underline = colors.purple
160 - },
161 -
162 - -- Autostart commands
163 - autostart = { },
164 -}
+0 −127 templates/config.ron deleted file mode 100644
@@ -1,127 +0,0 @@
1 -#![enable(implicit_some)]
2 -// OXWM Configuration File
3 -// Edit this file and reload with Mod+Shift+R (no compilation needed!)
4 -
5 -#DEFINE $terminal = "st"
6 -#DEFINE $color_blue = 0x6dade3
7 -#DEFINE $color_grey = 0xbbbbbb
8 -#DEFINE $color_green = 0x9ece6a
9 -#DEFINE $color_red = 0xf7768e
10 -#DEFINE $color_cyan = 0x0db9d7
11 -#DEFINE $color_purple = 0xad8ee6
12 -#DEFINE $color_lavender = 0xa9b1d6
13 -#DEFINE $color_bg = 0x1a1b26
14 -#DEFINE $color_fg = 0xbbbbbb
15 -#DEFINE $color_light_blue = 0x7aa2f7
16 -#DEFINE $modkey = Mod4
17 -#DEFINE $secondary_modkey = Mod1
18 -
19 -(
20 - border_width: 2,
21 - border_focused: $color_blue,
22 - border_unfocused: $color_grey,
23 - font: "monospace:style=Bold:size=10",
24 -
25 - gaps_enabled: true,
26 - gap_inner_horizontal: 5,
27 - gap_inner_vertical: 5,
28 - gap_outer_horizontal: 5,
29 - gap_outer_vertical: 5,
30 -
31 - modkey: $modkey,
32 -
33 - terminal: $terminal,
34 -
35 - tags: ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
36 - layout_symbols: [
37 - (name: "tiling", symbol: "[T]"),
38 - (name: "normie", symbol: "[F]"),
39 - ],
40 -
41 - // Keybinding Format:
42 - //
43 - // New format (supports keychords - multi-key sequences):
44 - // (keys: [(modifiers: [...], key: X), (modifiers: [...], key: Y)], action: ..., arg: ...)
45 - //
46 - // Old format (single key, backwards compatible):
47 - // (modifiers: [...], key: X, action: ..., arg: ...)
48 - //
49 - // Examples:
50 - // Single key: (keys: [(modifiers: [Mod4], key: Return)], action: Spawn, arg: "st")
51 - // Keychord: (keys: [(modifiers: [Mod4], key: Space), (modifiers: [], key: F)], action: Spawn, arg: "firefox")
52 - //
53 - // You can cancel any in-progress keychord by pressing Escape.
54 -
55 - keybindings: [
56 - // Basic keybindings (old format for backwards compatibility)
57 - (modifiers: [$modkey], key: Return, action: Spawn, arg: $terminal),
58 - (modifiers: [$modkey], key: D, action: Spawn, arg: ["sh", "-c", "dmenu_run -l 10"]),
59 - (modifiers: [$modkey], key: S, action: Spawn, arg: ["sh", "-c", "maim -s | xclip -selection clipboard -t image/png"]),
60 - (modifiers: [$modkey], key: Q, action: KillClient),
61 - (modifiers: [$modkey, Shift], key: F, action: ToggleFullScreen),
62 - (modifiers: [$modkey, Shift], key: Space, action: ToggleFloating),
63 - (modifiers: [$modkey], key: F, action: ChangeLayout, arg: "normie"),
64 - (modifiers: [$modkey], key: C, action: ChangeLayout, arg: "tiling"),
65 - (modifiers: [$secondary_modkey], key: N, action: CycleLayout),
66 - (modifiers: [$modkey], key: A, action: ToggleGaps),
67 - (modifiers: [$modkey, Shift], key: Q, action: Quit),
68 - (modifiers: [$modkey, Shift], key: R, action: Restart),
69 - (modifiers: [$modkey], key: H, action: FocusDirection, arg: 2),
70 - (modifiers: [$modkey], key: J, action: FocusDirection, arg: 1),
71 - (modifiers: [$modkey], key: K, action: FocusDirection, arg: 0),
72 - (modifiers: [$modkey], key: L, action: FocusDirection, arg: 3),
73 - (modifiers: [$modkey], key: Comma, action: FocusMonitor, arg: -1),
74 - (modifiers: [$modkey], key: Period, action: FocusMonitor, arg: 1),
75 - (modifiers: [$modkey], key: Key1, action: ViewTag, arg: 0),
76 - (modifiers: [$modkey], key: Key2, action: ViewTag, arg: 1),
77 - (modifiers: [$modkey], key: Key3, action: ViewTag, arg: 2),
78 - (modifiers: [$modkey], key: Key4, action: ViewTag, arg: 3),
79 - (modifiers: [$modkey], key: Key5, action: ViewTag, arg: 4),
80 - (modifiers: [$modkey], key: Key6, action: ViewTag, arg: 5),
81 - (modifiers: [$modkey], key: Key7, action: ViewTag, arg: 6),
82 - (modifiers: [$modkey], key: Key8, action: ViewTag, arg: 7),
83 - (modifiers: [$modkey], key: Key9, action: ViewTag, arg: 8),
84 - (modifiers: [$modkey, Shift], key: Key1, action: MoveToTag, arg: 0),
85 - (modifiers: [$modkey, Shift], key: Key2, action: MoveToTag, arg: 1),
86 - (modifiers: [$modkey, Shift], key: Key3, action: MoveToTag, arg: 2),
87 - (modifiers: [$modkey, Shift], key: Key4, action: MoveToTag, arg: 3),
88 - (modifiers: [$modkey, Shift], key: Key5, action: MoveToTag, arg: 4),
89 - (modifiers: [$modkey, Shift], key: Key6, action: MoveToTag, arg: 5),
90 - (modifiers: [$modkey, Shift], key: Key7, action: MoveToTag, arg: 6),
91 - (modifiers: [$modkey, Shift], key: Key8, action: MoveToTag, arg: 7),
92 - (modifiers: [$modkey, Shift], key: Key9, action: MoveToTag, arg: 8),
93 -
94 - (modifiers: [$modkey, Shift], key: H, action: SwapDirection, arg: 2),
95 - (modifiers: [$modkey, Shift], key: J, action: SwapDirection, arg: 1),
96 - (modifiers: [$modkey, Shift], key: K, action: SwapDirection, arg: 0),
97 - (modifiers: [$modkey, Shift], key: L, action: SwapDirection, arg: 3),
98 -
99 - // Example keychord bindings (uncomment to use):
100 - // KEYCHORDS
101 - // Press Mod4+Space, then t to spawn terminal
102 - (keys: [(modifiers: [Mod4], key: Space), (modifiers: [], key: T)], action: Spawn, arg: $terminal),
103 - ],
104 -
105 - status_blocks: [
106 - (format: "Ram: {used}/{total} GB", command: "Ram", interval_secs: 5, color: $color_light_blue, underline: true),
107 - (format: " │ ", command: "Static", interval_secs: 18446744073709551615, color: $color_lavender, underline: false),
108 - (format: "Kernel: {}", command: "Shell", command_arg: "uname -r", interval_secs: 18446744073709551615, color: $color_red, underline: true),
109 - (format: " │ ", command: "Static", interval_secs: 18446744073709551615, color: $color_lavender, underline: false),
110 - (format: "{}", command: "DateTime", command_arg: "%a, %b %d - %-I:%M %P", interval_secs: 1, color: $color_cyan, underline: true),
111 - ],
112 -
113 - scheme_normal: (foreground: $color_fg, background: $color_bg, underline: 0x444444),
114 - scheme_occupied: (foreground: $color_cyan, background: $color_bg, underline: $color_cyan),
115 - scheme_selected: (foreground: $color_cyan, background: $color_bg, underline: $color_purple),
116 -
117 - // Autostart commands - these are executed when the window manager starts
118 - // Commands are run in a shell, so you can use shell syntax (pipes, &&, etc.)
119 - // Example: ["picom", "nitrogen --restore", "~/.config/polybar/launch.sh"]
120 - autostart: [
121 - // Uncomment and add your autostart commands here:
122 - // "picom -b",
123 - // "nitrogen --restore &",
124 - // "dunst &",
125 - ],
126 -)
127 -
+213 −0 templates/oxwm.lua new file mode 100644
@@ -0,0 +1,213 @@
1 +---@meta
2 +
3 +---OXWM Configuration API
4 +---@class oxwm
5 +oxwm = {}
6 +
7 +---Spawn a command
8 +---@param cmd string|string[] Command to spawn (string or array of strings)
9 +---@return table Action table for keybinding
10 +function oxwm.spawn(cmd) end
11 +
12 +---Set the terminal emulator
13 +---@param terminal string Terminal command (e.g., "st", "alacritty")
14 +function oxwm.set_terminal(terminal) end
15 +
16 +---Set the modifier key
17 +---@param modkey string Modifier key ("Mod1", "Mod4", "Shift", "Control")
18 +function oxwm.set_modkey(modkey) end
19 +
20 +---Set workspace tags
21 +---@param tags string[] Array of tag names
22 +function oxwm.set_tags(tags) end
23 +
24 +---Set layout symbol override
25 +---@param name string Layout name (e.g., "tiling", "normie")
26 +---@param symbol string Symbol to display (e.g., "[T]", "[F]")
27 +function oxwm.set_layout_symbol(name, symbol) end
28 +
29 +---Quit the window manager
30 +---@return table Action table for keybinding
31 +function oxwm.quit() end
32 +
33 +---Restart the window manager
34 +---@return table Action table for keybinding
35 +function oxwm.restart() end
36 +
37 +---Recompile the window manager
38 +---@return table Action table for keybinding
39 +function oxwm.recompile() end
40 +
41 +---Toggle gaps on/off
42 +---@return table Action table for keybinding
43 +function oxwm.toggle_gaps() end
44 +
45 +---Show keybind overlay
46 +---@return table Action table for keybinding
47 +function oxwm.show_keybinds() end
48 +
49 +---Focus monitor by index
50 +---@param index integer Monitor index (-1 for previous, 1 for next)
51 +---@return table Action table for keybinding
52 +function oxwm.focus_monitor(index) end
53 +
54 +---Keybinding module
55 +---@class oxwm.key
56 +oxwm.key = {}
57 +
58 +---Bind a key combination to an action
59 +---@param modifiers string|string[] Modifier keys (e.g., {"Mod4"}, {"Mod4", "Shift"})
60 +---@param key string Key name (e.g., "Return", "Q", "1")
61 +---@param action table Action returned by oxwm functions
62 +function oxwm.key.bind(modifiers, key, action) end
63 +
64 +---Bind a keychord (multi-key sequence) to an action
65 +---@param keys table[] Array of key presses, each: {{modifiers}, key}
66 +---@param action table Action returned by oxwm functions
67 +function oxwm.key.chord(keys, action) end
68 +
69 +---Gap configuration module
70 +---@class oxwm.gaps
71 +oxwm.gaps = {}
72 +
73 +---Set gaps enabled/disabled
74 +---@param enabled boolean Enable or disable gaps
75 +function oxwm.gaps.set_enabled(enabled) end
76 +
77 +---Enable gaps
78 +function oxwm.gaps.enable() end
79 +
80 +---Disable gaps
81 +function oxwm.gaps.disable() end
82 +
83 +---Set inner gaps
84 +---@param horizontal integer Horizontal inner gap in pixels
85 +---@param vertical integer Vertical inner gap in pixels
86 +function oxwm.gaps.set_inner(horizontal, vertical) end
87 +
88 +---Set outer gaps
89 +---@param horizontal integer Horizontal outer gap in pixels
90 +---@param vertical integer Vertical outer gap in pixels
91 +function oxwm.gaps.set_outer(horizontal, vertical) end
92 +
93 +---Border configuration module
94 +---@class oxwm.border
95 +oxwm.border = {}
96 +
97 +---Set border width
98 +---@param width integer Border width in pixels
99 +function oxwm.border.set_width(width) end
100 +
101 +---Set focused window border color
102 +---@param color string|integer Color as hex string ("#ff0000", "0xff0000") or integer
103 +function oxwm.border.set_focused_color(color) end
104 +
105 +---Set unfocused window border color
106 +---@param color string|integer Color as hex string ("#666666", "0x666666") or integer
107 +function oxwm.border.set_unfocused_color(color) end
108 +
109 +---Client/window management module
110 +---@class oxwm.client
111 +oxwm.client = {}
112 +
113 +---Kill the focused window
114 +---@return table Action table for keybinding
115 +function oxwm.client.kill() end
116 +
117 +---Toggle fullscreen mode
118 +---@return table Action table for keybinding
119 +function oxwm.client.toggle_fullscreen() end
120 +
121 +---Toggle floating mode
122 +---@return table Action table for keybinding
123 +function oxwm.client.toggle_floating() end
124 +
125 +---Focus window in direction
126 +---@param direction "up"|"down"|"left"|"right" Direction to focus
127 +---@return table Action table for keybinding
128 +function oxwm.client.focus_direction(direction) end
129 +
130 +---Swap window in direction
131 +---@param direction "up"|"down"|"left"|"right" Direction to swap
132 +---@return table Action table for keybinding
133 +function oxwm.client.swap_direction(direction) end
134 +
135 +---Smart move window (move or swap)
136 +---@param direction "up"|"down"|"left"|"right" Direction to move
137 +---@return table Action table for keybinding
138 +function oxwm.client.smart_move(direction) end
139 +
140 +---Focus stack (next/previous window)
141 +---@param dir integer Direction (1 for next, -1 for previous)
142 +---@return table Action table for keybinding
143 +function oxwm.client.focus_stack(dir) end
144 +
145 +---Exchange client positions
146 +---@return table Action table for keybinding
147 +function oxwm.client.exchange() end
148 +
149 +---Layout management module
150 +---@class oxwm.layout
151 +oxwm.layout = {}
152 +
153 +---Cycle through layouts
154 +---@return table Action table for keybinding
155 +function oxwm.layout.cycle() end
156 +
157 +---Set specific layout
158 +---@param name string Layout name (e.g., "tiling", "normie")
159 +---@return table Action table for keybinding
160 +function oxwm.layout.set(name) end
161 +
162 +---Tag/workspace management module
163 +---@class oxwm.tag
164 +oxwm.tag = {}
165 +
166 +---View/switch to tag
167 +---@param index integer Tag index (0-based)
168 +---@return table Action table for keybinding
169 +function oxwm.tag.view(index) end
170 +
171 +---Move focused window to tag
172 +---@param index integer Tag index (0-based)
173 +---@return table Action table for keybinding
174 +function oxwm.tag.move_to(index) end
175 +
176 +---Status bar configuration module
177 +---@class oxwm.bar
178 +oxwm.bar = {}
179 +
180 +---Set status bar font
181 +---@param font string Font string (e.g., "monospace:style=Bold:size=10")
182 +function oxwm.bar.set_font(font) end
183 +
184 +---Add a status bar block
185 +---@param format string Format string with {} placeholders
186 +---@param command "DateTime"|"Shell"|"Ram"|"Static"|"Battery" Block command type
187 +---@param arg string|table|nil Command argument (format for DateTime, command for Shell, text for Static, formats table for Battery, nil for Ram)
188 +---@param interval integer Update interval in seconds
189 +---@param color string|integer Color as hex string or integer
190 +---@param underline boolean Whether to underline the block
191 +function oxwm.bar.add_block(format, command, arg, interval, color, underline) end
192 +
193 +---Set normal tag color scheme (unselected, no windows)
194 +---@param foreground string|integer Foreground color
195 +---@param background string|integer Background color
196 +---@param underline string|integer Underline color
197 +function oxwm.bar.set_scheme_normal(foreground, background, underline) end
198 +
199 +---Set occupied tag color scheme (unselected, has windows)
200 +---@param foreground string|integer Foreground color
201 +---@param background string|integer Background color
202 +---@param underline string|integer Underline color
203 +function oxwm.bar.set_scheme_occupied(foreground, background, underline) end
204 +
205 +---Set selected tag color scheme (currently selected tag)
206 +---@param foreground string|integer Foreground color
207 +---@param background string|integer Background color
208 +---@param underline string|integer Underline color
209 +function oxwm.bar.set_scheme_selected(foreground, background, underline) end
210 +
211 +---Add an autostart command
212 +---@param cmd string Command to run at startup
213 +function oxwm.autostart(cmd) end