tony / oxwm

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