From 4c635f357adb95235429d8905b8598a2643b4f3b Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 13:55:12 -0300 Subject: drag 2/3: a pane's or column's grip let go past the window's edge opens it in a new window (Handover.zig) --- src/Handover.zig | 307 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 307 insertions(+) create mode 100644 src/Handover.zig (limited to 'src/Handover.zig') diff --git a/src/Handover.zig b/src/Handover.zig new file mode 100644 index 00000000..fdbe509b --- /dev/null +++ b/src/Handover.zig @@ -0,0 +1,307 @@ +//! Panes between windows, as a browser's tabs go between its windows. A +//! pane's grip, or a column's, released past the window's edge carries it +//! out: dumped alone (dump.dumpBytes, `carried`), it opens in a new window +//! of its own, `pardes-gui -l` of that dump. The pane closes here only once +//! the new window answers on its 9P socket, so its text is never in no +//! window at all; a failed handover leaves it where it was, and a pane +//! edited while it was on its way stays here too (both then have it). +//! +//! The core only dumps, and closes or keeps when told (`finish`); the host +//! writes the dump, and its worker (`carry`, on a thread of its own) spawns +//! the window and waits for it, posting how it went into host_io.Inbox. +const Handover = @This(); + +const std = @import("std"); +const builtin = @import("builtin"); +const pardes = @import("pardes.zig"); +const layout = @import("layout.zig"); +const dump = @import("dump.zig"); +const ninep_io = @import("9p_io.zig"); +const Pardes = pardes.Pardes; +const MAX_PANES = pardes.MAX_PANES; +const libc = std.c; + +/// The handover in flight, one at a time: its number, what it carries, +/// and each carried pane's serial and revision as it was dumped. +seq: u32 = 0, +flying: bool = false, +carried: dump.Carried = .pane, +column_serial: u32 = 0, +count: usize = 0, +serials: [MAX_PANES]u32 = @splat(0), +revisions: [MAX_PANES]u32 = @splat(0), +/// The dump the host sends, gpa-owned while the handover flies. +bytes: ?[]u8 = null, + +pub fn deinit(h: *Handover, gpa: std.mem.Allocator) void { + if (h.bytes) |b| gpa.free(b); + h.bytes = null; +} + +/// Pane slot `at` (with what is attached to it, or alone when it is itself +/// an attachment), or column `at`, released past the window's edge: dumped, +/// and the host asked to carry it. Only text panes travel: a terminal's +/// shell is this process's child and would die with the pane here. +pub fn begin(h: *Handover, p: *Pardes, carried: dump.Carried, at: usize) void { + var keep: [MAX_PANES]bool = @splat(false); + var ids: [MAX_PANES]usize = undefined; + var n: usize = 0; + switch (carried) { + .pane => { + const f = layout.findPane(p, at) orelse return; + const end = if (layout.ownerOf(p, at) == null) layout.groupEnd(p, f.col, f.idx) else f.idx + 1; + for (p.col_panes[f.col][f.idx..end]) |id| { + ids[n] = id; + n += 1; + } + }, + .column => { + if (at >= p.ncol or p.col_n[at] == 0) return; + for (p.col_panes[at][0..p.col_n[at]]) |id| { + ids[n] = id; + n += 1; + } + }, + } + const said = if (carried == .pane) at else ids[0]; + if (h.flying) return p.setMessage(said, "a pane is already on its way to another window"); + for (ids[0..n]) |id| { + const pane = p.panes[id] orelse return; + if (pane.file == null) return p.setMessage(said, if (pane.isTerminal()) + "a terminal stays in its window: its shell is this window's child" + else + "only text panes go to another window, for now"); + } + for (ids[0..n]) |id| keep[id] = true; + const bytes = dump.dumpBytes(p, &keep, carried) catch |err| return p.reportError(said, "handover", err); + h.deinit(p.gpa); + h.bytes = bytes; + h.seq +%= 1; + h.flying = true; + h.carried = carried; + h.column_serial = if (carried == .column) layout.columnSerial(p, at) else 0; + h.count = n; + for (ids[0..n], 0..) |id, i| { + const pane = p.panes[id].?; + h.serials[i] = pane.serial; + h.revisions[i] = pane.file.?.revision; + } + p.setMessage(said, if (carried == .pane) "to a new window…" else "the column, to a new window…"); + p.emit(.{ .hand_over = .{ .seq = h.seq } }); +} + +/// How the host's handover `seq` went: taken by `to` (failure null), or +/// not. Taken, its panes close here, unless one was edited since it was +/// dumped: that one stays, so neither window loses the edit. +pub fn finish(h: *Handover, p: *Pardes, seq: u32, to: []const u8, failure: ?[]const u8) void { + if (!h.flying or seq != h.seq) return; + h.flying = false; + h.deinit(p.gpa); + var buf: [320]u8 = undefined; + if (failure) |why| { + const at = p.paneBySerial(h.serials[0]) orelse p.active; + return p.reportFailure(at, std.fmt.bufPrint(&buf, "handover: {s}; the pane stays here", .{why}) catch "handover failed; the pane stays here"); + } + var kept: usize = 0; + for (h.serials[0..h.count], h.revisions[0..h.count]) |serial, revision| { + const id = p.paneBySerial(serial) orelse continue; // closed with its owner + const pane = p.panes[id].?; + if (pane.file == null or pane.file.?.revision != revision) { + // Out of its group, or the owner's close would take it along. + pane.attached_to = null; + kept += 1; + continue; + } + p.removePane(id, null) catch |err| { + kept += 1; + p.reportError(id, "handover", err); + }; + } + if (h.carried == .column) if (layout.columnBySerial(p, h.column_serial)) |c| { + if (p.col_n[c] == 0 and p.ncol > 1) layout.dropColumn(p, c); + }; + layout.compute(p); + p.setMessage(p.active, if (kept == 0) + std.fmt.bufPrint(&buf, "moved to {s}", .{to}) catch "moved" + else + std.fmt.bufPrint(&buf, "copied to {s}; edited on the way, kept here too", .{to}) catch "copied"); +} + +// ---- the host's half: a worker that carries the dump ---- + +/// A handover for a worker: the dump's file, and the window's geometry for +/// a new one. The worker owns it and frees it with `gpa`. +pub const Job = struct { + gpa: std.mem.Allocator, + seq: u32, + path: [:0]u8, + /// `--geometry=` for a new window: `WxH`, `+X+Y` when the host can place it. + geometry: [64]u8 = undefined, + geometry_len: usize = 0, + /// Where it says how it went: (seq, true, where) or (seq, false, why); + /// the words are borrowed for the call. + post: *const fn (ctx: ?*anyopaque, seq: u32, ok: bool, words: []const u8) void, + post_ctx: ?*anyopaque, +}; + +/// The file a handover's dump goes in: the runtime directory, the user's +/// alone, else the dump directory. Null-terminated, `gpa`'s. +pub fn dumpPath(gpa: std.mem.Allocator, seq: u32) ![:0]u8 { + var dir_buf: [1024]u8 = undefined; + const dir: []const u8 = if (libc.getenv("XDG_RUNTIME_DIR")) |x| std.mem.span(x) else dump.defaultDirectory(&dir_buf) orelse return error.NoDirectory; + return std.fmt.allocPrintSentinel(gpa, "{s}/pardes-handover-{d}-{d}.zon", .{ dir, libc.getpid(), seq }, 0); +} + +/// Runs the handover on its own thread, detached; it removes the dump's +/// file once someone has it, or nobody will. +pub fn start(job: *Job) !void { + const thread = try std.Thread.spawn(.{}, carry, .{job}); + thread.detach(); +} + +fn carry(job: *Job) void { + defer { + _ = libc.unlink(job.path); + job.gpa.free(job.path); + job.gpa.destroy(job); + } + var words: [256]u8 = undefined; + const pid = spawnWindow(job) catch |err| return job.post(job.post_ctx, job.seq, false, std.fmt.bufPrint(&words, "no new window: {s}", .{@errorName(err)}) catch "no new window"); + // Up when its registry entry answers: it read the dump before it + // listened (gui.localSession), so the file is no longer needed. + var entry_buf: [512]u8 = undefined; + const run = libc.getenv("XDG_RUNTIME_DIR") orelse ""; + const entry = std.fmt.bufPrint(&entry_buf, "{s}/9p/pardes/{d}", .{ std.mem.span(run), pid }) catch ""; + var waited: u32 = 0; + while (waited < 15_000) : (waited += 50) { + if (libc.kill(pid, @enumFromInt(0)) != 0) + return job.post(job.post_ctx, job.seq, false, "the new window ended before it was up"); + if (ninep_io.Client.readLimit(job.gpa, entry, "status", "status", 256)) |status| { + job.gpa.free(status); + return job.post(job.post_ctx, job.seq, true, std.fmt.bufPrint(&words, "a new window (pardes/{d})", .{pid}) catch "a new window"); + } else |_| {} + sleepMs(50); + } + _ = libc.kill(pid, libc.SIG.TERM); + job.post(job.post_ctx, job.seq, false, "the new window did not come up in 15 s"); +} + +fn sleepMs(ms: u32) void { + var ts: libc.timespec = .{ .sec = 0, .nsec = @as(isize, ms) * std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); +} + +/// This program again, `-l` the dump: a new window, in a session of its own +/// (setsid) and not this one's child (forked twice), so it outlives this +/// window and leaves no zombie. Answers its pid. +fn spawnWindow(job: *Job) !libc.pid_t { + if (comptime builtin.os.tag != .linux) return error.Unsupported; + var exe_buf: [4096:0]u8 = undefined; + const n = libc.readlink("/proc/self/exe", &exe_buf, exe_buf.len - 1); + if (n <= 0) return error.NoExecutable; + exe_buf[@intCast(n)] = 0; + var geometry_z: [80:0]u8 = undefined; + const geometry = try std.fmt.bufPrintSentinel(&geometry_z, "--geometry={s}", .{job.geometry[0..job.geometry_len]}, 0); + const argv = [_:null]?[*:0]const u8{ &exe_buf, "-l", job.path, if (job.geometry_len > 0) geometry else null, null }; + var fds: [2]c_int = undefined; + if (libc.pipe(&fds) != 0) return error.NoPipe; + defer _ = libc.close(fds[0]); + const first = libc.fork(); + if (first < 0) { + _ = libc.close(fds[1]); + return error.NoFork; + } + if (first == 0) { + // Only async-signal-safe calls between fork and exec. + _ = libc.setsid(); + const second = libc.fork(); + if (second == 0) { + _ = libc.close(fds[1]); + _ = libc.execve(&exe_buf, &argv, @ptrCast(libc.environ)); + libc._exit(127); + } + _ = libc.write(fds[1], std.mem.asBytes(&second), @sizeOf(libc.pid_t)); + libc._exit(0); + } + _ = libc.close(fds[1]); + _ = libc.waitpid(first, null, 0); + var pid: libc.pid_t = 0; + if (libc.read(fds[0], std.mem.asBytes(&pid), @sizeOf(libc.pid_t)) != @sizeOf(libc.pid_t) or pid <= 0) return error.NoFork; + return pid; +} + +// ---- tests ---- + +/// Two text panes in one column, the lower one `/test.txt`'s twin made by +/// New, and the grip of pane `id` let go past the window's edge. +fn twoPanes(gpa: std.mem.Allocator) !*Pardes { + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 30 }); + errdefer p.deinit(); + _ = try p.setTestFile("alpha\nbeta\n"); + try std.testing.expect(p.executeBuiltinLine(p.active, "New")); + p.sync(); + return p; +} + +fn releaseOutside(p: *Pardes, id: usize) void { + const r = p.rects[id]; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = r.x, .row = p.tagTop(p.panes[id].?, r) } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = p.screen_w - 1, .row = r.y + 1 } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = p.screen_w - 1, .row = r.y + 1, .outside = true } }); +} + +test "a grip let go past the window's edge dumps its pane alone, and closes it only once another window has it" { + const p = try twoPanes(std.testing.allocator); + defer p.deinit(); + const f = layout.findPane(p, 0).?; + try std.testing.expect(p.col_n[f.col] == 2); + const other = p.col_panes[f.col][1 - f.idx]; + const before = p.rects[other]; + releaseOutside(p, 0); + // Dumped and asked for; nothing moved yet. + try std.testing.expect(p.handover.flying); + try std.testing.expect(p.drag == .none); + try std.testing.expect(p.panes[0] != null); + try std.testing.expectEqual(before, p.rects[other]); + var parsed = try dump.readZon(std.testing.allocator, p.handover.bytes.?, "test"); + defer parsed.deinit(); + try std.testing.expectEqual(@as(?dump.Carried, .pane), parsed.value.carried); + try std.testing.expectEqual(@as(usize, 1), parsed.value.panes.len); + try std.testing.expectEqual(@as(usize, 1), parsed.value.columns.len); + try std.testing.expectEqualStrings("/test.txt", parsed.value.panes[0].file.?.path); + // A second one waits for the first. + releaseOutside(p, other); + try std.testing.expect(p.panes[other] != null); + // Refused (no window took it): it stays. + p.update(.{ .handed = .{ .seq = p.handover.seq, .failure = "no window" } }); + try std.testing.expect(!p.handover.flying); + try std.testing.expect(p.panes[0] != null); + // Taken: it closes, and the pane beside it takes its rows (Del's rule). + releaseOutside(p, 0); + const serial = p.panes[0].?.serial; + p.update(.{ .handed = .{ .seq = p.handover.seq, .to = "pardes/1" } }); + try std.testing.expect(p.paneBySerial(serial) == null); + p.sync(); + try std.testing.expectEqual(@as(usize, 1), p.col_n[layout.findPane(p, other).?.col]); +} + +test "a pane edited while it is on its way to another window stays here too" { + const p = try twoPanes(std.testing.allocator); + defer p.deinit(); + releaseOutside(p, 0); + const pane = p.panes[0].?; + pane.file.?.revision += 1; // an edit after the dump + p.update(.{ .handed = .{ .seq = p.handover.seq, .to = "pardes/1" } }); + try std.testing.expect(p.panes[0] == pane); +} + +test "a terminal's grip let go past the edge stays: its shell is this window's" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30, .shells = 3 }); + defer p.deinit(); + p.update(.{ .resize = .{ .cols = 100, .rows = 30 } }); + const id = p.col_panes[1][0]; + try std.testing.expect(p.panes[id].?.isTerminal()); + releaseOutside(p, id); + try std.testing.expect(!p.handover.flying); + try std.testing.expect(p.panes[id] != null); +} -- cgit v1.3 From 24e66ebf34a3d30f9236d20e6c3ca34889cf2a55 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 14:14:59 -0300 Subject: drag 3/3: a grip let go over another pardes window drops its pane or column there (status pointer, adopt) --- src/Handover.zig | 235 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/gui/gui.zig | 6 ++ src/ninep/ctl.zig | 25 +++++- src/pardes.zig | 4 + 4 files changed, 269 insertions(+), 1 deletion(-) (limited to 'src/Handover.zig') diff --git a/src/Handover.zig b/src/Handover.zig index fdbe509b..3acfc4e6 100644 --- a/src/Handover.zig +++ b/src/Handover.zig @@ -5,6 +5,11 @@ //! the new window answers on its 9P socket, so its text is never in no //! window at all; a failed handover leaves it where it was, and a pane //! edited while it was on its way stays here too (both then have it). +//! Let go over another pardes window, the pane goes there instead: the +//! worker finds the window under the pointer among the registry's sessions +//! (each says in /status whether the pointer is over it) and writes it +//! `adopt ` (ninep/ctl.zig), which takes the pane in where the pointer +//! is (`adopt`) before the write is answered. //! //! The core only dumps, and closes or keeps when told (`finish`); the host //! writes the dump, and its worker (`carry`, on a thread of its own) spawns @@ -17,6 +22,8 @@ const pardes = @import("pardes.zig"); const layout = @import("layout.zig"); const dump = @import("dump.zig"); const ninep_io = @import("9p_io.zig"); +const panes = @import("panes.zig"); +const tagline = @import("tagline.zig"); const Pardes = pardes.Pardes; const MAX_PANES = pardes.MAX_PANES; const libc = std.c; @@ -127,6 +134,106 @@ pub fn finish(h: *Handover, p: *Pardes, seq: u32, to: []const u8, failure: ?[]co std.fmt.bufPrint(&buf, "copied to {s}; edited on the way, kept here too", .{to}) catch "copied"); } +// ---- the receiving window ---- + +/// A carried dump (`begin`'s) taken into this window where the pointer is: +/// a pane under the pane the pointer is over, out of that pane's rows +/// alone; a column beside the column the pointer is over, out of its width +/// alone. Every other pane stays where it was. Answers the slot of the +/// first pane taken; on an error nothing of it is left here. +pub fn adopt(p: *Pardes, bytes: []const u8) !usize { + var parsed = try dump.readZon(p.gpa, bytes, "adopt"); + defer parsed.deinit(); + const st = parsed.value; + const carried = st.carried orelse return error.NotCarried; + if (st.columns.len != 1 or st.columns[0].panes.len == 0) return error.NotCarried; + const order = st.columns[0].panes; + for (order) |i| if (i >= st.panes.len or st.panes[i].kind != .file) return error.NotText; + // Where the pointer is, else the middle of the pane with the keyboard. + layout.compute(p); + const here = p.rects[p.active]; + const x = if (p.pointer_inside) p.hover_col else here.x + here.w / 2; + const y = if (p.pointer_inside) p.hover_row else here.y + here.h / 2; + var slots: [MAX_PANES]usize = undefined; + var n: usize = 0; + errdefer for (slots[0..n]) |slot| p.removePane(slot, null) catch {}; + for (order) |i| { + const slot = p.freeSlot() orelse return error.TooManyPanes; + const src = st.panes[i]; + const pane = try panes.File.restore(p, slot, src); + slots[n] = slot; + n += 1; + tagline.restoreDumpTail(p, pane, src); + pane.collapsed = false; + } + // An attachment names its owner by its place in the dump. + for (order, 0..) |i, k| { + const owner = st.panes[i].attached_to orelse continue; + const at = std.mem.indexOfScalar(usize, order, owner) orelse continue; + p.panes[slots[k]].?.attached_to = p.panes[slots[at]].?.serial; + } + const tc = layout.targetColumn(p, x); + var heights: [MAX_PANES]u16 = @splat(0); + if (carried == .column or p.ncol == 0) { + const c = if (p.ncol == 0) layout.insertColumn(p, 0, false) else layout.insertColumn(p, tc, x < p.col_x[tc] + p.col_w[tc] / 2); + const col = c orelse return error.NoRoom; + if (carried == .column) if (st.columns[0].tag) |tag| { + p.col_tags[col].own = try p.gpa.dupe(u8, tag); + }; + for (slots[0..n], 0..) |slot, k| { + layout.insert(p, col, k, slot); + p.panes[slot].?.vweight = st.panes[order[k]].vweight; + } + p.active = slots[0]; + p.setActiveColumn(col); + p.sync(); + return slots[0]; + } + for (0..p.ncol) |c| for (p.col_panes[c][0..p.col_n[c]]) |id| { + heights[id] = p.rects[id].h; + }; + // The group under the pointer (a pane with what is attached to it): the + // new panes go under all of it, out of its owner's rows. + var after: usize = p.col_n[tc]; + var root: ?usize = null; + var k: usize = 0; + while (k < p.col_n[tc]) { + const end = layout.groupEnd(p, tc, k); + const first = p.col_panes[tc][k]; + const last = p.col_panes[tc][end - 1]; + root = first; + after = end; + if (y < p.rects[last].y + p.rects[last].h) break; + k = end; + } + if (root) |owner| { + const r = p.rects[owner]; + // Down to the pointer's row; let go over one of its attachments, + // half of it. + const keeps = @max(layout.minRows(p, owner), if (y >= r.y and y < r.y + r.h) (y - r.y) + 1 else r.h / 2); + const give = heights[owner] -| keeps; + if (give < 1 + layout.min_body_rows) return error.NoRoom; + heights[owner] = keeps; + // The carried share what was given as they shared their old rows. + var total: f32 = 0; + for (order) |i| total += st.panes[i].vweight; + var left = give; + for (slots[0..n], 0..) |slot, j| { + const share: u16 = if (j + 1 == n) left else @intFromFloat(@max(1, @floor(@as(f32, @floatFromInt(give)) * st.panes[order[j]].vweight / @max(total, 1)))); + heights[slot] = @min(share, left); + left -|= share; + } + } else for (slots[0..n]) |slot| { + heights[slot] = 1; + } + for (slots[0..n], 0..) |slot, j| layout.insert(p, tc, after + j, slot); + layout.setColumnWeights(p, tc, &heights); + p.active = slots[0]; + p.setActiveColumn(tc); + p.sync(); + return slots[0]; +} + // ---- the host's half: a worker that carries the dump ---- /// A handover for a worker: the dump's file, and the window's geometry for @@ -142,6 +249,10 @@ pub const Job = struct { /// the words are borrowed for the call. post: *const fn (ctx: ?*anyopaque, seq: u32, ok: bool, words: []const u8) void, post_ctx: ?*anyopaque, + /// This window's 9P socket, which its registry entry links to: the one + /// window never asked whether the pointer is over it. + own: [512]u8 = undefined, + own_len: usize = 0, }; /// The file a handover's dump goes in: the runtime directory, the user's @@ -166,6 +277,20 @@ fn carry(job: *Job) void { job.gpa.destroy(job); } var words: [256]u8 = undefined; + // Let go over another window: it takes the dump in, where the pointer + // is, before its `adopt` answers. A refusal (no room there, too many + // panes) leaves the pane here: no new window instead, the user aimed. + var dial_buf: [512]u8 = undefined; + if (windowUnderPointer(job, &dial_buf)) |dial| { + var line_buf: [600]u8 = undefined; + const line = std.fmt.bufPrint(&line_buf, "adopt {s}\n", .{job.path}) catch return job.post(job.post_ctx, job.seq, false, "its dump's name is too long"); + const name = std.fs.path.basename(dial); + if (ninep_io.Client.write(job.gpa, dial, "ctl", line)) { + return job.post(job.post_ctx, job.seq, true, std.fmt.bufPrint(&words, "pardes/{s}", .{name}) catch "another window"); + } else |err| return job.post(job.post_ctx, job.seq, false, std.fmt.bufPrint(&words, "pardes/{s} would not take it: {s}", .{ + name, if (err == error.Remote) ninep_io.Client.lastSaid() else @errorName(err), + }) catch "the window would not take it"); + } const pid = spawnWindow(job) catch |err| return job.post(job.post_ctx, job.seq, false, std.fmt.bufPrint(&words, "no new window: {s}", .{@errorName(err)}) catch "no new window"); // Up when its registry entry answers: it read the dump before it // listened (gui.localSession), so the file is no longer needed. @@ -186,6 +311,43 @@ fn carry(job: *Job) void { job.post(job.post_ctx, job.seq, false, "the new window did not come up in 15 s"); } +extern "c" fn readdir(dir: *libc.DIR) ?*libc.dirent; + +/// The registry entry of the window the pointer was let go over, asked of +/// every window by its `status` (`pointer in`): Wayland tells no client +/// where any window is, only whether the pointer is over its own, and the +/// window let go over learns it a moment after the release (the grab ends, +/// then it is entered), so it is asked a few times. None answering with a +/// pointer line at all (no other window, or an older pardes) ends it at once. +fn windowUnderPointer(job: *Job, out: *[512]u8) ?[]const u8 { + const run = std.mem.span(libc.getenv("XDG_RUNTIME_DIR") orelse return null); + var reg_buf: [512:0]u8 = undefined; + const reg = std.fmt.bufPrintSentinel(®_buf, "{s}/9p/pardes", .{run}, 0) catch return null; + const own = job.own[0..job.own_len]; + var round: u32 = 0; + while (round < 10) : (round += 1) { + if (round > 0) sleepMs(40); + const dir = libc.opendir(reg) orelse return null; + defer _ = libc.closedir(dir); + var windows: usize = 0; + while (readdir(dir)) |ent| { + const name = std.mem.sliceTo(&ent.name, 0); + if (name.len == 0 or name[0] == '.') continue; + const entry = std.fmt.bufPrintSentinel(out, "{s}/{s}", .{ reg, name }, 0) catch continue; + var link: [512]u8 = undefined; + const n = libc.readlink(entry, &link, link.len); + if (n > 0 and std.mem.eql(u8, link[0..@intCast(n)], own)) continue; + const status = ninep_io.Client.readLimit(job.gpa, entry, "status", "status", 256) catch continue; + defer job.gpa.free(status); + if (std.mem.indexOf(u8, status, "\npointer ") == null) continue; + windows += 1; + if (std.mem.indexOf(u8, status, "\npointer in\n") != null) return entry; + } + if (windows == 0) return null; + } + return null; +} + fn sleepMs(ms: u32) void { var ts: libc.timespec = .{ .sec = 0, .nsec = @as(isize, ms) * std.time.ns_per_ms }; _ = libc.nanosleep(&ts, null); @@ -305,3 +467,76 @@ test "a terminal's grip let go past the edge stays: its shell is this window's" try std.testing.expect(!p.handover.flying); try std.testing.expect(p.panes[id] != null); } + +test "a pane let go over another window goes under the pane the pointer is over, out of its rows alone, unsaved text and all" { + const gpa = std.testing.allocator; + const from = try twoPanes(gpa); + defer from.deinit(); + _ = pardes.ctlfs.pane.spliceBody(from, from.panes[0].?, 0, 0, "unsaved ").?; + releaseOutside(from, 0); + const to = try twoPanes(gpa); + defer to.deinit(); + to.sync(); + const before = to.rects; + const c = layout.findPane(to, 0).?.col; + const upper = to.col_panes[c][0]; + const lower = to.col_panes[c][1]; + // The pointer over the upper pane, six rows into it. + to.pointer_inside = true; + to.hover_col = to.rects[upper].x + 5; + to.hover_row = to.rects[upper].y + 6; + const id = try adopt(to, from.handover.bytes.?); + to.sync(); + const pane = to.panes[id].?; + try std.testing.expectEqualStrings("unsaved alpha\nbeta\n", pane.file.?.content); + try std.testing.expect(tagline.dirty(pane)); + try std.testing.expectEqual(upper, to.col_panes[c][0]); + try std.testing.expectEqual(id, to.col_panes[c][1]); + try std.testing.expectEqual(lower, to.col_panes[c][2]); + // The pane under the pointer keeps its top and gives its rows below + // the pointer; the new one is just there; every other pane is where it was. + try std.testing.expectEqual(before[upper].y, to.rects[upper].y); + try std.testing.expectEqual(@as(u16, 7), to.rects[upper].h); + try std.testing.expectEqual(before[upper].y + 7, to.rects[id].y); + try std.testing.expectEqual(before[upper].h - 7, to.rects[id].h); + for (to.panes, 0..) |slot, k| if (slot != null and k != upper and k != id) + try std.testing.expectEqual(before[k], to.rects[k]); + try std.testing.expectEqual(id, to.active); +} + +test "a column let go over another window goes beside the column the pointer is over, out of its width alone" { + const gpa = std.testing.allocator; + const from = try twoPanes(gpa); + defer from.deinit(); + const r = from.rects[0]; + const c = layout.findPane(from, 0).?.col; + from.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = from.col_x[c], .row = from.topBarHeight() } }); + from.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = from.screen_w - 1, .row = r.y } }); + from.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = from.screen_w - 1, .row = r.y, .outside = true } }); + try std.testing.expect(from.handover.flying); + try std.testing.expectEqual(dump.Carried.column, from.handover.carried); + const to = try Pardes.init(gpa, .{ .tty_only = true, .cols = 120, .rows = 30 }); + defer to.deinit(); + _ = try to.setTestFile("x\n"); + try std.testing.expect(to.executeBuiltinLine(to.active, "Newcol")); + to.sync(); + const ncol = to.ncol; + const widths = to.col_w; + const xs = to.col_x; + // Over the right half of the last column: the new one goes after it. + to.pointer_inside = true; + to.hover_col = to.col_x[ncol - 1] + to.col_w[ncol - 1] - 2; + to.hover_row = 10; + const id = try adopt(to, from.handover.bytes.?); + to.sync(); + try std.testing.expectEqual(ncol + 1, to.ncol); + try std.testing.expectEqual(ncol, layout.findPane(to, id).?.col); + try std.testing.expectEqual(@as(usize, 2), to.col_n[ncol]); + for (0..ncol - 1) |k| { + try std.testing.expectEqual(widths[k], to.col_w[k]); + try std.testing.expectEqual(xs[k], to.col_x[k]); + } + // The finish here: both panes and their column gone from the window. + from.update(.{ .handed = .{ .seq = from.handover.seq, .to = "pardes/2" } }); + try std.testing.expect(from.ncol == 1 or from.col_n[c] == 0 or layout.findPane(from, 0) == null); +} diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 39eedf89..5b80b342 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -2251,6 +2251,7 @@ fn localSession( defer core.deinit(); g.hit_core = core; defer g.hit_core = null; + core.windowed = true; core.native_images = true; core.native_image_patches = true; observeGuiFont(g, core); @@ -2386,6 +2387,7 @@ fn localSession( nc.native_image_patches = true; nc.host = host; if (fs) |f| f.reset(nc); + nc.windowed = true; core.deinit(); core = nc; g.hit_core = nc; @@ -4604,6 +4606,10 @@ fn handOver(ctx: ?*anyopaque, seq: u32, bytes: []const u8) void { return s.core.update(.{ .handed = .{ .seq = seq, .failure = "out of memory" } }); }; job.* = .{ .gpa = s.gpa, .seq = seq, .path = path, .post = Queue.pushHanded, .post_ctx = s.queue }; + if (s.fs) |f| { + job.own_len = @min(f.path().len, job.own.len); + @memcpy(job.own[0..job.own_len], f.path()[0..job.own_len]); + } if (s.gui) |g| { var w: c_int = 0; var h: c_int = 0; diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 258ea1ee..d9bd4372 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -380,10 +380,14 @@ fn statusText(p: *Pardes, buf: []u8) []const u8 { for (p.panes) |slot| count += @intFromBool(slot != null); const pid: u32 = if (comptime pardes.hosted) @intCast(std.c.getpid()) else 0; w.print("pid {d}\nversion {s}\npanes {d}\n", .{ pid, pardes.version, count }) catch {}; + // Whether the pointer is over this window: what a grip let go past + // another window's edge asks of every window, to find the one it was + // let go over (Handover.zig), where no window may know another's place. + if (p.windowed) w.print("pointer {s}\n", .{if (p.pointer_inside) "in" else "out"}) catch {}; return w.buffered(); } -pub const status_text_cap = 64 + pardes.version.len; +pub const status_text_cap = 80 + pardes.version.len; pub fn statusLen(p: *Pardes) u64 { var buf: [status_text_cap]u8 = undefined; @@ -804,6 +808,19 @@ pub fn writeRoot(p: *Pardes, req: Req) Reply { } continue; } + // `adopt `: a pane or column another window's grip carried + // here (Handover.zig), taken in where the pointer is. A window's + // word to a window, as `size` is a frontend's: no builtin. + if (std.mem.startsWith(u8, line, "adopt ")) { + const path = std.mem.trim(u8, line["adopt".len..], " \t"); + if (!apply) continue; + // ponytail: read on the 9P task, a small local file; a big + // one would want pardes.turn's yield. + const bytes = fs.readFile(p.gpa, path) catch |err| return refuseQuoting(p, req, @errorName(err), path); + defer p.gpa.free(bytes); + _ = pardes.Handover.adopt(p, bytes) catch |err| return refuseQuoting(p, req, @errorName(err), path); + continue; + } if (!apply) { if (checkBuiltin(p, req, line, .session)) |refusal| return refusal; continue; @@ -1731,6 +1748,12 @@ test "status reads the editor, and look and exec validate whole batches" { for (p.panes) |slot| live += @intFromBool(slot != null); try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "panes {d}", .{live}), lines.next().?); try testing.expect(lines.next() == null); + // A window says whether the pointer is over it. + p.windowed = true; + var again = std.mem.tokenizeScalar(u8, rd(p, root_status, 0, 4096).bytes, '\n'); + for (0..3) |_| _ = again.next(); + try testing.expectEqualStrings("pointer out", again.next().?); + p.windowed = false; const stat = call(p, .{ .tag = 1, .op = .getattr, .node = root_status }); try testing.expectEqual(@as(u64, status.bytes.len), stat.reply.attr.size); try testing.expectEqual(@as(u16, 0o444), stat.reply.attr.mode); diff --git a/src/pardes.zig b/src/pardes.zig index 99231a57..1b1355ef 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -4531,6 +4531,10 @@ pub const Pardes = struct { pointer_tag_hit: ?TagHit = null, raw_hover_intent: bool = false, pointer_inside: bool = false, + /// A pixel shell's window, which hears the pointer leave it: only then + /// does /status say whether the pointer is over it (a terminal's mouse + /// reports never say it left, so a tty would claim it for ever). + windowed: bool = false, /// The last plain B1 click, for acme's double-click (text.c:881, /// textselect: a second click at the same point within 500 ms). last_click: ?struct { id: usize, on_tag: bool, row: i32, col: i32, ms: i64 } = null, -- cgit v1.3 From 3b9ad2f510267d7be7280386cc95bb41a6e71308 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 16:06:18 -0300 Subject: merge: a pane a grip carried to another window is not kept as a closed pane (Store.away while Handover.finish closes it): it is open there, so Panes does not offer it back here; the dump golden gains drag's .carried = null --- src/Handover.zig | 6 ++++++ src/Store.zig | 9 ++++++--- test/snapshots/dump.golden | 1 + 3 files changed, 13 insertions(+), 3 deletions(-) (limited to 'src/Handover.zig') diff --git a/src/Handover.zig b/src/Handover.zig index 3acfc4e6..ced9baf0 100644 --- a/src/Handover.zig +++ b/src/Handover.zig @@ -110,6 +110,9 @@ pub fn finish(h: *Handover, p: *Pardes, seq: u32, to: []const u8, failure: ?[]co return p.reportFailure(at, std.fmt.bufPrint(&buf, "handover: {s}; the pane stays here", .{why}) catch "handover failed; the pane stays here"); } var kept: usize = 0; + // Moved, not closed: the other window has them now (Store.away). + p.store.away = true; + defer p.store.away = false; for (h.serials[0..h.count], h.revisions[0..h.count]) |serial, revision| { const id = p.paneBySerial(serial) orelse continue; // closed with its owner const pane = p.panes[id].?; @@ -443,6 +446,9 @@ test "a grip let go past the window's edge dumps its pane alone, and closes it o const serial = p.panes[0].?.serial; p.update(.{ .handed = .{ .seq = p.handover.seq, .to = "pardes/1" } }); try std.testing.expect(p.paneBySerial(serial) == null); + // Open in the other window, so not one of this session's closed panes + // (Store.zig): Panes does not offer it back here. + try std.testing.expect(p.store.closedBySerial(serial) == null); p.sync(); try std.testing.expectEqual(@as(usize, 1), p.col_n[layout.findPane(p, other).?.col]); } diff --git a/src/Store.zig b/src/Store.zig index e06c55e5..5e47d695 100644 --- a/src/Store.zig +++ b/src/Store.zig @@ -93,6 +93,9 @@ loaded: bool = false, pending: std.ArrayList(u8) = .empty, /// This session's closed panes, oldest first. closed: std.ArrayList(Closed) = .empty, +/// The panes closing now went to another window (Handover.finish): open +/// there, they are no closed panes of this session, so none is kept. +away: bool = false, fn clockNs() i128 { var ts: std.c.timespec = .{ .sec = 0, .nsec = 0 }; @@ -488,10 +491,10 @@ fn frame(gpa: std.mem.Allocator, out: *std.ArrayList(u8), kind: u8, parts: []con /// Pane `id`, about to close, kept as a record: what it was (a one-pane /// Dump) and where (its column, its rows, what it was attached to). Null /// for a pane that is no pane of the user's: a query pane, a preview, one -/// made and refused in the same step (never announced), or one whose dump -/// fails or is too big. `close` finishes it once its rows have gone. +/// carried to another window (`away`), one made and refused in the same +/// step (never announced), or one whose dump fails or is too big. `close` finishes it once its rows have gone. pub fn keep(s: *Store, p: *Pardes, id: usize) ?Kept { - _ = s; + if (s.away) return null; const pane = p.panes[id] orelse return null; if (pane.fs.unannounced or pane.query != null) return null; if (pane.file) |f| if (f.output) |o| if (o.from == .preview) return null; diff --git a/test/snapshots/dump.golden b/test/snapshots/dump.golden index 72bb85a7..2704918d 100644 --- a/test/snapshots/dump.golden +++ b/test/snapshots/dump.golden @@ -112,5 +112,6 @@ "Shell bash", }, .incl = .{ "/usr/include", "/usr/local/include" }, + .carried = null, } == end file -- cgit v1.3 From f8bf3331ce99d98b25b0dfcc877db9c1dd06f77b Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 21:08:13 -0300 Subject: merge: the handover carrier on io.concurrent: Handover.start runs carry on the shell's Io (the double fork and exec inside it as they were), Handover.task keeps the future, finish awaits it once the answer is in, deinit cancels it; its waits are Io sleeps, so a cancel stops it there, leaving a coming-up window its dump --- src/Handover.zig | 59 +++++++++++++++++++++++++++++++++++++++----------------- src/gui/gui.zig | 2 +- 2 files changed, 42 insertions(+), 19 deletions(-) (limited to 'src/Handover.zig') diff --git a/src/Handover.zig b/src/Handover.zig index ced9baf0..6124e49f 100644 --- a/src/Handover.zig +++ b/src/Handover.zig @@ -12,8 +12,9 @@ //! is (`adopt`) before the write is answered. //! //! The core only dumps, and closes or keeps when told (`finish`); the host -//! writes the dump, and its worker (`carry`, on a thread of its own) spawns -//! the window and waits for it, posting how it went into host_io.Inbox. +//! writes the dump, and its worker (`carry`, an io.concurrent job on the +//! shell's Io, as every background job is) spawns the window and waits for +//! it, posting how it went into host_io.Inbox. const Handover = @This(); const std = @import("std"); @@ -39,8 +40,20 @@ serials: [MAX_PANES]u32 = @splat(0), revisions: [MAX_PANES]u32 = @splat(0), /// The dump the host sends, gpa-owned while the handover flies. bytes: ?[]u8 = null, +/// The carrier (`carry`) while it flies, on the shell's Io: awaited when +/// its answer comes in (`finish`), cancelled at the session's end. +task: ?struct { future: std.Io.Future(void), io: std.Io } = null, pub fn deinit(h: *Handover, gpa: std.mem.Allocator) void { + // The session ends with the carrier still out: it stops at its next + // wait (a 9P call it is in finishes first, within its own budget). + if (h.task) |t| { + h.task = null; + var future = t.future; + pardes.turn.yield(); + future.cancel(t.io); + pardes.turn.back(); + } if (h.bytes) |b| gpa.free(b); h.bytes = null; } @@ -103,6 +116,14 @@ pub fn begin(h: *Handover, p: *Pardes, carried: dump.Carried, at: usize) void { pub fn finish(h: *Handover, p: *Pardes, seq: u32, to: []const u8, failure: ?[]const u8) void { if (!h.flying or seq != h.seq) return; h.flying = false; + // Its answer is the carrier's last word: what is left of it is freeing. + if (h.task) |t| { + h.task = null; + var future = t.future; + pardes.turn.yield(); + future.await(t.io); + pardes.turn.back(); + } h.deinit(p.gpa); var buf: [320]u8 = undefined; if (failure) |why| { @@ -266,16 +287,19 @@ pub fn dumpPath(gpa: std.mem.Allocator, seq: u32) ![:0]u8 { return std.fmt.allocPrintSentinel(gpa, "{s}/pardes-handover-{d}-{d}.zon", .{ dir, libc.getpid(), seq }, 0); } -/// Runs the handover on its own thread, detached; it removes the dump's -/// file once someone has it, or nobody will. -pub fn start(job: *Job) !void { - const thread = try std.Thread.spawn(.{}, carry, .{job}); - thread.detach(); +/// Runs the handover's carrier on `io` (io.concurrent), kept in `h.task` +/// until its answer: it owns `job`, and removes the dump's file once +/// someone has it, or nobody will. +pub fn start(h: *Handover, io: std.Io, job: *Job) !void { + h.task = .{ .future = try io.concurrent(carry, .{ io, job }), .io = io }; } -fn carry(job: *Job) void { +fn carry(io: std.Io, job: *Job) void { + // Cancelled while a new window is coming up: it may still be reading + // the dump, so the file stays for it. + var for_child = false; defer { - _ = libc.unlink(job.path); + if (!for_child) _ = libc.unlink(job.path); job.gpa.free(job.path); job.gpa.destroy(job); } @@ -284,7 +308,8 @@ fn carry(job: *Job) void { // is, before its `adopt` answers. A refusal (no room there, too many // panes) leaves the pane here: no new window instead, the user aimed. var dial_buf: [512]u8 = undefined; - if (windowUnderPointer(job, &dial_buf)) |dial| { + const under = windowUnderPointer(io, job, &dial_buf) catch return; + if (under) |dial| { var line_buf: [600]u8 = undefined; const line = std.fmt.bufPrint(&line_buf, "adopt {s}\n", .{job.path}) catch return job.post(job.post_ctx, job.seq, false, "its dump's name is too long"); const name = std.fs.path.basename(dial); @@ -308,7 +333,10 @@ fn carry(job: *Job) void { job.gpa.free(status); return job.post(job.post_ctx, job.seq, true, std.fmt.bufPrint(&words, "a new window (pardes/{d})", .{pid}) catch "a new window"); } else |_| {} - sleepMs(50); + io.sleep(.fromMilliseconds(50), .awake) catch { + for_child = true; + return; + }; } _ = libc.kill(pid, libc.SIG.TERM); job.post(job.post_ctx, job.seq, false, "the new window did not come up in 15 s"); @@ -322,14 +350,14 @@ extern "c" fn readdir(dir: *libc.DIR) ?*libc.dirent; /// window let go over learns it a moment after the release (the grab ends, /// then it is entered), so it is asked a few times. None answering with a /// pointer line at all (no other window, or an older pardes) ends it at once. -fn windowUnderPointer(job: *Job, out: *[512]u8) ?[]const u8 { +fn windowUnderPointer(io: std.Io, job: *Job, out: *[512]u8) std.Io.Cancelable!?[]const u8 { const run = std.mem.span(libc.getenv("XDG_RUNTIME_DIR") orelse return null); var reg_buf: [512:0]u8 = undefined; const reg = std.fmt.bufPrintSentinel(®_buf, "{s}/9p/pardes", .{run}, 0) catch return null; const own = job.own[0..job.own_len]; var round: u32 = 0; while (round < 10) : (round += 1) { - if (round > 0) sleepMs(40); + if (round > 0) try io.sleep(.fromMilliseconds(40), .awake); const dir = libc.opendir(reg) orelse return null; defer _ = libc.closedir(dir); var windows: usize = 0; @@ -351,11 +379,6 @@ fn windowUnderPointer(job: *Job, out: *[512]u8) ?[]const u8 { return null; } -fn sleepMs(ms: u32) void { - var ts: libc.timespec = .{ .sec = 0, .nsec = @as(isize, ms) * std.time.ns_per_ms }; - _ = libc.nanosleep(&ts, null); -} - /// This program again, `-l` the dump: a new window, in a session of its own /// (setsid) and not this one's child (forked twice), so it outlives this /// window and leaves no zombie. Answers its pid. diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 5d3cbafd..9c3a1256 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -4806,7 +4806,7 @@ fn handOver(ctx: ?*anyopaque, seq: u32, bytes: []const u8) void { std.fmt.bufPrint(&job.geometry, "{d}x{d}", .{ w, h })) catch ""; job.geometry_len = geometry.len; } - Handover.start(job) catch |err| { + s.core.handover.start(s.io, job) catch |err| { _ = libc.unlink(path); s.gpa.free(path); s.gpa.destroy(job); -- cgit v1.3