tony / oxwm

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