diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 77be3f4..68cf10f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,7 +28,7 @@ jobs: - name: Format check continue-on-error: true - run: zig fmt --check src/ + run: zig fmt --check src/ zephwm-bar/ - name: Build run: zig build diff --git a/src/event.zig b/src/event.zig index f523969..7403917 100644 --- a/src/event.zig +++ b/src/event.zig @@ -79,8 +79,8 @@ fn jsonEscapeWrite(w: anytype, s: []const u8) !void { fn getWorkspaceOutputName(ws: *tree.Container) []const u8 { if (ws.parent) |parent| { if (parent.type == .output) { - if (parent.workspace) |wsd| { - if (wsd.output_name.len > 0) return wsd.output_name; + if (parent.output_data) |od| { + if (od.name.len > 0) return od.name; } } } @@ -285,6 +285,8 @@ fn setFocus(ctx: *EventContext, con: *tree.Container) void { // Set X11 input focus if (con.window) |wd| { _ = xcb.setInputFocus(ctx.conn, xcb.INPUT_FOCUS_POINTER_ROOT, wd.id, xcb.CURRENT_TIME); + // Send WM_TAKE_FOCUS if the window supports it (ICCCM focus protocol) + sendTakeFocus(ctx, wd.id); updateActiveWindow(ctx, wd.id); } else { // No window (e.g. focusing a workspace) — clear active window @@ -292,6 +294,40 @@ fn setFocus(ctx: *EventContext, con: *tree.Container) void { } } +/// Send WM_TAKE_FOCUS ClientMessage if the window supports it (ICCCM). +fn sendTakeFocus(ctx: *EventContext, window: xcb.Window) void { + // Check if window supports WM_TAKE_FOCUS in WM_PROTOCOLS + const cookie = xcb.getProperty(ctx.conn, 0, window, ctx.atoms.wm_protocols, xcb.ATOM_ATOM, 0, 32); + const reply = xcb.getPropertyReply(ctx.conn, cookie, null) orelse return; + defer std.c.free(reply); + + const len = xcb.getPropertyValueLength(reply); + if (len <= 0) return; + const ptr = xcb.getPropertyValue(reply) orelse return; + const atoms_list: [*]const xcb.Atom = @ptrCast(@alignCast(ptr)); + const count: usize = @intCast(@divTrunc(len, 4)); + + var supports_take_focus = false; + for (atoms_list[0..count]) |atom| { + if (atom == ctx.atoms.wm_take_focus) { + supports_take_focus = true; + break; + } + } + if (!supports_take_focus) return; + + // Send WM_TAKE_FOCUS client message + var event_data: xcb.c.xcb_client_message_event_t = std.mem.zeroes(xcb.c.xcb_client_message_event_t); + event_data.response_type = xcb.CLIENT_MESSAGE; + event_data.format = 32; + event_data.window = window; + event_data.type = ctx.atoms.wm_protocols; + event_data.data.data32[0] = ctx.atoms.wm_take_focus; + event_data.data.data32[1] = xcb.CURRENT_TIME; + + _ = xcb.sendEvent(ctx.conn, 0, window, xcb.EVENT_MASK_NO_EVENT, @ptrCast(&event_data)); +} + /// Clear is_focused along the currently focused path only. O(depth). fn clearFocusedPath(root: *tree.Container) void { var con = root; @@ -446,11 +482,11 @@ pub fn relayoutAndRender(ctx: *EventContext) void { /// Collect all managed window IDs and set _NET_CLIENT_LIST on the root window. pub fn updateClientList(ctx: *EventContext) void { // Build client list from window_map (O(n) where n = managed windows, no tree walk) - var ids: [1024]u32 = undefined; + var ids: [4096]u32 = undefined; var count: usize = 0; var iter = ctx.window_map.iterator(); while (iter.next()) |entry| { - if (count >= 1024) break; + if (count >= ids.len) break; const con = entry.value_ptr.*; const wd = con.window orelse continue; if (entry.key_ptr.* != wd.id) continue; // skip frame_id entries @@ -666,6 +702,8 @@ const BatchedWindowProps = struct { window_type: []const u8 = "", window_role: []const u8 = "", should_float: bool = false, + min_w: u32 = 0, + min_h: u32 = 0, }; /// Read all window properties in a single batched roundtrip. @@ -680,6 +718,7 @@ fn readAllWindowPropertiesBatched(allocator: std.mem.Allocator, conn: *xcb.Conne const transient_cookie = xcb.getProperty(conn, 0, window, xcb.ATOM_WM_TRANSIENT_FOR, xcb.ATOM_WINDOW, 0, 1); const type_cookie = xcb.getProperty(conn, 0, window, atoms.net_wm_window_type, xcb.ATOM_ATOM, 0, 32); const role_cookie = xcb.getProperty(conn, 0, window, atoms.wm_window_role, xcb.ATOM_STRING, 0, 256); + const hints_cookie = xcb.getProperty(conn, 0, window, xcb.ATOM_WM_NORMAL_HINTS, xcb.ATOM_WM_SIZE_HINTS, 0, 18); var props = BatchedWindowProps{}; @@ -799,6 +838,24 @@ fn readAllWindowPropertiesBatched(allocator: std.mem.Allocator, conn: *xcb.Conne } } + // 6. WM_NORMAL_HINTS — extract minimum size constraints + if (xcb.getPropertyReply(conn, hints_cookie, null)) |reply| { + defer std.c.free(reply); + const len = xcb.getPropertyValueLength(reply); + // WM_SIZE_HINTS: flags at offset 0, min_width at offset 5, min_height at offset 6 (u32 units) + if (len >= 7 * 4) { + if (xcb.getPropertyValue(reply)) |ptr| { + const vals: [*]const u32 = @ptrCast(@alignCast(ptr)); + const flags = vals[0]; + const PMinSize: u32 = (1 << 4); // ICCCM PMinSize flag + if (flags & PMinSize != 0) { + props.min_w = vals[5]; + props.min_h = vals[6]; + } + } + } + } + return props; } @@ -892,6 +949,8 @@ fn handleMapRequest(ctx: *EventContext, ev: *xcb.MapRequestEvent) void { .window_role = props.window_role, .transient_for = props.transient_for, .pending_unmap = 0, // Window is unmapped at MapRequest time; reparent of unmapped window does not generate UnmapNotify + .min_w = props.min_w, + .min_h = props.min_h, }; con.is_floating = props.should_float; // Apply default border style from config @@ -1668,7 +1727,62 @@ fn handleExpose(ctx: *EventContext, ev: *xcb.c.xcb_expose_event_t) void { // --- Command execution --- +/// Collect window IDs of containers matching criteria (max 64). Walks tree depth-first. +/// Uses window IDs instead of raw pointers so commands that destroy/move containers +/// don't cause dangling pointer access. +fn collectMatchingWindowIds(root: *tree.Container, crit: *const criteria.Criteria, out: *[64]xcb.Window) usize { + var count: usize = 0; + collectMatchingWindowIdsRecursive(root, crit, out, &count); + return count; +} + +fn collectMatchingWindowIdsRecursive(con: *tree.Container, crit: *const criteria.Criteria, out: *[64]xcb.Window, count: *usize) void { + if (count.* >= 64) return; + if (criteria.matches(crit, con)) { + if (con.window) |wd| { + out[count.*] = wd.id; + count.* += 1; + } + } + var cur = con.children.first; + while (cur) |child| : (cur = child.next) { + collectMatchingWindowIdsRecursive(child, crit, out, count); + } +} + pub fn executeCommand(ctx: *EventContext, cmd: command_mod.Command) void { + // If command has criteria, execute on all matching containers instead of focused + if (cmd.criteria) |crit| { + var window_ids: [64]xcb.Window = undefined; + const match_count = collectMatchingWindowIds(ctx.tree_root, &crit, &window_ids); + if (match_count == 0) return; + + // Save original focused window ID for restoration + const original_focused_wid: ?xcb.Window = if (getFocusedContainer(ctx.tree_root)) |fc| + (if (fc.window) |wd| wd.id else null) + else + null; + + for (window_ids[0..match_count]) |wid| { + // Re-resolve container from window ID — it may have been destroyed by a prior command + const target = findContainerByWindow(ctx, wid) orelse continue; + setFocus(ctx, target); + var cmd_no_crit = cmd; + cmd_no_crit.criteria = null; + executeCommand(ctx, cmd_no_crit); + } + // Restore original focus only if the original window still exists and + // the command was not a focus command (i3 behavior: [criteria] focus keeps new focus) + if (cmd.type != .focus) { + if (original_focused_wid) |wid| { + if (findContainerByWindow(ctx, wid)) |orig| { + setFocus(ctx, orig); + } + } + } + return; + } + switch (cmd.type) { .split => executeSplit(ctx, cmd), .focus => executeFocus(ctx, cmd), @@ -2203,6 +2317,8 @@ fn executeExec(cmd: command_mod.Command) void { fn executeFloating(ctx: *EventContext) void { const focused = getFocusedContainer(ctx.tree_root) orelse return; + // Only windows and split_cons can float — workspaces/outputs/root cannot + if (focused.type != .window and focused.type != .split_con) return; focused.is_floating = !focused.is_floating; focused.markDirtyToWorkspace(); relayoutAndRender(ctx); @@ -2283,6 +2399,8 @@ fn executeBorder(ctx: *EventContext, cmd: command_mod.Command) void { fn executeFullscreen(ctx: *EventContext) void { const focused = getFocusedContainer(ctx.tree_root) orelse return; + // Only windows can be fullscreened + if (focused.type != .window) return; focused.is_fullscreen = if (focused.is_fullscreen != .none) .none else .window; focused.markDirtyToWorkspace(); @@ -2539,10 +2657,13 @@ fn executeMoveWorkspaceToOutput(ctx: *EventContext, cmd: command_mod.Command) vo target_out.appendChild(current_ws); current_ws.rect = target_out.rect; - // Update workspace output_name to match target output + // Update workspace output_name to match target output (must dupe to avoid aliased ownership) if (current_ws.workspace) |*wsd| { - if (target_out.workspace) |tout_wsd| { - wsd.output_name = tout_wsd.output_name; + if (target_out.output_data) |od| { + if (ctx.allocator.dupe(u8, od.name)) |new_name| { + if (wsd.output_name.len > 0) ctx.allocator.free(wsd.output_name); + wsd.output_name = new_name; + } else |_| {} // OOM: keep old output_name rather than aliasing } } diff --git a/src/ipc.zig b/src/ipc.zig index 9e390fe..e22a7f1 100644 --- a/src/ipc.zig +++ b/src/ipc.zig @@ -133,7 +133,9 @@ pub fn acceptClient(listen_fd: std.posix.fd_t) !std.posix.fd_t { /// Read a complete message from client fd into buf. /// Returns msg_type + payload slice, or null if EOF/disconnect. -/// Returns error.WouldBlock if no data available yet (EAGAIN). +/// Returns error.WouldBlock if no data available yet (EAGAIN) AND no bytes have been read. +/// If partial data was consumed and WouldBlock occurs, returns null (disconnect) to avoid +/// busy-looping on the single-threaded event loop. pub fn readMessage(fd: std.posix.fd_t, buf: []u8) error{WouldBlock}!?struct { msg_type: u32, payload: []const u8 } { if (buf.len < HEADER_SIZE) return null; @@ -141,7 +143,10 @@ pub fn readMessage(fd: std.posix.fd_t, buf: []u8) error{WouldBlock}!?struct { ms var total_read: usize = 0; while (total_read < HEADER_SIZE) { const n = std.posix.read(fd, buf[total_read..]) catch |err| { - if (err == error.WouldBlock) return error.WouldBlock; + if (err == error.WouldBlock) { + if (total_read == 0) return error.WouldBlock; + return null; // Partial header + WouldBlock: drop client to avoid busy-loop + } return null; }; if (n == 0) return null; // EOF @@ -155,10 +160,10 @@ pub fn readMessage(fd: std.posix.fd_t, buf: []u8) error{WouldBlock}!?struct { ms const total_needed = HEADER_SIZE + payload_len; if (buf.len < total_needed) return null; - // Read payload + // Read payload — once header is read, we must complete the message while (total_read < total_needed) { const n = std.posix.read(fd, buf[total_read..total_needed]) catch |err| { - if (err == error.WouldBlock) return error.WouldBlock; + if (err == error.WouldBlock) return null; // Partial payload: drop client to avoid busy-loop return null; }; if (n == 0) return null; @@ -203,10 +208,10 @@ pub fn sendRequest(allocator: std.mem.Allocator, sock_path: []const u8, msg_type const fd = connectToServer(sock_path) catch return null; defer std.posix.close(fd); - // Send + // Send (use writeAll to handle partial writes correctly) var send_buf: [4096 + HEADER_SIZE]u8 = undefined; const msg = encode(msg_type, payload, &send_buf); - _ = std.posix.write(fd, msg) catch return null; + writeAll(fd, msg) catch return null; // Read response var recv_buf: [65536]u8 = undefined; diff --git a/src/layout.zig b/src/layout.zig index 88b9c62..0b75d38 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -3,7 +3,7 @@ const log = std.log.scoped(.layout); const tree = @import("tree.zig"); const render = @import("render.zig"); -const MAX_TILING_CHILDREN: usize = 64; +const MAX_TILING_CHILDREN: usize = 256; /// Apply layout to a container's children. Recursively descends into split_con children. /// gap: pixel gap between windows diff --git a/src/main.zig b/src/main.zig index a5e4fe7..117f71b 100644 --- a/src/main.zig +++ b/src/main.zig @@ -158,8 +158,8 @@ fn handleIpcMessage(ctx: *event.EventContext, client_fd: std.posix.fd_t, msg_typ @intFromEnum(ipc.MessageType.get_tree) => buildTreeJson(ctx, &dyn_buf), @intFromEnum(ipc.MessageType.get_marks) => buildMarksJson(ctx, &dyn_buf), @intFromEnum(ipc.MessageType.get_bar_config) => buildBarConfigJson(ctx, &dyn_buf), - @intFromEnum(ipc.MessageType.get_config) => "{}", - @intFromEnum(ipc.MessageType.get_binding_modes) => "[\"default\"]", + @intFromEnum(ipc.MessageType.get_config) => buildConfigJson(ctx, &dyn_buf), + @intFromEnum(ipc.MessageType.get_binding_modes) => buildBindingModesJson(ctx, &dyn_buf), @intFromEnum(ipc.MessageType.subscribe) => blk: { // Parse subscription payload and register client registerSubscription(client_fd, payload, ctx.ipc_sub_fds, ctx.ipc_sub_masks); @@ -222,8 +222,8 @@ fn buildWorkspacesJson(ctx: *event.EventContext, buf: *[8192]u8) []const u8 { const ws_output_name = blk: { if (ws.parent) |parent| { if (parent.type == .output) { - if (parent.workspace) |parent_wsd| { - if (parent_wsd.output_name.len > 0) break :blk parent_wsd.output_name; + if (parent.output_data) |od| { + if (od.name.len > 0) break :blk od.name; } } } @@ -279,13 +279,14 @@ fn buildOutputsJson(ctx: *event.EventContext, buf: *[8192]u8) []const u8 { } // Output name: use stored name if available, else "default" - const out_name = if (out_con.workspace) |wsd| wsd.output_name else "default"; + const out_name = if (out_con.output_data) |od| od.name else "default"; const display_name = if (out_name.len > 0) out_name else "default"; + w.writeAll("{\"name\":\"") catch return "[]"; + jsonEscapeWrite(w, display_name) catch return "[]"; std.fmt.format(w, - "{{\"name\":\"{s}\",\"active\":true,\"primary\":{},\"rect\":{{\"x\":{d},\"y\":{d},\"width\":{d},\"height\":{d}}},\"current_workspace\":\"", + "\",\"active\":true,\"primary\":{},\"rect\":{{\"x\":{d},\"y\":{d},\"width\":{d},\"height\":{d}}},\"current_workspace\":\"", .{ - display_name, is_primary, out_con.rect.x, out_con.rect.y, @@ -294,7 +295,7 @@ fn buildOutputsJson(ctx: *event.EventContext, buf: *[8192]u8) []const u8 { }, ) catch return "[]"; jsonEscapeWrite(w, ws_name) catch return "[]"; - w.writeAll("\"}}") catch return "[]"; + w.writeAll("\"}") catch return "[]"; is_primary = false; } @@ -339,6 +340,71 @@ fn buildBarConfigJson(ctx: *event.EventContext, buf: *[8192]u8) []const u8 { return fbs.getWritten(); } +fn buildConfigJson(ctx: *event.EventContext, buf: *[8192]u8) []const u8 { + _ = ctx; + var fbs = std.io.fixedBufferStream(buf); + const w = fbs.writer(); + // i3 GET_CONFIG returns file contents in the "config" field + w.writeAll("{\"config\":\"") catch return "{}"; + + // Search same paths as loadConfig + const home = std.posix.getenv("HOME") orelse ""; + const xdg_config = std.posix.getenv("XDG_CONFIG_HOME"); + var path_buf: [512]u8 = undefined; + const config_path: []const u8 = blk: { + if (xdg_config) |xdg| { + const len = (std.fmt.bufPrint(&path_buf, "{s}/zephwm/config", .{xdg}) catch break :blk "").len; + if (std.fs.cwd().access(path_buf[0..len], .{})) |_| break :blk path_buf[0..len] else |_| {} + } + { + const len = (std.fmt.bufPrint(&path_buf, "{s}/.config/zephwm/config", .{home}) catch break :blk "").len; + if (std.fs.cwd().access(path_buf[0..len], .{})) |_| break :blk path_buf[0..len] else |_| {} + } + { + const len = (std.fmt.bufPrint(&path_buf, "{s}/.zephwm/config", .{home}) catch break :blk "").len; + if (std.fs.cwd().access(path_buf[0..len], .{})) |_| break :blk path_buf[0..len] else |_| {} + } + if (std.fs.cwd().access("/etc/zephwm/config", .{})) |_| { + const etc = "/etc/zephwm/config"; + @memcpy(path_buf[0..etc.len], etc); + break :blk path_buf[0..etc.len]; + } else |_| {} + break :blk ""; + }; + + // Read and emit file contents (not the path) + if (config_path.len > 0) { + if (std.fs.cwd().openFile(config_path, .{})) |file| { + defer file.close(); + var read_buf: [4096]u8 = undefined; + while (true) { + const n = file.read(&read_buf) catch break; + if (n == 0) break; + jsonEscapeWrite(w, read_buf[0..n]) catch return "{}"; + } + } else |_| {} + } + w.writeAll("\"}") catch return "{}"; + return fbs.getWritten(); +} + +fn buildBindingModesJson(ctx: *event.EventContext, buf: *[8192]u8) []const u8 { + var fbs = std.io.fixedBufferStream(buf); + const w = fbs.writer(); + w.writeAll("[\"default\"") catch return "[\"default\"]"; + // Add any extra modes defined in config + if (ctx.config) |cfg| { + var mode_iter = cfg.modes.keyIterator(); + while (mode_iter.next()) |key| { + w.writeAll(",\"") catch return "[\"default\"]"; + jsonEscapeWrite(w, key.*) catch return "[\"default\"]"; + w.writeByte('"') catch return "[\"default\"]"; + } + } + w.writeByte(']') catch return "[\"default\"]"; + return fbs.getWritten(); +} + fn buildMarksJson(ctx: *event.EventContext, buf: *[8192]u8) []const u8 { var fbs = std.io.fixedBufferStream(buf); const w = fbs.writer(); @@ -402,7 +468,9 @@ fn writeContainerJson(w: anytype, con: *tree.Container) !void { // name if (con.workspace) |wsd| { - try std.fmt.format(w, ",\"name\":\"{s}\"", .{wsd.name}); + try w.writeAll(",\"name\":\""); + try jsonEscapeWrite(w, wsd.name); + try w.writeAll("\""); } else if (con.window) |wd| { try w.writeAll(",\"name\":\""); try jsonEscapeWrite(w, wd.title); @@ -438,7 +506,11 @@ fn writeContainerJson(w: anytype, con: *tree.Container) !void { if (con.window) |wd| { try std.fmt.format(w, ",\"window\":{d}", .{wd.id}); if (wd.class.len > 0) { - try std.fmt.format(w, ",\"window_properties\":{{\"class\":\"{s}\",\"instance\":\"{s}\"}}", .{ wd.class, wd.instance }); + try w.writeAll(",\"window_properties\":{\"class\":\""); + try jsonEscapeWrite(w, wd.class); + try w.writeAll("\",\"instance\":\""); + try jsonEscapeWrite(w, wd.instance); + try w.writeAll("\"}"); } } diff --git a/src/output.zig b/src/output.zig index a24acb6..53f1b9f 100644 --- a/src/output.zig +++ b/src/output.zig @@ -46,10 +46,8 @@ pub fn detectOutputs( }; // Store output name in workspace data (reusing WorkspaceData for output_name) const name = try allocator.dupe(u8, info.nameSlice()); - const out_name = try allocator.dupe(u8, info.nameSlice()); - output_con.workspace = tree.WorkspaceData{ + output_con.output_data = tree.OutputData{ .name = name, - .output_name = out_name, }; tree_root.appendChild(output_con); @@ -74,10 +72,8 @@ pub fn detectOutputs( .h = screen.height_in_pixels, }; const name = try allocator.dupe(u8, "default"); - const out_name = try allocator.dupe(u8, "default"); - output_con.workspace = tree.WorkspaceData{ + output_con.output_data = tree.OutputData{ .name = name, - .output_name = out_name, }; tree_root.appendChild(output_con); @@ -216,7 +212,7 @@ pub fn updateOutputs( out_cur = tree_root.children.first; while (out_cur) |out_con| : (out_cur = out_con.next) { if (out_con.type != .output) continue; - const out_name = if (out_con.workspace) |wsd| wsd.output_name else ""; + const out_name = if (out_con.output_data) |od| od.name else ""; if (std.mem.eql(u8, out_name, name)) { // Update geometry out_con.rect = .{ .x = info.x, .y = info.y, .w = info.w, .h = info.h }; @@ -236,10 +232,8 @@ pub fn updateOutputs( const output_con = try tree.Container.create(allocator, .output); output_con.rect = .{ .x = info.x, .y = info.y, .w = info.w, .h = info.h }; const owned_name = try allocator.dupe(u8, name); - const owned_out_name = try allocator.dupe(u8, name); - output_con.workspace = tree.WorkspaceData{ + output_con.output_data = tree.OutputData{ .name = owned_name, - .output_name = owned_out_name, }; output_con.dirty = false; tree_root.appendChild(output_con); @@ -277,7 +271,7 @@ pub fn updateOutputs( while (out_cur) |out_con| { const next = out_con.next; if (out_con.type == .output and out_con.dirty) { - const out_name = if (out_con.workspace) |wsd| wsd.output_name else "?"; + const out_name = if (out_con.output_data) |od| od.name else "?"; std.debug.print("zephwm: output removed: {s}\n", .{out_name}); // Move all workspaces to first_output @@ -315,7 +309,7 @@ pub fn findByName(root: *tree.Container, name: []const u8) ?*tree.Container { var cur = root.children.first; while (cur) |child| : (cur = child.next) { if (child.type != .output) continue; - const out_name = if (child.workspace) |wsd| wsd.output_name else ""; + const out_name = if (child.output_data) |od| od.name else ""; if (std.mem.eql(u8, out_name, name)) return child; } return null; diff --git a/src/render.zig b/src/render.zig index 6ced65e..81d0b05 100644 --- a/src/render.zig +++ b/src/render.zig @@ -310,11 +310,11 @@ fn applyRecursive( con.children.len() > 1; // Single pass: process tiling, collect floating/fullscreen/border-normal - var floating_buf: [32]*tree.Container = undefined; + var floating_buf: [128]*tree.Container = undefined; var floating_count: usize = 0; - var fullscreen_buf: [8]*tree.Container = undefined; + var fullscreen_buf: [32]*tree.Container = undefined; var fullscreen_count: usize = 0; - var normal_border_buf: [32]*tree.Container = undefined; + var normal_border_buf: [128]*tree.Container = undefined; var normal_border_count: usize = 0; // For tabbed/stacked: pre-count tiling children, find focused tiling @@ -338,14 +338,14 @@ fn applyRecursive( var cur = con.children.first; while (cur) |child| : (cur = child.next) { if (child.is_fullscreen != .none) { - if (fullscreen_count < 8) { + if (fullscreen_count < fullscreen_buf.len) { fullscreen_buf[fullscreen_count] = child; fullscreen_count += 1; } continue; } if (child.is_floating) { - if (floating_count < 32) { + if (floating_count < floating_buf.len) { floating_buf[floating_count] = child; floating_count += 1; } @@ -370,7 +370,7 @@ fn applyRecursive( applyRecursive(conn, child, border_focus_color, border_unfocus_color); // Collect border normal windows inline (avoid second pass) if (child.type == .window and child.border_style == .normal) { - if (normal_border_count < 32) { + if (normal_border_count < normal_border_buf.len) { normal_border_buf[normal_border_count] = child; normal_border_count += 1; } diff --git a/src/tree.zig b/src/tree.zig index bf0e6fb..251007f 100644 --- a/src/tree.zig +++ b/src/tree.zig @@ -41,6 +41,9 @@ pub const WindowData = struct { last_color: u32 = 0xFFFFFFFF, /// Set by applyWindow when geometry changed. Used by sendConfigureNotifyChanged. geometry_changed: bool = true, + /// WM_NORMAL_HINTS minimum size constraints (0 = no constraint) + min_w: u32 = 0, + min_h: u32 = 0, }; pub const WorkspaceData = struct { @@ -50,6 +53,10 @@ pub const WorkspaceData = struct { urgent: bool = false, }; +pub const OutputData = struct { + name: []const u8, +}; + pub const ChildList = struct { first: ?*Container = null, last: ?*Container = null, @@ -135,6 +142,7 @@ pub const Container = struct { window_rect: Rect = .{}, window: ?WindowData = null, workspace: ?WorkspaceData = null, + output_data: ?OutputData = null, percent: f32 = 0.0, is_floating: bool = false, is_fullscreen: FullscreenMode = .none, @@ -185,6 +193,10 @@ pub const Container = struct { freeOwnedString(alloc, wsd.name); freeOwnedString(alloc, wsd.output_name); } + // Free allocator-owned output data + if (self.output_data) |od| { + freeOwnedString(alloc, od.name); + } // Free allocator-owned mark strings for (self.marks[0..self.mark_count]) |mark_opt| { if (mark_opt) |mark| { diff --git a/src/xcb.zig b/src/xcb.zig index 4f0a3f5..27c7c09 100644 --- a/src/xcb.zig +++ b/src/xcb.zig @@ -120,6 +120,7 @@ pub const ATOM_WM_CLASS: Atom = c.XCB_ATOM_WM_CLASS; pub const ATOM_WM_TRANSIENT_FOR: Atom = c.XCB_ATOM_WM_TRANSIENT_FOR; pub const ATOM_WM_HINTS: Atom = c.XCB_ATOM_WM_HINTS; pub const ATOM_WM_NORMAL_HINTS: Atom = c.XCB_ATOM_WM_NORMAL_HINTS; +pub const ATOM_WM_SIZE_HINTS: Atom = c.XCB_ATOM_WM_SIZE_HINTS; // Input focus pub const INPUT_FOCUS_POINTER_ROOT: u8 = c.XCB_INPUT_FOCUS_POINTER_ROOT; @@ -371,10 +372,12 @@ pub const KeyMap = struct { fn keysymData(self: *const KeyMap) []const Keysym { const total: usize = @as(usize, self.max_keycode - self.min_keycode + 1) * self.keysyms_per_keycode; - const ptr: [*]const Keysym = @ptrCast(@alignCast( - @as([*]const u8, @ptrCast(self.reply)) + @sizeOf(c.xcb_get_keyboard_mapping_reply_t), - )); - return ptr[0..total]; + if (total == 0) return &.{}; + // Use the XCB protocol accessor (ABI-safe, no manual pointer arithmetic) + const xcb_len: usize = @intCast(c.xcb_get_keyboard_mapping_keysyms_length(self.reply)); + const safe_total = @min(total, xcb_len); + const ptr: [*]const Keysym = @ptrCast(c.xcb_get_keyboard_mapping_keysyms(self.reply)); + return ptr[0..safe_total]; } pub fn getKeysym(self: *const KeyMap, keycode: Keycode, col: u8) Keysym { @@ -389,12 +392,14 @@ pub const KeyMap = struct { /// Find the first keycode that produces the given keysym (any column). pub fn getKeycode(self: *const KeyMap, keysym: Keysym) ?Keycode { const data = self.keysymData(); + if (data.len == 0) return null; var kc: usize = 0; const count: usize = @as(usize, self.max_keycode - self.min_keycode) + 1; while (kc < count) : (kc += 1) { const base = kc * self.keysyms_per_keycode; var col: usize = 0; while (col < self.keysyms_per_keycode) : (col += 1) { + if (base + col >= data.len) break; if (data[base + col] == keysym) { return @intCast(kc + self.min_keycode); } diff --git a/zephwm-bar/main.zig b/zephwm-bar/main.zig index c51549e..8c8de90 100644 --- a/zephwm-bar/main.zig +++ b/zephwm-bar/main.zig @@ -88,12 +88,12 @@ fn queryBarConfig(allocator: std.mem.Allocator, sock_path: []const u8) BarConfig const response = ipc.sendRequest(allocator, sock_path, .get_bar_config, "") orelse return cfg; defer allocator.free(response); - // Parse font + // Parse font (handles escaped quotes, then unescape) if (std.mem.indexOf(u8, response, "\"font\":\"")) |pos| { const start = pos + 8; - if (std.mem.indexOfScalar(u8, response[start..], '"')) |end| { - const len: u8 = @intCast(@min(end, 255)); - @memcpy(cfg.font[0..len], response[start..][0..len]); + if (findUnescapedQuote(response[start..])) |end| { + const raw = response[start..][0..end]; + const len: u8 = @intCast(unescapeJsonString(&cfg.font, raw)); cfg.font_len = len; } } @@ -108,12 +108,12 @@ fn queryBarConfig(allocator: std.mem.Allocator, sock_path: []const u8) BarConfig } } - // Parse status_command + // Parse status_command (handles escaped quotes, then unescape) if (std.mem.indexOf(u8, response, "\"status_command\":\"")) |pos| { const start = pos + 18; - if (std.mem.indexOfScalar(u8, response[start..], '"')) |end| { - const len: u16 = @intCast(@min(end, 511)); - @memcpy(cfg.status_command[0..len], response[start..][0..len]); + if (findUnescapedQuote(response[start..])) |end| { + const raw = response[start..][0..end]; + const len: u16 = @intCast(unescapeJsonString(&cfg.status_command, raw)); cfg.status_command_len = len; } } @@ -968,29 +968,24 @@ fn parseStatusUpdate( while (pos < inner.len and block_count.* < MAX_STATUS_BLOCKS) { // Find next block object const obj_start = std.mem.indexOfScalar(u8, inner[pos..], '{') orelse break; - const obj_end = std.mem.indexOfScalar(u8, inner[pos + obj_start..], '}') orelse break; + // Find matching '}' while skipping quoted strings + const obj_end = findMatchingBrace(inner[pos + obj_start ..]) orelse break; const obj = inner[pos + obj_start .. pos + obj_start + obj_end + 1]; const idx = block_count.*; blocks[idx] = .{}; - // Extract full_text + // Extract full_text (unescape JSON escapes) if (extractJsonString(obj, "\"full_text\":\"")) |ft| { - const copy_len = @min(ft.len, @as(usize, 256)); - @memcpy(blocks[idx].full_text[0..copy_len], ft[0..copy_len]); - blocks[idx].full_text_len = @intCast(copy_len); + blocks[idx].full_text_len = @intCast(unescapeJsonString(&blocks[idx].full_text, ft)); } - // Extract name + // Extract name (unescape JSON escapes) if (extractJsonString(obj, "\"name\":\"")) |nm| { - const copy_len = @min(nm.len, @as(usize, 64)); - @memcpy(blocks[idx].name[0..copy_len], nm[0..copy_len]); - blocks[idx].name_len = @intCast(copy_len); + blocks[idx].name_len = @intCast(unescapeJsonString(&blocks[idx].name, nm)); } - // Extract instance + // Extract instance (unescape JSON escapes) if (extractJsonString(obj, "\"instance\":\"")) |inst| { - const copy_len = @min(inst.len, @as(usize, 64)); - @memcpy(blocks[idx].instance[0..copy_len], inst[0..copy_len]); - blocks[idx].instance_len = @intCast(copy_len); + blocks[idx].instance_len = @intCast(unescapeJsonString(&blocks[idx].instance, inst)); } block_count.* += 1; @@ -1020,9 +1015,94 @@ fn jsonEscapeWrite(w: anytype, s: []const u8) !void { } } +/// Find the position of the matching '}' for a '{' at s[0], skipping quoted strings. +fn findMatchingBrace(s: []const u8) ?usize { + if (s.len == 0 or s[0] != '{') return null; + var depth: usize = 0; + var in_string = false; + var i: usize = 0; + while (i < s.len) : (i += 1) { + if (in_string) { + if (s[i] == '\\') { + i += 1; // skip escaped character + continue; + } + if (s[i] == '"') in_string = false; + continue; + } + switch (s[i]) { + '"' => in_string = true, + '{' => depth += 1, + '}' => { + depth -= 1; + if (depth == 0) return i; + }, + else => {}, + } + } + return null; +} + +/// Find position of next unescaped double-quote in a string. +/// Skips over backslash-escaped characters (e.g. \"). +fn findUnescapedQuote(s: []const u8) ?usize { + var i: usize = 0; + while (i < s.len) : (i += 1) { + if (s[i] == '\\') { + i += 1; // skip escaped character + continue; + } + if (s[i] == '"') return i; + } + return null; +} + fn extractJsonString(json: []const u8, key: []const u8) ?[]const u8 { const key_pos = std.mem.indexOf(u8, json, key) orelse return null; const val_start = key_pos + key.len; - const val_end = std.mem.indexOfScalar(u8, json[val_start..], '"') orelse return null; - return json[val_start .. val_start + val_end]; + // Scan for unescaped closing quote (skip \" sequences) + var i: usize = 0; + while (i < json[val_start..].len) : (i += 1) { + if (json[val_start + i] == '\\') { + i += 1; // skip escaped character + continue; + } + if (json[val_start + i] == '"') { + return json[val_start .. val_start + i]; + } + } + return null; +} + +/// Unescape JSON string escape sequences in-place into a destination buffer. +/// Handles: \" \\ \/ \b \f \n \r \t. Returns the unescaped length. +fn unescapeJsonString(dst: []u8, src: []const u8) usize { + var si: usize = 0; + var di: usize = 0; + while (si < src.len and di < dst.len) { + if (src[si] == '\\' and si + 1 < src.len) { + const next = src[si + 1]; + const replacement: ?u8 = switch (next) { + '"' => '"', + '\\' => '\\', + '/' => '/', + 'b' => 0x08, + 'f' => 0x0C, + 'n' => '\n', + 'r' => '\r', + 't' => '\t', + else => null, + }; + if (replacement) |ch| { + dst[di] = ch; + di += 1; + si += 2; + continue; + } + } + dst[di] = src[si]; + di += 1; + si += 1; + } + return di; }