tony / oxwm

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