tony / oxwm

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