summaryrefslogtreecommitdiff
path: root/src/Handover.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/Handover.zig')
-rw-r--r--src/Handover.zig571
1 files changed, 571 insertions, 0 deletions
diff --git a/src/Handover.zig b/src/Handover.zig
new file mode 100644
index 00000000..6124e49f
--- /dev/null
+++ b/src/Handover.zig
@@ -0,0 +1,571 @@
+//! 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).
+//! 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("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;
+
+/// 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,
+/// 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;
+}
+
+/// 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;
+ // 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 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;
+ // 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 (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 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
+/// 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}.zon", .{ 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.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.
+ 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 |_| {}
+ 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");
+}
+
+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(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(&reg_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 (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 ----
+
+/// 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);
+ // 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]);
+}
+
+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);
+}
+
+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);
+}