tony / oxwm

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