summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--abi/term.zig13
-rw-r--r--build/patches.zig37
-rw-r--r--build/patches/ghostty_kitty.zig21
-rw-r--r--core/Term.zig22
-rw-r--r--core/replica.zig49
-rw-r--r--core/tape.zig9
-rw-r--r--core/term/term.zig2
-rw-r--r--core/term/terminal.zig27
-rw-r--r--docs/ghostty-kitty-medium.md57
9 files changed, 211 insertions, 26 deletions
diff --git a/abi/term.zig b/abi/term.zig
index 37519309..187b99e5 100644
--- a/abi/term.zig
+++ b/abi/term.zig
@@ -308,6 +308,14 @@ pub const Parts = struct {
/// What reading its text can fail with.
pub const TextError = error{ OutOfMemory, WriteFailed, UnknownPoint };
+/// How a kitty image's medium is had (a file, a temporary file, shared
+/// memory: things of the session's machine): `read(ctx)` is the emulator's
+/// own read (which deletes a temporary file and unlinks shared memory),
+/// its bytes `gpa`'s (core/Term.zig `media`).
+pub const Media = *const fn (ctx: *const anyopaque, read: *const fn (ctx: *const anyopaque) MediumError![]u8, gpa: std.mem.Allocator) MediumError![]u8;
+/// What ghostty's loader fails a medium's read with.
+pub const MediumError = error{ OutOfMemory, InvalidData, UnsupportedMedium, DimensionsTooLarge, TemporaryFileNotInTempDir, TemporaryFileNotNamedCorrectly };
+
/// The entries, as `term.ops` gives them. An error set named here is what
/// the core's callers name (the tape's `Failure` reads `open`'s, the text
/// readers' are edit.zig's); `anyerror` where the core only passes one on
@@ -347,8 +355,9 @@ pub const Ops = struct {
/// Its emulator made again from its own snapshot where it is (a join:
/// every side does it); the snapshot's hash.
reload: *const fn (s: *State) anyerror!u64,
- /// Its program's kitty images by direct data alone (a replica's).
- direct: *const fn (s: *State) void,
+ /// How every terminal in the process has a kitty image's medium from
+ /// now on (the core's: a recorded answer).
+ media: *const fn (read: Media) void,
// ---- output and view ----
/// One read of its program's output (`Told` says where the tracked
diff --git a/build/patches.zig b/build/patches.zig
index 3d956d26..7c7b2d60 100644
--- a/build/patches.zig
+++ b/build/patches.zig
@@ -213,8 +213,45 @@ pub fn zstbi(b: *std.Build, patch: *std.Build.Step.Compile, zstbi_dep: *std.Buil
/// - an image may be no larger than a screen's storage
/// (TerminalImages.storage_limit) rather than ghostty's 400 MB, which a
/// program could make pardes read and hold before refusing it.
+/// - a medium's bytes (t=f, t=t, t=s) are had through `read_medium` when
+/// the host sets one, which is handed ghostty's own read: pardes makes
+/// that read a recorded answer, so a session reads a file once (deletes
+/// a temporary file, unlinks shared memory, once) and every replica of
+/// it is handed the same bytes or the same failure, never reading its
+/// own machine (core/Term.zig `media`; docs/ghostty-kitty-medium.md).
const ghostty_kitty = [_]Edit{
.{
+ .old = " /// Initialize a chunked immage from the first image transmission.\n",
+ .new =
+ \\ /// pardes (build/patches.zig): how a file's, a temporary file's or
+ \\ /// shared memory's bytes are had: `read(ctx)` is ghostty's own read
+ \\ /// (which deletes a temporary file and unlinks shared memory), its
+ \\ /// bytes `alloc`'s; null, it is made as it is.
+ \\ pub var read_medium: ?*const fn (ctx: *const anyopaque, read: *const fn (ctx: *const anyopaque) MediumError![]u8, alloc: Allocator) MediumError![]u8 = null;
+ \\ pub const MediumError = error{ OutOfMemory, InvalidData, UnsupportedMedium, DimensionsTooLarge, TemporaryFileNotInTempDir, TemporaryFileNotNamedCorrectly };
+ \\
+ \\ /// Initialize a chunked immage from the first image transmission.
+ \\
+ ,
+ },
+ .{
+ .old =
+ \\ switch (t.medium) {
+ \\ .direct => unreachable, // handled above
+ \\ .file => try result.readFile(.file, io, alloc, t, cmd.data),
+ \\ .temporary_file => try result.readFile(.temporary_file, io, alloc, t, cmd.data),
+ \\ .shared_memory => try result.readSharedMemory(io, alloc, t, cmd.data),
+ \\ }
+ \\
+ ,
+ .new =
+ \\ // pardes (build/patches.zig): through the host's `read_medium`.
+ \\ const medium: PardesMedium = .{ .loading = &result, .io = io, .alloc = alloc, .t = t, .path = cmd.data };
+ \\ result.data = .fromOwnedSlice(if (read_medium) |read| try read(&medium, PardesMedium.read, alloc) else try PardesMedium.read(&medium));
+ \\
+ ,
+ },
+ .{
.old = "const max_size = 400 * 1024 * 1024; // 400MB",
.new = "const max_size = 64 * 1024 * 1024; // pardes (build.zig): a screen's storage, TerminalImages.storage_limit",
},
diff --git a/build/patches/ghostty_kitty.zig b/build/patches/ghostty_kitty.zig
index a86d62d3..870c51e1 100644
--- a/build/patches/ghostty_kitty.zig
+++ b/build/patches/ghostty_kitty.zig
@@ -13,3 +13,24 @@ fn pardesOpenRegular(io: std.Io, path: []const u8) !std.Io.File {
const same = std.fmt.bufPrint(&buf, "/proc/self/fd/{d}", .{probe.handle}) catch unreachable;
return std.Io.Dir.cwd().openFile(io, same, .{});
}
+
+/// pardes (build.zig): a medium's read as ghostty makes it, handed to the
+/// host's `LoadingImage.read_medium`: its bytes, the caller's.
+const PardesMedium = struct {
+ loading: *LoadingImage,
+ io: std.Io,
+ alloc: Allocator,
+ t: command.Transmission,
+ path: []const u8,
+
+ fn read(ctx: *const anyopaque) LoadingImage.MediumError![]u8 {
+ const m: *const PardesMedium = @ptrCast(@alignCast(ctx));
+ switch (m.t.medium) {
+ .direct => unreachable, // read by the caller
+ .file => try m.loading.readFile(.file, m.io, m.alloc, m.t, m.path),
+ .temporary_file => try m.loading.readFile(.temporary_file, m.io, m.alloc, m.t, m.path),
+ .shared_memory => try m.loading.readSharedMemory(m.io, m.alloc, m.t, m.path),
+ }
+ return m.loading.data.toOwnedSlice(m.alloc);
+ }
+};
diff --git a/core/Term.zig b/core/Term.zig
index 89773f77..aa05a68f 100644
--- a/core/Term.zig
+++ b/core/Term.zig
@@ -102,10 +102,9 @@ pub const State = struct {
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
const parts = try walk.load(iface.Parts, arena.allocator(), bytes[8..][0..n], null);
+ o.media(media);
out.* = .{ .impl = try o.load(gpa, bytes[8 + n ..], &parts) };
writes +%= 1;
- // A replica's (a join's, a closed terminal brought back in a step).
- if (tape.replaying() or dump.terminal_gpa != null) o.direct(out.impl);
}
};
@@ -125,14 +124,27 @@ pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State {
const o = ops orelse return error.NoTerminal;
const s = try gpa.create(State);
errdefer gpa.destroy(s);
+ o.media(media);
s.* = .{ .impl = try o.open(gpa, cols, rows) };
writes +%= 1;
- // A replica's emulator loads its program's images by direct data alone
- // (P32): what is read off the session's machine is the session's.
- if (tape.replaying()) o.direct(s.impl);
return s;
}
+/// A kitty image's medium (a file, a temporary file, shared memory: the
+/// session's machine's) as its emulator reads it, made the tape's answer
+/// (P30: the device's answer as it was, as a file's bytes are): the session
+/// reads it, a temporary file deleted and shared memory unlinked there once,
+/// and every replica is handed the same bytes, or the same failure. Under
+/// screen state a replica feeds no emulator: the read is the session's.
+fn media(ctx: *const anyopaque, read: *const fn (*const anyopaque) iface.MediumError![]u8, gpa: std.mem.Allocator) iface.MediumError![]u8 {
+ if (tape.screenState()) return read(ctx);
+ return tape.valueIn(.medium, gpa, readMedium, .{ read, ctx });
+}
+
+fn readMedium(read: *const fn (*const anyopaque) iface.MediumError![]u8, ctx: *const anyopaque) iface.MediumError![]u8 {
+ return read(ctx);
+}
+
/// It and what it holds, freed, all of it with its own allocator (the
/// one it was opened with): the allocator a caller hands is not used.
pub fn close(s: *State, _: std.mem.Allocator) void {
diff --git a/core/replica.zig b/core/replica.zig
index a52061f4..14757d9a 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -4427,6 +4427,55 @@ test "bytes: a session's output past a unit's bound is cut into units under it,
try sameTerminals(b.a, b.r);
}
+test "bytes: a kitty image shown by a file, a temporary file or shared memory is the session's read, and the replica is handed its bytes: the same image, the cursor moved past it, the temporary file and the shared memory gone once, a missing file refused alike" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const shm = struct {
+ extern "c" fn shm_open(name: [*:0]const u8, flag: c_int, mode: std.c.mode_t) c_int;
+ extern "c" fn shm_unlink(name: [*:0]const u8) c_int;
+ extern "c" fn ftruncate(fd: c_int, len: i64) c_int;
+ };
+ // ghostty warns of the missing file, on the session alone.
+ const level = std.testing.log_level;
+ std.testing.log_level = .err;
+ defer std.testing.log_level = level;
+ const b = try BytesPair.init();
+ defer b.deinit();
+ const pixels: [12]u8 = @splat(0x7f); // 2 by 2, RGB
+ const pid = std.c.getpid();
+ var names: [4][80]u8 = undefined;
+ const file = try std.fmt.bufPrintSentinel(&names[0], "/tmp/pardes-replica-{d}-file.rgb", .{pid}, 0);
+ const temp = try std.fmt.bufPrintSentinel(&names[1], "/tmp/tty-graphics-protocol-pardes-replica-{d}.rgb", .{pid}, 0);
+ const object = try std.fmt.bufPrintSentinel(&names[2], "/pardes-replica-{d}", .{pid}, 0);
+ const missing = try std.fmt.bufPrintSentinel(&names[3], "/tmp/pardes-replica-{d}-missing.rgb", .{pid}, 0);
+ for ([_][:0]const u8{ file, temp }) |path| {
+ const fd = std.c.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(std.c.mode_t, 0o600));
+ try std.testing.expect(fd >= 0);
+ defer _ = std.c.close(fd);
+ try std.testing.expectEqual(@as(isize, pixels.len), std.c.write(fd, &pixels, pixels.len));
+ }
+ defer for ([_][:0]const u8{ file, temp }) |path| {
+ _ = std.c.unlink(path);
+ };
+ {
+ const fd = shm.shm_open(object, @bitCast(std.c.O{ .ACCMODE = .RDWR, .CREAT = true, .TRUNC = true }), 0o600);
+ try std.testing.expect(fd >= 0);
+ defer _ = std.c.close(fd);
+ try std.testing.expectEqual(@as(c_int, 0), shm.ftruncate(fd, pixels.len));
+ try std.testing.expectEqual(@as(isize, pixels.len), std.c.write(fd, &pixels, pixels.len));
+ }
+ defer _ = shm.shm_unlink(object);
+ const enc = std.base64.standard.Encoder;
+ var line: [256]u8 = undefined;
+ var b64: [128]u8 = undefined;
+ for ([_][:0]const u8{ file, temp, object, missing }, "ftsf", 7..) |path, medium, id|
+ try b.output(try std.fmt.bufPrint(&line, "\x1b_Ga=T,t={c},i={d},f=24,s=2,v=2;{s}\x1b\\ shown\r\n", .{ medium, id, enc.encode(&b64, path) }));
+ try agrees(b.a, b.r);
+ try sameTerminals(b.a, b.r);
+ try std.testing.expect(std.c.access(file, std.c.F_OK) == 0);
+ try std.testing.expect(std.c.access(temp, std.c.F_OK) != 0);
+ try std.testing.expect(shm.shm_open(object, @bitCast(std.c.O{ .ACCMODE = .RDONLY }), 0) < 0);
+}
+
test "a replica joined from the session's dump replays the units after it" {
const gpa = std.testing.allocator;
const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false);
diff --git a/core/tape.zig b/core/tape.zig
index d977b53e..f705636f 100644
--- a/core/tape.zig
+++ b/core/tape.zig
@@ -135,6 +135,9 @@ pub const Site = enum(u16) {
/// join (panes.reloadTerminals), which every replica's own reload
/// compares.
reload,
+ /// A kitty image's medium as a terminal's emulator read it (a file, a
+ /// temporary file, shared memory: Term.media), its bytes or its failure.
+ medium,
};
/// What the sites return. wire.semantics hashes their shape with the
@@ -1296,6 +1299,12 @@ pub fn authority(comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn"
return (on orelse &none).authority(f, args);
}
+/// `value` whose answer's slices are `a`'s on a replay, as `site`'s are:
+/// what its caller keeps (a kitty image's medium, Term.media).
+pub fn valueIn(comptime s: Site, a: std.mem.Allocator, comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? {
+ return (on orelse &none).call(s, a, f, args, false);
+}
+
/// What `authority` was asked: `f` and its arguments as they are.
fn question(comptime f: anytype, args: anytype) u64 {
var h = std.hash.Wyhash.init(@intFromPtr(&f));
diff --git a/core/term/term.zig b/core/term/term.zig
index b18f5875..59511727 100644
--- a/core/term/term.zig
+++ b/core/term/term.zig
@@ -32,7 +32,7 @@ pub const ops: iface.Ops = .{
.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),
+ .media = terminal_.media,
.feed = cast(iface.Ops, "feed", terminal_.feed),
.grid = cast(iface.Ops, "grid", terminal_.grid),
.viewTo = cast(iface.Ops, "viewTo", terminal_.viewTo),
diff --git a/core/term/terminal.zig b/core/term/terminal.zig
index 055c8981..e57193a6 100644
--- a/core/term/terminal.zig
+++ b/core/term/terminal.zig
@@ -195,11 +195,6 @@ 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
@@ -343,11 +338,11 @@ pub fn reload(s: *State) !u64 {
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 };
+ const kept = .{ s.changes, s.read, s.resize_to };
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] };
+ s.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined, .changes = kept[0] +% 1, .read = kept[1], .resize_to = kept[2] };
// 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);
@@ -357,8 +352,8 @@ pub fn reload(s: *State) !u64 {
/// 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.
+/// after a 10-byte envelope): an animation's current frame is stepped by
+/// each side's own draws, and no digest reads an image.
fn joinHash(bytes: []const u8) u64 {
const envelope = 10;
const head = 10;
@@ -379,7 +374,7 @@ fn joinHash(bytes: []const u8) u64 {
/// 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 = if (out.direct) .direct else .allWithTempDir(tempDir());
+ if (out.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = .allWithTempDir(tempDir());
};
const whole = out.wire();
switch (continuation) {
@@ -409,14 +404,10 @@ fn install(out: *State, continuation: ghostty_vt.snapshot.Continuation, saved: *
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;
- }
+/// How every terminal's kitty loader has a medium's bytes from now on
+/// (ghostty's `read_medium`, build/patches.zig).
+pub fn media(read: Term.Media) void {
+ if (comptime images_enabled) ghostty_vt.kitty.graphics.LoadingImage.read_medium = read;
}
/// The allocator it was opened with, its own from then on.
diff --git a/docs/ghostty-kitty-medium.md b/docs/ghostty-kitty-medium.md
new file mode 100644
index 00000000..c990ea6d
--- /dev/null
+++ b/docs/ghostty-kitty-medium.md
@@ -0,0 +1,57 @@
+# ghostty: a host cannot be the one that reads a kitty image's medium
+
+A note for upstream (https://github.com/ghostty-org/ghostty), against the
+commit pardes pins (83fb95624b04, 1.4.0, `build.zig.zon`). pardes patches
+its fetched copy at build time (build/patches.zig, `ghostty_kitty`, and
+build/patches/ghostty_kitty.zig) until upstream has a way, if it wants one.
+
+## What a host cannot do
+
+A kitty graphics transmission by file (`t=f`), temporary file (`t=t`) or
+shared memory (`t=s`) is read inside `LoadingImage.init`
+(`src/terminal/kitty/graphics_image.zig`): `readFile` opens, checks and
+reads the path, and deletes a temporary file; `readSharedMemory` opens,
+maps, copies and unlinks the object. A host of libghostty-vt can allow or
+refuse each medium (`LoadingImage.Limits`), and nothing else: it cannot
+be the one that has the bytes.
+
+pardes needs to. A session's terminal is parsed by its own emulator and,
+the same bytes in the same order, by the emulator of every client of the
+session, each on its own machine. A file or a shared memory object names
+something on the session's machine, and a temporary file or an object is
+gone once its first reader has read it. So a client must not read the
+medium: it must be handed the bytes the session read, or the failure the
+session met, and the program must be answered once, by the session. If a
+client refuses the medium instead, a shown image (`a=T`) moves the
+session's cursor past it and not the client's, and the two terminals part.
+
+## The patch
+
+`LoadingImage.read_medium`, a hook a host may set (null: ghostty's read
+as it is). When set, `init` hands it ghostty's own read as a function and
+a context, and the allocator the bytes are to be in; what it returns
+becomes the image's data:
+
+```zig
+pub var read_medium: ?*const fn (ctx: *const anyopaque, read: *const fn (ctx: *const anyopaque) MediumError![]u8, alloc: Allocator) MediumError![]u8 = null;
+```
+
+The read itself is ghostty's, unchanged (`readFile`, `readSharedMemory`,
+their checks, the deletion and the unlink), behind a small struct appended
+to the file (`PardesMedium.read`). pardes's hook calls it on the session
+and records what it returned; a client's hook returns the recorded bytes
+(or error) without calling it. Everything before the read (the limits,
+the PNG check, the path's NUL check) and after it (decompression,
+decoding, the size checks of `complete`, the answer) runs on every side
+alike.
+
+## Why not rewrite the transmission instead
+
+The other way is to turn `t=f`, `t=t` and `t=s` into direct data before
+the emulator sees it. That parses the APC outside ghostty, repeats its
+rules (the temporary directory and the name a temporary file must have,
+the `/proc`, `/sys` and device refusals, the shared memory range by
+format, offset and size, `S` meaning an exact length), and re-encodes the
+bytes as base64 a third larger, chunked to the protocol's limits. It also
+changes what the emulator sees, so its answer to the program has to be
+checked to match. The hook keeps all of that in ghostty.