tony / oxwm

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