tony / oxwm

Branch: 9c02ffe
Switch branches/tags
master
emzywastaken refactor(wm): centralize config reload logic with callback fn 43022c0 2026-02-22
599 lines · 20.7 KB Raw Blame History
1 const std = @import("std");
2 const mem = std.mem;
3
4 const display_mod = @import("x11/display.zig");
5 const xlib = @import("x11/xlib.zig");
6 const events = @import("x11/events.zig");
7 const atoms_mod = @import("x11/atoms.zig");
8 const chord_mod = @import("keyboard/chord.zig");
9 const client_mod = @import("client.zig");
10 const monitor_mod = @import("monitor.zig");
11 const bar_mod = @import("bar/bar.zig");
12 const blocks_mod = @import("bar/blocks/blocks.zig");
13 const config_mod = @import("config/config.zig");
14 const overlay_mod = @import("overlay.zig");
15 const animations = @import("animations.zig");
16 const tiling = @import("layouts/tiling.zig");
17 const monocle = @import("layouts/monocle.zig");
18 const floating = @import("layouts/floating.zig");
19 const scrolling = @import("layouts/scrolling.zig");
20 const grid = @import("layouts/grid.zig");
21
22 const Display = display_mod.Display;
23 const Atoms = atoms_mod.Atoms;
24 const ChordState = chord_mod.ChordState;
25 const Client = client_mod.Client;
26 const Monitor = monitor_mod.Monitor;
27 const Bar = bar_mod.Bar;
28 const Config = config_mod.Config;
29
30 // Standard ICCCM WM_STATE values used by get_state and set_client_state.
31 pub const NormalState: c_long = 1;
32 pub const WithdrawnState: c_long = 0;
33 pub const IconicState: c_long = 3;
34 pub const IsViewable: c_int = 2;
35
36 pub const Cursors = struct {
37 normal: xlib.Cursor,
38 resize: xlib.Cursor,
39 move: xlib.Cursor,
40
41 pub fn init(display: *Display) Cursors {
42 return .{
43 .normal = xlib.XCreateFontCursor(display.handle, xlib.XC_left_ptr),
44 .resize = xlib.XCreateFontCursor(display.handle, xlib.XC_sizing),
45 .move = xlib.XCreateFontCursor(display.handle, xlib.XC_fleur),
46 };
47 }
48 };
49
50 pub const WindowManager = struct {
51 allocator: mem.Allocator,
52
53 /// The connection to the X server.
54 display: Display,
55 x11_fd: c_int,
56 /// Invisible 1×1 window used to satisfy the _NET_SUPPORTING_WM_CHECK
57 /// EWMH convention.
58 wm_check_window: xlib.Window,
59
60 atoms: Atoms,
61 cursors: Cursors,
62 /// Cached numlock modifier mask, refreshed before any key/button grab.
63 numlock_mask: c_uint,
64
65 config: Config,
66 /// Path to the config file that was loaded.
67 /// Null if using default config.
68 config_path: ?[]const u8,
69
70 /// Head of the linked list of all managed monitors.
71 monitors: ?*Monitor,
72 /// The monitor that currently has input focus.
73 selected_monitor: ?*Monitor,
74
75 /// Head of the linked list of status bars (one per monitor).
76 bars: ?*Bar,
77
78 chord: ChordState,
79
80 overlay: ?*overlay_mod.Keybind_Overlay,
81
82 scroll_animation: animations.Scroll_Animation,
83 animation_config: animations.Animation_Config,
84
85 running: bool,
86 last_motion_monitor: ?*Monitor,
87
88 /// Initialises the window manager
89 ///
90 /// Returns an error if the display cannot be opened or another WM is
91 /// already running.
92 pub fn init(allocator: mem.Allocator, config: Config, config_path: ?[]const u8) !WindowManager {
93 var display = try Display.open();
94 errdefer display.close();
95
96 try display.become_window_manager();
97
98 const x11_fd = xlib.XConnectionNumber(display.handle);
99
100 const atoms_result = Atoms.init(display.handle, display.root);
101 const cursors = Cursors.init(&display);
102 _ = xlib.XDefineCursor(display.handle, display.root, cursors.normal);
103
104 tiling.set_display(display.handle);
105 tiling.set_screen_size(display.screen_width(), display.screen_height());
106
107 monitor_mod.init(allocator);
108
109 var wm = WindowManager{
110 .allocator = allocator,
111 .display = display,
112 .x11_fd = x11_fd,
113 .wm_check_window = atoms_result.check_window,
114 .atoms = atoms_result.atoms,
115 .cursors = cursors,
116 .numlock_mask = 0,
117 .config = config,
118 .config_path = config_path,
119 .monitors = null,
120 .selected_monitor = null,
121 .bars = null,
122 .chord = .{},
123 .overlay = null,
124 .scroll_animation = .{},
125 .animation_config = .{ .duration_ms = 150, .easing = .ease_out },
126 .running = true,
127 .last_motion_monitor = null,
128 };
129
130 wm.setup_monitors();
131 wm.setup_bars();
132 wm.setup_overlay();
133
134 return wm;
135 }
136
137 /// Release all allocated memory owned by the WM.
138 pub fn deinit(self: *WindowManager) void {
139 bar_mod.destroy_bars(self.bars, self.allocator, self.display.handle);
140 self.bars = null;
141
142 if (self.overlay) |o| {
143 o.deinit(self.allocator);
144 self.overlay = null;
145 }
146
147 var mon = self.monitors;
148 while (mon) |m| {
149 const next = m.next;
150 monitor_mod.destroy(m);
151 mon = next;
152 }
153 self.monitors = null;
154 self.selected_monitor = null;
155
156 _ = xlib.XDestroyWindow(self.display.handle, self.wm_check_window);
157
158 self.display.close();
159 self.config.deinit();
160 }
161
162 fn setup_monitors(self: *WindowManager) void {
163 if (xlib.XineramaIsActive(self.display.handle) != 0) {
164 var screen_count: c_int = 0;
165 const screens = xlib.XineramaQueryScreens(self.display.handle, &screen_count);
166
167 if (screen_count > 0 and screens != null) {
168 var prev_monitor: ?*Monitor = null;
169 var index: usize = 0;
170
171 while (index < @as(usize, @intCast(screen_count))) : (index += 1) {
172 const screen = screens[index];
173 const mon = monitor_mod.create() orelse continue;
174
175 mon.num = @intCast(index);
176 mon.mon_x = screen.x_org;
177 mon.mon_y = screen.y_org;
178 mon.mon_w = screen.width;
179 mon.mon_h = screen.height;
180 mon.win_x = screen.x_org;
181 mon.win_y = screen.y_org;
182 mon.win_w = screen.width;
183 mon.win_h = screen.height;
184 mon.lt[0] = &tiling.layout;
185 mon.lt[1] = &monocle.layout;
186 mon.lt[2] = &floating.layout;
187 mon.lt[3] = &scrolling.layout;
188 mon.lt[4] = &grid.layout;
189
190 for (0..10) |i| {
191 mon.pertag.ltidxs[i][0] = mon.lt[0];
192 mon.pertag.ltidxs[i][1] = mon.lt[1];
193 mon.pertag.ltidxs[i][2] = mon.lt[2];
194 mon.pertag.ltidxs[i][3] = mon.lt[3];
195 mon.pertag.ltidxs[i][4] = mon.lt[4];
196 }
197
198 self.init_monitor_gaps(mon);
199
200 if (prev_monitor) |prev| {
201 prev.next = mon;
202 } else {
203 self.monitors = mon;
204 self.selected_monitor = mon;
205 }
206 prev_monitor = mon;
207 }
208
209 _ = xlib.XFree(@ptrCast(screens));
210 }
211 }
212
213 // Fallback: single monitor covering the full screen.
214 if (self.monitors == null) {
215 const mon = monitor_mod.create() orelse return;
216 mon.num = 0;
217 mon.mon_x = 0;
218 mon.mon_y = 0;
219 mon.mon_w = self.display.screen_width();
220 mon.mon_h = self.display.screen_height();
221 mon.win_x = 0;
222 mon.win_y = 0;
223 mon.win_w = mon.mon_w;
224 mon.win_h = mon.mon_h;
225 mon.lt[0] = &tiling.layout;
226 mon.lt[1] = &monocle.layout;
227 mon.lt[2] = &floating.layout;
228 mon.lt[3] = &scrolling.layout;
229 mon.lt[4] = &grid.layout;
230
231 for (0..10) |i| {
232 mon.pertag.ltidxs[i][0] = mon.lt[0];
233 mon.pertag.ltidxs[i][1] = mon.lt[1];
234 mon.pertag.ltidxs[i][2] = mon.lt[2];
235 mon.pertag.ltidxs[i][3] = mon.lt[3];
236 mon.pertag.ltidxs[i][4] = mon.lt[4];
237 }
238
239 self.init_monitor_gaps(mon);
240 self.monitors = mon;
241 self.selected_monitor = mon;
242 }
243
244 // Mirror into monitor_mod so legacy code that still reads the
245 // module-level vars continues to work during the transition.
246 // TODO(wm-refactor): remove once all callers use self.monitors.
247 monitor_mod.monitors = self.monitors;
248 monitor_mod.selected_monitor = self.selected_monitor;
249 }
250
251 fn init_monitor_gaps(self: *WindowManager, mon: *Monitor) void {
252 const cfg = &self.config;
253 const any_gap_nonzero = cfg.gap_inner_h != 0 or cfg.gap_inner_v != 0 or
254 cfg.gap_outer_h != 0 or cfg.gap_outer_v != 0;
255
256 if (cfg.gaps_enabled and any_gap_nonzero) {
257 mon.gap_inner_h = cfg.gap_inner_h;
258 mon.gap_inner_v = cfg.gap_inner_v;
259 mon.gap_outer_h = cfg.gap_outer_h;
260 mon.gap_outer_v = cfg.gap_outer_v;
261 } else {
262 mon.gap_inner_h = 0;
263 mon.gap_inner_v = 0;
264 mon.gap_outer_h = 0;
265 mon.gap_outer_v = 0;
266 }
267 }
268
269 pub fn setup_bars(self: *WindowManager) void {
270 var current_monitor = self.monitors;
271 var last_bar: ?*Bar = null;
272
273 while (current_monitor) |monitor| {
274 const bar = Bar.create(
275 self.allocator,
276 self.display.handle,
277 self.display.screen,
278 monitor,
279 self.config,
280 ) orelse {
281 current_monitor = monitor.next;
282 continue;
283 };
284
285 if (tiling.bar_height == 0) {
286 tiling.set_bar_height(bar.height);
287 }
288
289 self.populate_bar_blocks(bar);
290
291 if (last_bar) |prev| {
292 prev.next = bar;
293 } else {
294 self.bars = bar;
295 }
296 last_bar = bar;
297
298 std.debug.print("bar created for monitor {d}\n", .{monitor.num});
299 current_monitor = monitor.next;
300 }
301 }
302
303 pub fn populate_bar_blocks(self: *WindowManager, bar: *Bar) void {
304 if (self.config.blocks.items.len > 0) {
305 for (self.config.blocks.items) |cfg_block| {
306 bar.add_block(config_block_to_bar_block(cfg_block));
307 }
308 } else {
309 bar.add_block(blocks_mod.Block.init_ram("", 5, 0x7aa2f7, true));
310 bar.add_block(blocks_mod.Block.init_static(" | ", 0x666666, false));
311 bar.add_block(blocks_mod.Block.init_datetime("", "%H:%M", 1, 0x0db9d7, true));
312 }
313 }
314
315 fn setup_overlay(self: *WindowManager) void {
316 self.overlay = overlay_mod.Keybind_Overlay.init(
317 self.display.handle,
318 self.display.screen,
319 self.display.root,
320 self.config.font,
321 self.allocator,
322 );
323 }
324
325 // Wrap free functions in `bar_mod` with `self.bars` passed in.
326
327 pub fn invalidate_bars(self: *WindowManager) void {
328 bar_mod.invalidate_bars(self.bars);
329 }
330
331 pub fn window_to_bar(self: *WindowManager, win: xlib.Window) ?*Bar {
332 return bar_mod.window_to_bar(self.bars, win);
333 }
334
335 /// Refreshes the cached numlock modifier bitmask from the X server's
336 /// current modifier map. Called before any key or button grab so that
337 /// grabs cover all numlock combinations.
338 pub fn update_numlock_mask(self: *WindowManager) void {
339 self.numlock_mask = 0;
340 const modmap = xlib.XGetModifierMapping(self.display.handle);
341 if (modmap == null) return;
342 defer _ = xlib.XFreeModifiermap(modmap);
343
344 const numlock_keycode = xlib.XKeysymToKeycode(self.display.handle, xlib.XK_Num_Lock);
345
346 var modifier_index: usize = 0;
347 while (modifier_index < 8) : (modifier_index += 1) {
348 var key_index: usize = 0;
349 while (key_index < @as(usize, @intCast(modmap.*.max_keypermod))) : (key_index += 1) {
350 const keycode = modmap.*.modifiermap[modifier_index * @as(usize, @intCast(modmap.*.max_keypermod)) + key_index];
351 if (keycode == numlock_keycode) {
352 self.numlock_mask = @as(c_uint, 1) << @intCast(modifier_index);
353 }
354 }
355 }
356 }
357
358 /// Grabs all configured keybinds and mouse buttons from the X server.
359 /// Replaces any existing grabs. Call after config load or reload.
360 pub fn grab_keybinds(self: *WindowManager) void {
361 self.update_numlock_mask();
362 const modifiers = [_]c_uint{ 0, xlib.LockMask, self.numlock_mask, self.numlock_mask | xlib.LockMask };
363
364 _ = xlib.XUngrabKey(self.display.handle, xlib.AnyKey, xlib.AnyModifier, self.display.root);
365
366 for (self.config.keybinds.items) |keybind| {
367 if (keybind.key_count == 0) continue;
368 const first_key = keybind.keys[0];
369 const keycode = xlib.XKeysymToKeycode(self.display.handle, @intCast(first_key.keysym));
370 if (keycode != 0) {
371 for (modifiers) |modifier| {
372 _ = xlib.XGrabKey(
373 self.display.handle,
374 keycode,
375 first_key.mod_mask | modifier,
376 self.display.root,
377 xlib.True,
378 xlib.GrabModeAsync,
379 xlib.GrabModeAsync,
380 );
381 }
382 }
383 }
384
385 for (self.config.buttons.items) |button| {
386 if (button.click == .client_win) {
387 for (modifiers) |modifier| {
388 _ = xlib.XGrabButton(
389 self.display.handle,
390 @intCast(button.button),
391 button.mod_mask | modifier,
392 self.display.root,
393 xlib.True,
394 xlib.ButtonPressMask | xlib.ButtonReleaseMask | xlib.PointerMotionMask,
395 xlib.GrabModeAsync,
396 xlib.GrabModeAsync,
397 xlib.None,
398 xlib.None,
399 );
400 }
401 }
402 }
403
404 std.debug.print("grabbed {d} keybinds from config\n", .{self.config.keybinds.items.len});
405 }
406
407 pub fn ungrab_keybinds(self: *WindowManager) void {
408 _ = xlib.XUngrabKey(self.display.handle, xlib.AnyKey, xlib.AnyModifier, self.display.root);
409 }
410
411 /// Walk the existing window tree and call `manage_fn` for each window
412 /// that should be managed. Non-transient windows are processed first
413 /// so transient (dialog) windows can be stacked on top.
414 pub fn scan_existing_windows(self: *WindowManager, manage_fn: fn (xlib.Window, *xlib.XWindowAttributes, *WindowManager) void) void {
415 var root_return: xlib.Window = undefined;
416 var parent_return: xlib.Window = undefined;
417 var children: [*c]xlib.Window = undefined;
418 var num_children: c_uint = undefined;
419
420 if (xlib.XQueryTree(self.display.handle, self.display.root, &root_return, &parent_return, &children, &num_children) == 0) {
421 return;
422 }
423
424 var index: c_uint = 0;
425 while (index < num_children) : (index += 1) {
426 var window_attrs: xlib.XWindowAttributes = undefined;
427 if (xlib.XGetWindowAttributes(self.display.handle, children[index], &window_attrs) == 0) {
428 continue;
429 }
430 if (window_attrs.override_redirect != 0) continue;
431
432 var trans: xlib.Window = 0;
433 if (xlib.XGetTransientForHint(self.display.handle, children[index], &trans) != 0) continue;
434
435 if (window_attrs.map_state == IsViewable or self.get_state(children[index]) == IconicState) {
436 manage_fn(children[index], &window_attrs, self);
437 }
438 }
439
440 index = 0;
441 while (index < num_children) : (index += 1) {
442 var window_attrs: xlib.XWindowAttributes = undefined;
443 if (xlib.XGetWindowAttributes(self.display.handle, children[index], &window_attrs) == 0) {
444 continue;
445 }
446 var trans: xlib.Window = 0;
447 if (xlib.XGetTransientForHint(self.display.handle, children[index], &trans) != 0) {
448 if (window_attrs.map_state == IsViewable or self.get_state(children[index]) == IconicState) {
449 manage_fn(children[index], &window_attrs, self);
450 }
451 }
452 }
453
454 if (children != null) _ = xlib.XFree(@ptrCast(children));
455 }
456
457 /// Reads the ICCCM WM_STATE property for a window.
458 /// Returns WithdrawnState if the property is absent or malformed.
459 pub fn get_state(self: *WindowManager, window: xlib.Window) c_long {
460 var actual_type: xlib.Atom = 0;
461 var actual_format: c_int = 0;
462 var num_items: c_ulong = 0;
463 var bytes_after: c_ulong = 0;
464 var prop: [*c]u8 = null;
465
466 const result = xlib.XGetWindowProperty(
467 self.display.handle,
468 window,
469 self.atoms.wm_state,
470 0,
471 2,
472 xlib.False,
473 self.atoms.wm_state,
474 &actual_type,
475 &actual_format,
476 &num_items,
477 &bytes_after,
478 &prop,
479 );
480
481 if (result != 0 or actual_type != self.atoms.wm_state or num_items < 1) {
482 if (prop != null) _ = xlib.XFree(prop);
483 return WithdrawnState;
484 }
485
486 const state: c_long = @as(*c_long, @ptrCast(@alignCast(prop))).*;
487 _ = xlib.XFree(prop);
488 return state;
489 }
490
491 /// Run the event loop until `self.running` is set to false.
492 ///
493 /// `event_fn` dispatches a single XEvent
494 /// `tick_fn` is called once per loop iteration to advance animations
495 pub fn run(
496 self: *WindowManager,
497 event_fn: fn (*xlib.XEvent, *WindowManager) void,
498 tick_fn: fn (*WindowManager) void,
499 ) void {
500 var fds = [_]std.posix.pollfd{
501 .{ .fd = self.x11_fd, .events = std.posix.POLL.IN, .revents = 0 },
502 };
503
504 _ = xlib.XSync(self.display.handle, xlib.False);
505
506 while (self.running) {
507 while (xlib.XPending(self.display.handle) > 0) {
508 var event = self.display.next_event();
509 event_fn(&event, self);
510 }
511
512 tick_fn(self);
513
514 var current_bar = self.bars;
515 while (current_bar) |bar| {
516 bar.update_blocks();
517 bar.draw(self.display.handle, self.config);
518 current_bar = bar.next;
519 }
520
521 const poll_timeout: i32 = if (self.scroll_animation.is_active()) 16 else 1000;
522 _ = std.posix.poll(&fds, poll_timeout) catch 0;
523 }
524 }
525
526 /// Reloads the configuration
527 ///
528 /// `load_fn` repopulates `self.config`
529 /// keys/buttons are unbound before reload and rebound after
530 pub fn reload_config(
531 self: *WindowManager,
532 load_fn: fn (*WindowManager) void,
533 ) void {
534 std.debug.print("reloading config...\n", .{});
535
536 self.ungrab_keybinds();
537
538 self.config.keybinds.clearRetainingCapacity();
539 self.config.buttons.clearRetainingCapacity();
540 self.config.rules.clearRetainingCapacity();
541 self.config.blocks.clearRetainingCapacity();
542
543 load_fn(self);
544
545 bar_mod.destroy_bars(self.bars, self.allocator, self.display.handle);
546 self.bars = null;
547 self.setup_bars();
548 self.rebuild_bar_blocks();
549
550 self.grab_keybinds();
551 }
552
553 fn rebuild_bar_blocks(self: *WindowManager) void {
554 var current_bar = self.bars;
555 while (current_bar) |bar| {
556 bar.clear_blocks();
557 self.populate_bar_blocks(bar);
558 current_bar = bar.next;
559 }
560 }
561 };
562
563 /// Converts a config block description into a live status bar block.
564 pub fn config_block_to_bar_block(cfg: config_mod.Block) blocks_mod.Block {
565 return switch (cfg.block_type) {
566 .static => blocks_mod.Block.init_static(cfg.format, cfg.color, cfg.underline),
567 .datetime => blocks_mod.Block.init_datetime(
568 cfg.format,
569 cfg.datetime_format orelse "%H:%M",
570 cfg.interval,
571 cfg.color,
572 cfg.underline,
573 ),
574 .ram => blocks_mod.Block.init_ram(cfg.format, cfg.interval, cfg.color, cfg.underline),
575 .shell => blocks_mod.Block.init_shell(
576 cfg.format,
577 cfg.command orelse "",
578 cfg.interval,
579 cfg.color,
580 cfg.underline,
581 ),
582 .battery => blocks_mod.Block.init_battery(
583 cfg.format_charging orelse "",
584 cfg.format_discharging orelse "",
585 cfg.format_full orelse "",
586 cfg.battery_name orelse "BAT0",
587 cfg.interval,
588 cfg.color,
589 cfg.underline,
590 ),
591 .cpu_temp => blocks_mod.Block.init_cpu_temp(
592 cfg.format,
593 cfg.thermal_zone orelse "thermal_zone0",
594 cfg.interval,
595 cfg.color,
596 cfg.underline,
597 ),
598 };
599 }