summaryrefslogtreecommitdiff
path: root/src/Handover.zig
blob: fdbe509bd016e1332f3fe460f8c26325b4bc3ef0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
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);
}