tony / oxwm

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