tony / oxwm

Branch: 3328e33
Switch branches/tags
master
tonybanters added systray to bar, updated background to match config bg color 3328e33 2026-03-23
601 lines · 20.6 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.KeybindOverlay,
82
83 scroll_animation: animations.ScrollAnimation,
84 animation_config: animations.AnimationConfig,
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.becomeWindowManager();
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.setDisplay(display.handle);
106 tiling.setScreenSize(display.screenWidth(), display.screenHeight());
107
108 var wm = WindowManager{
109 .allocator = allocator,
110 .display = display,
111 .x11_fd = x11_fd,
112 .wm_check_window = atoms_result.check_window,
113 .atoms = atoms_result.atoms,
114 .cursors = cursors,
115 .numlock_mask = 0,
116 .config = config,
117 .config_path = config_path,
118 .monitors = null,
119 .selected_monitor = null,
120 .bars = null,
121 .chord = .{},
122 .overlay = null,
123 .scroll_animation = .{},
124 .animation_config = .{ .duration_ms = 150, .easing = .ease_out },
125 .running = true,
126 .last_motion_monitor = null,
127 };
128
129 wm.setupMonitors();
130 wm.setupBars();
131 wm.setupOverlay();
132
133 return wm;
134 }
135
136 /// Release all allocated memory owned by the WM.
137 pub fn deinit(self: *WindowManager) void {
138 bar_mod.destroyBars(self.bars, self.display.handle);
139 self.bars = null;
140
141 if (self.overlay) |o| {
142 o.deinit(self.allocator);
143 self.overlay = null;
144 }
145
146 var mon = self.monitors;
147 while (mon) |m| {
148 const next = m.next;
149 monitor_mod.destroy(self.allocator, m);
150 mon = next;
151 }
152 self.monitors = null;
153 self.selected_monitor = null;
154
155 _ = xlib.XDestroyWindow(self.display.handle, self.wm_check_window);
156
157 self.display.close();
158 self.config.deinit();
159 }
160
161 fn setupMonitors(self: *WindowManager) void {
162 if (xlib.XineramaIsActive(self.display.handle) != 0) {
163 var screen_count: c_int = 0;
164 const screens = xlib.XineramaQueryScreens(self.display.handle, &screen_count);
165
166 if (screen_count > 0 and screens != null) {
167 var prev_monitor: ?*Monitor = null;
168 var index: usize = 0;
169
170 while (index < @as(usize, @intCast(screen_count))) : (index += 1) {
171 const screen = screens[index];
172 const mon = monitor_mod.create(self.allocator) orelse continue;
173
174 mon.num = @intCast(index);
175 mon.mon_x = screen.x_org;
176 mon.mon_y = screen.y_org;
177 mon.mon_w = screen.width;
178 mon.mon_h = screen.height;
179 mon.win_x = screen.x_org;
180 mon.win_y = screen.y_org;
181 mon.win_w = screen.width;
182 mon.win_h = screen.height;
183 mon.lt[0] = &tiling.layout;
184 mon.lt[1] = &monocle.layout;
185 mon.lt[2] = &floating.layout;
186 mon.lt[3] = &scrolling.layout;
187 mon.lt[4] = &grid.layout;
188
189 for (0..10) |i| {
190 mon.pertag.ltidxs[i][0] = mon.lt[0];
191 mon.pertag.ltidxs[i][1] = mon.lt[1];
192 mon.pertag.ltidxs[i][2] = mon.lt[2];
193 mon.pertag.ltidxs[i][3] = mon.lt[3];
194 mon.pertag.ltidxs[i][4] = mon.lt[4];
195 }
196
197 self.initMonitorGaps(mon);
198
199 if (prev_monitor) |prev| {
200 prev.next = mon;
201 } else {
202 self.monitors = mon;
203 self.selected_monitor = mon;
204 }
205 prev_monitor = mon;
206 }
207
208 _ = xlib.XFree(@ptrCast(screens));
209 }
210 }
211
212 // Fallback: single monitor covering the full screen.
213 if (self.monitors == null) {
214 const mon = monitor_mod.create(self.allocator) orelse return;
215 mon.num = 0;
216 mon.mon_x = 0;
217 mon.mon_y = 0;
218 mon.mon_w = self.display.screenWidth();
219 mon.mon_h = self.display.screenHeight();
220 mon.win_x = 0;
221 mon.win_y = 0;
222 mon.win_w = mon.mon_w;
223 mon.win_h = mon.mon_h;
224 mon.lt[0] = &tiling.layout;
225 mon.lt[1] = &monocle.layout;
226 mon.lt[2] = &floating.layout;
227 mon.lt[3] = &scrolling.layout;
228 mon.lt[4] = &grid.layout;
229
230 for (0..10) |i| {
231 mon.pertag.ltidxs[i][0] = mon.lt[0];
232 mon.pertag.ltidxs[i][1] = mon.lt[1];
233 mon.pertag.ltidxs[i][2] = mon.lt[2];
234 mon.pertag.ltidxs[i][3] = mon.lt[3];
235 mon.pertag.ltidxs[i][4] = mon.lt[4];
236 }
237
238 self.initMonitorGaps(mon);
239 self.monitors = mon;
240 self.selected_monitor = mon;
241 }
242 }
243
244 fn initMonitorGaps(self: *WindowManager, mon: *Monitor) void {
245 const cfg = &self.config;
246 const any_gap_nonzero = cfg.gap_inner_h != 0 or cfg.gap_inner_v != 0 or
247 cfg.gap_outer_h != 0 or cfg.gap_outer_v != 0;
248
249 mon.smartgaps_enabled = cfg.smartgaps_enabled;
250
251 if (cfg.gaps_enabled and any_gap_nonzero) {
252 mon.gap_inner_h = cfg.gap_inner_h;
253 mon.gap_inner_v = cfg.gap_inner_v;
254 mon.gap_outer_h = cfg.gap_outer_h;
255 mon.gap_outer_v = cfg.gap_outer_v;
256 } else {
257 mon.gap_inner_h = 0;
258 mon.gap_inner_v = 0;
259 mon.gap_outer_h = 0;
260 mon.gap_outer_v = 0;
261 }
262 }
263
264 pub fn setupBars(self: *WindowManager) void {
265 var current_monitor = self.monitors;
266 var last_bar: ?*Bar = null;
267 var is_first_bar = true;
268
269 while (current_monitor) |monitor| {
270 const bar = Bar.create(
271 self.allocator,
272 self.display.handle,
273 self.display.screen,
274 monitor,
275 self.config,
276 is_first_bar,
277 ) orelse {
278 current_monitor = monitor.next;
279 continue;
280 };
281 is_first_bar = false;
282
283 if (tiling.bar_height == 0) {
284 tiling.setBarHeight(bar.height);
285 }
286
287 self.populateBarBlocks(bar);
288
289 if (last_bar) |prev| {
290 prev.next = bar;
291 } else {
292 self.bars = bar;
293 }
294 last_bar = bar;
295
296 std.debug.print("bar created for monitor {d}\n", .{monitor.num});
297 current_monitor = monitor.next;
298 }
299 }
300
301 pub fn populateBarBlocks(self: *WindowManager, bar: *Bar) void {
302 if (self.config.blocks.items.len > 0) {
303 for (self.config.blocks.items) |cfg_block| {
304 bar.addBlock(configBlockToBarBlock(cfg_block));
305 }
306 } else {
307 bar.addBlock(blocks_mod.Block.initRam("", 5, 0x7aa2f7, true));
308 bar.addBlock(blocks_mod.Block.initStatic(" | ", 0x666666, false));
309 bar.addBlock(blocks_mod.Block.initDatetime("", "%H:%M", 1, 0x0db9d7, true));
310 }
311 }
312
313 fn setupOverlay(self: *WindowManager) void {
314 self.overlay = overlay_mod.KeybindOverlay.init(
315 self.display.handle,
316 self.display.screen,
317 self.display.root,
318 self.config.font,
319 self.allocator,
320 );
321 }
322
323 // Wrap free functions in `bar_mod` with `self.bars` passed in.
324
325 pub fn invalidateBars(self: *WindowManager) void {
326 bar_mod.invalidateBars(self.bars);
327 }
328
329 pub fn windowToBar(self: *WindowManager, win: xlib.Window) ?*Bar {
330 return bar_mod.windowToBar(self.bars, win);
331 }
332
333 pub fn getSystray(self: *WindowManager) ?*bar_mod.Systray {
334 return bar_mod.getSystray(self.bars);
335 }
336
337 /// Refreshes the cached numlock modifier bitmask from the X server's
338 /// current modifier map. Called before any key or button grab so that
339 /// grabs cover all numlock combinations.
340 pub fn updateNumlockMask(self: *WindowManager) void {
341 self.numlock_mask = 0;
342 const modmap = xlib.XGetModifierMapping(self.display.handle);
343 if (modmap == null) return;
344 defer _ = xlib.XFreeModifiermap(modmap);
345
346 const numlock_keycode = xlib.XKeysymToKeycode(self.display.handle, xlib.XK_Num_Lock);
347
348 var modifier_index: usize = 0;
349 while (modifier_index < 8) : (modifier_index += 1) {
350 var key_index: usize = 0;
351 while (key_index < @as(usize, @intCast(modmap.*.max_keypermod))) : (key_index += 1) {
352 const keycode = modmap.*.modifiermap[modifier_index * @as(usize, @intCast(modmap.*.max_keypermod)) + key_index];
353 if (keycode == numlock_keycode) {
354 self.numlock_mask = @as(c_uint, 1) << @intCast(modifier_index);
355 }
356 }
357 }
358 }
359
360 /// Grabs all configured keybinds and mouse buttons from the X server.
361 /// Replaces any existing grabs. Call after config load or reload.
362 pub fn grabKeybinds(self: *WindowManager) void {
363 self.updateNumlockMask();
364 const modifiers = [_]c_uint{ 0, xlib.LockMask, self.numlock_mask, self.numlock_mask | xlib.LockMask };
365
366 _ = xlib.XUngrabKey(self.display.handle, xlib.AnyKey, xlib.AnyModifier, self.display.root);
367
368 for (self.config.keybinds.items) |keybind| {
369 if (keybind.key_count == 0) continue;
370 const first_key = keybind.keys[0];
371 const keycode = xlib.XKeysymToKeycode(self.display.handle, @intCast(first_key.keysym));
372 if (keycode != 0) {
373 for (modifiers) |modifier| {
374 _ = xlib.XGrabKey(
375 self.display.handle,
376 keycode,
377 first_key.mod_mask | modifier,
378 self.display.root,
379 xlib.True,
380 xlib.GrabModeAsync,
381 xlib.GrabModeAsync,
382 );
383 }
384 }
385 }
386
387 for (self.config.buttons.items) |button| {
388 if (button.click == .client_win) {
389 for (modifiers) |modifier| {
390 _ = xlib.XGrabButton(
391 self.display.handle,
392 @intCast(button.button),
393 button.mod_mask | modifier,
394 self.display.root,
395 xlib.True,
396 xlib.ButtonPressMask | xlib.ButtonReleaseMask | xlib.PointerMotionMask,
397 xlib.GrabModeAsync,
398 xlib.GrabModeAsync,
399 xlib.None,
400 xlib.None,
401 );
402 }
403 }
404 }
405
406 std.debug.print("grabbed {d} keybinds from config\n", .{self.config.keybinds.items.len});
407 }
408
409 pub fn ungrabKeybinds(self: *WindowManager) void {
410 _ = xlib.XUngrabKey(self.display.handle, xlib.AnyKey, xlib.AnyModifier, self.display.root);
411 }
412
413 /// Walk the existing window tree and call `manageFn` for each window
414 /// that should be managed. Non-transient windows are processed first
415 /// so transient (dialog) windows can be stacked on top.
416 pub fn scanExistingWindows(self: *WindowManager, manageFn: fn (xlib.Window, *xlib.XWindowAttributes, *WindowManager) void) void {
417 var root_return: xlib.Window = undefined;
418 var parent_return: xlib.Window = undefined;
419 var children: [*c]xlib.Window = undefined;
420 var num_children: c_uint = undefined;
421
422 if (xlib.XQueryTree(self.display.handle, self.display.root, &root_return, &parent_return, &children, &num_children) == 0) {
423 return;
424 }
425
426 var index: c_uint = 0;
427 while (index < num_children) : (index += 1) {
428 var window_attrs: xlib.XWindowAttributes = undefined;
429 if (xlib.XGetWindowAttributes(self.display.handle, children[index], &window_attrs) == 0) {
430 continue;
431 }
432 if (window_attrs.override_redirect != 0) continue;
433
434 var trans: xlib.Window = 0;
435 if (xlib.XGetTransientForHint(self.display.handle, children[index], &trans) != 0) continue;
436
437 if (window_attrs.map_state == IsViewable or self.getState(children[index]) == IconicState) {
438 manageFn(children[index], &window_attrs, self);
439 }
440 }
441
442 index = 0;
443 while (index < num_children) : (index += 1) {
444 var window_attrs: xlib.XWindowAttributes = undefined;
445 if (xlib.XGetWindowAttributes(self.display.handle, children[index], &window_attrs) == 0) {
446 continue;
447 }
448 var trans: xlib.Window = 0;
449 if (xlib.XGetTransientForHint(self.display.handle, children[index], &trans) != 0) {
450 if (window_attrs.map_state == IsViewable or self.getState(children[index]) == IconicState) {
451 manageFn(children[index], &window_attrs, self);
452 }
453 }
454 }
455
456 if (children != null) _ = xlib.XFree(@ptrCast(children));
457 }
458
459 /// Reads the ICCCM WM_STATE property for a window.
460 /// Returns WithdrawnState if the property is absent or malformed.
461 pub fn getState(self: *WindowManager, window: xlib.Window) c_long {
462 var actual_type: xlib.Atom = 0;
463 var actual_format: c_int = 0;
464 var num_items: c_ulong = 0;
465 var bytes_after: c_ulong = 0;
466 var prop: [*c]u8 = null;
467
468 const result = xlib.XGetWindowProperty(
469 self.display.handle,
470 window,
471 self.atoms.wm_state,
472 0,
473 2,
474 xlib.False,
475 self.atoms.wm_state,
476 &actual_type,
477 &actual_format,
478 &num_items,
479 &bytes_after,
480 &prop,
481 );
482
483 if (result != 0 or actual_type != self.atoms.wm_state or num_items < 1) {
484 if (prop != null) _ = xlib.XFree(prop);
485 return WithdrawnState;
486 }
487
488 const state: c_long = @as(*c_long, @ptrCast(@alignCast(prop))).*;
489 _ = xlib.XFree(prop);
490 return state;
491 }
492
493 /// Run the event loop until `self.running` is set to false.
494 ///
495 /// `eventFn` dispatches a single XEvent
496 /// `tickFn` is called once per loop iteration to advance animations
497 pub fn run(
498 self: *WindowManager,
499 eventFn: fn (*xlib.XEvent, *WindowManager) void,
500 tickFn: fn (*WindowManager) void,
501 ) void {
502 var fds = [_]std.posix.pollfd{
503 .{ .fd = self.x11_fd, .events = std.posix.POLL.IN, .revents = 0 },
504 };
505
506 _ = xlib.XSync(self.display.handle, xlib.False);
507
508 while (self.running) {
509 while (xlib.XPending(self.display.handle) > 0) {
510 var event = self.display.nextEvent();
511 eventFn(&event, self);
512 }
513
514 tickFn(self);
515
516 var current_bar = self.bars;
517 while (current_bar) |bar| {
518 bar.updateBlocks();
519 bar.draw(self.display.handle, self.config);
520 current_bar = bar.next;
521 }
522
523 const poll_timeout: i32 = if (self.scroll_animation.isActive()) 16 else 1000;
524 _ = std.posix.poll(&fds, poll_timeout) catch 0;
525 }
526 }
527
528 /// Reloads the configuration
529 ///
530 /// `loadFn` repopulates `self.config`
531 /// keys/buttons are unbound before reload and rebound after
532 pub fn reloadConfig(
533 self: *WindowManager,
534 loadFn: fn (*WindowManager) void,
535 ) void {
536 std.debug.print("reloading config...\n", .{});
537
538 self.ungrabKeybinds();
539
540 self.config.keybinds.clearRetainingCapacity();
541 self.config.buttons.clearRetainingCapacity();
542 self.config.rules.clearRetainingCapacity();
543 self.config.blocks.clearRetainingCapacity();
544
545 loadFn(self);
546
547 bar_mod.destroyBars(self.bars, self.display.handle);
548 self.bars = null;
549 self.setupBars();
550 self.rebuildBarBlocks();
551
552 self.grabKeybinds();
553 }
554
555 fn rebuildBarBlocks(self: *WindowManager) void {
556 var current_bar = self.bars;
557 while (current_bar) |bar| {
558 bar.clearBlocks();
559 self.populateBarBlocks(bar);
560 current_bar = bar.next;
561 }
562 }
563 };
564
565 /// Converts a config block description into a live status bar block.
566 pub fn configBlockToBarBlock(cfg: config_mod.Block) blocks_mod.Block {
567 return switch (cfg.block_type) {
568 .static => blocks_mod.Block.initStatic(cfg.format, cfg.color, cfg.underline),
569 .datetime => blocks_mod.Block.initDatetime(
570 cfg.format,
571 cfg.datetime_format orelse "%H:%M",
572 cfg.interval,
573 cfg.color,
574 cfg.underline,
575 ),
576 .ram => blocks_mod.Block.initRam(cfg.format, cfg.interval, cfg.color, cfg.underline),
577 .shell => blocks_mod.Block.initShell(
578 cfg.format,
579 cfg.command orelse "",
580 cfg.interval,
581 cfg.color,
582 cfg.underline,
583 ),
584 .battery => blocks_mod.Block.initBattery(
585 cfg.format_charging orelse "",
586 cfg.format_discharging orelse "",
587 cfg.format_full orelse "",
588 cfg.battery_name orelse "BAT0",
589 cfg.interval,
590 cfg.color,
591 cfg.underline,
592 ),
593 .cpu_temp => blocks_mod.Block.initCpuTemp(
594 cfg.format,
595 cfg.thermal_zone orelse "thermal_zone0",
596 cfg.interval,
597 cfg.color,
598 cfg.underline,
599 ),
600 };
601 }