tony / oxwm

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