summaryrefslogtreecommitdiff
path: root/core/term
diff options
context:
space:
mode:
Diffstat (limited to 'core/term')
-rw-r--r--core/term/TerminalImages.zig9
-rw-r--r--core/term/term.zig4
-rw-r--r--core/term/terminal.zig383
3 files changed, 337 insertions, 59 deletions
diff --git a/core/term/TerminalImages.zig b/core/term/TerminalImages.zig
index feba5ddc..d0d364a1 100644
--- a/core/term/TerminalImages.zig
+++ b/core/term/TerminalImages.zig
@@ -24,9 +24,6 @@ const image_decode_pixels: usize = 64 * 1024 * 1024;
/// oldest past this): a 4K picture in RGBA, with room for a second.
pub const storage_limit = 64 * 1024 * 1024;
-/// This pane asks for its images as glyph art even where pixels could be
-/// drawn (the Petscii builtin).
-petscii: bool = false,
/// Pixels in RGBA for images ghostty-vt holds in another format (RGB,
/// grey): only for images on screen, dropped the frame they are not.
/// The emulator's own allocator's, as the emulator is (`draw`'s `own`):
@@ -191,7 +188,7 @@ pub fn draw(
const bottom = pages.getBottomRight(.viewport) orelse return;
const cw: u32 = @max(1, where.cell_w);
const ch: u32 = @max(1, where.cell_h);
- const ctx: Ctx = .{ .ti = ti, .own = own, .gpa = gpa, .out = out, .pane = where.pane, .serial = where.serial, .tx = where.tx, .body_y = where.body_y, .cols = where.cols, .rows_of = rows_of, .cw = cw, .ch = ch };
+ const ctx: Ctx = .{ .ti = ti, .own = own, .gpa = gpa, .out = out, .pane = where.pane, .serial = where.serial, .tx = where.tx, .body_y = where.body_y, .cols = where.cols, .rows_of = rows_of, .cw = cw, .ch = ch, .glyph = where.petscii };
// Handed on lowest z first (the storage's order is a hash map's), the
// order a shell draws them in; equal z keeps the order they came in.
const first = out.items.len;
@@ -283,6 +280,8 @@ const Ctx = struct {
rows_of: []const ?u16,
cw: u32,
ch: u32,
+ /// Its images as glyph art (the pane's Petscii).
+ glyph: bool,
/// Draw `src` of `img` over `dst`, one cell row of it at a time: a row
/// is shown, or not, or shown elsewhere, as the body lays it out.
@@ -323,7 +322,7 @@ const Ctx = struct {
},
.key = plain.Placement.keyOf(ctx.serial, img.id, @truncate(img.generation)),
.z = z,
- .art = .{ .glyph = ctx.ti.petscii },
+ .art = .{ .glyph = ctx.glyph },
}) catch {};
}
}
diff --git a/core/term/term.zig b/core/term/term.zig
index 6e36816a..b18f5875 100644
--- a/core/term/term.zig
+++ b/core/term/term.zig
@@ -31,6 +31,8 @@ pub const ops: iface.Ops = .{
.parts = cast(iface.Ops, "parts", terminal_.parts),
.snapshot = cast(iface.Ops, "snapshot", terminal_.snapshot),
.load = cast(iface.Ops, "load", terminal_.load),
+ .reload = cast(iface.Ops, "reload", terminal_.reload),
+ .direct = cast(iface.Ops, "direct", terminal_.direct),
.feed = cast(iface.Ops, "feed", terminal_.feed),
.grid = cast(iface.Ops, "grid", terminal_.grid),
.viewTo = cast(iface.Ops, "viewTo", terminal_.viewTo),
@@ -62,8 +64,6 @@ pub const ops: iface.Ops = .{
.spanColor = terminal_.spanColor,
.paint = cast(iface.Ops, "paint", terminal_.paint),
.images = cast(iface.Ops, "images", terminal_.images),
- .petscii = cast(iface.Ops, "petscii", terminal_.petscii),
- .togglePetscii = cast(iface.Ops, "togglePetscii", terminal_.togglePetscii),
.hasImages = cast(iface.Ops, "hasImages", terminal_.hasImages),
.encoder = cast(iface.Ops, "encoder", terminal_.encoder),
.encoderFree = cast(iface.Ops, "encoderFree", terminal_.encoderFree),
diff --git a/core/term/terminal.zig b/core/term/terminal.zig
index d99cfb79..055c8981 100644
--- a/core/term/terminal.zig
+++ b/core/term/terminal.zig
@@ -181,9 +181,6 @@ pub const State = struct {
reply: [4096]u8 = undefined,
reply_len: u16 = 0,
reply_dropped: u32 = 0,
- /// The grid cell the program last heard the mouse at, so motion is
- /// reported once per cell.
- mouse_cell: ?ghostty_vt.Coordinate = null,
/// The kitty graphics its program placed, as drawn (TerminalImages.zig).
images: TerminalImages = if (images_enabled) .{} else {},
/// Counts the emulator's writes (output, a resize, its view scrolled):
@@ -198,16 +195,25 @@ pub const State = struct {
/// the step reads the grid it had, as its replicas' replays do, and the
/// rows sent them for it (Screens.fill) are of that grid's numbering.
resize_to: ?struct { cols: u16, rows: u16 } = null,
+ /// Its program's kitty images by direct data alone (`direct`): a
+ /// replica's emulator, which is not the session's. A file, a temporary
+ /// file or shared memory is the session's machine's (and a temporary
+ /// one is deleted by its first reader): its image is absent here.
+ direct: bool = false,
/// The stream over the emulator, its answers to the program and its
/// size reports routed here, PNG decoded: what `create` and a dump's
- /// load both do once the emulator is in place.
- fn wire(s: *State) void {
- s.stream = .init(.{ .handler = .{ .inner = s.vt.vtHandler() }, .allocator = s.gpa });
+ /// load both do once the emulator is in place. False when the stream's
+ /// keeper of a sequence in flight had no room (ghostty goes on without
+ /// it, swallowing the error): `open` and `load` refuse the terminal then,
+ /// as at any allocation that fails.
+ fn wire(s: *State) bool {
+ s.stream = .init(.{ .handler = .{ .inner = s.vt.vtHandler() }, .allocator = s.gpa, .continuation_max_bytes = continuation_max });
s.stream.handler.inner.effects.write_pty = ptyReport;
s.stream.handler.inner.effects.device_attributes = ptyDeviceAttrs;
s.stream.handler.inner.effects.size = ptySize;
if (comptime images_enabled) TerminalImages.installPngDecoder();
+ return s.stream.continuation.?.bytes.capacity > 0;
}
};
@@ -253,8 +259,6 @@ pub fn parts(s: *const State) Term.Parts {
return .{
.reply = s.reply[0..s.reply_len],
.reply_dropped = s.reply_dropped,
- .mouse_cell = if (s.mouse_cell) |c| .{ .x = c.x, .y = c.y } else null,
- .petscii = if (comptime images_enabled) s.images.petscii else false,
.view = s.vt.screens.active.pages.scrollbar().offset,
.phase = h.phase,
.started = h.started,
@@ -268,14 +272,42 @@ pub fn parts(s: *const State) Term.Parts {
};
}
+/// The most bytes of a sequence its program began and has not ended (a
+/// CSI, an OSC, a UTF-8 codepoint, a kitty graphics chunk: 4 KiB of payload)
+/// that its stream keeps, so a snapshot taken between any two reads carries
+/// it (`snapshot`). Past it the sequence is lost at a cut, as every one was
+/// before.
+pub const continuation_max = 64 * 1024;
+
/// Its emulator as the dump keeps it: ghostty's snapshot (both screens,
-/// their history, styles, links and kitty images). A sequence its program
-/// had begun and not ended is not kept: the snapshot is at the ground
-/// state. `slim`, a join's dump (dump.zig `dumpJoin`): its size alone, an
+/// their history, styles, links and kitty images), and the sequence its
+/// program had begun and not ended, which `load` feeds again. `slim`, a
+/// join's dump under screen state (dump.zig `dumpJoin`): its size alone, an
/// emulator made afresh there, which its first delta replaces.
pub fn snapshot(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer, slim: bool) !void {
if (slim) return w.writeAll(std.mem.asBytes(&[2]u16{ s.vt.cols, s.vt.rows }));
- try ghostty_vt.snapshot.encode(gpa, w, &s.vt, .{ .continuation = .ground });
+ var held: std.Io.Writer.Allocating = .init(gpa);
+ defer held.deinit();
+ s.stream.writeContinuation(&held.writer) catch |err| switch (err) {
+ // Longer than it keeps: lost, as at the ground state.
+ error.ContinuationUnavailable, error.ContinuationDisabled => held.clearRetainingCapacity(),
+ error.WriteFailed => return error.OutOfMemory,
+ };
+ const continuation: ghostty_vt.snapshot.Continuation = if (held.written().len > 0) .{ .bytes = held.written() } else .ground;
+ try ghostty_vt.snapshot.encode(gpa, w, &s.vt, .{ .continuation = continuation });
+}
+
+/// `snapshot`'s bytes decoded, the emulator not yet at its address.
+fn decode(gpa: std.mem.Allocator, bytes: []const u8) !ghostty_vt.snapshot.Decoded {
+ if (bytes.len == 4) {
+ const size = std.mem.bytesToValue([2]u16, bytes[0..4]);
+ return .{ .terminal = try emulator(gpa, @max(1, size[0]), @max(1, size[1]), scrollback_max), .continuation = .ground, .history_rows = .{} };
+ }
+ var reader: std.Io.Reader = .fixed(bytes);
+ return ghostty_vt.snapshot.decodeExact(gpa, terminalIo(), &reader, .{
+ .max_continuation_bytes = continuation_max,
+ .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0,
+ });
}
/// `snapshot`'s bytes and `parts` back into a new terminal, as `open`
@@ -283,28 +315,81 @@ pub fn snapshot(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer, slim
pub fn load(gpa: std.mem.Allocator, bytes: []const u8, saved: *const Term.Parts) !*State {
const out = try gpa.create(State);
errdefer gpa.destroy(out);
- var reader: std.Io.Reader = .fixed(bytes);
- if (reader.buffer.len == 4) {
- const size = std.mem.bytesToValue([2]u16, bytes[0..4]);
- out.* = .{ .gpa = gpa, .vt = try emulator(gpa, @max(1, size[0]), @max(1, size[1])), .stream = undefined };
- } else {
- var decoded = try ghostty_vt.snapshot.decodeExact(gpa, terminalIo(), &reader, .{
- .max_continuation_bytes = 0,
- .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0,
- });
- defer decoded.deinit(gpa);
- out.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined };
+ var decoded = try decode(gpa, bytes);
+ defer decoded.deinit(gpa);
+ out.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined };
+ if (!install(out, decoded.continuation, saved)) {
+ out.stream.deinit();
+ out.vt.deinit(gpa);
+ return error.OutOfMemory;
+ }
+ return out;
+}
+
+/// Its emulator made again from its own snapshot, where it is, what pardes
+/// keeps beside it kept: what a replica and its session do at a join, so
+/// that both, and the joiner loaded from the session's, hold the same pages
+/// (ghostty cuts rows into pages, and prunes whole ones, by its history,
+/// which a snapshot does not carry). The snapshot's hash, which every side
+/// compares; on an error it is as it was.
+pub fn reload(s: *State) !u64 {
+ const gpa = s.gpa;
+ var bytes: std.Io.Writer.Allocating = .init(gpa);
+ defer bytes.deinit();
+ try snapshot(s, gpa, &bytes.writer, false);
+ var decoded = try decode(gpa, bytes.written());
+ defer decoded.deinit(gpa);
+ var saved = parts(s);
+ var reply: [@typeInfo(@FieldType(State, "reply")).array.len]u8 = undefined;
+ @memcpy(reply[0..saved.reply.len], saved.reply);
+ saved.reply = reply[0..saved.reply.len];
+ const kept = .{ s.changes, s.read, s.resize_to, s.direct };
+ if (comptime images_enabled) s.images.deinit(gpa);
+ s.stream.deinit();
+ s.vt.deinit(gpa);
+ s.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined, .changes = kept[0] +% 1, .read = kept[1], .resize_to = kept[2], .direct = kept[3] };
+ // Short of room for its sequence in flight it goes on without it (lost
+ // at the next cut), as ghostty's stream does: not worth a terminal.
+ _ = install(s, decoded.continuation, &saved);
+ return joinHash(bytes.written());
+}
+
+/// What a join compares of a snapshot (`reload`): every record of it but
+/// its kitty images' (tags 8 to 10, which ghostty's framing makes optional:
+/// snapshot/record.zig, a u16 tag, a u32 length, a u32 CRC and the payload,
+/// after a 10-byte envelope): an image by file or shared memory is the
+/// session's alone (P32, `direct`), and no digest reads an image.
+fn joinHash(bytes: []const u8) u64 {
+ const envelope = 10;
+ const head = 10;
+ var h: std.hash.Wyhash = .init(0);
+ h.update(bytes[0..@min(bytes.len, envelope)]);
+ var at: usize = envelope;
+ while (at + head <= bytes.len) {
+ const tag = std.mem.readInt(u16, bytes[at..][0..2], .little);
+ const end = @min(bytes.len, at + head + std.mem.readInt(u32, bytes[at + 2 ..][0..4], .little));
+ if (tag < 8 or tag > 10) h.update(bytes[at..end]);
+ at = end;
}
+ return h.final();
+}
+
+/// A decoded emulator at its address made a terminal: its stream wired,
+/// the sequence in flight fed again, what pardes kept beside it put back;
+/// whether its stream had all the room it wanted (`wire`).
+fn install(out: *State, continuation: ghostty_vt.snapshot.Continuation, saved: *const Term.Parts) bool {
if (comptime images_enabled) inline for (.{ .primary, .alternate }) |which| {
- if (out.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = .allWithTempDir(tempDir());
+ if (out.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = if (out.direct) .direct else .allWithTempDir(tempDir());
};
- out.wire();
+ const whole = out.wire();
+ switch (continuation) {
+ .ground => {},
+ .bytes => |bytes| out.stream.nextSlice(bytes),
+ }
const reply = saved.reply[0..@min(saved.reply.len, out.reply.len)];
@memcpy(out.reply[0..reply.len], reply);
out.reply_len = @intCast(reply.len);
out.reply_dropped = saved.reply_dropped;
- out.mouse_cell = coordinate(saved.mouse_cell);
- out.images = if (images_enabled) .{ .petscii = saved.petscii } else {};
const h = &out.stream.handler;
h.phase = saved.phase;
h.started = saved.started;
@@ -321,7 +406,17 @@ pub fn load(gpa: std.mem.Allocator, bytes: []const u8, saved: *const Term.Parts)
const screen = out.vt.screens.active;
const bottom = screen.pages.scrollbar().offset;
screen.scroll(.{ .delta_row = @as(isize, @intCast(saved.view)) - @as(isize, @intCast(bottom)) });
- return out;
+ return whole;
+}
+
+/// Its program's kitty images by direct data alone from now on: the
+/// emulator of a replica that is not the session (P32).
+pub fn direct(s: *State) void {
+ if (comptime !images_enabled) return;
+ s.direct = true;
+ inline for (.{ .primary, .alternate }) |which| {
+ if (s.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = .direct;
+ }
}
/// The allocator it was opened with, its own from then on.
@@ -607,10 +702,13 @@ pub fn paste(state: ?*const State, text: []u8) [3][]const u8 {
/// 1015 urxvt, 1005 UTF-8, else X10) how, modifiers as shift+4, meta+8,
/// ctrl+16. `col`,`row` are the 0-based grid cell; a drag that left the
/// grid is reported clamped to its edge, motion only when the cell
-/// changed. Empty when the program does not hear of it.
-pub fn mouse(state: *State, buf: *[64]u8, action: Term.MouseAction, button: ?Term.MouseButton, mods: Term.MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 {
+/// changed from `last`, the cell it last heard of (its pane's, which a
+/// rollback puts back). Empty when the program does not hear of it.
+pub fn mouse(state: *State, last: *?Term.Parts.Coordinate, buf: *[64]u8, action: Term.MouseAction, button: ?Term.MouseButton, mods: Term.MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 {
const input = ghostty_vt.input;
var writer = std.Io.Writer.fixed(buf);
+ var cell = coordinate(last.*);
+ defer last.* = if (cell) |c| .{ .x = c.x, .y = c.y } else null;
var opts: input.MouseEncodeOptions = .{
.event = state.vt.flags.mouse_event,
.format = state.vt.flags.mouse_format,
@@ -620,7 +718,7 @@ pub fn mouse(state: *State, buf: *[64]u8, action: Term.MouseAction, button: ?Ter
.padding = .{},
},
.any_button_pressed = any_pressed,
- .last_cell = &state.mouse_cell,
+ .last_cell = &cell,
};
// A release is always reported; the rest only over the grid, or held.
if (action == .release) opts.any_button_pressed = true;
@@ -649,7 +747,7 @@ pub fn mouse(state: *State, buf: *[64]u8, action: Term.MouseAction, button: ?Ter
/// program: its mouse report while it tracks the mouse, else, on the
/// alternate screen, an arrow key in the cursor keys' mode (none for a
/// sideways turn). Null when the wheel is not the program's (`Modes.wheel`).
-pub fn wheel(state: *State, buf: *[64]u8, turn: Term.MouseButton, col: u16, row: u16, mods: Term.MouseMods) ?[]const u8 {
+pub fn wheel(state: *State, last: *?Term.Parts.Coordinate, buf: *[64]u8, turn: Term.MouseButton, col: u16, row: u16, mods: Term.MouseMods) ?[]const u8 {
const now = modes(state);
if (!now.wheel) return null;
const m = &state.vt.modes;
@@ -658,7 +756,7 @@ pub fn wheel(state: *State, buf: *[64]u8, turn: Term.MouseButton, col: u16, row:
.wheel_down => if (m.get(.cursor_keys)) "\x1bOB" else "\x1b[B",
else => null,
};
- return mouse(state, buf, .press, turn, mods, col, row, false);
+ return mouse(state, last, buf, .press, turn, mods, col, row, false);
}
/// The whole scrollback as plain text, `gpa`-owned: what a terminal's body
@@ -731,11 +829,14 @@ pub fn close(state: *State) void {
}
/// A terminal pane's emulator, `cols` by `rows`, as `open` makes one.
-fn emulator(gpa: std.mem.Allocator, cols: u16, rows: u16) !ghostty_vt.Terminal {
+/// How much history a terminal keeps, in bytes of ghostty's pages.
+const scrollback_max = 16 * 1024 * 1024;
+
+fn emulator(gpa: std.mem.Allocator, cols: u16, rows: u16, history: usize) !ghostty_vt.Terminal {
return ghostty_vt.Terminal.init(terminalIo(), gpa, .{
.cols = cols,
.rows = rows,
- .max_scrollback_bytes = 16 * 1024 * 1024,
+ .max_scrollback_bytes = history,
.kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0,
// Every kitty medium, as ghostty and kitty take them: a file (t=f),
// a temporary file it then deletes (t=t, in the temp directory and
@@ -750,12 +851,22 @@ fn emulator(gpa: std.mem.Allocator, cols: u16, rows: u16) !ghostty_vt.Terminal {
/// A new emulator, `cols` by `rows`, allocated with `gpa`, its own from
/// then on (`State.gpa`).
pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State {
+ return openKeeping(gpa, cols, rows, scrollback_max);
+}
+
+/// `open`, keeping `history` bytes of history (the tests below fill a
+/// smaller one).
+fn openKeeping(gpa: std.mem.Allocator, cols: u16, rows: u16, history: usize) !*State {
const state = try gpa.create(State);
errdefer gpa.destroy(state);
// Every other field its default, never what the heap had: a digest
// reads them, and two replicas must agree (core/replica.zig).
- state.* = .{ .gpa = gpa, .vt = try emulator(gpa, cols, rows), .stream = undefined };
- state.wire();
+ state.* = .{ .gpa = gpa, .vt = try emulator(gpa, cols, rows, history), .stream = undefined };
+ if (!state.wire()) {
+ state.stream.deinit();
+ state.vt.deinit(gpa);
+ return error.OutOfMemory;
+ }
return state;
}
@@ -1456,21 +1567,6 @@ pub fn due(state: *const State) ?u64 {
return state.images.animation_due_ms;
}
-/// The Petscii builtin on a terminal: its kitty graphics as glyph art,
-/// or back to pixels where the shell draws pixels.
-pub fn togglePetscii(state: *State) void {
- if (comptime !images_enabled) return;
- state.images.petscii = !state.images.petscii;
-}
-
-/// Whether the pane draws its kitty graphics as glyph art by choice; null
-/// for a pane with no emulator.
-pub fn petscii(maybe: ?*const State) ?bool {
- if (comptime !images_enabled) return null;
- const state = maybe orelse return null;
- return state.images.petscii;
-}
-
/// Whether the screen showing holds any kitty graphics image.
pub fn hasImages(maybe: ?*const State) bool {
if (comptime !images_enabled) return false;
@@ -1522,3 +1618,186 @@ test "the luminance table answers exactly what ghostty computes" {
}
}
}
+
+/// Its snapshot as the dump writes it, `gpa`'s (the tests below).
+fn snapshotOf(gpa: std.mem.Allocator, s: *const State) ![]u8 {
+ var out: std.Io.Writer.Allocating = .init(gpa);
+ errdefer out.deinit();
+ try snapshot(s, gpa, &out.writer, false);
+ return out.toOwnedSlice();
+}
+
+/// Two terminals as a replica compares them: their snapshots' bytes, what
+/// pardes keeps beside the emulator, and the digest.
+fn expectSame(gpa: std.mem.Allocator, a: *const State, b: *const State) !void {
+ const x = try snapshotOf(gpa, a);
+ defer gpa.free(x);
+ const y = try snapshotOf(gpa, b);
+ defer gpa.free(y);
+ try std.testing.expectEqualSlices(u8, x, y);
+ var ma: [marks_len]u8 = undefined;
+ var mb: [marks_len]u8 = undefined;
+ try std.testing.expectEqualSlices(u8, marksOf(a, &ma), marksOf(b, &mb));
+ try std.testing.expectEqualSlices(u8, a.reply[0..a.reply_len], b.reply[0..b.reply_len]);
+ var ha: std.hash.Wyhash = .init(0);
+ var hb: std.hash.Wyhash = .init(0);
+ digest(a, &ha, true);
+ digest(b, &hb, true);
+ try std.testing.expectEqual(ha.final(), hb.final());
+}
+
+test "a snapshot taken inside a sequence carries it: over pardes's own handler the load continues as the terminal fed whole" {
+ // ghostty promises the continuation for its standard handler; pardes's
+ // MarkedHandler wraps it (OSC 133 marks, erases): cut at every byte of
+ // a CSI, an OSC (a link, pardes's own marks), a UTF-8 codepoint, a
+ // kitty graphics payload (APC) and a device query.
+ const gpa = std.testing.allocator;
+ const streams = [_][]const u8{
+ "a\x1b[38;2;10;20;30mcolour\x1b[0m b",
+ "\x1b]8;;https://example.com/x\x1b\\link\x1b]8;;\x1b\\ c",
+ "x\u{1F469}\u{200D}\u{1F4BB}y \u{6F22}\u{5B57} \u{E9}",
+ "\x1b_Ga=T,i=7,f=24,s=1,v=1;AAAA\x1b\\ after",
+ "\x1b]133;A;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07ls\r\n\x1b]133;C;aid=pardes\x07out\r\n\x1b]133;D;0;aid=pardes\x07",
+ "q\x1b[6n\x1b[c\x1b[16t z",
+ };
+ for (streams) |stream| for (1..stream.len) |cut| {
+ const whole = try open(gpa, 24, 5);
+ defer close(whole);
+ whole.stream.nextSlice(stream[0..cut]);
+ whole.stream.nextSlice(stream[cut..]);
+ const cutting = try open(gpa, 24, 5);
+ defer close(cutting);
+ cutting.stream.nextSlice(stream[0..cut]);
+ const bytes = try snapshotOf(gpa, cutting);
+ defer gpa.free(bytes);
+ const loaded = try load(gpa, bytes, &parts(cutting));
+ defer close(loaded);
+ loaded.stream.nextSlice(stream[cut..]);
+ expectSame(gpa, whole, loaded) catch |err| {
+ std.debug.print("cut at byte {d} of {f}\n", .{ cut, std.ascii.hexEscape(stream, .lower) });
+ return err;
+ };
+ };
+}
+
+/// What the join tests below stream: plain text, a build's log, and heavy
+/// colour and links (a truecolour a cell, a link a word, marks piled on
+/// letters, wide characters: what runs a page out of room for styles,
+/// links and graphemes), `lines` of it, no clear.
+const Corpus = enum { text, logs, heavy };
+
+fn corpus(gpa: std.mem.Allocator, which: Corpus, lines: usize) ![]u8 {
+ var out: std.Io.Writer.Allocating = .init(gpa);
+ errdefer out.deinit();
+ const w = &out.writer;
+ var prng: std.Random.DefaultPrng = .init(@as(u64, @intFromEnum(which)) + 11);
+ const random = prng.random();
+ const words = [_][]const u8{ "the", "quick", "brown", "fox", "jumps", "over", "a", "lazy", "dog", "./core/replica.zig:1234:", "error:", "expected", "\u{6F22}\u{5B57}", "na\u{EF}ve" };
+ for (0..lines) |i| switch (which) {
+ .text => {
+ for (0..random.uintLessThan(usize, 18)) |_| try w.print("{s} ", .{words[random.uintLessThan(usize, words.len)]});
+ try w.print("{d}\r\n", .{i});
+ },
+ .logs => try w.print("[{d:>3}%] \x1b[32mBuilding CXX object\x1b[0m src/CMakeFiles/core.dir/module_{d}.cpp.o{s}\r\n", .{ i * 100 / lines, i, if (i % 9 == 0) " \x1b[1;33mwarning:\x1b[0m unused variable" else "" }),
+ .heavy => switch (i % 3) {
+ 0 => {
+ for (0..100) |x| try w.print("\x1b[38;2;{d};{d};{d}m{c}", .{ (i * 7 + x * 3) % 256, (i * 13 + x * 5) % 256, (x * 11 + i) % 256, @as(u8, @intCast(97 + (x + i) % 26)) });
+ try w.writeAll("\x1b[0m\r\n");
+ },
+ 1 => {
+ for (0..18) |x| try w.print("\x1b]8;;https://example.com/{d}/{d}\x1b\\w{d}\x1b]8;;\x1b\\ ", .{ i, x, x });
+ try w.writeAll("\r\n");
+ },
+ else => {
+ for (0..40) |x| {
+ try w.writeByte(@intCast(97 + (x + i) % 26));
+ for (0..1 + x % 6) |j| try w.print("{u}", .{@as(u21, @intCast(0x300 + (x * 3 + j + i) % 0x6f))});
+ }
+ try w.writeAll(" \u{6F22}\u{5B57}\u{6F22}\u{5B57} \u{1F469}\u{200D}\u{1F4BB}\r\n");
+ },
+ },
+ };
+ return out.toOwnedSlice();
+}
+
+/// `bytes[from..to]` fed in reads of 4 KiB, and two reflows on the way
+/// at `stops` (to a little over half the width and three rows taller, then
+/// back), as the join tests' every side takes them.
+fn feedReflowing(s: *State, bytes: []const u8, from: usize, to: usize, stops: [2]usize) void {
+ const cols = s.vt.cols;
+ const rows = s.vt.rows;
+ var at = from;
+ while (at < to) {
+ if (at == stops[0]) resize(s, cols / 2 + 1, rows + 3, false);
+ if (at == stops[1]) resize(s, cols * 2 - 2, rows - 3, false);
+ var end = @min(to, at + 4096);
+ for (stops) |stop| if (at < stop and stop < end) {
+ end = stop;
+ };
+ s.stream.nextSlice(bytes[at..end]);
+ at = end;
+ }
+}
+
+fn sameSnapshot(gpa: std.mem.Allocator, a: *const State, b: *const State) !bool {
+ const x = try snapshotOf(gpa, a);
+ defer gpa.free(x);
+ const y = try snapshotOf(gpa, b);
+ defer gpa.free(y);
+ return std.mem.eql(u8, x, y);
+}
+
+test "a join at a cut: every side reloaded from its own snapshot holds the same terminal as the joiner, after more bytes and after two reflows; a joiner nobody reloaded for with heavy colour does not" {
+ // The sizing pass's join check (reports/pardes-term-bytes.md, section 2)
+ // in the tree: a scrollback past its limit (pruned a page at a time,
+ // by the history of its pages), cut at a random read boundary, often
+ // inside a sequence.
+ const gpa = std.testing.allocator;
+ var prng: std.Random.DefaultPrng = .init(29);
+ const random = prng.random();
+ var heavy_apart: usize = 0;
+ for ([_]Corpus{ .text, .logs, .heavy }, [_]usize{ 6000, 6000, 3000 }) |which, lines| {
+ const bytes = try corpus(gpa, which, lines);
+ defer gpa.free(bytes);
+ for (0..2) |_| {
+ const cut = bytes.len / 3 + random.uintLessThan(usize, bytes.len / 3);
+ const mid = cut + (bytes.len - cut) / 2;
+ const stops: [2]usize = .{ mid + (bytes.len - mid) / 3, mid + 2 * (bytes.len - mid) / 3 };
+ // The session, and a replica that was there from the start.
+ const session = try openKeeping(gpa, 120, 40, 1 << 20);
+ defer close(session);
+ const there = try openKeeping(gpa, 120, 40, 1 << 20);
+ defer close(there);
+ feedReflowing(session, bytes, 0, cut, stops);
+ feedReflowing(there, bytes, 0, cut, stops);
+ // The same join made without the reload: the session as it
+ // would go on, and a joiner loaded from its snapshot.
+ const lineage = try openKeeping(gpa, 120, 40, 1 << 20);
+ defer close(lineage);
+ feedReflowing(lineage, bytes, 0, cut, stops);
+ const before = try snapshotOf(gpa, session);
+ defer gpa.free(before);
+ const unreloaded = try load(gpa, before, &parts(session));
+ defer close(unreloaded);
+ // The join as it is made: every side reloads, the joiner loads
+ // the session's snapshot taken after (the join's dump).
+ const hash = try reload(session);
+ try std.testing.expectEqual(hash, try reload(there));
+ try std.testing.expectEqual(hash, joinHash(before));
+ const after = try snapshotOf(gpa, session);
+ defer gpa.free(after);
+ const joiner = try load(gpa, after, &parts(session));
+ defer close(joiner);
+ for ([_]*State{ session, there, joiner, unreloaded, lineage }) |s| feedReflowing(s, bytes, cut, mid, stops);
+ try expectSame(gpa, session, there);
+ try expectSame(gpa, session, joiner);
+ if (!try sameSnapshot(gpa, lineage, unreloaded)) heavy_apart += @intFromBool(which == .heavy);
+ for ([_]*State{ session, there, joiner }) |s| feedReflowing(s, bytes, mid, bytes.len, stops);
+ try expectSame(gpa, session, there);
+ try expectSame(gpa, session, joiner);
+ }
+ }
+ // The fault the reload mends is real: a joiner nobody reloaded for is
+ // another terminal once heavy colour has pruned pages cut otherwise.
+ try std.testing.expectEqual(2, heavy_apart);
+}