tony / oxwm

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