tony / oxwm

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