tony / oxwm

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