tony / oxwm

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