tony / oxwm

Branch: c7d9989
Switch branches/tags
master
emzywastaken refactor(client): remove allocator global, document functions and `window_to_client` now takes a monitors list c7d9989 2026-02-21
2527 lines · 88.6 KB Raw Blame History
1 const std = @import("std");
2 const VERSION = "v0.11.2";
3 const Atoms = @import("x11/atoms.zig").Atoms;
4 const kchord = @import("keyboard/chord.zig");
5 const display_mod = @import("x11/display.zig");
6 const events = @import("x11/events.zig");
7 const xlib = @import("x11/xlib.zig");
8 const client_mod = @import("client.zig");
9 const monitor_mod = @import("monitor.zig");
10 const tiling = @import("layouts/tiling.zig");
11 const monocle = @import("layouts/monocle.zig");
12 const floating = @import("layouts/floating.zig");
13 const scrolling = @import("layouts/scrolling.zig");
14 const grid = @import("layouts/grid.zig");
15 const animations = @import("animations.zig");
16 const bar_mod = @import("bar/bar.zig");
17 const blocks_mod = @import("bar/blocks/blocks.zig");
18 const config_mod = @import("config/config.zig");
19 const lua = @import("config/lua.zig");
20 const overlay_mod = @import("overlay.zig");
21
22 const Display = display_mod.Display;
23 const Client = client_mod.Client;
24 const Monitor = monitor_mod.Monitor;
25
26 var running: bool = true;
27 var gpa = std.heap.GeneralPurposeAllocator(.{}){};
28
29 var atoms: Atoms = undefined;
30 var wm_check_window: xlib.Window = undefined;
31
32 const Cursors = struct {
33 normal: xlib.Cursor,
34 resize: xlib.Cursor,
35 move: xlib.Cursor,
36
37 fn init(display: *Display) Cursors {
38 return .{
39 .normal = xlib.XCreateFontCursor(display.handle, xlib.XC_left_ptr),
40 .resize = xlib.XCreateFontCursor(display.handle, xlib.XC_sizing),
41 .move = xlib.XCreateFontCursor(display.handle, xlib.XC_fleur),
42 };
43 }
44 };
45
46 var cursors: Cursors = undefined;
47
48 const NormalState: c_long = 1;
49 const WithdrawnState: c_long = 0;
50 const IconicState: c_long = 3;
51 const IsViewable: c_int = 2;
52 const snap_distance: i32 = 32;
53
54 var numlock_mask: c_uint = 0;
55
56 var config: config_mod.Config = undefined;
57 var config_path_global: ?[]const u8 = null;
58
59 /// Interim pointer to the X11 display, used only by `arrange` until the
60 /// WindowManager struct refactor moves display ownership there properly.
61 var wm_display: ?*Display = null;
62
63 var scroll_animation: animations.Scroll_Animation = .{};
64 var animation_config: animations.Animation_Config = .{ .duration_ms = 150, .easing = .ease_out };
65
66 var chord = kchord.ChordState{};
67
68 var keybind_overlay: ?*overlay_mod.Keybind_Overlay = null;
69
70 fn print_help() void {
71 std.debug.print(
72 \\oxwm - A window manager
73 \\
74 \\USAGE:
75 \\ oxwm [OPTIONS]
76 \\
77 \\OPTIONS:
78 \\ --init Create default config in ~/.config/oxwm/config.lua
79 \\ --config <PATH> Use custom config file
80 \\ --validate Validate config file without starting window manager
81 \\ --version Print version information
82 \\ --help Print this help message
83 \\
84 \\CONFIG:
85 \\ Location: ~/.config/oxwm/config.lua
86 \\ Edit the config file and use Mod+Shift+R to reload
87 \\ No compilation needed - instant hot-reload!
88 \\
89 \\FIRST RUN:
90 \\ Run 'oxwm --init' to create a config file
91 \\ Or just start oxwm and it will create one automatically
92 \\
93 , .{});
94 }
95
96 fn get_config_path(allocator: std.mem.Allocator) ![]u8 {
97 const config_home = std.posix.getenv("XDG_CONFIG_HOME") orelse blk: {
98 const home = std.posix.getenv("HOME") orelse return error.CouldNotGetHomeDir;
99 break :blk try std.fs.path.join(allocator, &.{ home, ".config" });
100 };
101 defer if (std.posix.getenv("XDG_CONFIG_HOME") == null) allocator.free(config_home);
102
103 const config_path = try std.fs.path.join(allocator, &.{ config_home, "oxwm", "config.lua" });
104 return config_path;
105 }
106
107 fn init_config(allocator: std.mem.Allocator) void {
108 const config_path = get_config_path(allocator) catch return;
109 defer allocator.free(config_path);
110
111 const template = @embedFile("templates/config.lua");
112
113 if (std.fs.path.dirname(config_path)) |dir_path| {
114 var root = std.fs.openDirAbsolute("/", .{}) catch |err| {
115 std.debug.print("error: could not open root directory: {}\n", .{err});
116 return;
117 };
118 defer root.close();
119
120 const relative_path = std.mem.trimLeft(u8, dir_path, "/");
121 root.makePath(relative_path) catch |err| {
122 std.debug.print("error: could not create config directory: {}\n", .{err});
123 return;
124 };
125 }
126
127 const file = std.fs.createFileAbsolute(config_path, .{}) catch |err| {
128 std.debug.print("error: could not create config file: {}\n", .{err});
129 return;
130 };
131 defer file.close();
132
133 _ = file.writeAll(template) catch |err| {
134 std.debug.print("error: could not write config file: {}\n", .{err});
135 return;
136 };
137
138 std.debug.print("Config created at {s}\n", .{config_path});
139 std.debug.print("Edit the file and reload with Mod+Shift+R\n", .{});
140 std.debug.print("No compilation needed - changes take effect immediately!\n", .{});
141 }
142
143 fn validate_config(allocator: std.mem.Allocator, config_path: []const u8) !void {
144 config = config_mod.Config.init(allocator);
145 defer config.deinit();
146
147 if (!lua.init(&config)) {
148 std.debug.print("error: failed to initialize lua\n", .{});
149 std.process.exit(1);
150 }
151 defer lua.deinit();
152
153 _ = std.fs.cwd().statFile(config_path) catch |err| {
154 std.debug.print("error: config file not found: {s}\n", .{config_path});
155 std.debug.print(" {}\n", .{err});
156 std.process.exit(1);
157 };
158
159 if (lua.load_file(config_path)) {
160 std.debug.print("✓ config valid: {s}\n", .{config_path});
161 std.process.exit(0);
162 } else {
163 std.debug.print("✗ config validation failed\n", .{});
164 std.process.exit(1);
165 }
166 }
167
168 pub fn main() !void {
169 const allocator = gpa.allocator();
170 defer _ = gpa.deinit();
171
172 const default_config_path = try get_config_path(allocator);
173 defer allocator.free(default_config_path);
174
175 var config_path: []const u8 = default_config_path;
176 var validate_mode: bool = false;
177 var args = std.process.args();
178 _ = args.skip();
179 while (args.next()) |arg| {
180 if (std.mem.eql(u8, arg, "-c") or std.mem.eql(u8, arg, "--config")) {
181 if (args.next()) |path| config_path = path;
182 } else if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) {
183 print_help();
184 return;
185 } else if (std.mem.eql(u8, arg, "-v") or std.mem.eql(u8, arg, "--version")) {
186 std.debug.print("{s}\n", .{VERSION});
187 return;
188 } else if (std.mem.eql(u8, arg, "--init")) {
189 init_config(allocator);
190 return;
191 } else if (std.mem.eql(u8, arg, "--validate")) {
192 validate_mode = true;
193 }
194 }
195
196 if (validate_mode) {
197 try validate_config(allocator, config_path);
198 return;
199 }
200
201 std.debug.print("oxwm starting\n", .{});
202
203 config = config_mod.Config.init(allocator);
204 defer config.deinit();
205
206 if (lua.init(&config)) {
207 const loaded = if (std.fs.cwd().statFile(config_path)) |_|
208 lua.load_file(config_path)
209 else |_| blk: {
210 init_config(allocator);
211 break :blk lua.load_config();
212 };
213
214 if (loaded) {
215 config_path_global = config_path;
216 std.debug.print("loaded config from {s}\n", .{config_path});
217 } else {
218 std.debug.print("no config found, using defaults\n", .{});
219 initialize_default_config();
220 }
221 } else {
222 std.debug.print("failed to init lua, using defaults\n", .{});
223 initialize_default_config();
224 }
225
226 var display = Display.open() catch |err| {
227 std.debug.print("failed to open display: {}\n", .{err});
228 return;
229 };
230 defer display.close();
231
232 x11_fd = xlib.XConnectionNumber(display.handle);
233 wm_display = &display;
234
235 std.debug.print("display opened: screen={d} root=0x{x}\n", .{ display.screen, display.root });
236 std.debug.print("screen size: {d}x{d}\n", .{ display.screen_width(), display.screen_height() });
237
238 display.become_window_manager() catch |err| {
239 std.debug.print("failed to become window manager: {}\n", .{err});
240 return;
241 };
242
243 std.debug.print("successfully became window manager\n", .{});
244
245 const atoms_result = Atoms.init(display.handle, display.root);
246 atoms = atoms_result.atoms;
247 wm_check_window = atoms_result.check_window;
248 std.debug.print("atoms initialized with EWMH support\n", .{});
249
250 cursors = Cursors.init(&display);
251 _ = xlib.XDefineCursor(display.handle, display.root, cursors.normal);
252 monitor_mod.init(allocator);
253 tiling.set_display(display.handle);
254 tiling.set_screen_size(display.screen_width(), display.screen_height());
255
256 setup_monitors(&display);
257 setup_bars(allocator, &display);
258 setup_overlay(allocator, &display);
259 grab_keybinds(&display);
260 scan_existing_windows(&display);
261
262 try run_autostart_commands(allocator, config.autostart.items);
263 std.debug.print("entering event loop\n", .{});
264 run_event_loop(&display);
265
266 bar_mod.destroy_bars(allocator, display.handle);
267
268 var mon = monitor_mod.monitors;
269 while (mon) |m| {
270 const next = m.next;
271 monitor_mod.destroy(m);
272 mon = next;
273 }
274
275 if (keybind_overlay) |overlay| {
276 overlay.deinit(allocator);
277 }
278
279 lua.deinit();
280 std.debug.print("oxwm exiting\n", .{});
281 }
282
283 fn setup_bars(allocator: std.mem.Allocator, display: *Display) void {
284 var current_monitor = monitor_mod.monitors;
285 var last_bar: ?*bar_mod.Bar = null;
286
287 while (current_monitor) |monitor| {
288 const bar = bar_mod.Bar.create(allocator, display.handle, display.screen, monitor, config);
289 if (bar) |created_bar| {
290 if (tiling.bar_height == 0) {
291 tiling.set_bar_height(created_bar.height);
292 }
293
294 if (config.blocks.items.len > 0) {
295 for (config.blocks.items) |cfg_block| {
296 const block = config_block_to_bar_block(cfg_block);
297 created_bar.add_block(block);
298 }
299 } else {
300 created_bar.add_block(blocks_mod.Block.init_ram("", 5, 0x7aa2f7, true));
301 created_bar.add_block(blocks_mod.Block.init_static(" | ", 0x666666, false));
302 created_bar.add_block(blocks_mod.Block.init_datetime("", "%H:%M", 1, 0x0db9d7, true));
303 }
304
305 if (last_bar) |prev| {
306 prev.next = created_bar;
307 } else {
308 bar_mod.bars = created_bar;
309 }
310 last_bar = created_bar;
311 std.debug.print("bar created for monitor {d}\n", .{monitor.num});
312 }
313 current_monitor = monitor.next;
314 }
315 }
316
317 fn setup_overlay(allocator: std.mem.Allocator, display: *Display) void {
318 keybind_overlay = overlay_mod.Keybind_Overlay.init(display.handle, display.screen, display.root, config.font, allocator);
319 }
320
321 fn config_block_to_bar_block(cfg: config_mod.Block) blocks_mod.Block {
322 return switch (cfg.block_type) {
323 .static => blocks_mod.Block.init_static(cfg.format, cfg.color, cfg.underline),
324 .datetime => blocks_mod.Block.init_datetime(cfg.format, cfg.datetime_format orelse "%H:%M", cfg.interval, cfg.color, cfg.underline),
325 .ram => blocks_mod.Block.init_ram(cfg.format, cfg.interval, cfg.color, cfg.underline),
326 .shell => blocks_mod.Block.init_shell(cfg.format, cfg.command orelse "", cfg.interval, cfg.color, cfg.underline),
327 .battery => blocks_mod.Block.init_battery(
328 cfg.format_charging orelse "",
329 cfg.format_discharging orelse "",
330 cfg.format_full orelse "",
331 cfg.battery_name orelse "BAT0",
332 cfg.interval,
333 cfg.color,
334 cfg.underline,
335 ),
336 .cpu_temp => blocks_mod.Block.init_cpu_temp(
337 cfg.format,
338 cfg.thermal_zone orelse "thermal_zone0",
339 cfg.interval,
340 cfg.color,
341 cfg.underline,
342 ),
343 };
344 }
345
346 fn setup_monitors(display: *Display) void {
347 std.debug.print("checking xinerama...\n", .{});
348 if (xlib.XineramaIsActive(display.handle) != 0) {
349 std.debug.print("xinerama is active!\n", .{});
350 var screen_count: c_int = 0;
351 const screens = xlib.XineramaQueryScreens(display.handle, &screen_count);
352
353 if (screen_count > 0 and screens != null) {
354 var prev_monitor: ?*Monitor = null;
355 var index: usize = 0;
356
357 while (index < @as(usize, @intCast(screen_count))) : (index += 1) {
358 const screen = screens[index];
359 const mon = monitor_mod.create() orelse continue;
360
361 mon.num = @intCast(index);
362 mon.mon_x = screen.x_org;
363 mon.mon_y = screen.y_org;
364 mon.mon_w = screen.width;
365 mon.mon_h = screen.height;
366 mon.win_x = screen.x_org;
367 mon.win_y = screen.y_org;
368 mon.win_w = screen.width;
369 mon.win_h = screen.height;
370 mon.lt[0] = &tiling.layout;
371 mon.lt[1] = &monocle.layout;
372 mon.lt[2] = &floating.layout;
373 mon.lt[3] = &scrolling.layout;
374 mon.lt[4] = &grid.layout;
375 for (0..10) |i| {
376 mon.pertag.ltidxs[i][0] = mon.lt[0];
377 mon.pertag.ltidxs[i][1] = mon.lt[1];
378 mon.pertag.ltidxs[i][2] = mon.lt[2];
379 mon.pertag.ltidxs[i][3] = mon.lt[3];
380 mon.pertag.ltidxs[i][4] = mon.lt[4];
381 }
382
383 init_monitor_gaps(mon);
384
385 if (prev_monitor) |prev| {
386 prev.next = mon;
387 } else {
388 monitor_mod.monitors = mon;
389 }
390 prev_monitor = mon;
391
392 std.debug.print("monitor {d}: {d}x{d} at ({d},{d})\n", .{ index, mon.mon_w, mon.mon_h, mon.mon_x, mon.mon_y });
393 }
394
395 monitor_mod.selected_monitor = monitor_mod.monitors;
396 _ = xlib.XFree(@ptrCast(screens));
397 return;
398 }
399 } else {
400 std.debug.print("xinerama not active, using single monitor\n", .{});
401 }
402
403 const mon = monitor_mod.create() orelse return;
404 mon.mon_x = 0;
405 mon.mon_y = 0;
406 mon.mon_w = display.screen_width();
407 mon.mon_h = display.screen_height();
408 mon.win_x = 0;
409 mon.win_y = 0;
410 mon.win_w = display.screen_width();
411 mon.win_h = display.screen_height();
412 mon.lt[0] = &tiling.layout;
413 mon.lt[1] = &monocle.layout;
414 mon.lt[2] = &floating.layout;
415 mon.lt[3] = &scrolling.layout;
416 mon.lt[4] = &grid.layout;
417 for (0..10) |i| {
418 mon.pertag.ltidxs[i][0] = mon.lt[0];
419 mon.pertag.ltidxs[i][1] = mon.lt[1];
420 mon.pertag.ltidxs[i][2] = mon.lt[2];
421 mon.pertag.ltidxs[i][3] = mon.lt[3];
422 mon.pertag.ltidxs[i][4] = mon.lt[4];
423 }
424
425 init_monitor_gaps(mon);
426
427 monitor_mod.monitors = mon;
428 monitor_mod.selected_monitor = mon;
429 std.debug.print("monitor created: {d}x{d}\n", .{ mon.mon_w, mon.mon_h });
430 }
431
432 fn init_monitor_gaps(mon: *Monitor) void {
433 const any_gap_nonzero = config.gap_inner_h != 0 or config.gap_inner_v != 0 or
434 config.gap_outer_h != 0 or config.gap_outer_v != 0;
435
436 if (config.gaps_enabled and any_gap_nonzero) {
437 mon.gap_inner_h = config.gap_inner_h;
438 mon.gap_inner_v = config.gap_inner_v;
439 mon.gap_outer_h = config.gap_outer_h;
440 mon.gap_outer_v = config.gap_outer_v;
441 } else {
442 mon.gap_inner_h = 0;
443 mon.gap_inner_v = 0;
444 mon.gap_outer_h = 0;
445 mon.gap_outer_v = 0;
446 }
447 }
448
449 fn make_keybind(mod: u32, key: u64, action: config_mod.Action) config_mod.Keybind {
450 var kb: config_mod.Keybind = .{ .action = action };
451 kb.keys[0] = .{ .mod_mask = mod, .keysym = key };
452 kb.key_count = 1;
453 return kb;
454 }
455
456 fn make_keybind_int(mod: u32, key: u64, action: config_mod.Action, int_arg: i32) config_mod.Keybind {
457 var kb = make_keybind(mod, key, action);
458 kb.int_arg = int_arg;
459 return kb;
460 }
461
462 fn make_keybind_str(mod: u32, key: u64, action: config_mod.Action, str_arg: []const u8) config_mod.Keybind {
463 var kb = make_keybind(mod, key, action);
464 kb.str_arg = str_arg;
465 return kb;
466 }
467
468 fn initialize_default_config() void {
469 const mod_key: u32 = 1 << 6;
470 const shift_key: u32 = 1 << 0;
471 const control_key: u32 = 1 << 2;
472
473 config.add_keybind(make_keybind(mod_key, 0xff0d, .spawn_terminal)) catch {};
474 config.add_keybind(make_keybind_str(mod_key, 'd', .spawn, "rofi -show drun")) catch {};
475 config.add_keybind(make_keybind_str(mod_key, 's', .spawn, "maim -s | xclip -selection clipboard -t image/png")) catch {};
476 config.add_keybind(make_keybind(mod_key, 'q', .kill_client)) catch {};
477 config.add_keybind(make_keybind(mod_key | shift_key, 'q', .quit)) catch {};
478 config.add_keybind(make_keybind(mod_key | shift_key, 'r', .reload_config)) catch {};
479 config.add_keybind(make_keybind(mod_key, 'j', .focus_next)) catch {};
480 config.add_keybind(make_keybind(mod_key, 'k', .focus_prev)) catch {};
481 config.add_keybind(make_keybind(mod_key | shift_key, 'j', .move_next)) catch {};
482 config.add_keybind(make_keybind(mod_key | shift_key, 'k', .move_prev)) catch {};
483 config.add_keybind(make_keybind_int(mod_key, 'h', .resize_master, -50)) catch {};
484 config.add_keybind(make_keybind_int(mod_key, 'l', .resize_master, 50)) catch {};
485 config.add_keybind(make_keybind(mod_key, 'i', .inc_master)) catch {};
486 config.add_keybind(make_keybind(mod_key, 'p', .dec_master)) catch {};
487 config.add_keybind(make_keybind(mod_key, 'a', .toggle_gaps)) catch {};
488 config.add_keybind(make_keybind(mod_key, 'f', .toggle_fullscreen)) catch {};
489 config.add_keybind(make_keybind(mod_key, 0x0020, .toggle_floating)) catch {};
490 config.add_keybind(make_keybind(mod_key, 'n', .cycle_layout)) catch {};
491 config.add_keybind(make_keybind_int(mod_key, 0x002c, .focus_monitor, -1)) catch {};
492 config.add_keybind(make_keybind_int(mod_key, 0x002e, .focus_monitor, 1)) catch {};
493 config.add_keybind(make_keybind_int(mod_key | shift_key, 0x002c, .send_to_monitor, -1)) catch {};
494 config.add_keybind(make_keybind_int(mod_key | shift_key, 0x002e, .send_to_monitor, 1)) catch {};
495
496 var tag_index: i32 = 0;
497 while (tag_index < 9) : (tag_index += 1) {
498 const keysym: u64 = @as(u64, '1') + @as(u64, @intCast(tag_index));
499 config.add_keybind(make_keybind_int(mod_key, keysym, .view_tag, tag_index)) catch {};
500 config.add_keybind(make_keybind_int(mod_key | shift_key, keysym, .move_to_tag, tag_index)) catch {};
501 config.add_keybind(make_keybind_int(mod_key | control_key, keysym, .toggle_view_tag, tag_index)) catch {};
502 config.add_keybind(make_keybind_int(mod_key | control_key | shift_key, keysym, .toggle_tag, tag_index)) catch {};
503 }
504
505 config.add_button(.{ .click = .client_win, .mod_mask = mod_key, .button = 1, .action = .move_mouse }) catch {};
506 config.add_button(.{ .click = .client_win, .mod_mask = mod_key, .button = 3, .action = .resize_mouse }) catch {};
507 }
508
509 fn grab_keybinds(display: *Display) void {
510 update_numlock_mask(display);
511 const modifiers = [_]c_uint{ 0, xlib.LockMask, numlock_mask, numlock_mask | xlib.LockMask };
512
513 _ = xlib.XUngrabKey(display.handle, xlib.AnyKey, xlib.AnyModifier, display.root);
514
515 for (config.keybinds.items) |keybind| {
516 if (keybind.key_count == 0) continue;
517 const first_key = keybind.keys[0];
518 const keycode = xlib.XKeysymToKeycode(display.handle, @intCast(first_key.keysym));
519 if (keycode != 0) {
520 for (modifiers) |modifier| {
521 _ = xlib.XGrabKey(
522 display.handle,
523 keycode,
524 first_key.mod_mask | modifier,
525 display.root,
526 xlib.True,
527 xlib.GrabModeAsync,
528 xlib.GrabModeAsync,
529 );
530 }
531 }
532 }
533
534 for (config.buttons.items) |button| {
535 if (button.click == .client_win) {
536 for (modifiers) |modifier| {
537 _ = xlib.XGrabButton(
538 display.handle,
539 @intCast(button.button),
540 button.mod_mask | modifier,
541 display.root,
542 xlib.True,
543 xlib.ButtonPressMask | xlib.ButtonReleaseMask | xlib.PointerMotionMask,
544 xlib.GrabModeAsync,
545 xlib.GrabModeAsync,
546 xlib.None,
547 xlib.None,
548 );
549 }
550 }
551 }
552
553 std.debug.print("grabbed {d} keybinds from config\n", .{config.keybinds.items.len});
554 }
555
556 fn get_state(display: *Display, window: xlib.Window) c_long {
557 var actual_type: xlib.Atom = 0;
558 var actual_format: c_int = 0;
559 var num_items: c_ulong = 0;
560 var bytes_after: c_ulong = 0;
561 var prop: [*c]u8 = null;
562
563 const result = xlib.XGetWindowProperty(
564 display.handle,
565 window,
566 atoms.wm_state,
567 0,
568 2,
569 xlib.False,
570 atoms.wm_state,
571 &actual_type,
572 &actual_format,
573 &num_items,
574 &bytes_after,
575 &prop,
576 );
577
578 if (result != 0 or actual_type != atoms.wm_state or num_items < 1) {
579 if (prop != null) {
580 _ = xlib.XFree(prop);
581 }
582 return WithdrawnState;
583 }
584
585 const state: c_long = @as(*c_long, @ptrCast(@alignCast(prop))).*;
586 _ = xlib.XFree(prop);
587 return state;
588 }
589
590 fn scan_existing_windows(display: *Display) void {
591 var root_return: xlib.Window = undefined;
592 var parent_return: xlib.Window = undefined;
593 var children: [*c]xlib.Window = undefined;
594 var num_children: c_uint = undefined;
595
596 if (xlib.XQueryTree(display.handle, display.root, &root_return, &parent_return, &children, &num_children) == 0) {
597 return;
598 }
599
600 var index: c_uint = 0;
601 while (index < num_children) : (index += 1) {
602 var window_attrs: xlib.XWindowAttributes = undefined;
603 if (xlib.XGetWindowAttributes(display.handle, children[index], &window_attrs) == 0) {
604 continue;
605 }
606 if (window_attrs.override_redirect != 0) {
607 continue;
608 }
609 var trans: xlib.Window = 0;
610 if (xlib.XGetTransientForHint(display.handle, children[index], &trans) != 0) {
611 continue;
612 }
613 if (window_attrs.map_state == IsViewable or get_state(display, children[index]) == IconicState) {
614 manage(display, children[index], &window_attrs);
615 }
616 }
617
618 index = 0;
619 while (index < num_children) : (index += 1) {
620 var window_attrs: xlib.XWindowAttributes = undefined;
621 if (xlib.XGetWindowAttributes(display.handle, children[index], &window_attrs) == 0) {
622 continue;
623 }
624 var trans: xlib.Window = 0;
625 if (xlib.XGetTransientForHint(display.handle, children[index], &trans) != 0) {
626 if (window_attrs.map_state == IsViewable or get_state(display, children[index]) == IconicState) {
627 manage(display, children[index], &window_attrs);
628 }
629 }
630 }
631
632 if (children != null) {
633 _ = xlib.XFree(@ptrCast(children));
634 }
635 }
636
637 fn run_event_loop(display: *Display) void {
638 const fd = xlib.XConnectionNumber(display.handle);
639 var fds = [_]std.posix.pollfd{
640 .{ .fd = fd, .events = std.posix.POLL.IN, .revents = 0 },
641 };
642
643 _ = xlib.XSync(display.handle, xlib.False);
644
645 while (running) {
646 while (xlib.XPending(display.handle) > 0) {
647 var event = display.next_event();
648 handle_event(display, &event);
649 }
650
651 tick_animations();
652
653 var current_bar = bar_mod.bars;
654 while (current_bar) |bar| {
655 bar.update_blocks();
656 bar.draw(display.handle, &config.tags, config);
657 current_bar = bar.next;
658 }
659
660 const poll_timeout: i32 = if (scroll_animation.is_active()) 16 else 1000;
661 _ = std.posix.poll(&fds, poll_timeout) catch 0;
662 }
663 }
664
665 fn handle_event(display: *Display, event: *xlib.XEvent) void {
666 const event_type = events.get_event_type(event);
667
668 if (event_type == .button_press) {
669 std.debug.print("EVENT: button_press received type={d}\n", .{event.type});
670 }
671
672 switch (event_type) {
673 .map_request => handle_map_request(display, &event.xmaprequest),
674 .configure_request => handle_configure_request(display, &event.xconfigurerequest),
675 .key_press => handle_key_press(display, &event.xkey),
676 .destroy_notify => handle_destroy_notify(display, &event.xdestroywindow),
677 .unmap_notify => handle_unmap_notify(display, &event.xunmap),
678 .enter_notify => handle_enter_notify(display, &event.xcrossing),
679 .focus_in => handle_focus_in(display, &event.xfocus),
680 .motion_notify => handle_motion_notify(display, &event.xmotion),
681 .client_message => handle_client_message(display, &event.xclient),
682 .button_press => handle_button_press(display, &event.xbutton),
683 .expose => handle_expose(display, &event.xexpose),
684 .property_notify => handle_property_notify(display, &event.xproperty),
685 else => {},
686 }
687 }
688
689 fn handle_map_request(display: *Display, event: *xlib.XMapRequestEvent) void {
690 std.debug.print("map_request: window=0x{x}\n", .{event.window});
691
692 var window_attributes: xlib.XWindowAttributes = undefined;
693 if (xlib.XGetWindowAttributes(display.handle, event.window, &window_attributes) == 0) {
694 return;
695 }
696 if (window_attributes.override_redirect != 0) {
697 return;
698 }
699 if (client_mod.window_to_client(monitor_mod.monitors, event.window) != null) {
700 return;
701 }
702
703 manage(display, event.window, &window_attributes);
704 }
705
706 fn manage(display: *Display, win: xlib.Window, window_attrs: *xlib.XWindowAttributes) void {
707 const client = client_mod.create(gpa.allocator(), win) orelse return;
708 var trans: xlib.Window = 0;
709
710 client.x = window_attrs.x;
711 client.y = window_attrs.y;
712 client.width = window_attrs.width;
713 client.height = window_attrs.height;
714 client.old_x = window_attrs.x;
715 client.old_y = window_attrs.y;
716 client.old_width = window_attrs.width;
717 client.old_height = window_attrs.height;
718 client.old_border_width = window_attrs.border_width;
719 client.border_width = config.border_width;
720
721 update_title(display, client);
722
723 if (xlib.XGetTransientForHint(display.handle, win, &trans) != 0) {
724 if (client_mod.window_to_client(monitor_mod.monitors, trans)) |transient_client| {
725 client.monitor = transient_client.monitor;
726 client.tags = transient_client.tags;
727 }
728 }
729
730 if (client.monitor == null) {
731 client.monitor = monitor_mod.selected_monitor;
732 apply_rules(display, client);
733 }
734
735 const monitor = client.monitor orelse return;
736
737 if (client.x + client.width > monitor.win_x + monitor.win_w) {
738 client.x = monitor.win_x + monitor.win_w - client.width - 2 * client.border_width;
739 }
740 if (client.y + client.height > monitor.win_y + monitor.win_h) {
741 client.y = monitor.win_y + monitor.win_h - client.height - 2 * client.border_width;
742 }
743 client.x = @max(client.x, monitor.win_x);
744 client.y = @max(client.y, monitor.win_y);
745
746 _ = xlib.XSetWindowBorderWidth(display.handle, win, @intCast(client.border_width));
747 _ = xlib.XSetWindowBorder(display.handle, win, config.border_unfocused);
748 tiling.send_configure(client);
749
750 update_window_type(display, client);
751 update_size_hints(display, client);
752 update_wm_hints(display, client);
753
754 _ = xlib.XSelectInput(
755 display.handle,
756 win,
757 xlib.EnterWindowMask | xlib.FocusChangeMask | xlib.PropertyChangeMask | xlib.StructureNotifyMask,
758 );
759 grabbuttons(display, client, false);
760
761 if (!client.is_floating) {
762 client.is_floating = trans != 0 or client.is_fixed;
763 client.old_state = client.is_floating;
764 }
765 if (client.is_floating) {
766 _ = xlib.XRaiseWindow(display.handle, client.window);
767 }
768
769 client_mod.attach_aside(client);
770 client_mod.attach_stack(client);
771
772 _ = xlib.XChangeProperty(display.handle, display.root, atoms.net_client_list, xlib.XA_WINDOW, 32, xlib.PropModeAppend, @ptrCast(&client.window), 1);
773 _ = xlib.XMoveResizeWindow(display.handle, client.window, client.x + 2 * display.screen_width(), client.y, @intCast(client.width), @intCast(client.height));
774 set_client_state(display, client, NormalState);
775
776 if (client.monitor == monitor_mod.selected_monitor) {
777 const selmon = monitor_mod.selected_monitor orelse return;
778 unfocus_client(display, selmon.sel, false);
779 }
780 monitor.sel = client;
781
782 if (is_scrolling_layout(monitor)) {
783 monitor.scroll_offset = 0;
784 }
785
786 arrange(monitor);
787 _ = xlib.XMapWindow(display.handle, win);
788 focus(display, null);
789 }
790
791 fn handle_configure_request(display: *Display, event: *xlib.XConfigureRequestEvent) void {
792 const client = client_mod.window_to_client(monitor_mod.monitors, event.window);
793
794 if (client) |managed_client| {
795 if ((event.value_mask & xlib.c.CWBorderWidth) != 0) {
796 managed_client.border_width = event.border_width;
797 } else if (managed_client.is_floating or (managed_client.monitor != null and managed_client.monitor.?.lt[managed_client.monitor.?.sel_lt] == null)) {
798 const monitor = managed_client.monitor orelse return;
799 if ((event.value_mask & xlib.c.CWX) != 0) {
800 managed_client.old_x = managed_client.x;
801 managed_client.x = monitor.mon_x + event.x;
802 }
803 if ((event.value_mask & xlib.c.CWY) != 0) {
804 managed_client.old_y = managed_client.y;
805 managed_client.y = monitor.mon_y + event.y;
806 }
807 if ((event.value_mask & xlib.c.CWWidth) != 0) {
808 managed_client.old_width = managed_client.width;
809 managed_client.width = event.width;
810 }
811 if ((event.value_mask & xlib.c.CWHeight) != 0) {
812 managed_client.old_height = managed_client.height;
813 managed_client.height = event.height;
814 }
815 const client_full_width = managed_client.width + managed_client.border_width * 2;
816 const client_full_height = managed_client.height + managed_client.border_width * 2;
817 if ((managed_client.x + managed_client.width) > monitor.mon_x + monitor.mon_w and managed_client.is_floating) {
818 managed_client.x = monitor.mon_x + @divTrunc(monitor.mon_w, 2) - @divTrunc(client_full_width, 2);
819 }
820 if ((managed_client.y + managed_client.height) > monitor.mon_y + monitor.mon_h and managed_client.is_floating) {
821 managed_client.y = monitor.mon_y + @divTrunc(monitor.mon_h, 2) - @divTrunc(client_full_height, 2);
822 }
823 if (((event.value_mask & (xlib.c.CWX | xlib.c.CWY)) != 0) and ((event.value_mask & (xlib.c.CWWidth | xlib.c.CWHeight)) == 0)) {
824 tiling.send_configure(managed_client);
825 }
826 if (client_mod.is_visible(managed_client)) {
827 _ = xlib.XMoveResizeWindow(display.handle, managed_client.window, managed_client.x, managed_client.y, @intCast(managed_client.width), @intCast(managed_client.height));
828 }
829 } else {
830 tiling.send_configure(managed_client);
831 }
832 } else {
833 var changes: xlib.XWindowChanges = undefined;
834 changes.x = event.x;
835 changes.y = event.y;
836 changes.width = event.width;
837 changes.height = event.height;
838 changes.border_width = event.border_width;
839 changes.sibling = event.above;
840 changes.stack_mode = event.detail;
841 _ = xlib.XConfigureWindow(display.handle, event.window, @intCast(event.value_mask), &changes);
842 }
843 _ = xlib.XSync(display.handle, xlib.False);
844 }
845
846 fn reset_chord_state(display_handle: *xlib.Display) void {
847 chord.reset(display_handle);
848 }
849
850 fn handle_key_press(display: *Display, event: *xlib.XKeyEvent) void {
851 const keysym = xlib.XKeycodeToKeysym(display.handle, @intCast(event.keycode), 0);
852
853 if (keybind_overlay) |overlay| {
854 if (overlay.handle_key(keysym)) {
855 return;
856 }
857 }
858
859 const clean_state = event.state & ~@as(c_uint, xlib.LockMask | xlib.Mod2Mask);
860 const current_time = std.time.milliTimestamp();
861
862 if (chord.index > 0 and (current_time - chord.last_timestamp) > kchord.timeout_ms) {
863 reset_chord_state(display.handle);
864 }
865
866 _ = chord.push(.{ .mod_mask = clean_state, .keysym = keysym });
867
868 for (config.keybinds.items) |keybind| {
869 if (keybind.key_count == 0) continue;
870
871 if (keybind.key_count == chord.index) {
872 var matches = true;
873 for (0..keybind.key_count) |i| {
874 if (chord.keys[i].keysym != keybind.keys[i].keysym or chord.keys[i].mod_mask != keybind.keys[i].mod_mask) {
875 matches = false;
876 break;
877 }
878 }
879 if (matches) {
880 execute_action(display, keybind.action, keybind.int_arg, keybind.str_arg);
881 reset_chord_state(display.handle);
882 return;
883 }
884 }
885 }
886
887 var has_partial_match = false;
888 for (config.keybinds.items) |keybind| {
889 if (keybind.key_count > chord.index) {
890 var matches = true;
891 for (0..chord.index) |i| {
892 if (chord.keys[i].keysym != keybind.keys[i].keysym or chord.keys[i].mod_mask != keybind.keys[i].mod_mask) {
893 matches = false;
894 break;
895 }
896 }
897 if (matches) {
898 has_partial_match = true;
899 break;
900 }
901 }
902 }
903
904 if (has_partial_match) {
905 chord.grab_keyboard(display.handle, display.root);
906 } else if (!has_partial_match) {
907 reset_chord_state(display.handle);
908 }
909 }
910
911 fn execute_action(display: *Display, action: config_mod.Action, int_arg: i32, str_arg: ?[]const u8) void {
912 switch (action) {
913 .spawn_terminal => spawn_terminal(),
914 .spawn => {
915 if (str_arg) |cmd| {
916 spawn_command(cmd);
917 }
918 },
919 .kill_client => kill_focused(display),
920 .quit => {
921 std.debug.print("quit keybind pressed\n", .{});
922 running = false;
923 },
924 .reload_config => reload_config(display),
925 .restart => reload_config(display),
926 .show_keybinds => {
927 if (keybind_overlay) |overlay| {
928 const mon = monitor_mod.selected_monitor orelse monitor_mod.monitors;
929 if (mon) |m| {
930 overlay.toggle(m.mon_x, m.mon_y, m.mon_w, m.mon_h, &config);
931 }
932 }
933 },
934 .focus_next => focusstack(display, 1),
935 .focus_prev => focusstack(display, -1),
936 .move_next => movestack(display, 1),
937 .move_prev => movestack(display, -1),
938 .resize_master => setmfact(@as(f32, @floatFromInt(int_arg)) / 1000.0),
939 .inc_master => incnmaster(1),
940 .dec_master => incnmaster(-1),
941 .toggle_floating => toggle_floating(display),
942 .toggle_fullscreen => toggle_fullscreen(display),
943 .toggle_gaps => toggle_gaps(),
944 .cycle_layout => cycle_layout(),
945 .set_layout => set_layout(str_arg),
946 .set_layout_tiling => set_layout_index(0),
947 .set_layout_floating => set_layout_index(2),
948 .view_tag => {
949 const tag_mask: u32 = @as(u32, 1) << @intCast(int_arg);
950 view(display, tag_mask);
951 },
952 .view_next_tag => view_adjacent_tag(display, 1),
953 .view_prev_tag => view_adjacent_tag(display, -1),
954 .view_next_nonempty_tag => view_adjacent_nonempty_tag(display, 1),
955 .view_prev_nonempty_tag => view_adjacent_nonempty_tag(display, -1),
956 .move_to_tag => {
957 const tag_mask: u32 = @as(u32, 1) << @intCast(int_arg);
958 tag_client(display, tag_mask);
959 },
960 .toggle_view_tag => {
961 const tag_mask: u32 = @as(u32, 1) << @intCast(int_arg);
962 toggle_view(display, tag_mask);
963 },
964 .toggle_tag => {
965 const tag_mask: u32 = @as(u32, 1) << @intCast(int_arg);
966 toggle_client_tag(display, tag_mask);
967 },
968 .focus_monitor => focusmon(display, int_arg),
969 .send_to_monitor => sendmon(display, int_arg),
970 .scroll_left => {
971 scroll_layout(-1);
972 },
973 .scroll_right => {
974 scroll_layout(1);
975 },
976 }
977 }
978
979 fn reload_config(display: *Display) void {
980 std.debug.print("reloading config...\n", .{});
981
982 ungrab_keybinds(display);
983
984 config.keybinds.clearRetainingCapacity();
985 config.buttons.clearRetainingCapacity();
986 config.rules.clearRetainingCapacity();
987 config.blocks.clearRetainingCapacity();
988
989 lua.deinit();
990 _ = lua.init(&config);
991
992 const loaded = if (config_path_global) |path|
993 lua.load_file(path)
994 else
995 lua.load_config();
996
997 if (loaded) {
998 if (config_path_global) |path| {
999 std.debug.print("reloaded config from {s}\n", .{path});
1000 } else {
1001 std.debug.print("reloaded config from ~/.config/oxwm/config.lua\n", .{});
1002 }
1003 } else {
1004 std.debug.print("reload failed, restoring defaults\n", .{});
1005 initialize_default_config();
1006 }
1007
1008 bar_mod.destroy_bars(gpa.allocator(), display.handle);
1009 setup_bars(gpa.allocator(), display);
1010 rebuild_bar_blocks();
1011
1012 grab_keybinds(display);
1013 }
1014
1015 fn rebuild_bar_blocks() void {
1016 var current_bar = bar_mod.bars;
1017 while (current_bar) |bar| {
1018 bar.clear_blocks();
1019 if (config.blocks.items.len > 0) {
1020 for (config.blocks.items) |cfg_block| {
1021 const block = config_block_to_bar_block(cfg_block);
1022 bar.add_block(block);
1023 }
1024 } else {
1025 bar.add_block(blocks_mod.Block.init_ram("", 5, 0x7aa2f7, true));
1026 bar.add_block(blocks_mod.Block.init_static(" | ", 0x666666, false));
1027 bar.add_block(blocks_mod.Block.init_datetime("", "%H:%M", 1, 0x0db9d7, true));
1028 }
1029 current_bar = bar.next;
1030 }
1031 }
1032
1033 fn ungrab_keybinds(display: *Display) void {
1034 _ = xlib.XUngrabKey(display.handle, xlib.AnyKey, xlib.AnyModifier, display.root);
1035 }
1036
1037 /// File descriptor for the X11 connection. Set once after the display is
1038 /// opened and used only in post-fork child setup to close the inherited fd.
1039 var x11_fd: c_int = -1;
1040
1041 fn spawn_child_setup() void {
1042 _ = std.c.setsid();
1043 if (x11_fd >= 0) std.posix.close(@intCast(x11_fd));
1044 const sigchld_handler = std.posix.Sigaction{
1045 .handler = .{ .handler = std.posix.SIG.DFL },
1046 .mask = std.mem.zeroes(std.posix.sigset_t),
1047 .flags = 0,
1048 };
1049 std.posix.sigaction(std.posix.SIG.CHLD, &sigchld_handler, null);
1050 }
1051
1052 fn spawn_command(cmd: []const u8) void {
1053 std.debug.print("running cmd: {s}\n", .{cmd});
1054 const pid = std.posix.fork() catch return;
1055 if (pid == 0) {
1056 spawn_child_setup();
1057 var cmd_buf: [1024]u8 = undefined;
1058 if (cmd.len >= cmd_buf.len) {
1059 std.posix.exit(1);
1060 }
1061 @memcpy(cmd_buf[0..cmd.len], cmd);
1062 cmd_buf[cmd.len] = 0;
1063 const argv = [_:null]?[*:0]const u8{ "sh", "-c", @ptrCast(&cmd_buf) };
1064 _ = std.posix.execvpeZ("sh", &argv, std.c.environ) catch {};
1065 std.posix.exit(1);
1066 }
1067 }
1068
1069 fn spawn_terminal() void {
1070 const pid = std.posix.fork() catch return;
1071 if (pid == 0) {
1072 spawn_child_setup();
1073 var term_buf: [256]u8 = undefined;
1074 const terminal = config.terminal;
1075 if (terminal.len >= term_buf.len) {
1076 std.posix.exit(1);
1077 }
1078 @memcpy(term_buf[0..terminal.len], terminal);
1079 term_buf[terminal.len] = 0;
1080 const term_ptr: [*:0]const u8 = @ptrCast(&term_buf);
1081 const argv = [_:null]?[*:0]const u8{term_ptr};
1082 _ = std.posix.execvpeZ(term_ptr, &argv, std.c.environ) catch {};
1083 std.posix.exit(1);
1084 }
1085 }
1086
1087 fn movestack(display: *Display, direction: i32) void {
1088 const monitor = monitor_mod.selected_monitor orelse return;
1089 const current = monitor.sel orelse return;
1090
1091 if (current.is_floating) {
1092 return;
1093 }
1094
1095 var target: ?*Client = null;
1096
1097 if (direction > 0) {
1098 target = current.next;
1099 while (target) |client| {
1100 if (client_mod.is_visible(client) and !client.is_floating) {
1101 break;
1102 }
1103 target = client.next;
1104 }
1105 if (target == null) {
1106 target = monitor.clients;
1107 while (target) |client| {
1108 if (client == current) {
1109 break;
1110 }
1111 if (client_mod.is_visible(client) and !client.is_floating) {
1112 break;
1113 }
1114 target = client.next;
1115 }
1116 }
1117 } else {
1118 var prev: ?*Client = null;
1119 var iter = monitor.clients;
1120 while (iter) |client| {
1121 if (client == current) {
1122 break;
1123 }
1124 if (client_mod.is_visible(client) and !client.is_floating) {
1125 prev = client;
1126 }
1127 iter = client.next;
1128 }
1129 if (prev == null) {
1130 iter = current.next;
1131 while (iter) |client| {
1132 if (client_mod.is_visible(client) and !client.is_floating) {
1133 prev = client;
1134 }
1135 iter = client.next;
1136 }
1137 }
1138 target = prev;
1139 }
1140
1141 if (target) |swap_client| {
1142 if (swap_client != current) {
1143 client_mod.swap_clients(current, swap_client);
1144 arrange(monitor);
1145 focus(display, current);
1146 }
1147 }
1148 }
1149
1150 fn toggle_view(display: *Display, tag_mask: u32) void {
1151 const monitor = monitor_mod.selected_monitor orelse return;
1152 const new_tags = monitor.tagset[monitor.sel_tags] ^ tag_mask;
1153 if (new_tags != 0) {
1154 monitor.tagset[monitor.sel_tags] = new_tags;
1155
1156 if (new_tags == ~@as(u32, 0)) {
1157 monitor.pertag.prevtag = monitor.pertag.curtag;
1158 monitor.pertag.curtag = 0;
1159 }
1160
1161 if ((new_tags & (@as(u32, 1) << @intCast(monitor.pertag.curtag -| 1))) == 0) {
1162 monitor.pertag.prevtag = monitor.pertag.curtag;
1163 var i: u32 = 0;
1164 while (i < 9) : (i += 1) {
1165 if ((new_tags & (@as(u32, 1) << @intCast(i))) != 0) break;
1166 }
1167 monitor.pertag.curtag = i + 1;
1168 }
1169
1170 monitor.nmaster = monitor.pertag.nmasters[monitor.pertag.curtag];
1171 monitor.mfact = monitor.pertag.mfacts[monitor.pertag.curtag];
1172 monitor.sel_lt = monitor.pertag.sellts[monitor.pertag.curtag];
1173
1174 focus_top_client(display, monitor);
1175 arrange(monitor);
1176 bar_mod.invalidate_bars();
1177 }
1178 }
1179
1180 fn toggle_client_tag(display: *Display, tag_mask: u32) void {
1181 const monitor = monitor_mod.selected_monitor orelse return;
1182 const client = monitor.sel orelse return;
1183 const new_tags = client.tags ^ tag_mask;
1184 if (new_tags != 0) {
1185 client.tags = new_tags;
1186 focus_top_client(display, monitor);
1187 arrange(monitor);
1188 bar_mod.invalidate_bars();
1189 }
1190 }
1191
1192 fn toggle_gaps() void {
1193 const monitor = monitor_mod.selected_monitor orelse return;
1194 if (monitor.gap_inner_h == 0) {
1195 monitor.gap_inner_h = config.gap_inner_h;
1196 monitor.gap_inner_v = config.gap_inner_v;
1197 monitor.gap_outer_h = config.gap_outer_h;
1198 monitor.gap_outer_v = config.gap_outer_v;
1199 } else {
1200 monitor.gap_inner_h = 0;
1201 monitor.gap_inner_v = 0;
1202 monitor.gap_outer_h = 0;
1203 monitor.gap_outer_v = 0;
1204 }
1205 arrange(monitor);
1206 }
1207
1208 fn kill_focused(display: *Display) void {
1209 const selected = monitor_mod.selected_monitor orelse return;
1210 const client = selected.sel orelse return;
1211 std.debug.print("killing window: 0x{x}\n", .{client.window});
1212
1213 if (!send_event(display, client, atoms.wm_delete)) {
1214 _ = xlib.XGrabServer(display.handle);
1215 _ = xlib.XKillClient(display.handle, client.window);
1216 _ = xlib.XSync(display.handle, xlib.False);
1217 _ = xlib.XUngrabServer(display.handle);
1218 }
1219 }
1220
1221 fn toggle_fullscreen(display: *Display) void {
1222 const selected = monitor_mod.selected_monitor orelse return;
1223 const client = selected.sel orelse return;
1224 set_fullscreen(display, client, !client.is_fullscreen);
1225 }
1226
1227 fn set_fullscreen(display: *Display, client: *Client, fullscreen: bool) void {
1228 const monitor = client.monitor orelse return;
1229
1230 if (fullscreen and !client.is_fullscreen) {
1231 var fullscreen_atom = atoms.net_wm_state_fullscreen;
1232 _ = xlib.XChangeProperty(
1233 display.handle,
1234 client.window,
1235 atoms.net_wm_state,
1236 xlib.XA_ATOM,
1237 32,
1238 xlib.PropModeReplace,
1239 @ptrCast(&fullscreen_atom),
1240 1,
1241 );
1242 client.is_fullscreen = true;
1243 client.old_state = client.is_floating;
1244 client.old_border_width = client.border_width;
1245 client.border_width = 0;
1246 client.is_floating = true;
1247
1248 _ = xlib.XSetWindowBorderWidth(display.handle, client.window, 0);
1249 tiling.resize_client(client, monitor.mon_x, monitor.mon_y, monitor.mon_w, monitor.mon_h);
1250 _ = xlib.XRaiseWindow(display.handle, client.window);
1251
1252 std.debug.print("fullscreen enabled: window=0x{x}\n", .{client.window});
1253 } else if (!fullscreen and client.is_fullscreen) {
1254 var no_atom: xlib.Atom = 0;
1255 _ = xlib.XChangeProperty(
1256 display.handle,
1257 client.window,
1258 atoms.net_wm_state,
1259 xlib.XA_ATOM,
1260 32,
1261 xlib.PropModeReplace,
1262 @ptrCast(&no_atom),
1263 0,
1264 );
1265 client.is_fullscreen = false;
1266 client.is_floating = client.old_state;
1267 client.border_width = client.old_border_width;
1268
1269 client.x = client.old_x;
1270 client.y = client.old_y;
1271 client.width = client.old_width;
1272 client.height = client.old_height;
1273
1274 tiling.resize_client(client, client.x, client.y, client.width, client.height);
1275 arrange(monitor);
1276
1277 std.debug.print("fullscreen disabled: window=0x{x}\n", .{client.window});
1278 }
1279 }
1280
1281 fn view(display: *Display, tag_mask: u32) void {
1282 const monitor = monitor_mod.selected_monitor orelse return;
1283 if (tag_mask == monitor.tagset[monitor.sel_tags]) {
1284 return;
1285 }
1286 monitor.sel_tags ^= 1;
1287 if (tag_mask != 0) {
1288 monitor.tagset[monitor.sel_tags] = tag_mask;
1289 monitor.pertag.prevtag = monitor.pertag.curtag;
1290
1291 if (tag_mask == ~@as(u32, 0)) {
1292 monitor.pertag.curtag = 0;
1293 } else {
1294 var i: u32 = 0;
1295 while (i < 9) : (i += 1) {
1296 if ((tag_mask & (@as(u32, 1) << @intCast(i))) != 0) break;
1297 }
1298 monitor.pertag.curtag = i + 1;
1299 }
1300 } else {
1301 const tmp = monitor.pertag.prevtag;
1302 monitor.pertag.prevtag = monitor.pertag.curtag;
1303 monitor.pertag.curtag = tmp;
1304 }
1305
1306 monitor.nmaster = monitor.pertag.nmasters[monitor.pertag.curtag];
1307 monitor.mfact = monitor.pertag.mfacts[monitor.pertag.curtag];
1308 monitor.sel_lt = monitor.pertag.sellts[monitor.pertag.curtag];
1309
1310 focus_top_client(display, monitor);
1311 arrange(monitor);
1312 bar_mod.invalidate_bars();
1313 std.debug.print("view: tag_mask={d}\n", .{monitor.tagset[monitor.sel_tags]});
1314 }
1315
1316 fn view_adjacent_tag(display: *Display, direction: i32) void {
1317 const monitor = monitor_mod.selected_monitor orelse return;
1318 const current_tag = monitor.pertag.curtag;
1319 var new_tag: i32 = @intCast(current_tag);
1320
1321 new_tag += direction;
1322 if (new_tag < 1) new_tag = 9;
1323 if (new_tag > 9) new_tag = 1;
1324
1325 const tag_mask: u32 = @as(u32, 1) << @intCast(new_tag - 1);
1326 view(display, tag_mask);
1327 }
1328
1329 fn view_adjacent_nonempty_tag(display: *Display, direction: i32) void {
1330 const monitor = monitor_mod.selected_monitor orelse return;
1331 const current_tag = monitor.pertag.curtag;
1332 var new_tag: i32 = @intCast(current_tag);
1333
1334 var attempts: i32 = 0;
1335 while (attempts < 9) : (attempts += 1) {
1336 new_tag += direction;
1337 if (new_tag < 1) new_tag = 9;
1338 if (new_tag > 9) new_tag = 1;
1339
1340 const tag_mask: u32 = @as(u32, 1) << @intCast(new_tag - 1);
1341 if (has_clients_on_tag(monitor, tag_mask)) {
1342 view(display, tag_mask);
1343 return;
1344 }
1345 }
1346 }
1347
1348 fn has_clients_on_tag(monitor: *monitor_mod.Monitor, tag_mask: u32) bool {
1349 var client = monitor.clients;
1350 while (client) |c| {
1351 if ((c.tags & tag_mask) != 0) {
1352 return true;
1353 }
1354 client = c.next;
1355 }
1356 return false;
1357 }
1358
1359 fn tag_client(display: *Display, tag_mask: u32) void {
1360 const monitor = monitor_mod.selected_monitor orelse return;
1361 const client = monitor.sel orelse return;
1362 if (tag_mask == 0) {
1363 return;
1364 }
1365 client.tags = tag_mask;
1366 focus_top_client(display, monitor);
1367 arrange(monitor);
1368 bar_mod.invalidate_bars();
1369 std.debug.print("tag_client: window=0x{x} tag_mask={d}\n", .{ client.window, tag_mask });
1370 }
1371
1372 fn focus_top_client(display: *Display, monitor: *Monitor) void {
1373 var visible_client = monitor.stack;
1374 while (visible_client) |client| {
1375 if (client_mod.is_visible(client)) {
1376 focus(display, client);
1377 return;
1378 }
1379 visible_client = client.stack_next;
1380 }
1381 monitor.sel = null;
1382 _ = xlib.XSetInputFocus(display.handle, display.root, xlib.RevertToPointerRoot, xlib.CurrentTime);
1383 }
1384
1385 fn focusstack(display: *Display, direction: i32) void {
1386 const monitor = monitor_mod.selected_monitor orelse return;
1387 const current = monitor.sel orelse return;
1388
1389 var next_client: ?*Client = null;
1390
1391 if (direction > 0) {
1392 next_client = current.next;
1393 while (next_client) |client| {
1394 if (client_mod.is_visible(client)) {
1395 break;
1396 }
1397 next_client = client.next;
1398 }
1399 if (next_client == null) {
1400 next_client = monitor.clients;
1401 while (next_client) |client| {
1402 if (client_mod.is_visible(client)) {
1403 break;
1404 }
1405 next_client = client.next;
1406 }
1407 }
1408 } else {
1409 var prev: ?*Client = null;
1410 var iter = monitor.clients;
1411 while (iter) |client| {
1412 if (client == current) {
1413 break;
1414 }
1415 if (client_mod.is_visible(client)) {
1416 prev = client;
1417 }
1418 iter = client.next;
1419 }
1420 if (prev == null) {
1421 iter = current.next;
1422 while (iter) |client| {
1423 if (client_mod.is_visible(client)) {
1424 prev = client;
1425 }
1426 iter = client.next;
1427 }
1428 }
1429 next_client = prev;
1430 }
1431
1432 if (next_client) |client| {
1433 focus(display, client);
1434 if (client.monitor) |client_monitor| {
1435 restack(display, client_monitor);
1436 }
1437 }
1438 }
1439
1440 fn toggle_floating(_: *Display) void {
1441 const monitor = monitor_mod.selected_monitor orelse return;
1442 const client = monitor.sel orelse return;
1443
1444 if (client.is_fullscreen) {
1445 return;
1446 }
1447
1448 client.is_floating = !client.is_floating;
1449
1450 if (client.is_floating) {
1451 tiling.resize(client, client.x, client.y, client.width, client.height, false);
1452 }
1453
1454 arrange(monitor);
1455 std.debug.print("toggle_floating: window=0x{x} floating={}\n", .{ client.window, client.is_floating });
1456 }
1457
1458 fn incnmaster(delta: i32) void {
1459 const monitor = monitor_mod.selected_monitor orelse return;
1460 const new_val = @max(0, monitor.nmaster + delta);
1461 monitor.nmaster = new_val;
1462 monitor.pertag.nmasters[monitor.pertag.curtag] = new_val;
1463 arrange(monitor);
1464 std.debug.print("incnmaster: nmaster={d}\n", .{monitor.nmaster});
1465 }
1466
1467 fn setmfact(delta: f32) void {
1468 const monitor = monitor_mod.selected_monitor orelse return;
1469 const new_mfact = monitor.mfact + delta;
1470 if (new_mfact < 0.05 or new_mfact > 0.95) {
1471 return;
1472 }
1473 monitor.mfact = new_mfact;
1474 monitor.pertag.mfacts[monitor.pertag.curtag] = new_mfact;
1475 arrange(monitor);
1476 std.debug.print("setmfact: mfact={d:.2}\n", .{monitor.mfact});
1477 }
1478
1479 fn cycle_layout() void {
1480 const monitor = monitor_mod.selected_monitor orelse return;
1481 const new_lt = (monitor.sel_lt + 1) % 5;
1482 monitor.sel_lt = new_lt;
1483 monitor.pertag.sellts[monitor.pertag.curtag] = new_lt;
1484 if (new_lt != 3) {
1485 monitor.scroll_offset = 0;
1486 }
1487 arrange(monitor);
1488 bar_mod.invalidate_bars();
1489 if (monitor.lt[monitor.sel_lt]) |layout| {
1490 std.debug.print("cycle_layout: {s}\n", .{layout.symbol});
1491 }
1492 }
1493
1494 fn set_layout(layout_name: ?[]const u8) void {
1495 const monitor = monitor_mod.selected_monitor orelse return;
1496 const name = layout_name orelse return;
1497
1498 const new_lt: u32 = if (std.mem.eql(u8, name, "tiling") or std.mem.eql(u8, name, "[]="))
1499 0
1500 else if (std.mem.eql(u8, name, "monocle") or std.mem.eql(u8, name, "[M]"))
1501 1
1502 else if (std.mem.eql(u8, name, "floating") or std.mem.eql(u8, name, "><>"))
1503 2
1504 else if (std.mem.eql(u8, name, "scrolling") or std.mem.eql(u8, name, "[S]"))
1505 3
1506 else if (std.mem.eql(u8, name, "grid") or std.mem.eql(u8, name, "[#]"))
1507 4
1508 else {
1509 std.debug.print("set_layout: unknown layout '{s}'\n", .{name});
1510 return;
1511 };
1512
1513 monitor.sel_lt = new_lt;
1514 monitor.pertag.sellts[monitor.pertag.curtag] = new_lt;
1515 if (new_lt != 3) {
1516 monitor.scroll_offset = 0;
1517 }
1518 arrange(monitor);
1519 bar_mod.invalidate_bars();
1520 if (monitor.lt[monitor.sel_lt]) |layout| {
1521 std.debug.print("set_layout: {s}\n", .{layout.symbol});
1522 }
1523 }
1524
1525 fn set_layout_index(index: u32) void {
1526 const monitor = monitor_mod.selected_monitor orelse return;
1527 monitor.sel_lt = index;
1528 monitor.pertag.sellts[monitor.pertag.curtag] = index;
1529 if (index != 3) {
1530 monitor.scroll_offset = 0;
1531 }
1532 arrange(monitor);
1533 bar_mod.invalidate_bars();
1534 if (monitor.lt[monitor.sel_lt]) |layout| {
1535 std.debug.print("set_layout_index: {s}\n", .{layout.symbol});
1536 }
1537 }
1538
1539 fn focusmon(display: *Display, direction: i32) void {
1540 const selmon = monitor_mod.selected_monitor orelse return;
1541 const target = monitor_mod.dir_to_monitor(direction) orelse return;
1542 if (target == selmon) {
1543 return;
1544 }
1545 unfocus_client(display, selmon.sel, false);
1546 monitor_mod.selected_monitor = target;
1547 focus(display, null);
1548 std.debug.print("focusmon: monitor {d}\n", .{target.num});
1549 }
1550
1551 fn sendmon(display: *Display, direction: i32) void {
1552 const source_monitor = monitor_mod.selected_monitor orelse return;
1553 const client = source_monitor.sel orelse return;
1554 const target = monitor_mod.dir_to_monitor(direction) orelse return;
1555
1556 if (target == source_monitor) {
1557 return;
1558 }
1559
1560 client_mod.detach(client);
1561 client_mod.detach_stack(client);
1562 client.monitor = target;
1563 client.tags = target.tagset[target.sel_tags];
1564 client_mod.attach_aside(client);
1565 client_mod.attach_stack(client);
1566
1567 focus_top_client(display, source_monitor);
1568 arrange(source_monitor);
1569 arrange(target);
1570
1571 std.debug.print("sendmon: window=0x{x} to monitor {d}\n", .{ client.window, target.num });
1572 }
1573
1574 fn snap_x(client: *Client, new_x: i32, monitor: *Monitor) i32 {
1575 const client_width = client.width + 2 * client.border_width;
1576 if (@abs(monitor.win_x - new_x) < snap_distance) {
1577 return monitor.win_x;
1578 } else if (@abs((monitor.win_x + monitor.win_w) - (new_x + client_width)) < snap_distance) {
1579 return monitor.win_x + monitor.win_w - client_width;
1580 }
1581 return new_x;
1582 }
1583
1584 fn snap_y(client: *Client, new_y: i32, monitor: *Monitor) i32 {
1585 const client_height = client.height + 2 * client.border_width;
1586 if (@abs(monitor.win_y - new_y) < snap_distance) {
1587 return monitor.win_y;
1588 } else if (@abs((monitor.win_y + monitor.win_h) - (new_y + client_height)) < snap_distance) {
1589 return monitor.win_y + monitor.win_h - client_height;
1590 }
1591 return new_y;
1592 }
1593
1594 fn movemouse(display: *Display) void {
1595 const monitor = monitor_mod.selected_monitor orelse return;
1596 const client = monitor.sel orelse return;
1597
1598 if (client.is_fullscreen) {
1599 return;
1600 }
1601
1602 restack(display, monitor);
1603
1604 const was_floating = client.is_floating;
1605 if (!client.is_floating) {
1606 client.is_floating = true;
1607 }
1608
1609 var root_x: c_int = undefined;
1610 var root_y: c_int = undefined;
1611 var dummy_win: xlib.Window = undefined;
1612 var dummy_int: c_int = undefined;
1613 var dummy_uint: c_uint = undefined;
1614
1615 _ = xlib.XQueryPointer(display.handle, display.root, &dummy_win, &dummy_win, &root_x, &root_y, &dummy_int, &dummy_int, &dummy_uint);
1616
1617 const grab_result = xlib.XGrabPointer(
1618 display.handle,
1619 display.root,
1620 xlib.False,
1621 xlib.ButtonPressMask | xlib.ButtonReleaseMask | xlib.PointerMotionMask,
1622 xlib.GrabModeAsync,
1623 xlib.GrabModeAsync,
1624 xlib.None,
1625 cursors.move,
1626 xlib.CurrentTime,
1627 );
1628
1629 if (grab_result != xlib.GrabSuccess) {
1630 return;
1631 }
1632
1633 const start_x = client.x;
1634 const start_y = client.y;
1635 const pointer_start_x = root_x;
1636 const pointer_start_y = root_y;
1637 var last_time: c_ulong = 0;
1638
1639 var event: xlib.XEvent = undefined;
1640 var done = false;
1641
1642 while (!done) {
1643 _ = xlib.XNextEvent(display.handle, &event);
1644
1645 switch (event.type) {
1646 xlib.MotionNotify => {
1647 const motion = &event.xmotion;
1648 if ((motion.time - last_time) < (1000 / 60)) {
1649 continue;
1650 }
1651 last_time = motion.time;
1652 const delta_x = motion.x_root - pointer_start_x;
1653 const delta_y = motion.y_root - pointer_start_y;
1654 var new_x = start_x + delta_x;
1655 var new_y = start_y + delta_y;
1656 if (client.monitor) |client_monitor| {
1657 new_x = snap_x(client, new_x, client_monitor);
1658 new_y = snap_y(client, new_y, client_monitor);
1659 }
1660 tiling.resize(client, new_x, new_y, client.width, client.height, true);
1661 },
1662 xlib.ButtonRelease => {
1663 done = true;
1664 },
1665 else => {},
1666 }
1667 }
1668
1669 _ = xlib.XUngrabPointer(display.handle, xlib.CurrentTime);
1670
1671 const new_mon = monitor_mod.rect_to_monitor(client.x, client.y, client.width, client.height);
1672 if (new_mon != null and new_mon != monitor) {
1673 client_mod.detach(client);
1674 client_mod.detach_stack(client);
1675 client.monitor = new_mon;
1676 client.tags = new_mon.?.tagset[new_mon.?.sel_tags];
1677 client_mod.attach_aside(client);
1678 client_mod.attach_stack(client);
1679 monitor_mod.selected_monitor = new_mon;
1680 focus(display, client);
1681 arrange(monitor);
1682 arrange(new_mon.?);
1683 } else {
1684 arrange(monitor);
1685 }
1686
1687 if (config.auto_tile and !was_floating) {
1688 const drop_monitor = client.monitor orelse return;
1689 const center_x = client.x + @divTrunc(client.width, 2);
1690 const center_y = client.y + @divTrunc(client.height, 2);
1691
1692 if (client_mod.tiled_window_at(client, drop_monitor, center_x, center_y)) |target| {
1693 client_mod.insert_before(client, target);
1694 }
1695
1696 client.is_floating = false;
1697 arrange(drop_monitor);
1698 }
1699 }
1700
1701 fn resizemouse(display: *Display) void {
1702 const monitor = monitor_mod.selected_monitor orelse return;
1703 const client = monitor.sel orelse return;
1704
1705 if (client.is_fullscreen) {
1706 return;
1707 }
1708
1709 restack(display, monitor);
1710
1711 if (!client.is_floating) {
1712 client.is_floating = true;
1713 }
1714
1715 const grab_result = xlib.XGrabPointer(
1716 display.handle,
1717 display.root,
1718 xlib.False,
1719 xlib.ButtonPressMask | xlib.ButtonReleaseMask | xlib.PointerMotionMask,
1720 xlib.GrabModeAsync,
1721 xlib.GrabModeAsync,
1722 xlib.None,
1723 cursors.resize,
1724 xlib.CurrentTime,
1725 );
1726
1727 if (grab_result != xlib.GrabSuccess) {
1728 return;
1729 }
1730
1731 _ = xlib.XWarpPointer(display.handle, xlib.None, client.window, 0, 0, 0, 0, client.width + client.border_width - 1, client.height + client.border_width - 1);
1732
1733 var event: xlib.XEvent = undefined;
1734 var done = false;
1735 var last_time: c_ulong = 0;
1736
1737 while (!done) {
1738 _ = xlib.XNextEvent(display.handle, &event);
1739
1740 switch (event.type) {
1741 xlib.MotionNotify => {
1742 const motion = &event.xmotion;
1743 if ((motion.time - last_time) < (1000 / 60)) {
1744 continue;
1745 }
1746 last_time = motion.time;
1747 var new_width = @max(1, motion.x_root - client.x - 2 * client.border_width + 1);
1748 var new_height = @max(1, motion.y_root - client.y - 2 * client.border_width + 1);
1749 if (client.monitor) |client_monitor| {
1750 const client_right = client.x + new_width + 2 * client.border_width;
1751 const client_bottom = client.y + new_height + 2 * client.border_width;
1752 const mon_right = client_monitor.win_x + client_monitor.win_w;
1753 const mon_bottom = client_monitor.win_y + client_monitor.win_h;
1754 if (@abs(mon_right - client_right) < snap_distance) {
1755 new_width = @max(1, mon_right - client.x - 2 * client.border_width);
1756 }
1757 if (@abs(mon_bottom - client_bottom) < snap_distance) {
1758 new_height = @max(1, mon_bottom - client.y - 2 * client.border_width);
1759 }
1760 }
1761 tiling.resize(client, client.x, client.y, new_width, new_height, true);
1762 },
1763 xlib.ButtonRelease => {
1764 done = true;
1765 },
1766 else => {},
1767 }
1768 }
1769
1770 _ = xlib.XUngrabPointer(display.handle, xlib.CurrentTime);
1771 arrange(monitor);
1772 }
1773
1774 fn handle_expose(display: *Display, event: *xlib.XExposeEvent) void {
1775 if (event.count != 0) return;
1776
1777 if (bar_mod.window_to_bar(event.window)) |bar| {
1778 bar.invalidate();
1779 bar.draw(display.handle, &config.tags, config);
1780 }
1781 }
1782
1783 fn clean_mask(mask: c_uint) c_uint {
1784 const lock: c_uint = @intCast(xlib.LockMask);
1785 const shift: c_uint = @intCast(xlib.ShiftMask);
1786 const ctrl: c_uint = @intCast(xlib.ControlMask);
1787 const mod1: c_uint = @intCast(xlib.Mod1Mask);
1788 const mod2: c_uint = @intCast(xlib.Mod2Mask);
1789 const mod3: c_uint = @intCast(xlib.Mod3Mask);
1790 const mod4: c_uint = @intCast(xlib.Mod4Mask);
1791 const mod5: c_uint = @intCast(xlib.Mod5Mask);
1792 return mask & ~(lock | numlock_mask) & (shift | ctrl | mod1 | mod2 | mod3 | mod4 | mod5);
1793 }
1794
1795 fn handle_button_press(display: *Display, event: *xlib.XButtonEvent) void {
1796 std.debug.print("button_press: window=0x{x} subwindow=0x{x}\n", .{ event.window, event.subwindow });
1797
1798 const clicked_monitor = monitor_mod.window_to_monitor(display.handle, display.root, event.window);
1799 if (clicked_monitor) |monitor| {
1800 if (monitor != monitor_mod.selected_monitor) {
1801 if (monitor_mod.selected_monitor) |selmon| {
1802 unfocus_client(display, selmon.sel, true);
1803 }
1804 monitor_mod.selected_monitor = monitor;
1805 focus(display, null);
1806 }
1807 }
1808
1809 if (bar_mod.window_to_bar(event.window)) |bar| {
1810 const clicked_tag = bar.handle_click(event.x, &config.tags);
1811 if (clicked_tag) |tag_index| {
1812 const tag_mask: u32 = @as(u32, 1) << @intCast(tag_index);
1813 view(display, tag_mask);
1814 }
1815 return;
1816 }
1817
1818 const click_client = client_mod.window_to_client(monitor_mod.monitors, event.window);
1819 if (click_client) |found_client| {
1820 focus(display, found_client);
1821 if (monitor_mod.selected_monitor) |selmon| {
1822 restack(display, selmon);
1823 }
1824 _ = xlib.XAllowEvents(display.handle, xlib.ReplayPointer, xlib.CurrentTime);
1825 }
1826
1827 const clean_state = clean_mask(event.state);
1828 for (config.buttons.items) |button| {
1829 if (button.click != .client_win) continue;
1830 const button_clean_mask = clean_mask(button.mod_mask);
1831 if (clean_state == button_clean_mask and event.button == button.button) {
1832 switch (button.action) {
1833 .move_mouse => movemouse(display),
1834 .resize_mouse => resizemouse(display),
1835 .toggle_floating => {
1836 if (click_client) |found_client| {
1837 found_client.is_floating = !found_client.is_floating;
1838 if (monitor_mod.selected_monitor) |monitor| {
1839 arrange(monitor);
1840 }
1841 }
1842 },
1843 }
1844 return;
1845 }
1846 }
1847 }
1848
1849 fn handle_client_message(display: *Display, event: *xlib.XClientMessageEvent) void {
1850 const client = client_mod.window_to_client(monitor_mod.monitors, event.window) orelse return;
1851
1852 if (event.message_type == atoms.net_wm_state) {
1853 const action = event.data.l[0];
1854 const first_property = @as(xlib.Atom, @intCast(event.data.l[1]));
1855 const second_property = @as(xlib.Atom, @intCast(event.data.l[2]));
1856
1857 if (first_property == atoms.net_wm_state_fullscreen or second_property == atoms.net_wm_state_fullscreen) {
1858 const net_wm_state_remove = 0;
1859 const net_wm_state_add = 1;
1860 const net_wm_state_toggle = 2;
1861
1862 if (action == net_wm_state_add) {
1863 set_fullscreen(display, client, true);
1864 } else if (action == net_wm_state_remove) {
1865 set_fullscreen(display, client, false);
1866 } else if (action == net_wm_state_toggle) {
1867 set_fullscreen(display, client, !client.is_fullscreen);
1868 }
1869 }
1870 } else if (event.message_type == atoms.net_active_window) {
1871 const selected = monitor_mod.selected_monitor orelse return;
1872 if (client != selected.sel and !client.is_urgent) {
1873 set_urgent(display, client, true);
1874 }
1875 }
1876 }
1877
1878 fn handle_destroy_notify(display: *Display, event: *xlib.XDestroyWindowEvent) void {
1879 const client = client_mod.window_to_client(monitor_mod.monitors, event.window) orelse return;
1880 std.debug.print("destroy_notify: window=0x{x}\n", .{event.window});
1881 unmanage(display, client);
1882 }
1883
1884 fn handle_unmap_notify(display: *Display, event: *xlib.XUnmapEvent) void {
1885 const client = client_mod.window_to_client(monitor_mod.monitors, event.window) orelse return;
1886 std.debug.print("unmap_notify: window=0x{x}\n", .{event.window});
1887 unmanage(display, client);
1888 }
1889
1890 fn unmanage(display: *Display, client: *Client) void {
1891 const client_monitor = client.monitor;
1892
1893 var next_focus: ?*Client = null;
1894 if (client_monitor) |monitor| {
1895 if (monitor.sel == client and is_scrolling_layout(monitor)) {
1896 next_focus = client.next;
1897 if (next_focus == null) {
1898 var prev: ?*Client = null;
1899 var iter = monitor.clients;
1900 while (iter) |c| {
1901 if (c == client) break;
1902 prev = c;
1903 iter = c.next;
1904 }
1905 next_focus = prev;
1906 }
1907 }
1908 }
1909
1910 client_mod.detach(client);
1911 client_mod.detach_stack(client);
1912
1913 if (client_monitor) |monitor| {
1914 if (monitor.sel == client) {
1915 monitor.sel = if (next_focus) |nf| nf else monitor.stack;
1916 }
1917 if (is_scrolling_layout(monitor)) {
1918 const target = if (monitor.sel) |sel| scrolling.get_target_scroll_for_window(monitor, sel) else 0;
1919 if (target == 0) {
1920 monitor.scroll_offset = scrolling.get_scroll_step(monitor);
1921 } else {
1922 monitor.scroll_offset = 0;
1923 }
1924 }
1925 arrange(monitor);
1926 }
1927
1928 if (client_monitor) |monitor| {
1929 if (monitor.sel) |selected| {
1930 focus(display, selected);
1931 }
1932 }
1933
1934 client_mod.destroy(gpa.allocator(), client);
1935 update_client_list(display);
1936 bar_mod.invalidate_bars();
1937 }
1938
1939 fn handle_enter_notify(display: *Display, event: *xlib.XCrossingEvent) void {
1940 if ((event.mode != xlib.NotifyNormal or event.detail == xlib.NotifyInferior) and event.window != display.root) {
1941 return;
1942 }
1943
1944 const client = client_mod.window_to_client(monitor_mod.monitors, event.window);
1945 const target_mon = if (client) |c| c.monitor else monitor_mod.window_to_monitor(display.handle, display.root, event.window);
1946 const selmon = monitor_mod.selected_monitor;
1947
1948 if (target_mon != selmon) {
1949 if (selmon) |sel| {
1950 unfocus_client(display, sel.sel, true);
1951 }
1952 monitor_mod.selected_monitor = target_mon;
1953 } else if (client == null) {
1954 return;
1955 } else if (selmon) |sel| {
1956 if (client.? == sel.sel) {
1957 return;
1958 }
1959 }
1960
1961 focus(display, client);
1962 }
1963
1964 fn handle_focus_in(display: *Display, event: *xlib.XFocusChangeEvent) void {
1965 const selmon = monitor_mod.selected_monitor orelse return;
1966 const selected = selmon.sel orelse return;
1967 if (event.window != selected.window) {
1968 set_focus(display, selected);
1969 }
1970 }
1971
1972 fn set_focus(display: *Display, client: *Client) void {
1973 if (!client.never_focus) {
1974 _ = xlib.XSetInputFocus(display.handle, client.window, xlib.RevertToPointerRoot, xlib.CurrentTime);
1975 _ = xlib.XChangeProperty(display.handle, display.root, atoms.net_active_window, xlib.XA_WINDOW, 32, xlib.PropModeReplace, @ptrCast(&client.window), 1);
1976 }
1977 _ = send_event(display, client, atoms.wm_take_focus);
1978 }
1979
1980 var last_motion_monitor: ?*Monitor = null;
1981
1982 fn handle_motion_notify(display: *Display, event: *xlib.XMotionEvent) void {
1983 if (event.window != display.root) {
1984 return;
1985 }
1986
1987 const target_mon = monitor_mod.rect_to_monitor(event.x_root, event.y_root, 1, 1);
1988 if (target_mon != last_motion_monitor and last_motion_monitor != null) {
1989 if (monitor_mod.selected_monitor) |selmon| {
1990 unfocus_client(display, selmon.sel, true);
1991 }
1992 monitor_mod.selected_monitor = target_mon;
1993 focus(display, null);
1994 }
1995 last_motion_monitor = target_mon;
1996 }
1997
1998 fn handle_property_notify(display: *Display, event: *xlib.XPropertyEvent) void {
1999 if (event.state == xlib.PropertyDelete) {
2000 return;
2001 }
2002
2003 const client = client_mod.window_to_client(monitor_mod.monitors, event.window) orelse return;
2004
2005 if (event.atom == xlib.XA_WM_TRANSIENT_FOR) {
2006 var trans: xlib.Window = 0;
2007 if (!client.is_floating and xlib.XGetTransientForHint(display.handle, client.window, &trans) != 0) {
2008 client.is_floating = client_mod.window_to_client(monitor_mod.monitors, trans) != null;
2009 if (client.is_floating) {
2010 if (client.monitor) |monitor| {
2011 arrange(monitor);
2012 }
2013 }
2014 }
2015 } else if (event.atom == xlib.XA_WM_NORMAL_HINTS) {
2016 client.hints_valid = false;
2017 } else if (event.atom == xlib.XA_WM_HINTS) {
2018 update_wm_hints(display, client);
2019 bar_mod.invalidate_bars();
2020 } else if (event.atom == xlib.XA_WM_NAME or event.atom == atoms.net_wm_name) {
2021 update_title(display, client);
2022 } else if (event.atom == atoms.net_wm_window_type) {
2023 update_window_type(display, client);
2024 }
2025 }
2026
2027 fn unfocus_client(display: *Display, client: ?*Client, reset_input_focus: bool) void {
2028 const unfocus_target = client orelse return;
2029 grabbuttons(display, unfocus_target, false);
2030 _ = xlib.XSetWindowBorder(display.handle, unfocus_target.window, config.border_unfocused);
2031 if (reset_input_focus) {
2032 _ = xlib.XSetInputFocus(display.handle, display.root, xlib.RevertToPointerRoot, xlib.CurrentTime);
2033 _ = xlib.XDeleteProperty(display.handle, display.root, atoms.net_active_window);
2034 }
2035 }
2036
2037 fn set_client_state(display: *Display, client: *Client, state: c_long) void {
2038 var data: [2]c_long = .{ state, xlib.None };
2039 _ = xlib.c.XChangeProperty(display.handle, client.window, atoms.wm_state, xlib.XA_ATOM, 32, xlib.PropModeReplace, @ptrCast(&data), 2);
2040 }
2041
2042 fn update_numlock_mask(display: *Display) void {
2043 numlock_mask = 0;
2044 const modmap = xlib.XGetModifierMapping(display.handle);
2045 if (modmap == null) return;
2046 defer _ = xlib.XFreeModifiermap(modmap);
2047
2048 const numlock_keycode = xlib.XKeysymToKeycode(display.handle, xlib.XK_Num_Lock);
2049
2050 var modifier_index: usize = 0;
2051 while (modifier_index < 8) : (modifier_index += 1) {
2052 var key_index: usize = 0;
2053 while (key_index < @as(usize, @intCast(modmap.*.max_keypermod))) : (key_index += 1) {
2054 const keycode = modmap.*.modifiermap[modifier_index * @as(usize, @intCast(modmap.*.max_keypermod)) + key_index];
2055 if (keycode == numlock_keycode) {
2056 numlock_mask = @as(c_uint, 1) << @intCast(modifier_index);
2057 }
2058 }
2059 }
2060 }
2061
2062 fn grabbuttons(display: *Display, client: *Client, focused: bool) void {
2063 update_numlock_mask(display);
2064 const modifiers = [_]c_uint{ 0, xlib.LockMask, numlock_mask, numlock_mask | xlib.LockMask };
2065
2066 _ = xlib.XUngrabButton(display.handle, xlib.AnyButton, xlib.AnyModifier, client.window);
2067 if (!focused) {
2068 _ = xlib.XGrabButton(
2069 display.handle,
2070 xlib.AnyButton,
2071 xlib.AnyModifier,
2072 client.window,
2073 xlib.False,
2074 xlib.ButtonPressMask | xlib.ButtonReleaseMask,
2075 xlib.GrabModeSync,
2076 xlib.GrabModeSync,
2077 xlib.None,
2078 xlib.None,
2079 );
2080 }
2081 for (config.buttons.items) |button| {
2082 if (button.click == .client_win) {
2083 for (modifiers) |modifier| {
2084 _ = xlib.XGrabButton(
2085 display.handle,
2086 @intCast(button.button),
2087 button.mod_mask | modifier,
2088 client.window,
2089 xlib.False,
2090 xlib.ButtonPressMask | xlib.ButtonReleaseMask,
2091 xlib.GrabModeAsync,
2092 xlib.GrabModeSync,
2093 xlib.None,
2094 xlib.None,
2095 );
2096 }
2097 }
2098 }
2099 }
2100
2101 fn focus(display: *Display, target_client: ?*Client) void {
2102 const selmon = monitor_mod.selected_monitor orelse return;
2103
2104 var focus_client = target_client;
2105 if (focus_client == null or !client_mod.is_visible(focus_client.?)) {
2106 focus_client = selmon.stack;
2107 while (focus_client) |iter| {
2108 if (client_mod.is_visible(iter)) break;
2109 focus_client = iter.stack_next;
2110 }
2111 }
2112
2113 if (selmon.sel != null and selmon.sel != focus_client) {
2114 unfocus_client(display, selmon.sel, false);
2115 }
2116
2117 if (focus_client) |client| {
2118 if (client.monitor != selmon) {
2119 monitor_mod.selected_monitor = client.monitor;
2120 }
2121 if (client.is_urgent) {
2122 set_urgent(display, client, false);
2123 }
2124 client_mod.detach_stack(client);
2125 client_mod.attach_stack(client);
2126 grabbuttons(display, client, true);
2127 _ = xlib.XSetWindowBorder(display.handle, client.window, config.border_focused);
2128 if (!client.never_focus) {
2129 _ = xlib.XSetInputFocus(display.handle, client.window, xlib.RevertToPointerRoot, xlib.CurrentTime);
2130 _ = xlib.XChangeProperty(display.handle, display.root, atoms.net_active_window, xlib.XA_WINDOW, 32, xlib.PropModeReplace, @ptrCast(&client.window), 1);
2131 }
2132 _ = send_event(display, client, atoms.wm_take_focus);
2133 } else {
2134 _ = xlib.XSetInputFocus(display.handle, display.root, xlib.RevertToPointerRoot, xlib.CurrentTime);
2135 _ = xlib.XDeleteProperty(display.handle, display.root, atoms.net_active_window);
2136 }
2137
2138 const current_selmon = monitor_mod.selected_monitor orelse return;
2139 current_selmon.sel = focus_client;
2140
2141 if (focus_client) |client| {
2142 if (is_scrolling_layout(current_selmon)) {
2143 scroll_to_window(client, true);
2144 }
2145 }
2146
2147 bar_mod.invalidate_bars();
2148 }
2149
2150 fn restack(display: *Display, monitor: *Monitor) void {
2151 bar_mod.invalidate_bars();
2152 const selected_client = monitor.sel orelse return;
2153
2154 if (selected_client.is_floating or monitor.lt[monitor.sel_lt] == null) {
2155 _ = xlib.XRaiseWindow(display.handle, selected_client.window);
2156 }
2157
2158 if (monitor.lt[monitor.sel_lt] != null) {
2159 var window_changes: xlib.c.XWindowChanges = undefined;
2160 window_changes.stack_mode = xlib.c.Below;
2161 window_changes.sibling = monitor.bar_win;
2162
2163 var current = monitor.stack;
2164 while (current) |client| {
2165 if (!client.is_floating and client_mod.is_visible(client)) {
2166 _ = xlib.c.XConfigureWindow(display.handle, client.window, xlib.c.CWSibling | xlib.c.CWStackMode, &window_changes);
2167 window_changes.sibling = client.window;
2168 }
2169 current = client.stack_next;
2170 }
2171 }
2172
2173 _ = xlib.XSync(display.handle, xlib.False);
2174
2175 var discard_event: xlib.XEvent = undefined;
2176 while (xlib.c.XCheckMaskEvent(display.handle, xlib.EnterWindowMask, &discard_event) != 0) {}
2177 }
2178
2179 fn arrange(monitor: *Monitor) void {
2180 // TODO: display will become a WindowManager field; for now
2181 // we use a module-level pointer set once after the display is opened.
2182 if (wm_display) |display| {
2183 showhide(display, monitor);
2184 }
2185 if (monitor.lt[monitor.sel_lt]) |layout| {
2186 if (layout.arrange_fn) |arrange_fn| {
2187 arrange_fn(monitor);
2188 }
2189 }
2190 if (wm_display) |display| {
2191 restack(display, monitor);
2192 }
2193 }
2194
2195 fn tick_animations() void {
2196 if (!scroll_animation.is_active()) return;
2197
2198 const monitor = monitor_mod.selected_monitor orelse return;
2199 if (scroll_animation.update()) |new_offset| {
2200 monitor.scroll_offset = new_offset;
2201 arrange(monitor);
2202 }
2203 }
2204
2205 fn is_scrolling_layout(monitor: *Monitor) bool {
2206 if (monitor.lt[monitor.sel_lt]) |layout| {
2207 return layout.arrange_fn == scrolling.layout.arrange_fn;
2208 }
2209 return false;
2210 }
2211
2212 fn scroll_layout(direction: i32) void {
2213 const monitor = monitor_mod.selected_monitor orelse return;
2214 if (!is_scrolling_layout(monitor)) return;
2215
2216 const scroll_step = scrolling.get_scroll_step(monitor);
2217 const max_scroll = scrolling.get_max_scroll(monitor);
2218
2219 const current = if (scroll_animation.is_active())
2220 scroll_animation.target()
2221 else
2222 monitor.scroll_offset;
2223
2224 var target = current + direction * scroll_step;
2225 target = @max(0, @min(target, max_scroll));
2226
2227 scroll_animation.start(monitor.scroll_offset, target, animation_config);
2228 }
2229
2230 fn scroll_to_window(client: *Client, animate: bool) void {
2231 const monitor = client.monitor orelse return;
2232 if (!is_scrolling_layout(monitor)) return;
2233
2234 const target = scrolling.get_target_scroll_for_window(monitor, client);
2235
2236 if (animate) {
2237 scroll_animation.start(monitor.scroll_offset, target, animation_config);
2238 } else {
2239 monitor.scroll_offset = target;
2240 arrange(monitor);
2241 }
2242 }
2243
2244 fn showhide_client(display: *Display, client: ?*Client) void {
2245 const target = client orelse return;
2246 if (client_mod.is_visible(target)) {
2247 _ = xlib.XMoveWindow(display.handle, target.window, target.x, target.y);
2248 const monitor = target.monitor orelse return;
2249 if ((monitor.lt[monitor.sel_lt] == null or target.is_floating) and !target.is_fullscreen) {
2250 tiling.resize(target, target.x, target.y, target.width, target.height, false);
2251 }
2252 showhide_client(display, target.stack_next);
2253 } else {
2254 showhide_client(display, target.stack_next);
2255 const client_width = target.width + 2 * target.border_width;
2256 _ = xlib.XMoveWindow(display.handle, target.window, -2 * client_width, target.y);
2257 }
2258 }
2259
2260 fn showhide(display: *Display, monitor: *Monitor) void {
2261 showhide_client(display, monitor.stack);
2262 }
2263
2264 fn update_size_hints(display: *Display, client: *Client) void {
2265 var size_hints: xlib.XSizeHints = undefined;
2266 var msize: c_long = 0;
2267
2268 if (xlib.XGetWMNormalHints(display.handle, client.window, &size_hints, &msize) == 0) {
2269 size_hints.flags = xlib.PSize;
2270 }
2271
2272 if ((size_hints.flags & xlib.PBaseSize) != 0) {
2273 client.base_width = size_hints.base_width;
2274 client.base_height = size_hints.base_height;
2275 } else if ((size_hints.flags & xlib.PMinSize) != 0) {
2276 client.base_width = size_hints.min_width;
2277 client.base_height = size_hints.min_height;
2278 } else {
2279 client.base_width = 0;
2280 client.base_height = 0;
2281 }
2282
2283 if ((size_hints.flags & xlib.PResizeInc) != 0) {
2284 client.increment_width = size_hints.width_inc;
2285 client.increment_height = size_hints.height_inc;
2286 } else {
2287 client.increment_width = 0;
2288 client.increment_height = 0;
2289 }
2290
2291 if ((size_hints.flags & xlib.PMaxSize) != 0) {
2292 client.max_width = size_hints.max_width;
2293 client.max_height = size_hints.max_height;
2294 } else {
2295 client.max_width = 0;
2296 client.max_height = 0;
2297 }
2298
2299 if ((size_hints.flags & xlib.PMinSize) != 0) {
2300 client.min_width = size_hints.min_width;
2301 client.min_height = size_hints.min_height;
2302 } else if ((size_hints.flags & xlib.PBaseSize) != 0) {
2303 client.min_width = size_hints.base_width;
2304 client.min_height = size_hints.base_height;
2305 } else {
2306 client.min_width = 0;
2307 client.min_height = 0;
2308 }
2309
2310 if ((size_hints.flags & xlib.PAspect) != 0) {
2311 client.min_aspect = @as(f32, @floatFromInt(size_hints.min_aspect.y)) / @as(f32, @floatFromInt(size_hints.min_aspect.x));
2312 client.max_aspect = @as(f32, @floatFromInt(size_hints.max_aspect.x)) / @as(f32, @floatFromInt(size_hints.max_aspect.y));
2313 } else {
2314 client.min_aspect = 0.0;
2315 client.max_aspect = 0.0;
2316 }
2317
2318 client.is_fixed = (client.max_width != 0 and client.max_height != 0 and client.max_width == client.min_width and client.max_height == client.min_height);
2319 client.hints_valid = true;
2320 }
2321
2322 fn update_wm_hints(display: *Display, client: *Client) void {
2323 const wmh = xlib.XGetWMHints(display.handle, client.window);
2324 if (wmh) |hints| {
2325 defer _ = xlib.XFree(@ptrCast(hints));
2326
2327 if (client == (monitor_mod.selected_monitor orelse return).sel and (hints.*.flags & xlib.XUrgencyHint) != 0) {
2328 hints.*.flags = hints.*.flags & ~@as(c_long, xlib.XUrgencyHint);
2329 _ = xlib.XSetWMHints(display.handle, client.window, hints);
2330 } else {
2331 client.is_urgent = (hints.*.flags & xlib.XUrgencyHint) != 0;
2332 }
2333
2334 if ((hints.*.flags & xlib.InputHint) != 0) {
2335 client.never_focus = hints.*.input == 0;
2336 } else {
2337 client.never_focus = false;
2338 }
2339 }
2340 }
2341
2342 fn update_window_type(display: *Display, client: *Client) void {
2343 const state = get_atom_prop(display, client, atoms.net_wm_state);
2344 const window_type = get_atom_prop(display, client, atoms.net_wm_window_type);
2345
2346 if (state == atoms.net_wm_state_fullscreen) {
2347 set_fullscreen(display, client, true);
2348 }
2349 if (window_type == atoms.net_wm_window_type_dialog) {
2350 client.is_floating = true;
2351 }
2352 }
2353
2354 fn update_title(display: *Display, client: *Client) void {
2355 if (!get_text_prop(display, client.window, atoms.net_wm_name, &client.name)) {
2356 _ = get_text_prop(display, client.window, xlib.XA_WM_NAME, &client.name);
2357 }
2358 if (client.name[0] == 0) {
2359 @memcpy(client.name[0..6], "broken");
2360 }
2361 }
2362
2363 fn get_atom_prop(display: *Display, client: *Client, prop: xlib.Atom) xlib.Atom {
2364 var actual_type: xlib.Atom = undefined;
2365 var actual_format: c_int = undefined;
2366 var num_items: c_ulong = undefined;
2367 var bytes_after: c_ulong = undefined;
2368 var prop_data: [*c]u8 = undefined;
2369
2370 if (xlib.XGetWindowProperty(display.handle, client.window, prop, 0, @sizeOf(xlib.Atom), xlib.False, xlib.XA_ATOM, &actual_type, &actual_format, &num_items, &bytes_after, &prop_data) == 0 and prop_data != null) {
2371 const atom: xlib.Atom = @as(*xlib.Atom, @ptrCast(@alignCast(prop_data))).*;
2372 _ = xlib.XFree(@ptrCast(prop_data));
2373 return atom;
2374 }
2375 return 0;
2376 }
2377
2378 fn get_text_prop(display: *Display, window: xlib.Window, atom: xlib.Atom, text: *[256]u8) bool {
2379 var name: xlib.XTextProperty = undefined;
2380 text[0] = 0;
2381
2382 if (xlib.XGetTextProperty(display.handle, window, &name, atom) == 0 or name.nitems == 0) {
2383 return false;
2384 }
2385
2386 if (name.encoding == xlib.XA_STRING) {
2387 const len = @min(name.nitems, 255);
2388 @memcpy(text[0..len], name.value[0..len]);
2389 text[len] = 0;
2390 } else {
2391 var list: [*c][*c]u8 = undefined;
2392 var count: c_int = undefined;
2393 if (xlib.XmbTextPropertyToTextList(display.handle, &name, &list, &count) >= xlib.Success and count > 0 and list[0] != null) {
2394 const str = std.mem.sliceTo(list[0], 0);
2395 const copy_len = @min(str.len, 255);
2396 @memcpy(text[0..copy_len], str[0..copy_len]);
2397 text[copy_len] = 0;
2398 xlib.XFreeStringList(list);
2399 }
2400 }
2401 text[255] = 0;
2402 _ = xlib.XFree(@ptrCast(name.value));
2403 return true;
2404 }
2405
2406 fn apply_rules(display: *Display, client: *Client) void {
2407 var class_hint: xlib.XClassHint = .{ .res_name = null, .res_class = null };
2408 _ = xlib.XGetClassHint(display.handle, client.window, &class_hint);
2409
2410 const class_str: []const u8 = if (class_hint.res_class) |ptr| std.mem.sliceTo(ptr, 0) else "";
2411 const instance_str: []const u8 = if (class_hint.res_name) |ptr| std.mem.sliceTo(ptr, 0) else "";
2412
2413 client.is_floating = false;
2414 client.tags = 0;
2415 var rule_focus = false;
2416
2417 for (config.rules.items) |rule| {
2418 const class_matches = if (rule.class) |rc| std.mem.indexOf(u8, class_str, rc) != null else true;
2419 const instance_matches = if (rule.instance) |ri| std.mem.indexOf(u8, instance_str, ri) != null else true;
2420 const title_matches = if (rule.title) |rt| std.mem.indexOf(u8, std.mem.sliceTo(&client.name, 0), rt) != null else true;
2421
2422 if (class_matches and instance_matches and title_matches) {
2423 client.is_floating = rule.is_floating;
2424 client.tags |= rule.tags;
2425 if (rule.monitor >= 0) {
2426 var target = monitor_mod.monitors;
2427 var index: i32 = 0;
2428 while (target) |mon| {
2429 if (index == rule.monitor) {
2430 client.monitor = mon;
2431 break;
2432 }
2433 index += 1;
2434 target = mon.next;
2435 }
2436 }
2437 if (rule.focus) {
2438 rule_focus = true;
2439 }
2440 }
2441 }
2442
2443 if (class_hint.res_class) |ptr| {
2444 _ = xlib.XFree(@ptrCast(ptr));
2445 }
2446 if (class_hint.res_name) |ptr| {
2447 _ = xlib.XFree(@ptrCast(ptr));
2448 }
2449
2450 const monitor = client.monitor orelse return;
2451 if (client.tags == 0) {
2452 client.tags = monitor.tagset[monitor.sel_tags];
2453 }
2454
2455 if (rule_focus and client.tags != 0) {
2456 const monitor_tagset = monitor.tagset[monitor.sel_tags];
2457 const is_tag_focused = (monitor_tagset & client.tags) == client.tags;
2458 if (!is_tag_focused) {
2459 view(display, client.tags);
2460 }
2461 }
2462 }
2463
2464 fn update_client_list(display: *Display) void {
2465 _ = xlib.XDeleteProperty(display.handle, display.root, atoms.net_client_list);
2466
2467 var current_monitor = monitor_mod.monitors;
2468 while (current_monitor) |monitor| {
2469 var current_client = monitor.clients;
2470 while (current_client) |client| {
2471 _ = xlib.XChangeProperty(display.handle, display.root, atoms.net_client_list, xlib.XA_WINDOW, 32, xlib.PropModeAppend, @ptrCast(&client.window), 1);
2472 current_client = client.next;
2473 }
2474 current_monitor = monitor.next;
2475 }
2476 }
2477
2478 fn send_event(display: *Display, client: *Client, protocol: xlib.Atom) bool {
2479 var protocols: [*c]xlib.Atom = undefined;
2480 var num_protocols: c_int = 0;
2481 var exists = false;
2482
2483 if (xlib.XGetWMProtocols(display.handle, client.window, &protocols, &num_protocols) != 0) {
2484 var index: usize = 0;
2485 while (index < @as(usize, @intCast(num_protocols))) : (index += 1) {
2486 if (protocols[index] == protocol) {
2487 exists = true;
2488 break;
2489 }
2490 }
2491 _ = xlib.XFree(@ptrCast(protocols));
2492 }
2493
2494 if (exists) {
2495 var event: xlib.XEvent = undefined;
2496 event.type = xlib.ClientMessage;
2497 event.xclient.window = client.window;
2498 event.xclient.message_type = atoms.wm_protocols;
2499 event.xclient.format = 32;
2500 event.xclient.data.l[0] = @intCast(protocol);
2501 event.xclient.data.l[1] = xlib.CurrentTime;
2502 _ = xlib.XSendEvent(display.handle, client.window, xlib.False, xlib.NoEventMask, &event);
2503 }
2504 return exists;
2505 }
2506
2507 fn set_urgent(display: *Display, client: *Client, urgent: bool) void {
2508 client.is_urgent = urgent;
2509 const wmh = xlib.XGetWMHints(display.handle, client.window);
2510 if (wmh) |hints| {
2511 if (urgent) {
2512 hints.*.flags = hints.*.flags | xlib.XUrgencyHint;
2513 } else {
2514 hints.*.flags = hints.*.flags & ~@as(c_long, xlib.XUrgencyHint);
2515 }
2516 _ = xlib.XSetWMHints(display.handle, client.window, hints);
2517 _ = xlib.XFree(@ptrCast(hints));
2518 }
2519 }
2520
2521 fn run_autostart_commands(_: std.mem.Allocator, commands: []const []const u8) !void {
2522 for (commands) |cmd| spawn_command(cmd);
2523 }
2524
2525 test {
2526 _ = @import("x11/events.zig");
2527 }