tony / oxwm

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