diff options
Diffstat (limited to 'core/Handover.zig')
| -rw-r--r-- | core/Handover.zig | 698 |
1 files changed, 698 insertions, 0 deletions
diff --git a/core/Handover.zig b/core/Handover.zig new file mode 100644 index 00000000..5347fb95 --- /dev/null +++ b/core/Handover.zig @@ -0,0 +1,698 @@ +//! 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 (`Carried`, each pane as dump.savePane makes it, in +//! the image of one dump, `handover-<seq>`: Db.zig), 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). +//! 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 <dump>` (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`, 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"); +const builtin = @import("builtin"); +const pardes = @import("root.zig"); +const layout = @import("layout.zig"); +const dump = @import("dump.zig"); +const ninep_io = @import("runtime").ninep_io; +const panes = @import("panes.zig"); +const tagline = @import("tagline.zig"); +const walk = @import("walk.zig"); +const Pardes = pardes.Pardes; +const MAX_PANES = pardes.MAX_PANES; +/// libc: fork and exec of a window, and file calls in the cancelable carry task that must not see its cancel (its defer's unlink). +const libc = std.c; + +/// What a grip carries out of its window: one pane with the panes attached +/// to it, or a whole column. +pub const Kind = enum { pane, column }; + +/// What a handover's image holds, as its root `carried` (a build before +/// the image's, 0.24, wrote `carried_magic`, then this as a byte dump). +const Carried = struct { + kind: Kind, + /// A carried column's tag. + tag: ?[]const u8 = null, + /// Each pane as dump.savePane makes it, top to bottom. + panes: []const []const u8, + weights: []const f32, + /// Which of them each one is attached to (layout.zig, "Attached panes"). + owners: []const ?u32, +}; +pub const carried_magic = "pardes-carried\n"; + +/// 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: Kind = .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, +/// 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, + +/// The dump in flight and its carrier are the host's errand, not the +/// session's (core/walk.zig). +pub const replica = .{ .authority = .{ "bytes", "task" } }; + +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; +} + +/// 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: Kind, at: usize) void { + const v = p.view(); + 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 (v.cols[f.col].panes[f.idx..end]) |id| { + ids[n] = id; + n += 1; + } + }, + .column => { + if (at >= v.ncol or v.cols[at].n == 0) return; + for (v.cols[at].panes[0..p.view().cols[at].n]) |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"); + } + const bytes = dumpCarried(p, carried, at, ids[0..n], h.seq +% 1) 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 { + const v = p.view(); + 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| { + const at = p.paneBySerial(h.serials[0]) orelse v.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; + // 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].?; + 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 (v.cols[c].n == 0 and v.ncol > 1) layout.dropColumn(p, c); + }; + layout.compute(p); + p.setMessage(v.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 dump of panes `ids` (gpa's), carried as `kind` from column `at`'s +/// (a pane's, `at` is its slot): an image of one dump, handover `seq`. +fn dumpCarried(p: *Pardes, kind: Kind, at: usize, ids: []const usize, seq: u32) ![]u8 { + const arena = p.scratch.allocator(); + const bytes = try arena.alloc([]const u8, ids.len); + const weights = try arena.alloc(f32, ids.len); + const owners = try arena.alloc(?u32, ids.len); + for (ids, 0..) |id, i| { + const pane = p.panes[id].?; + bytes[i] = try dump.savePane(arena, pane, false); + weights[i] = pane.vweight; + const owner = layout.ownerOf(p, id); + owners[i] = if (owner) |o| if (std.mem.indexOfScalar(usize, ids, o)) |k| @intCast(k) else null else null; + } + const value: Carried = .{ + .kind = kind, + .tag = if (kind == .column) p.view().col_tags[at].own else null, + .panes = bytes, + .weights = weights, + .owners = owners, + }; + var buf: std.Io.Writer.Allocating = .init(p.gpa); + defer buf.deinit(); + var db = try walk.Mem.init(std.Io.failing, .{ .buffer = &buf, .file_id = 0 }); + var w: walk.Put = .{ .gpa = p.gpa }; + defer w.deinit(); + try db.runContext(struct { + w: *walk.Put, + value: *const Carried, + pub fn run(ctx: @This(), cursor: *walk.Mem.Cursor(.read_write)) !void { + try ctx.w.member(try walk.Mem.HashMap(.read_write).init(cursor.*), "carried", Carried, ctx.value); + } + }{ .w = &w, .value = &value }); + var name: [32]u8 = undefined; + return pardes.Db.image(p.gpa, std.fmt.bufPrint(&name, "handover-{d}", .{seq}) catch unreachable, buf.written(), w.blobs.items, ids.len, ""); // a u32 fits 32 +} + +/// Whether `bytes` are a handover's dump (`dumpCarried`'s, or an older +/// build's), not a session's. +pub fn carries(gpa: std.mem.Allocator, bytes: []const u8) bool { + if (std.mem.startsWith(u8, bytes, carried_magic)) return true; + if (!pardes.Db.isImage(bytes)) return false; + const r = pardes.Db.Read.open(gpa, bytes, null) catch return false; + defer r.close(); + return (walk.Get.member(r.root(), "carried") catch null) != null; +} + +/// The carried panes in `bytes`, made in `a`. +fn readCarried(a: std.mem.Allocator, bytes: []const u8) !Carried { + if (pardes.Db.isImage(bytes)) { + const r = pardes.Db.Read.open(a, bytes, null) catch return error.NotCarried; + defer r.close(); + const at = (walk.Get.member(r.root(), "carried") catch return error.NotCarried) orelse return error.NotCarried; + var l: walk.Get = .init(a); + defer l.deinit(); + return l.get(Carried, at) catch error.NotCarried; + } + if (!std.mem.startsWith(u8, bytes, carried_magic)) return error.NotCarried; + return walk.load(Carried, a, bytes[carried_magic.len..], null); +} + +// ---- 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 arena: std.heap.ArenaAllocator = .init(p.gpa); + defer arena.deinit(); + const st = try readCarried(arena.allocator(), bytes); + const carried = st.kind; + if (st.panes.len == 0 or st.weights.len != st.panes.len or st.owners.len != st.panes.len) return error.NotCarried; + // Where the pointer is, else the middle of the pane with the keyboard. + layout.compute(p); + const here = p.view().rects[p.view().active]; + const x = if (p.view().pointer_inside) p.view().hover_col else here.x + here.w / 2; + const y = if (p.view().pointer_inside) p.view().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 (st.panes) |one| { + const slot = p.freeSlot() orelse return error.TooManyPanes; + const pane = try dump.loadPane(p, slot, one); + slots[n] = slot; + n += 1; + if (pane.file == null) return error.NotText; + } + // An attachment names its owner by its place in the dump. + for (st.owners, 0..) |owner, k| { + const at = owner orelse continue; + if (at >= n) 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.view().ncol == 0) { + const c = if (p.view().ncol == 0) layout.insertColumn(p, 0, false) else layout.insertColumn(p, tc, x < p.view().col_x[tc] + p.view().col_w[tc] / 2); + const col = c orelse return error.NoRoom; + if (carried == .column) if (st.tag) |tag| { + p.view().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.weights[k]; + } + p.view().active = slots[0]; + p.setActiveColumn(col); + p.sync(); + return slots[0]; + } + for (0..p.view().ncol) |c| for (p.view().cols[c].panes[0..p.view().cols[c].n]) |id| { + heights[id] = p.view().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.view().cols[tc].n; + var root: ?usize = null; + var k: usize = 0; + while (k < p.view().cols[tc].n) { + const end = layout.groupEnd(p, tc, k); + const first = p.view().cols[tc].panes[k]; + const last = p.view().cols[tc].panes[end - 1]; + root = first; + after = end; + if (y < p.view().rects[last].y + p.view().rects[last].h) break; + k = end; + } + if (root) |owner| { + const r = p.view().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 (st.weights) |w| total += w; + 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.weights[j] / @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.view().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 +/// 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, + /// 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 +/// 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}.xitdb", .{ dir, libc.getpid(), seq }, 0); +} + +/// 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(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 { + if (!for_child) _ = libc.unlink(job.path); + job.gpa.free(job.path); + 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; + 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.Io.Dir.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"); + } + // A runtime directory a window's socket cannot be made in (9p_io's + // `<dir>/pardes-9p-<pid>.sock.<pid>`, a pid at most 7 digits) is said + // before a window is made that could never answer. + const run = std.mem.span(libc.getenv("XDG_RUNTIME_DIR") orelse ""); + if (run.len + "/pardes-9p-.sock.".len + 2 * "4194304".len + 1 > ninep_io.sun_path_len) + return job.post(job.post_ctx, job.seq, false, std.fmt.bufPrint(&words, "no new window: XDG_RUNTIME_DIR is {d} bytes, too long for its 9P socket", .{run.len}) catch unreachable); // a number fits 256 + 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 entry = std.fmt.bufPrint(&entry_buf, "{s}/9p/pardes/{d}", .{ run, pid }) catch unreachable; // under sun_path, checked above + var waited: u32 = 0; + while (waited < 15_000) : (waited += 50) { + if (libc.kill(pid, @fromBackingInt(@intCast(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 unreachable); // a pid fits 256 + } else |_| {} + 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"); +} + +/// 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(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) try io.sleep(.fromMilliseconds(40), .awake); + const dir = libc.opendir(reg) orelse return null; + defer _ = libc.closedir(dir); + var windows: usize = 0; + while (libc.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; +} + +/// 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 ---- + +extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; + +/// 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.view().active, "New")); + p.sync(); + return p; +} + +fn releaseOutside(p: *Pardes, id: usize) void { + const v = p.view(); + const r = v.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 = v.screen_w - 1, .row = r.y + 1 } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = v.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.view().cols[f.col].n == 2); + const other = p.view().cols[f.col].panes[1 - f.idx]; + const before = p.view().rects[other]; + releaseOutside(p, 0); + // Dumped and asked for; nothing moved yet. + try std.testing.expect(p.handover.flying); + try std.testing.expect(p.view().drag == .none); + try std.testing.expect(p.panes[0] != null); + try std.testing.expectEqual(before, p.view().rects[other]); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const carried = try readCarried(arena.allocator(), p.handover.bytes.?); + try std.testing.expectEqual(Kind.pane, carried.kind); + try std.testing.expectEqual(@as(usize, 1), carried.panes.len); + const pane = try walk.load(pardes.Pane, arena.allocator(), carried.panes[0], null); + try std.testing.expectEqualStrings("/test.txt", pane.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); + // 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.view().cols[layout.findPane(p, other).?.col].n); +} + +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" { + if (pardes.Term.ops == null) return error.SkipZigTest; // the classic boot's three shells + 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.view().cols[1].panes[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); +} + +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.view().rects; + const c = layout.findPane(to, 0).?.col; + const upper = to.view().cols[c].panes[0]; + const lower = to.view().cols[c].panes[1]; + // The pointer over the upper pane, six rows into it. + to.view().pointer_inside = true; + to.view().hover_col = to.view().rects[upper].x + 5; + to.view().hover_row = to.view().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.view().cols[c].panes[0]); + try std.testing.expectEqual(id, to.view().cols[c].panes[1]); + try std.testing.expectEqual(lower, to.view().cols[c].panes[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.view().rects[upper].y); + try std.testing.expectEqual(@as(u16, 7), to.view().rects[upper].h); + try std.testing.expectEqual(before[upper].y + 7, to.view().rects[id].y); + try std.testing.expectEqual(before[upper].h - 7, to.view().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.view().rects[k]); + try std.testing.expectEqual(id, to.view().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.view().rects[0]; + const c = layout.findPane(from, 0).?.col; + from.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = from.view().col_x[c], .row = from.topBarHeight() } }); + from.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = from.view().screen_w - 1, .row = r.y } }); + from.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = from.view().screen_w - 1, .row = r.y, .outside = true } }); + try std.testing.expect(from.handover.flying); + try std.testing.expectEqual(Kind.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.view().active, "Newcol")); + to.sync(); + const ncol = to.view().ncol; + const widths = to.view().col_w; + const xs = to.view().col_x; + // Over the right half of the last column: the new one goes after it. + to.view().pointer_inside = true; + to.view().hover_col = to.view().col_x[ncol - 1] + to.view().col_w[ncol - 1] - 2; + to.view().hover_row = 10; + const id = try adopt(to, from.handover.bytes.?); + to.sync(); + try std.testing.expectEqual(ncol + 1, to.view().ncol); + try std.testing.expectEqual(ncol, layout.findPane(to, id).?.col); + try std.testing.expectEqual(@as(usize, 2), to.view().cols[ncol].n); + for (0..ncol - 1) |k| { + try std.testing.expectEqual(widths[k], to.view().col_w[k]); + try std.testing.expectEqual(xs[k], to.view().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.view().ncol == 1 or from.view().cols[c].n == 0 or layout.findPane(from, 0) == null); +} + +test "a handover under a runtime directory too long for a window's socket is refused in words, no window made" { + if (comptime builtin.os.tag != .linux) return error.SkipZigTest; + const gpa = std.testing.allocator; + const Said = struct { + var ok: ?bool = null; + var buf: [256]u8 = undefined; + var len: usize = 0; + fn post(_: ?*anyopaque, _: u32, ok_: bool, words: []const u8) void { + ok = ok_; + len = @min(words.len, buf.len); + @memcpy(buf[0..len], words[0..len]); + } + }; + const old = if (libc.getenv("XDG_RUNTIME_DIR")) |v| try gpa.dupeSentinel(u8, std.mem.span(v), 0) else null; + defer if (old) |v| { + _ = setenv("XDG_RUNTIME_DIR", v, 1); + gpa.free(v); + } else { + _ = @import("dev").host_io.testUnsetenv("XDG_RUNTIME_DIR"); + }; + // The ledger's case, past 490 bytes, and one past sun_path alone. + for ([_]usize{ 600, 100 }) |n| { + var dir_buf: [601:0]u8 = undefined; + @memset(dir_buf[0..n], 'r'); + dir_buf[0] = '/'; + dir_buf[n] = 0; + try std.testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", dir_buf[0..n :0], 1)); + const job = try gpa.create(Job); + job.* = .{ .gpa = gpa, .seq = 1, .path = try gpa.dupeSentinel(u8, "/nonexistent/pardes-handover.xitdb", 0), .post = Said.post, .post_ctx = null }; + Said.ok = null; + carry(std.testing.io, job); + try std.testing.expectEqual(@as(?bool, false), Said.ok); + try std.testing.expect(std.mem.indexOf(u8, Said.buf[0..Said.len], "XDG_RUNTIME_DIR is") != null); + } +} |
