tony / oxwm

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