tony / oxwm

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